A 3D three-body gravitational simulation with visualization and analytics
Project description
🌌 3-Body Gravitational Simulation
A Python-based 3D visualization of the three-body problem using matplotlib, scipy, and numpy. This project is a physics-inspired simulation that visually demonstrates the chaotic dynamics of three mutually gravitating bodies in space.
🎯 Focus: Educational simulation with real-time animation and configurable parameters.
✨ Features
- 🔧 Interactive CLI config menu (customize masses, positions, velocities,
G, and more) - 🎥 Smooth 3D animation using
matplotlib.animation - 📦 Saves simulation data as CSV (
3body_simulation_output.csv) - 🎬 Exports animation as MP4 using FFmpeg
- 🧠 Stop condition when all bodies leave the viewport
- 🚫 Hides out-of-bound bodies gracefully to avoid clutter
- 📈 Easy to analyze trajectory data post-simulation
📦 Requirements
- Python 3.7+
numpyscipymatplotlibpandasffmpeg(for saving MP4)
Install dependencies:
pip install numpy scipy matplotlib pandas
Install FFmpeg (for saving animation):
- Windows: Download from ffmpeg.org and add it to PATH
- Linux/macOS:
sudo apt install ffmpeg # Debian/Ubuntu
brew install ffmpeg # macOS (Homebrew)
🚀 Run the Simulation
python 3body_simulation.py
You'll see a CLI menu:
- Press Enter to use defaults
- Type E to edit custom values like mass, velocity, position,
G, etc.
After the simulation:
- You’ll get an MP4 animation
- All positional data will be saved to a CSV for further analysis
📊 Optional Data Plotting (Post-Simulation)
To analyze saved trajectories:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("3body_simulation_output.csv")
for planet_id in [1, 2, 3]:
subset = df[df['planet'] == planet_id]
plt.plot(subset['x'], subset['y'], label=f'Body {planet_id}')
plt.xlabel('X')
plt.ylabel('Y')
plt.title("2D Trajectory Plot (XY Plane)")
plt.legend()
plt.grid(True)
plt.show()
⚠️ Known Limitations and Inaccuracies
This simulator prioritizes visual understanding and usability over exact scientific accuracy.
🔬 Physics & Math Simplifications:
- No collisions: Bodies are point masses with no radius or collision detection
- No energy tracking: System energy is not computed or conserved
- Simplified gravity: A small constant (
+1e-5) is added in the denominator to avoid division by zero - No adaptive time step: Fixed time sampling via
np.linspaceis used - Newtonian only: No general relativity, relativistic corrections, or external forces
🎥 Rendering/Animation:
- Bodies are still rendered briefly after leaving axis limits for smoother transition
- Simulation stops only after all 3 bodies exit bounds, not individually
🛠️ To-Do / Future Enhancements
- Add energy and angular momentum conservation metrics
- Enable real-world unit support (e.g., AU, kg, seconds)
- Collision detection or merging logic
- Symplectic integrators (Leapfrog/Euler-Cromer) for better long-term stability
- Web-based interface using WebGL (maybe Three.js)
📁 Project Structure
.
├── 3body_simulation.py # Main simulation code
├── data.py
├── 3body_simulation_output.csv # Trajectory data (auto-generated)
├── media/
│ └── 3body_simulation.mp4 # Output animation (auto-generated)
└── README.md # This file
💡 Inspiration
The chaotic nature of the 3-body problem is a beautiful representation of how simple rules can lead to complex behavior. This simulation is my take on exploring it visually, interactively, and accessibly.
🤝 License
This project is free to use under the MIT License. Feel free to fork, improve, or contribute back!
🙌 Acknowledgments
scipy.integrate.solve_ivp— for solving the ODE systemmatplotlib.animation— for powerful visual rendering- Community contributors and educators for inspiring open-source learning
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file threebodysim-0.1.0.tar.gz.
File metadata
- Download URL: threebodysim-0.1.0.tar.gz
- Upload date:
- Size: 6.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
be4f8e3d8e3784ccff6d7ccaa1502b67285e64b365aeff5f234d93bd19ac0853
|
|
| MD5 |
07feaaa56c0993bca612ec081eaa5d42
|
|
| BLAKE2b-256 |
333a859474afe96ba9821b9b0bd2155e3ad03f3236876b1755a414b978c9c576
|
File details
Details for the file threebodysim-0.1.0-py3-none-any.whl.
File metadata
- Download URL: threebodysim-0.1.0-py3-none-any.whl
- Upload date:
- Size: 7.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
09016346070a8fcff6807c841afb2820a2c10b075408813018562bef8170416c
|
|
| MD5 |
34c8f9b5ad29646e621c2b524ce56a94
|
|
| BLAKE2b-256 |
90939be5d4a778df1f968573c28b0e62e1210517976a3f8e3add035c57c2961b
|