"""Reading the input file that describes the system to simulate.
Two formats are supported:
* **JSON** (``.json``), the recommended format;
* the original **INI-style text** format (``.txt``) with ``[Global]`` and
``[Planet]`` sections.
Use :func:`load_system` for either one. It picks the reader from the file extension.
"""
from __future__ import annotations
import json
from dataclasses import dataclass
from pathlib import Path
from typing import List, Tuple, Union
import numpy as np
PathLike = Union[str, Path]
[docs]
@dataclass
class System:
"""A set of bodies plus the simulation settings.
Attributes:
names: One label per body.
masses: Masses, shape ``(n,)``.
positions: Initial positions, shape ``(n, dim)`` with ``dim`` 2 or 3.
velocities: Initial velocities, shape ``(n, dim)``.
G: Gravitational constant.
dt: Integration time step.
final_time: Time at which the simulation stops.
softening: Optional softening length (0 means pure Newtonian gravity).
"""
names: List[str]
masses: np.ndarray
positions: np.ndarray
velocities: np.ndarray
G: float = 1.0
dt: float = 0.01
final_time: float = 5.0
softening: float = 0.0
def __post_init__(self) -> None:
self.masses = np.asarray(self.masses, dtype=float)
self.positions = np.asarray(self.positions, dtype=float)
self.velocities = np.asarray(self.velocities, dtype=float)
n = len(self.masses)
if n == 0:
raise ValueError("The system needs at least one body.")
if self.positions.ndim != 2 or self.positions.shape[1] not in (2, 3):
raise ValueError("Every position must have 2 or 3 components, the same for all bodies.")
if self.positions.shape != (n, self.positions.shape[1]) or self.velocities.shape != self.positions.shape:
raise ValueError("Each body needs one mass, one position and one velocity of the same length.")
if np.any(self.masses <= 0):
raise ValueError("All masses must be positive.")
if self.dt <= 0 or self.final_time <= 0:
raise ValueError("dt and final_time must be positive.")
if self.softening < 0:
raise ValueError("softening cannot be negative.")
if len(self.names) != n:
raise ValueError("Number of names does not match number of bodies.")
@property
def n_bodies(self) -> int:
return len(self.masses)
@property
def dim(self) -> int:
return self.positions.shape[1]
# --------------------------------------------------------------------------- #
# Original text format
# --------------------------------------------------------------------------- #
[docs]
def read_config(file_name: PathLike) -> Tuple[list, list]:
"""Read the INI-style text config file (the original project format).
The file starts with a ``[Global]`` section (``G``, ``dt``, ``final_time``)
followed by one ``[Planet]`` section per body (``name``, ``mass``, ``x_0``,
``y_0``, ``vx_0``, ``vy_0``). Values are read **in order**, so keep the
order of the lines as in the examples.
Args:
file_name: Path of the config file.
Raises:
RuntimeError: If the file cannot be opened or a line cannot be parsed.
Returns:
A list with the global values ``[G, dt, final_time]`` and a list of
planets, each ``[name, mass, x_0, y_0, vx_0, vy_0]``.
"""
global_var: list = []
planet_var: list = []
allplanet_var: list = []
planet_flag = False
try:
with open(file_name, "r", encoding="utf-8") as file:
next(file, None) # skip the [Global] header line
for line in file:
if not line.strip():
continue
# Append lines to global_var until the first [Planet] section,
# then collect one list of values per planet.
if "Planet" in line:
planet_flag = True
if planet_var:
allplanet_var.append(planet_var[:])
planet_var.clear()
continue
value = line.split("=", 1)[1].strip()
if not planet_flag:
global_var.append(int(value) if "final_time" in line else float(value))
else:
try:
planet_var.append(float(value))
except ValueError:
planet_var.append(value) # e.g. the planet name
if planet_var:
allplanet_var.append(planet_var[:])
except (OSError, IndexError, ValueError) as err:
raise RuntimeError(
f"Failed to process config file '{file_name}', make sure to input the correct config file."
) from err
return global_var, allplanet_var
def _system_from_txt(path: PathLike) -> System:
global_var, planets = read_config(path)
defaults = [1.0, 0.01, 5.0]
G, dt, final_time = (list(global_var) + defaults[len(global_var):])[:3]
for i, p in enumerate(planets):
if len(p) != 6:
raise ValueError(
f"Planet {i + 1} in '{path}' has {len(p)} values; expected 6 "
"(name, mass, x_0, y_0, vx_0, vy_0)."
)
return System(
names=[str(p[0]) for p in planets],
masses=[p[1] for p in planets],
positions=[[p[2], p[3]] for p in planets],
velocities=[[p[4], p[5]] for p in planets],
G=float(G),
dt=float(dt),
final_time=float(final_time),
)
# --------------------------------------------------------------------------- #
# JSON format
# --------------------------------------------------------------------------- #
[docs]
def system_from_dict(data: dict) -> System:
"""Build a :class:`System` from a dictionary with the JSON layout.
See the *Input format* page of the documentation for all fields.
"""
if "bodies" not in data or not isinstance(data["bodies"], list):
raise ValueError("The input needs a 'bodies' list.")
names, masses, pos, vel = [], [], [], []
for i, body in enumerate(data["bodies"]):
missing = {"mass", "position", "velocity"} - set(body)
if missing:
raise ValueError(f"Body {i} is missing: {', '.join(sorted(missing))}")
names.append(str(body.get("name", f"body {i}")))
masses.append(float(body["mass"]))
pos.append(body["position"])
vel.append(body["velocity"])
try:
positions = np.array(pos, dtype=float)
velocities = np.array(vel, dtype=float)
except ValueError as err:
raise ValueError("Positions and velocities must all have the same number of components.") from err
return System(
names=names,
masses=masses,
positions=positions,
velocities=velocities,
G=float(data.get("G", 1.0)),
dt=float(data.get("dt", 0.01)),
final_time=float(data.get("final_time", 5.0)),
softening=float(data.get("softening", 0.0)),
)
[docs]
def load_system(path: PathLike) -> System:
"""Load a system from a ``.json`` or ``.txt`` file.
Args:
path: Input file. The extension selects the format.
Returns:
A validated :class:`System`.
Raises:
FileNotFoundError: If the file does not exist.
ValueError: If the content is invalid.
"""
path = Path(path)
if not path.exists():
raise FileNotFoundError(path)
if path.suffix.lower() == ".json":
with open(path, "r", encoding="utf-8") as f:
try:
data = json.load(f)
except json.JSONDecodeError as err:
raise ValueError(f"'{path}' is not valid JSON: {err}") from err
return system_from_dict(data)
try:
return _system_from_txt(path)
except RuntimeError as err:
raise ValueError(str(err)) from err