celestial-rhapsody 0.1.0__tar.gz
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.
- celestial_rhapsody-0.1.0/LICENSE.txt +28 -0
- celestial_rhapsody-0.1.0/PKG-INFO +99 -0
- celestial_rhapsody-0.1.0/README.md +74 -0
- celestial_rhapsody-0.1.0/pyproject.toml +45 -0
- celestial_rhapsody-0.1.0/setup.cfg +4 -0
- celestial_rhapsody-0.1.0/src/celestial_rhapsody/__init__.py +29 -0
- celestial_rhapsody-0.1.0/src/celestial_rhapsody/__main__.py +5 -0
- celestial_rhapsody-0.1.0/src/celestial_rhapsody/animation.py +90 -0
- celestial_rhapsody-0.1.0/src/celestial_rhapsody/cli.py +87 -0
- celestial_rhapsody-0.1.0/src/celestial_rhapsody/config.py +220 -0
- celestial_rhapsody-0.1.0/src/celestial_rhapsody/solvers.py +152 -0
- celestial_rhapsody-0.1.0/src/celestial_rhapsody.egg-info/PKG-INFO +99 -0
- celestial_rhapsody-0.1.0/src/celestial_rhapsody.egg-info/SOURCES.txt +18 -0
- celestial_rhapsody-0.1.0/src/celestial_rhapsody.egg-info/dependency_links.txt +1 -0
- celestial_rhapsody-0.1.0/src/celestial_rhapsody.egg-info/entry_points.txt +2 -0
- celestial_rhapsody-0.1.0/src/celestial_rhapsody.egg-info/requires.txt +10 -0
- celestial_rhapsody-0.1.0/src/celestial_rhapsody.egg-info/top_level.txt +1 -0
- celestial_rhapsody-0.1.0/tests/test_cli.py +28 -0
- celestial_rhapsody-0.1.0/tests/test_config.py +111 -0
- celestial_rhapsody-0.1.0/tests/test_solvers.py +63 -0
|
@@ -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,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
|
+

