celestial-rhapsody 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,29 @@
1
+ """Celestial Rhapsody: a configurable N-body gravitational simulation.
2
+
3
+ Quick use from Python::
4
+
5
+ from celestial_rhapsody import load_system, simulate, animate
6
+
7
+ system = load_system("examples/figure_eight.json")
8
+ trajectory = simulate(system)
9
+ animate(trajectory, "figure_eight.gif")
10
+ """
11
+
12
+ __version__ = "0.1.0"
13
+
14
+ from .config import System, load_system, read_config, system_from_dict # noqa: E402
15
+ from .solvers import Trajectory, accelerations, simulate, total_energy # noqa: E402
16
+ from .animation import animate # noqa: E402
17
+
18
+ __all__ = [
19
+ "System",
20
+ "Trajectory",
21
+ "load_system",
22
+ "read_config",
23
+ "system_from_dict",
24
+ "simulate",
25
+ "accelerations",
26
+ "total_energy",
27
+ "animate",
28
+ "__version__",
29
+ ]
@@ -0,0 +1,5 @@
1
+ """Allows ``python -m celestial_rhapsody run input.json``."""
2
+
3
+ from .cli import main
4
+
5
+ raise SystemExit(main())
@@ -0,0 +1,90 @@
1
+ """Animation of a :class:`~celestial_rhapsody.solvers.Trajectory` (GIF or MP4)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ from pathlib import Path
7
+ from typing import Optional, Union
8
+
9
+ import matplotlib
10
+
11
+ matplotlib.use("Agg") # render without a screen (laptops, servers, CI)
12
+ import matplotlib.pyplot as plt # noqa: E402
13
+ import numpy as np # noqa: E402
14
+ from matplotlib import animation # noqa: E402
15
+
16
+ from .solvers import Trajectory # noqa: E402
17
+
18
+
19
+ def animate(
20
+ trajectory: Trajectory,
21
+ output: Union[str, Path] = "movie.gif",
22
+ fps: int = 30,
23
+ trail: Optional[int] = None,
24
+ title: Optional[str] = None,
25
+ dpi: int = 100,
26
+ ) -> Path:
27
+ """Save an animation of the orbits in the x-y plane.
28
+
29
+ The format comes from the file extension: ``.gif`` works everywhere,
30
+ ``.mp4`` needs `ffmpeg <https://ffmpeg.org>`_.
31
+
32
+ Args:
33
+ trajectory: Output of :func:`celestial_rhapsody.simulate`.
34
+ output: File to write, e.g. ``"orbits.gif"``.
35
+ fps: Frames per second.
36
+ trail: Number of past frames drawn behind each body.
37
+ ``None`` (default) draws the whole path; ``0`` draws none.
38
+ title: Optional plot title.
39
+ dpi: Resolution.
40
+
41
+ Returns:
42
+ Path of the written file.
43
+ """
44
+ output = Path(output)
45
+ suffix = output.suffix.lower()
46
+ if suffix == ".gif":
47
+ writer = animation.PillowWriter(fps=fps)
48
+ elif suffix == ".mp4":
49
+ if shutil.which("ffmpeg") is None:
50
+ raise RuntimeError("Saving .mp4 needs ffmpeg installed. Use a .gif output, or install ffmpeg.")
51
+ writer = animation.FFMpegWriter(fps=fps)
52
+ else:
53
+ raise ValueError(f"Unsupported output type '{suffix}'. Use .gif or .mp4.")
54
+
55
+ pos = trajectory.positions[:, :, :2]
56
+ n_frames, n_bodies, _ = pos.shape
57
+
58
+ fig, ax = plt.subplots(figsize=(6, 6))
59
+ lo, hi = pos.min(axis=(0, 1)), pos.max(axis=(0, 1))
60
+ half = 0.55 * max(hi - lo) + 1e-9
61
+ centre = (lo + hi) / 2
62
+ ax.set_xlim(centre[0] - half, centre[0] + half)
63
+ ax.set_ylim(centre[1] - half, centre[1] + half)
64
+ ax.set_aspect("equal")
65
+ ax.set_xlabel("x")
66
+ ax.set_ylabel("y")
67
+ if title:
68
+ ax.set_title(title)
69
+
70
+ colors = plt.cm.tab10(np.arange(n_bodies) % 10)
71
+ sizes = 30 + 70 * trajectory.masses / trajectory.masses.max()
72
+ lines = [ax.plot([], [], "-", lw=1.2, color=colors[i], alpha=0.7, label=trajectory.names[i])[0]
73
+ for i in range(n_bodies)]
74
+ dots = ax.scatter(pos[0, :, 0], pos[0, :, 1], s=sizes, c=colors, zorder=3)
75
+ if n_bodies <= 10:
76
+ ax.legend(loc="upper right", fontsize=8)
77
+ clock = ax.text(0.02, 0.96, "", transform=ax.transAxes)
78
+
79
+ def update(k: int):
80
+ start = 0 if trail is None else max(0, k - trail)
81
+ for i, line in enumerate(lines):
82
+ line.set_data(pos[start:k + 1, i, 0], pos[start:k + 1, i, 1])
83
+ dots.set_offsets(pos[k])
84
+ clock.set_text(f"t = {trajectory.times[k]:.2f}")
85
+ return [*lines, dots, clock]
86
+
87
+ movie = animation.FuncAnimation(fig, update, frames=n_frames, interval=1000 / fps, blit=True)
88
+ movie.save(str(output), writer=writer, dpi=dpi)
89
+ plt.close(fig)
90
+ return output
@@ -0,0 +1,87 @@
1
+ """Command-line interface: ``nbody run input.json``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import List, Optional
9
+
10
+ from . import __version__
11
+ from .animation import animate
12
+ from .config import load_system
13
+ from .solvers import METHODS, simulate
14
+
15
+
16
+ def build_parser() -> argparse.ArgumentParser:
17
+ parser = argparse.ArgumentParser(
18
+ prog="nbody",
19
+ description="Celestial Rhapsody: simulate N bodies under Newtonian gravity and save an animation.",
20
+ )
21
+ parser.add_argument("--version", action="version", version=f"celestial-rhapsody {__version__}")
22
+ sub = parser.add_subparsers(dest="command", required=True)
23
+
24
+ run = sub.add_parser("run", help="Run a simulation and save an animation.")
25
+ run.add_argument("input", type=Path, help="Input file (.json or .txt).")
26
+ run.add_argument("-o", "--output", type=Path, default=None,
27
+ help="Animation file, .gif or .mp4 (default: input name + .gif).")
28
+ run.add_argument("--method", choices=sorted(METHODS), default="rk4", help="Integrator (default: rk4).")
29
+ run.add_argument("--every", type=int, default=2,
30
+ help="Draw one animation frame every N time steps (default: 2).")
31
+ run.add_argument("--fps", type=int, default=30, help="Frames per second (default: 30).")
32
+ run.add_argument("--trail", type=int, default=None,
33
+ help="Trail length in frames (default: full path; 0 = no trail).")
34
+ run.add_argument("--dt", type=float, default=None, help="Override dt from the input file.")
35
+ run.add_argument("--final-time", type=float, default=None, help="Override final_time from the input file.")
36
+
37
+ check = sub.add_parser("check", help="Validate an input file and print a summary.")
38
+ check.add_argument("input", type=Path)
39
+ return parser
40
+
41
+
42
+ def main(argv: Optional[List[str]] = None) -> int:
43
+ """Entry point of the ``nbody`` command. Returns the exit code."""
44
+ args = build_parser().parse_args(argv)
45
+
46
+ try:
47
+ system = load_system(args.input)
48
+ except FileNotFoundError:
49
+ print(f"error: file not found: {args.input}", file=sys.stderr)
50
+ return 1
51
+ except ValueError as err:
52
+ print(f"error: invalid input: {err}", file=sys.stderr)
53
+ return 1
54
+
55
+ if args.command == "check":
56
+ print(f"OK: {system.n_bodies} bodies ({', '.join(system.names)}), {system.dim}D, "
57
+ f"G={system.G}, dt={system.dt}, final_time={system.final_time}")
58
+ return 0
59
+
60
+ if args.dt is not None:
61
+ system.dt = args.dt
62
+ if args.final_time is not None:
63
+ system.final_time = args.final_time
64
+ output = args.output or args.input.with_suffix(".gif")
65
+ if output.suffix.lower() not in (".gif", ".mp4"):
66
+ print(f"error: unsupported output type '{output.suffix}'. Use .gif or .mp4.", file=sys.stderr)
67
+ return 1
68
+
69
+ print(f"Simulating {system.n_bodies} bodies with {args.method.upper()} "
70
+ f"up to t={system.final_time} (dt={system.dt})...")
71
+ trajectory = simulate(system, method=args.method, save_every=args.every)
72
+ print(f"Relative energy drift: {trajectory.energy_drift:.2e}")
73
+ if trajectory.energy_drift > 1e-2:
74
+ print("warning: energy drift above 1%; consider a smaller --dt.", file=sys.stderr)
75
+
76
+ print(f"Rendering {len(trajectory.times)} frames to {output} ...")
77
+ try:
78
+ animate(trajectory, output, fps=args.fps, trail=args.trail, title=args.input.stem)
79
+ except (RuntimeError, ValueError) as err:
80
+ print(f"error: {err}", file=sys.stderr)
81
+ return 1
82
+ print(f"Done: {output}")
83
+ return 0
84
+
85
+
86
+ if __name__ == "__main__":
87
+ raise SystemExit(main())
@@ -0,0 +1,220 @@
1
+ """Reading the input file that describes the system to simulate.
2
+
3
+ Two formats are supported:
4
+
5
+ * **JSON** (``.json``), the recommended format;
6
+ * the original **INI-style text** format (``.txt``) with ``[Global]`` and
7
+ ``[Planet]`` sections.
8
+
9
+ Use :func:`load_system` for either one. It picks the reader from the file extension.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import List, Tuple, Union
18
+
19
+ import numpy as np
20
+
21
+ PathLike = Union[str, Path]
22
+
23
+
24
+ @dataclass
25
+ class System:
26
+ """A set of bodies plus the simulation settings.
27
+
28
+ Attributes:
29
+ names: One label per body.
30
+ masses: Masses, shape ``(n,)``.
31
+ positions: Initial positions, shape ``(n, dim)`` with ``dim`` 2 or 3.
32
+ velocities: Initial velocities, shape ``(n, dim)``.
33
+ G: Gravitational constant.
34
+ dt: Integration time step.
35
+ final_time: Time at which the simulation stops.
36
+ softening: Optional softening length (0 means pure Newtonian gravity).
37
+ """
38
+
39
+ names: List[str]
40
+ masses: np.ndarray
41
+ positions: np.ndarray
42
+ velocities: np.ndarray
43
+ G: float = 1.0
44
+ dt: float = 0.01
45
+ final_time: float = 5.0
46
+ softening: float = 0.0
47
+
48
+ def __post_init__(self) -> None:
49
+ self.masses = np.asarray(self.masses, dtype=float)
50
+ self.positions = np.asarray(self.positions, dtype=float)
51
+ self.velocities = np.asarray(self.velocities, dtype=float)
52
+ n = len(self.masses)
53
+ if n == 0:
54
+ raise ValueError("The system needs at least one body.")
55
+ if self.positions.ndim != 2 or self.positions.shape[1] not in (2, 3):
56
+ raise ValueError("Every position must have 2 or 3 components, the same for all bodies.")
57
+ if self.positions.shape != (n, self.positions.shape[1]) or self.velocities.shape != self.positions.shape:
58
+ raise ValueError("Each body needs one mass, one position and one velocity of the same length.")
59
+ if np.any(self.masses <= 0):
60
+ raise ValueError("All masses must be positive.")
61
+ if self.dt <= 0 or self.final_time <= 0:
62
+ raise ValueError("dt and final_time must be positive.")
63
+ if self.softening < 0:
64
+ raise ValueError("softening cannot be negative.")
65
+ if len(self.names) != n:
66
+ raise ValueError("Number of names does not match number of bodies.")
67
+
68
+ @property
69
+ def n_bodies(self) -> int:
70
+ return len(self.masses)
71
+
72
+ @property
73
+ def dim(self) -> int:
74
+ return self.positions.shape[1]
75
+
76
+
77
+ # --------------------------------------------------------------------------- #
78
+ # Original text format
79
+ # --------------------------------------------------------------------------- #
80
+ def read_config(file_name: PathLike) -> Tuple[list, list]:
81
+ """Read the INI-style text config file (the original project format).
82
+
83
+ The file starts with a ``[Global]`` section (``G``, ``dt``, ``final_time``)
84
+ followed by one ``[Planet]`` section per body (``name``, ``mass``, ``x_0``,
85
+ ``y_0``, ``vx_0``, ``vy_0``). Values are read **in order**, so keep the
86
+ order of the lines as in the examples.
87
+
88
+ Args:
89
+ file_name: Path of the config file.
90
+
91
+ Raises:
92
+ RuntimeError: If the file cannot be opened or a line cannot be parsed.
93
+
94
+ Returns:
95
+ A list with the global values ``[G, dt, final_time]`` and a list of
96
+ planets, each ``[name, mass, x_0, y_0, vx_0, vy_0]``.
97
+ """
98
+ global_var: list = []
99
+ planet_var: list = []
100
+ allplanet_var: list = []
101
+ planet_flag = False
102
+
103
+ try:
104
+ with open(file_name, "r", encoding="utf-8") as file:
105
+ next(file, None) # skip the [Global] header line
106
+ for line in file:
107
+ if not line.strip():
108
+ continue
109
+ # Append lines to global_var until the first [Planet] section,
110
+ # then collect one list of values per planet.
111
+ if "Planet" in line:
112
+ planet_flag = True
113
+ if planet_var:
114
+ allplanet_var.append(planet_var[:])
115
+ planet_var.clear()
116
+ continue
117
+
118
+ value = line.split("=", 1)[1].strip()
119
+ if not planet_flag:
120
+ global_var.append(int(value) if "final_time" in line else float(value))
121
+ else:
122
+ try:
123
+ planet_var.append(float(value))
124
+ except ValueError:
125
+ planet_var.append(value) # e.g. the planet name
126
+
127
+ if planet_var:
128
+ allplanet_var.append(planet_var[:])
129
+ except (OSError, IndexError, ValueError) as err:
130
+ raise RuntimeError(
131
+ f"Failed to process config file '{file_name}', make sure to input the correct config file."
132
+ ) from err
133
+
134
+ return global_var, allplanet_var
135
+
136
+
137
+ def _system_from_txt(path: PathLike) -> System:
138
+ global_var, planets = read_config(path)
139
+ defaults = [1.0, 0.01, 5.0]
140
+ G, dt, final_time = (list(global_var) + defaults[len(global_var):])[:3]
141
+ for i, p in enumerate(planets):
142
+ if len(p) != 6:
143
+ raise ValueError(
144
+ f"Planet {i + 1} in '{path}' has {len(p)} values; expected 6 "
145
+ "(name, mass, x_0, y_0, vx_0, vy_0)."
146
+ )
147
+ return System(
148
+ names=[str(p[0]) for p in planets],
149
+ masses=[p[1] for p in planets],
150
+ positions=[[p[2], p[3]] for p in planets],
151
+ velocities=[[p[4], p[5]] for p in planets],
152
+ G=float(G),
153
+ dt=float(dt),
154
+ final_time=float(final_time),
155
+ )
156
+
157
+
158
+ # --------------------------------------------------------------------------- #
159
+ # JSON format
160
+ # --------------------------------------------------------------------------- #
161
+ def system_from_dict(data: dict) -> System:
162
+ """Build a :class:`System` from a dictionary with the JSON layout.
163
+
164
+ See the *Input format* page of the documentation for all fields.
165
+ """
166
+ if "bodies" not in data or not isinstance(data["bodies"], list):
167
+ raise ValueError("The input needs a 'bodies' list.")
168
+ names, masses, pos, vel = [], [], [], []
169
+ for i, body in enumerate(data["bodies"]):
170
+ missing = {"mass", "position", "velocity"} - set(body)
171
+ if missing:
172
+ raise ValueError(f"Body {i} is missing: {', '.join(sorted(missing))}")
173
+ names.append(str(body.get("name", f"body {i}")))
174
+ masses.append(float(body["mass"]))
175
+ pos.append(body["position"])
176
+ vel.append(body["velocity"])
177
+ try:
178
+ positions = np.array(pos, dtype=float)
179
+ velocities = np.array(vel, dtype=float)
180
+ except ValueError as err:
181
+ raise ValueError("Positions and velocities must all have the same number of components.") from err
182
+ return System(
183
+ names=names,
184
+ masses=masses,
185
+ positions=positions,
186
+ velocities=velocities,
187
+ G=float(data.get("G", 1.0)),
188
+ dt=float(data.get("dt", 0.01)),
189
+ final_time=float(data.get("final_time", 5.0)),
190
+ softening=float(data.get("softening", 0.0)),
191
+ )
192
+
193
+
194
+ def load_system(path: PathLike) -> System:
195
+ """Load a system from a ``.json`` or ``.txt`` file.
196
+
197
+ Args:
198
+ path: Input file. The extension selects the format.
199
+
200
+ Returns:
201
+ A validated :class:`System`.
202
+
203
+ Raises:
204
+ FileNotFoundError: If the file does not exist.
205
+ ValueError: If the content is invalid.
206
+ """
207
+ path = Path(path)
208
+ if not path.exists():
209
+ raise FileNotFoundError(path)
210
+ if path.suffix.lower() == ".json":
211
+ with open(path, "r", encoding="utf-8") as f:
212
+ try:
213
+ data = json.load(f)
214
+ except json.JSONDecodeError as err:
215
+ raise ValueError(f"'{path}' is not valid JSON: {err}") from err
216
+ return system_from_dict(data)
217
+ try:
218
+ return _system_from_txt(path)
219
+ except RuntimeError as err:
220
+ raise ValueError(str(err)) from err
@@ -0,0 +1,152 @@
1
+ """Newtonian gravity and the time integrators (Euler, RK2, RK4)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Callable, Dict, List, Tuple
7
+
8
+ import numpy as np
9
+
10
+ from .config import System
11
+
12
+ State = Tuple[np.ndarray, np.ndarray] # (positions, velocities)
13
+
14
+
15
+ @dataclass
16
+ class Trajectory:
17
+ """Result of :func:`simulate`.
18
+
19
+ Attributes:
20
+ times: Times of the saved frames, shape ``(n_frames,)``.
21
+ positions: Shape ``(n_frames, n_bodies, dim)``.
22
+ velocities: Shape ``(n_frames, n_bodies, dim)``.
23
+ energy: Total energy at each saved frame. It should stay nearly constant;
24
+ a large drift means ``dt`` is too big.
25
+ names: Body labels.
26
+ masses: Body masses.
27
+ """
28
+
29
+ times: np.ndarray
30
+ positions: np.ndarray
31
+ velocities: np.ndarray
32
+ energy: np.ndarray
33
+ names: List[str]
34
+ masses: np.ndarray
35
+
36
+ @property
37
+ def energy_drift(self) -> float:
38
+ """Relative change of total energy between first and last frame."""
39
+ e0 = self.energy[0]
40
+ return float(abs((self.energy[-1] - e0) / e0)) if e0 != 0 else float(abs(self.energy[-1]))
41
+
42
+
43
+ def accelerations(positions: np.ndarray, masses: np.ndarray, G: float = 1.0, softening: float = 0.0) -> np.ndarray:
44
+ r"""Gravitational acceleration of every body due to all the others.
45
+
46
+ .. math::
47
+
48
+ \mathbf{a}_i = -G \sum_{k \neq i} m_k
49
+ \frac{\mathbf{r}_i - \mathbf{r}_k}{\left(|\mathbf{r}_i - \mathbf{r}_k|^2 + \epsilon^2\right)^{3/2}}
50
+
51
+ Args:
52
+ positions: Shape ``(n, dim)``.
53
+ masses: Shape ``(n,)``.
54
+ G: Gravitational constant.
55
+ softening: Softening length :math:`\epsilon`.
56
+
57
+ Returns:
58
+ Accelerations, shape ``(n, dim)``.
59
+ """
60
+ r_ik = positions[:, np.newaxis, :] - positions[np.newaxis, :, :] # r_i - r_k
61
+ dist2 = np.sum(r_ik**2, axis=-1) + softening**2
62
+ np.fill_diagonal(dist2, np.inf) # a body does not attract itself
63
+ inv_r3 = dist2**-1.5
64
+ return -G * np.einsum("ik,ikd,k->id", inv_r3, r_ik, masses)
65
+
66
+
67
+ def total_energy(positions: np.ndarray, velocities: np.ndarray, masses: np.ndarray,
68
+ G: float = 1.0, softening: float = 0.0) -> float:
69
+ """Kinetic plus gravitational potential energy."""
70
+ kinetic = 0.5 * np.sum(masses * np.sum(velocities**2, axis=-1))
71
+ i, k = np.triu_indices(len(masses), k=1)
72
+ dist = np.sqrt(np.sum((positions[i] - positions[k]) ** 2, axis=-1) + softening**2)
73
+ potential = -G * np.sum(masses[i] * masses[k] / dist)
74
+ return float(kinetic + potential)
75
+
76
+
77
+ # --------------------------------------------------------------------------- #
78
+ # Integrators: each takes the state and returns the state one step later.
79
+ # --------------------------------------------------------------------------- #
80
+ def euler_step(x: np.ndarray, v: np.ndarray, dt: float, acc: Callable[[np.ndarray], np.ndarray]) -> State:
81
+ """Forward Euler (1st order). Simple but drifts quickly; for teaching only."""
82
+ return x + dt * v, v + dt * acc(x)
83
+
84
+
85
+ def rk2_step(x: np.ndarray, v: np.ndarray, dt: float, acc: Callable[[np.ndarray], np.ndarray]) -> State:
86
+ """Midpoint Runge-Kutta (2nd order)."""
87
+ x_mid = x + 0.5 * dt * v
88
+ v_mid = v + 0.5 * dt * acc(x)
89
+ return x + dt * v_mid, v + dt * acc(x_mid)
90
+
91
+
92
+ def rk4_step(x: np.ndarray, v: np.ndarray, dt: float, acc: Callable[[np.ndarray], np.ndarray]) -> State:
93
+ """Classic Runge-Kutta (4th order). The default."""
94
+ k1x, k1v = v, acc(x)
95
+ k2x, k2v = v + 0.5 * dt * k1v, acc(x + 0.5 * dt * k1x)
96
+ k3x, k3v = v + 0.5 * dt * k2v, acc(x + 0.5 * dt * k2x)
97
+ k4x, k4v = v + dt * k3v, acc(x + dt * k3x)
98
+ x_new = x + dt / 6.0 * (k1x + 2 * k2x + 2 * k3x + k4x)
99
+ v_new = v + dt / 6.0 * (k1v + 2 * k2v + 2 * k3v + k4v)
100
+ return x_new, v_new
101
+
102
+
103
+ METHODS: Dict[str, Callable] = {"euler": euler_step, "rk2": rk2_step, "rk4": rk4_step}
104
+
105
+
106
+ def simulate(system: System, method: str = "rk4", save_every: int = 1) -> Trajectory:
107
+ """Integrate the system from ``t = 0`` to ``system.final_time``.
108
+
109
+ The last step is shortened if needed so the run ends exactly at ``final_time``.
110
+
111
+ Args:
112
+ system: Bodies and settings, usually from :func:`celestial_rhapsody.load_system`.
113
+ method: ``"rk4"`` (default), ``"rk2"`` or ``"euler"``.
114
+ save_every: Keep one frame every ``save_every`` steps. The final state is always kept.
115
+
116
+ Returns:
117
+ A :class:`Trajectory`.
118
+ """
119
+ if method not in METHODS:
120
+ raise ValueError(f"Unknown method '{method}'. Choose from: {', '.join(METHODS)}")
121
+ if save_every < 1:
122
+ raise ValueError("save_every must be at least 1.")
123
+ step = METHODS[method]
124
+ m, G, eps = system.masses, system.G, system.softening
125
+
126
+ def acc(pos: np.ndarray) -> np.ndarray:
127
+ return accelerations(pos, m, G, eps)
128
+
129
+ x, v = system.positions.copy(), system.velocities.copy()
130
+ t, T, dt = 0.0, system.final_time, system.dt
131
+ times, xs, vs, es = [t], [x.copy()], [v.copy()], [total_energy(x, v, m, G, eps)]
132
+
133
+ n = 0
134
+ while t < T - 1e-12 * T:
135
+ h = min(dt, T - t) # do not overshoot final_time
136
+ x, v = step(x, v, h, acc)
137
+ t += h
138
+ n += 1
139
+ if n % save_every == 0 or t >= T - 1e-12 * T:
140
+ times.append(t)
141
+ xs.append(x.copy())
142
+ vs.append(v.copy())
143
+ es.append(total_energy(x, v, m, G, eps))
144
+
145
+ return Trajectory(
146
+ times=np.array(times),
147
+ positions=np.array(xs),
148
+ velocities=np.array(vs),
149
+ energy=np.array(es),
150
+ names=list(system.names),
151
+ masses=m.copy(),
152
+ )
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: celestial-rhapsody
3
+ Version: 0.1.0
4
+ Summary: Configurable N-body gravitational simulation: input file in, animation out.
5
+ Author: Valeria Monserrat Aceituno Salinas, Aditya Swardiana
6
+ Author-email: Jam Sadiq <jamlucky.qau@gmail.com>
7
+ License-Expression: BSD-3-Clause
8
+ Project-URL: Homepage, https://github.com/jam-sadiq/celestial-rhapsody
9
+ Project-URL: Documentation, https://jam-sadiq.github.io/celestial-rhapsody
10
+ Keywords: n-body,gravity,simulation,orbits,animation
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Scientific/Engineering :: Physics
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE.txt
16
+ Requires-Dist: numpy>=1.22
17
+ Requires-Dist: matplotlib>=3.5
18
+ Requires-Dist: pillow>=9.0
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest>=7; extra == "test"
21
+ Provides-Extra: docs
22
+ Requires-Dist: sphinx>=7; extra == "docs"
23
+ Requires-Dist: furo; extra == "docs"
24
+ Dynamic: license-file
25
+
26
+ # Celestial Rhapsody
27
+
28
+ A multi-body gravitational simulation, configured entirely through an input
29
+ file. You give it initial masses, positions and velocities, and it gives you an
30
+ animation of the orbits.
31
+
32
+ ![Three-body orbit](https://raw.githubusercontent.com/jam-sadiq/celestial-rhapsody/main/docs/source/_static/three_body.gif)
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ pip install git+https://github.com/jam-sadiq/celestial-rhapsody.git
38
+ ```
39
+
40
+ or, from a copy of this folder: `pip install .`
41
+
42
+ ## Quick start
43
+
44
+ ```bash
45
+ nbody run examples/three_body.json # -> examples/three_body.gif
46
+ ```
47
+
48
+ A minimal input file:
49
+
50
+ ```json
51
+ {
52
+ "G": 1.0,
53
+ "dt": 0.01,
54
+ "final_time": 10,
55
+ "bodies": [
56
+ {"name": "Star", "mass": 1.0, "position": [0, 0], "velocity": [0, 0]},
57
+ {"name": "Planet", "mass": 0.001, "position": [1, 0], "velocity": [0, 1]}
58
+ ]
59
+ }
60
+ ```
61
+
62
+ The original `.txt` format (`[Global]` / `[Planet]` sections) also works. See
63
+ `examples/three_body.txt`.
64
+
65
+ From Python:
66
+
67
+ ```python
68
+ from celestial_rhapsody import load_system, simulate, animate
69
+
70
+ trajectory = simulate(load_system("examples/three_body.json"), method="rk4")
71
+ animate(trajectory, "three_body.gif")
72
+ ```
73
+
74
+ ## Documentation
75
+
76
+ Installation guide, tutorial, input format and API reference:
77
+ **https://jam-sadiq.github.io/celestial-rhapsody**
78
+
79
+ To build it locally:
80
+
81
+ ```bash
82
+ pip install -e ".[docs]"
83
+ cd docs && make html # open docs/build/html/index.html
84
+ ```
85
+
86
+ ## Development
87
+
88
+ ```bash
89
+ pip install -e ".[test]"
90
+ pytest
91
+ ```
92
+
93
+ ## Authors
94
+
95
+ Jam Sadiq, in collaboration with Valeria Monserrat Aceituno Salinas, and Aditya Swardiana
96
+
97
+ ## License
98
+
99
+ BSD 3-Clause. See [LICENSE.txt](https://github.com/jam-sadiq/celestial-rhapsody/blob/main/LICENSE.txt).
@@ -0,0 +1,12 @@
1
+ celestial_rhapsody/__init__.py,sha256=b2x_miwBtIo8gW92aumgFTA7VlO0W0WO-OVhrDi3tT0,740
2
+ celestial_rhapsody/__main__.py,sha256=jzSBkVrigEDGcQP2x-9rtVPeE7bLPE1p7vHhyYnuHZU,111
3
+ celestial_rhapsody/animation.py,sha256=tqJ6NF7T8gObHcfLQnmRiUnbLWdUhHuednVE4PiWmrw,3158
4
+ celestial_rhapsody/cli.py,sha256=gSM2ihqog9FpQlITCzLABAykkSNuGdXOXFNeiQIWdKU,3680
5
+ celestial_rhapsody/config.py,sha256=nO0Q-_egBGNaaoydNOLzLNjyR7Oqe0S9e8JPDfxg13A,7993
6
+ celestial_rhapsody/solvers.py,sha256=UfM1U888Cs7Y22n0g-Ce3EjHKGq8swP8x2t8cw5FgNc,5562
7
+ celestial_rhapsody-0.1.0.dist-info/licenses/LICENSE.txt,sha256=4BOeJghLRrIsdJpHNHFLwvfQjiSRdJ9R7yhjtw9yPCE,1496
8
+ celestial_rhapsody-0.1.0.dist-info/METADATA,sha256=ZOHXyRlRiitaPmGedLjSj40p0eI5x66FQzQFNB3VUuo,2631
9
+ celestial_rhapsody-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ celestial_rhapsody-0.1.0.dist-info/entry_points.txt,sha256=iWMIGqUPMeGLDQOuSfUcLm9uDdlpzMr4WJ5Q4pOwHdI,54
11
+ celestial_rhapsody-0.1.0.dist-info/top_level.txt,sha256=z6ZoLhgcbHhO57LqJqJ43c72ZtkUxtnrTlP_ZfbQeY8,19
12
+ celestial_rhapsody-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ nbody = celestial_rhapsody.cli:main
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, Jam Sadiq
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1 @@
1
+ celestial_rhapsody