|
|
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,74 @@
|
|
|
1
|
+
# Celestial Rhapsody
|
|
2
|
+
|
|
3
|
+
A multi-body gravitational simulation, configured entirely through an input
|
|
4
|
+
file. You give it initial masses, positions and velocities, and it gives you an
|
|
5
|
+
animation of the orbits.
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install git+https://github.com/jam-sadiq/celestial-rhapsody.git
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
or, from a copy of this folder: `pip install .`
|
|
16
|
+
|
|
17
|
+
## Quick start
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
nbody run examples/three_body.json # -> examples/three_body.gif
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
A minimal input file:
|
|
24
|
+
|
|
25
|
+
```json
|
|
26
|
+
{
|
|
27
|
+
"G": 1.0,
|
|
28
|
+
"dt": 0.01,
|
|
29
|
+
"final_time": 10,
|
|
30
|
+
"bodies": [
|
|
31
|
+
{"name": "Star", "mass": 1.0, "position": [0, 0], "velocity": [0, 0]},
|
|
32
|
+
{"name": "Planet", "mass": 0.001, "position": [1, 0], "velocity": [0, 1]}
|
|
33
|
+
]
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The original `.txt` format (`[Global]` / `[Planet]` sections) also works. See
|
|
38
|
+
`examples/three_body.txt`.
|
|
39
|
+
|
|
40
|
+
From Python:
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from celestial_rhapsody import load_system, simulate, animate
|
|
44
|
+
|
|
45
|
+
trajectory = simulate(load_system("examples/three_body.json"), method="rk4")
|
|
46
|
+
animate(trajectory, "three_body.gif")
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Documentation
|
|
50
|
+
|
|
51
|
+
Installation guide, tutorial, input format and API reference:
|
|
52
|
+
**https://jam-sadiq.github.io/celestial-rhapsody**
|
|
53
|
+
|
|
54
|
+
To build it locally:
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pip install -e ".[docs]"
|
|
58
|
+
cd docs && make html # open docs/build/html/index.html
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Development
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
pip install -e ".[test]"
|
|
65
|
+
pytest
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Authors
|
|
69
|
+
|
|
70
|
+
Jam Sadiq, in collaboration with Valeria Monserrat Aceituno Salinas, and Aditya Swardiana
|
|
71
|
+
|
|
72
|
+
## License
|
|
73
|
+
|
|
74
|
+
BSD 3-Clause. See [LICENSE.txt](https://github.com/jam-sadiq/celestial-rhapsody/blob/main/LICENSE.txt).
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "celestial-rhapsody"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Configurable N-body gravitational simulation: input file in, animation out."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "BSD-3-Clause"
|
|
12
|
+
license-files = ["LICENSE.txt"]
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "Jam Sadiq", email = "jamlucky.qau@gmail.com" },
|
|
15
|
+
{ name = "Valeria Monserrat Aceituno Salinas" },
|
|
16
|
+
{ name = "Aditya Swardiana" }
|
|
17
|
+
]
|
|
18
|
+
keywords = ["n-body", "gravity", "simulation", "orbits", "animation"]
|
|
19
|
+
classifiers = [
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Topic :: Scientific/Engineering :: Physics",
|
|
22
|
+
]
|
|
23
|
+
dependencies = [
|
|
24
|
+
"numpy>=1.22",
|
|
25
|
+
"matplotlib>=3.5",
|
|
26
|
+
"pillow>=9.0",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.optional-dependencies]
|
|
30
|
+
test = ["pytest>=7"]
|
|
31
|
+
docs = ["sphinx>=7", "furo"]
|
|
32
|
+
|
|
33
|
+
[project.scripts]
|
|
34
|
+
# After `pip install`, the terminal command `nbody` calls celestial_rhapsody.cli.main()
|
|
35
|
+
nbody = "celestial_rhapsody.cli:main"
|
|
36
|
+
|
|
37
|
+
[project.urls]
|
|
38
|
+
Homepage = "https://github.com/jam-sadiq/celestial-rhapsody"
|
|
39
|
+
Documentation = "https://jam-sadiq.github.io/celestial-rhapsody"
|
|
40
|
+
|
|
41
|
+
[tool.setuptools.packages.find]
|
|
42
|
+
where = ["src"]
|
|
43
|
+
|
|
44
|
+
[tool.pytest.ini_options]
|
|
45
|
+
testpaths = ["tests"]
|
|
@@ -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,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
|
+

|
|
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,18 @@
|
|
|
1
|
+
LICENSE.txt
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/celestial_rhapsody/__init__.py
|
|
5
|
+
src/celestial_rhapsody/__main__.py
|
|
6
|
+
src/celestial_rhapsody/animation.py
|
|
7
|
+
src/celestial_rhapsody/cli.py
|
|
8
|
+
src/celestial_rhapsody/config.py
|
|
9
|
+
src/celestial_rhapsody/solvers.py
|
|
10
|
+
src/celestial_rhapsody.egg-info/PKG-INFO
|
|
11
|
+
src/celestial_rhapsody.egg-info/SOURCES.txt
|
|
12
|
+
src/celestial_rhapsody.egg-info/dependency_links.txt
|
|
13
|
+
src/celestial_rhapsody.egg-info/entry_points.txt
|
|
14
|
+
src/celestial_rhapsody.egg-info/requires.txt
|
|
15
|
+
src/celestial_rhapsody.egg-info/top_level.txt
|
|
16
|
+
tests/test_cli.py
|
|
17
|
+
tests/test_config.py
|
|
18
|
+
tests/test_solvers.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
celestial_rhapsody
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
from celestial_rhapsody.cli import main
|
|
4
|
+
|
|
5
|
+
EXAMPLES = Path(__file__).resolve().parents[1] / "examples"
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_check_json(capsys):
|
|
9
|
+
assert main(["check", str(EXAMPLES / "three_body.json")]) == 0
|
|
10
|
+
assert "OK: 3 bodies" in capsys.readouterr().out
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def test_check_txt(capsys):
|
|
14
|
+
assert main(["check", str(EXAMPLES / "three_body.txt")]) == 0
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_run_writes_gif(tmp_path):
|
|
18
|
+
out = tmp_path / "movie.gif"
|
|
19
|
+
assert main(["run", str(EXAMPLES / "three_body.json"), "-o", str(out), "--final-time", "0.5", "--every", "5"]) == 0
|
|
20
|
+
assert out.stat().st_size > 0
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_missing_file(tmp_path):
|
|
24
|
+
assert main(["check", str(tmp_path / "nope.json")]) == 1
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_bad_output_extension(tmp_path):
|
|
28
|
+
assert main(["run", str(EXAMPLES / "three_body.json"), "-o", str(tmp_path / "x.avi"), "--final-time", "0.1"]) == 1
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Tests for reading input files.
|
|
2
|
+
|
|
3
|
+
The read_config tests are the original project tests, kept unchanged apart from
|
|
4
|
+
the import and the location of the data files.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pytest
|
|
12
|
+
|
|
13
|
+
from celestial_rhapsody.config import load_system, read_config, system_from_dict
|
|
14
|
+
|
|
15
|
+
DATA = Path(__file__).parent / "data"
|
|
16
|
+
EXAMPLES = Path(__file__).resolve().parents[1] / "examples"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
# --- original tests -------------------------------------------------------
|
|
20
|
+
def test_util_input_empty_config():
|
|
21
|
+
var_a, var_b = read_config(DATA / "config_1.txt")
|
|
22
|
+
assert not bool(var_a)
|
|
23
|
+
assert not bool(var_b)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_util_input_global_only():
|
|
27
|
+
var_a, var_b = read_config(DATA / "config_2.txt")
|
|
28
|
+
assert var_a == [1.0]
|
|
29
|
+
assert not bool(var_b)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_util_input_planet_only():
|
|
33
|
+
var_a, var_b = read_config(DATA / "config_3.txt")
|
|
34
|
+
assert not bool(var_a)
|
|
35
|
+
assert var_b == [["Earth", 0.5, 1.0, 2.0, 0.01, 0.02]]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_util_input_global_1_planet():
|
|
39
|
+
var_a, var_b = read_config(DATA / "config_4.txt")
|
|
40
|
+
assert var_a == [1.0]
|
|
41
|
+
assert var_b == [["Earth", 0.5, 1.0, 2.0, 0.01, 0.02]]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_util_input_global_2_planets():
|
|
45
|
+
var_a, var_b = read_config(DATA / "config_5.txt")
|
|
46
|
+
assert var_a == [1.0]
|
|
47
|
+
assert var_b == [
|
|
48
|
+
["Earth", 0.5, 1.0, 2.0, 0.01, 0.02],
|
|
49
|
+
["Mars", 0.4, -5.0, 2.0, 0.04, 0.01],
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_util_input_global_type():
|
|
54
|
+
var_a, var_b = read_config(DATA / "config_6.txt")
|
|
55
|
+
assert isinstance(var_a[0], float)
|
|
56
|
+
assert isinstance(var_a[1], float)
|
|
57
|
+
assert isinstance(var_a[2], int)
|
|
58
|
+
assert var_b == []
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_read_config_missing_file():
|
|
62
|
+
with pytest.raises(RuntimeError):
|
|
63
|
+
read_config(DATA / "does_not_exist.txt")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# --- new: loading systems -------------------------------------------------
|
|
67
|
+
def test_txt_and_json_examples_agree():
|
|
68
|
+
a = load_system(EXAMPLES / "three_body.txt")
|
|
69
|
+
b = load_system(EXAMPLES / "three_body.json")
|
|
70
|
+
assert a.names == b.names
|
|
71
|
+
np.testing.assert_allclose(a.positions, b.positions)
|
|
72
|
+
np.testing.assert_allclose(a.velocities, b.velocities)
|
|
73
|
+
assert (a.G, a.dt, a.final_time) == (b.G, b.dt, b.final_time)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@pytest.mark.parametrize("name", ["three_body.json", "figure_eight.json", "inner_solar_system.json"])
|
|
77
|
+
def test_examples_load(name):
|
|
78
|
+
assert load_system(EXAMPLES / name).n_bodies >= 3
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def test_json_missing_field():
|
|
82
|
+
with pytest.raises(ValueError, match="missing"):
|
|
83
|
+
system_from_dict({"bodies": [{"mass": 1, "position": [0, 0]}]})
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_json_negative_mass():
|
|
87
|
+
with pytest.raises(ValueError, match="mass"):
|
|
88
|
+
system_from_dict({"bodies": [{"mass": -1, "position": [0, 0], "velocity": [0, 0]}]})
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_json_mixed_dimensions():
|
|
92
|
+
with pytest.raises(ValueError):
|
|
93
|
+
system_from_dict({"bodies": [
|
|
94
|
+
{"mass": 1, "position": [0, 0], "velocity": [0, 0]},
|
|
95
|
+
{"mass": 1, "position": [1, 0, 0], "velocity": [0, 0, 0]},
|
|
96
|
+
]})
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def test_json_syntax_error(tmp_path):
|
|
100
|
+
f = tmp_path / "bad.json"
|
|
101
|
+
f.write_text("{ not json")
|
|
102
|
+
with pytest.raises(ValueError, match="not valid JSON"):
|
|
103
|
+
load_system(f)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_json_defaults(tmp_path):
|
|
107
|
+
f = tmp_path / "s.json"
|
|
108
|
+
f.write_text(json.dumps({"bodies": [{"mass": 1, "position": [0, 0], "velocity": [0, 0]}]}))
|
|
109
|
+
s = load_system(f)
|
|
110
|
+
assert (s.G, s.dt, s.final_time, s.softening) == (1.0, 0.01, 5.0, 0.0)
|
|
111
|
+
assert s.names == ["body 0"]
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pytest
|
|
3
|
+
|
|
4
|
+
from celestial_rhapsody import System, accelerations, simulate
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def original_n_body_acc(positions, masses, G=1.0):
|
|
8
|
+
"""Loop version, as written in the original nbody.py (N_Body), for comparison."""
|
|
9
|
+
acc = np.zeros_like(positions)
|
|
10
|
+
for i in range(len(positions)):
|
|
11
|
+
for k in range(len(positions)):
|
|
12
|
+
if k != i:
|
|
13
|
+
r_ik = positions[i] - positions[k]
|
|
14
|
+
acc[i] -= G * masses[k] * r_ik / np.linalg.norm(r_ik) ** 3
|
|
15
|
+
return acc
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def circular_binary(dt=0.01, T=10.0):
|
|
19
|
+
# Two unit masses 1 apart, each on a circle of radius 0.5: v = sqrt(G m / (4 r)) = sqrt(0.5)
|
|
20
|
+
v = np.sqrt(0.5)
|
|
21
|
+
return System(names=["a", "b"], masses=[1, 1], positions=[[0.5, 0], [-0.5, 0]],
|
|
22
|
+
velocities=[[0, v], [0, -v]], G=1.0, dt=dt, final_time=T)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def test_vectorised_matches_original_loop():
|
|
26
|
+
rng = np.random.default_rng(1)
|
|
27
|
+
pos, m = rng.normal(size=(7, 2)), rng.uniform(0.1, 2, size=7)
|
|
28
|
+
np.testing.assert_allclose(accelerations(pos, m, G=2.5), original_n_body_acc(pos, m, G=2.5))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_newtons_law_two_bodies():
|
|
32
|
+
a = accelerations(np.array([[0.0, 0.0], [2.0, 0.0]]), np.array([3.0, 1.0]))
|
|
33
|
+
np.testing.assert_allclose(a, [[0.25, 0.0], [-0.75, 0.0]])
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_total_momentum_change_is_zero():
|
|
37
|
+
rng = np.random.default_rng(0)
|
|
38
|
+
m = rng.uniform(0.5, 2, size=5)
|
|
39
|
+
a = accelerations(rng.normal(size=(5, 3)), m)
|
|
40
|
+
np.testing.assert_allclose(np.sum(m[:, None] * a, axis=0), 0, atol=1e-12)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_rk4_circular_orbit():
|
|
44
|
+
tr = simulate(circular_binary())
|
|
45
|
+
sep = np.linalg.norm(tr.positions[:, 0] - tr.positions[:, 1], axis=-1)
|
|
46
|
+
np.testing.assert_allclose(sep, 1.0, rtol=1e-6)
|
|
47
|
+
assert tr.energy_drift < 1e-8
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_higher_order_is_more_accurate():
|
|
51
|
+
drift = {m: simulate(circular_binary(dt=0.01, T=5), method=m).energy_drift for m in ("euler", "rk2", "rk4")}
|
|
52
|
+
assert drift["rk4"] < drift["rk2"] < drift["euler"]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_ends_exactly_at_final_time():
|
|
56
|
+
tr = simulate(circular_binary(dt=0.03, T=1.0), save_every=7)
|
|
57
|
+
assert tr.times[0] == 0.0
|
|
58
|
+
assert tr.times[-1] == pytest.approx(1.0)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_bad_method():
|
|
62
|
+
with pytest.raises(ValueError):
|
|
63
|
+
simulate(circular_binary(), method="magic")
|