pyorbiter 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.
pyorbiter/__init__.py ADDED
@@ -0,0 +1,67 @@
1
+ """pyorbiter: a tidy N-body physics engine for orbital simulations.
2
+
3
+ The Python sibling of the orbitr R package (https://orbit-r.com). Build a system,
4
+ simulate it, and get back a tidy DataFrame (pandas by default, polars if you
5
+ ask for it with ``orb.set_backend("polars")``)::
6
+
7
+ import pyorbiter as orb
8
+
9
+ sim = (
10
+ orb.create_system()
11
+ .add_sun()
12
+ .add_planet("Earth", parent="Sun")
13
+ .simulate(time_step=orb.seconds_per_day, duration=orb.seconds_per_year)
14
+ )
15
+ orb.plot_orbits(sim)
16
+
17
+ Units are SI throughout: meters, kilograms, seconds. Angles are in degrees.
18
+ """
19
+
20
+ from ._frames import get_backend, run_settings, set_backend
21
+ from .analysis import (
22
+ conserved_quantities,
23
+ get_angular_momentum,
24
+ get_energy,
25
+ get_momentum,
26
+ get_orbital_elements,
27
+ shift_reference_frame,
28
+ )
29
+ from .constants import * # noqa: F401,F403
30
+ from .constants import __all__ as _constants
31
+ from .plotting import (
32
+ animate_system,
33
+ animate_system_3d,
34
+ plot_orbits,
35
+ plot_orbits_3d,
36
+ plot_system,
37
+ plot_system_3d,
38
+ )
39
+ from .simulate import calc_acceleration, continue_simulation, simulate_system, system_from_simulation
40
+ from .system import (
41
+ OrbitSystem,
42
+ add_body,
43
+ add_body_keplerian,
44
+ add_planet,
45
+ add_sun,
46
+ create_system,
47
+ export_bodies,
48
+ get_bodies,
49
+ load_solar_system,
50
+ load_system,
51
+ remove_body,
52
+ save_system,
53
+ )
54
+
55
+ __version__ = "0.1.0"
56
+
57
+ __all__ = [
58
+ "OrbitSystem", "create_system", "add_body", "add_sun", "add_body_keplerian", "add_planet",
59
+ "remove_body", "get_bodies", "load_solar_system", "save_system", "load_system", "export_bodies",
60
+ "simulate_system", "continue_simulation", "system_from_simulation", "calc_acceleration",
61
+ "shift_reference_frame", "get_orbital_elements", "get_energy", "get_momentum",
62
+ "get_angular_momentum", "conserved_quantities",
63
+ "plot_orbits", "plot_orbits_3d", "plot_system", "plot_system_3d",
64
+ "animate_system", "animate_system_3d",
65
+ "set_backend", "get_backend", "run_settings",
66
+ *_constants,
67
+ ]
pyorbiter/_frames.py ADDED
@@ -0,0 +1,350 @@
1
+ """DataFrame backends: pandas (the default) or polars.
2
+
3
+ The engine computes with pandas internally. This module converts at the
4
+ package boundary, so every public function accepts either kind of DataFrame
5
+ and hands back the kind it was given. Conversion goes column by column
6
+ through numpy, so polars support does not need pyarrow.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import functools
12
+ import weakref
13
+
14
+ import numpy as np
15
+ import pandas as pd
16
+
17
+ BACKENDS = ("pandas", "polars")
18
+
19
+ _default_backend = "pandas"
20
+
21
+ # polars DataFrames have no `.attrs`, so the settings of the run that produced
22
+ # a frame are kept here, keyed by the frame's id() and dropped when the frame
23
+ # is garbage collected.
24
+ _run_settings: dict[int, tuple[weakref.ref, dict]] = {}
25
+
26
+
27
+ def set_backend(backend: str) -> None:
28
+ """Choose the DataFrame library pyorbiter returns.
29
+
30
+ Sets the default kind of DataFrame for the functions that create one from
31
+ a system: ``simulate_system`` and ``get_bodies``. Both also take a
32
+ ``backend`` argument that overrides the default for a single call. The
33
+ setting lasts for the rest of the Python session.
34
+
35
+ Functions that are given a DataFrame (the analysis functions,
36
+ ``continue_simulation``) ignore this setting and return the same kind they
37
+ were given. A polars LazyFrame is collected, and a polars DataFrame comes
38
+ back.
39
+
40
+ Parameters
41
+ ----------
42
+ backend : str
43
+ ``"pandas"`` or ``"polars"``. pyorbiter starts with ``"pandas"``.
44
+
45
+ Returns
46
+ -------
47
+ None
48
+ Called for its side effect.
49
+
50
+ Raises
51
+ ------
52
+ ValueError
53
+ If ``backend`` is not ``"pandas"`` or ``"polars"``.
54
+ ImportError
55
+ If ``backend`` is ``"polars"`` and polars is not installed. The
56
+ default is left unchanged. Install it with ``pip install polars``.
57
+
58
+ See Also
59
+ --------
60
+ get_backend : See which library is the current default.
61
+ simulate_system : Takes a ``backend`` argument for a single call.
62
+ run_settings : Read the settings of a run from either kind of DataFrame.
63
+
64
+ Examples
65
+ --------
66
+ Switch to polars, simulate, and switch back.
67
+
68
+ ```{python}
69
+ import pyorbiter as orb
70
+
71
+ orb.set_backend("polars")
72
+ sim = orb.create_system().add_sun().add_planet("Earth", parent="Sun").simulate(
73
+ time_step=orb.seconds_per_day, duration=30 * orb.seconds_per_day)
74
+
75
+ orb.set_backend("pandas")
76
+ sim.head()
77
+ ```
78
+ """
79
+ global _default_backend
80
+ backend = _check_backend(backend)
81
+ if backend == "polars":
82
+ _polars() # fail here, before switching, if polars is missing
83
+ _default_backend = backend
84
+
85
+
86
+ def get_backend() -> str:
87
+ """The DataFrame library pyorbiter currently returns by default.
88
+
89
+ This is the library used by ``simulate_system`` and ``get_bodies`` when
90
+ their ``backend`` argument is left as ``None``. Change it with
91
+ ``set_backend``.
92
+
93
+ Returns
94
+ -------
95
+ str
96
+ ``"pandas"`` or ``"polars"``. It is ``"pandas"`` unless ``set_backend``
97
+ has been called.
98
+
99
+ See Also
100
+ --------
101
+ set_backend : Change the default.
102
+
103
+ Examples
104
+ --------
105
+ ```{python}
106
+ import pyorbiter as orb
107
+
108
+ orb.get_backend()
109
+ ```
110
+ """
111
+ return _default_backend
112
+
113
+
114
+ def _check_backend(backend) -> str:
115
+ if backend not in BACKENDS:
116
+ raise ValueError("`backend` must be 'pandas' or 'polars'.")
117
+ return backend
118
+
119
+
120
+ def resolve_backend(backend: str | None) -> str:
121
+ """An explicit backend, else the default set by :func:`set_backend`."""
122
+ backend = _default_backend if backend is None else _check_backend(backend)
123
+ if backend == "polars":
124
+ _polars()
125
+ return backend
126
+
127
+
128
+ def _polars():
129
+ try:
130
+ import polars as pl
131
+ except ImportError:
132
+ raise ImportError("The polars backend needs the 'polars' package. "
133
+ "Install it with: pip install polars") from None
134
+ return pl
135
+
136
+
137
+ def _polars_kind(obj) -> str | None:
138
+ """``"DataFrame"`` or ``"LazyFrame"`` for a polars frame, else None (without importing polars)."""
139
+ for cls in type(obj).__mro__:
140
+ if cls.__module__.split(".")[0] == "polars" and cls.__name__ in ("DataFrame", "LazyFrame"):
141
+ return cls.__name__
142
+ return None
143
+
144
+
145
+ def is_frame(obj) -> bool:
146
+ """True for a pandas DataFrame or a polars DataFrame / LazyFrame."""
147
+ return isinstance(obj, pd.DataFrame) or _polars_kind(obj) is not None
148
+
149
+
150
+ def to_pandas(frame) -> pd.DataFrame:
151
+ """A pandas copy of a polars frame (pandas frames pass through untouched).
152
+
153
+ The run settings recorded for a polars frame become the copy's ``attrs``.
154
+ """
155
+ kind = _polars_kind(frame)
156
+ if kind is None:
157
+ return frame
158
+ settings = run_settings(frame)
159
+ if kind == "LazyFrame":
160
+ frame = frame.collect()
161
+ out = pd.DataFrame({name: frame[name].to_numpy() for name in frame.columns})
162
+ out.attrs = settings
163
+ return out
164
+
165
+
166
+ def to_polars(frame: pd.DataFrame):
167
+ """A polars copy of a pandas DataFrame, with its ``attrs`` recorded as run settings."""
168
+ pl = _polars()
169
+ columns = {}
170
+ for name in frame.columns:
171
+ values = frame[name].to_numpy()
172
+ if values.dtype == object:
173
+ # Text columns (body ids) come out of pandas as object arrays, with
174
+ # NaN for a missing value where polars wants null
175
+ items = [None if missing else value
176
+ for value, missing in zip(values.tolist(), frame[name].isna().tolist())]
177
+ try:
178
+ columns[str(name)] = pl.Series(str(name), items, dtype=pl.String)
179
+ except (TypeError, ValueError, pl.exceptions.PolarsError):
180
+ columns[str(name)] = pl.Series(str(name), items, strict=False)
181
+ else:
182
+ columns[str(name)] = pl.Series(str(name), np.ascontiguousarray(values))
183
+ out = pl.DataFrame(columns)
184
+ _record_run_settings(out, frame.attrs)
185
+ return out
186
+
187
+
188
+ def to_backend(frame: pd.DataFrame, backend: str | None = None):
189
+ """Convert an internal pandas DataFrame to the requested (or default) backend."""
190
+ return to_polars(frame) if resolve_backend(backend) == "polars" else frame
191
+
192
+
193
+ def _record_run_settings(frame, settings: dict) -> None:
194
+ if not settings:
195
+ return
196
+ key = id(frame)
197
+ _run_settings[key] = (weakref.ref(frame, lambda _, key=key: _run_settings.pop(key, None)),
198
+ dict(settings))
199
+
200
+
201
+ def run_settings(sim_data) -> dict:
202
+ """The settings of the run that produced a simulation.
203
+
204
+ ``simulate_system`` records the gravitational constant, softening length,
205
+ integrator and time step it used alongside its result. The analysis
206
+ functions read them from there, so that ``get_energy``, for example, uses
207
+ the same ``G`` and softening as the run. This function returns them as a
208
+ dict, and works the same way for pandas and polars results.
209
+
210
+ Parameters
211
+ ----------
212
+ sim_data : DataFrame
213
+ The output of ``simulate_system``, ``continue_simulation`` or
214
+ ``shift_reference_frame``, as a pandas or polars DataFrame.
215
+
216
+ Returns
217
+ -------
218
+ dict
219
+ The recorded settings:
220
+
221
+ - ``G``: gravitational constant in m^3 kg^-1 s^-2.
222
+ - ``softening``: softening length in meters.
223
+ - ``method``: the integrator, ``"verlet"``, ``"euler_cromer"`` or
224
+ ``"euler"``.
225
+ - ``time_step``: time between recorded states in seconds. After
226
+ ``continue_simulation`` this is the step of the latest segment.
227
+
228
+ The dict is a copy, so changing it does not change the DataFrame. It
229
+ is empty if nothing is recorded for ``sim_data``.
230
+
231
+ See Also
232
+ --------
233
+ simulate_system : Records the settings.
234
+ continue_simulation : Reuses the recorded settings for the next segment.
235
+ get_energy : Uses the recorded ``G`` and softening.
236
+ set_backend : Choose between pandas and polars results.
237
+
238
+ Notes
239
+ -----
240
+ For a pandas DataFrame the settings live in ``sim_data.attrs``, and this
241
+ function returns a copy of that dict. pandas carries ``attrs`` through
242
+ most operations, such as filtering rows.
243
+
244
+ A polars DataFrame has nowhere to keep them, so they are remembered only
245
+ for the exact DataFrame pyorbiter returned. Anything you derive from it
246
+ (``filter``, ``sort``, ``with_columns``, ``clone``, a file read back)
247
+ gives an empty dict here. For a polars run that did not use the defaults,
248
+ pass ``G`` and ``softening`` to the analysis functions, and ``G``,
249
+ ``softening`` and ``method`` to ``continue_simulation``, yourself.
250
+
251
+ Examples
252
+ --------
253
+ ```{python}
254
+ import pyorbiter as orb
255
+
256
+ sim = orb.create_system().add_sun().add_planet("Earth", parent="Sun").simulate(
257
+ time_step=orb.seconds_per_day, duration=30 * orb.seconds_per_day,
258
+ softening=1e4)
259
+
260
+ orb.run_settings(sim)
261
+ ```
262
+
263
+ A polars result keeps its settings only until you derive a new DataFrame
264
+ from it.
265
+
266
+ ```{python}
267
+ import polars as pl
268
+ import pyorbiter as orb
269
+
270
+ sim = orb.create_system().add_sun().add_planet("Earth", parent="Sun").simulate(
271
+ time_step=orb.seconds_per_day, duration=30 * orb.seconds_per_day,
272
+ backend="polars")
273
+ earth = sim.filter(pl.col("id") == "Earth")
274
+
275
+ {"returned by pyorbiter": orb.run_settings(sim), "after filter": orb.run_settings(earth)}
276
+ ```
277
+ """
278
+ if isinstance(sim_data, pd.DataFrame):
279
+ return dict(sim_data.attrs)
280
+ entry = _run_settings.get(id(sim_data))
281
+ if entry is None or entry[0]() is not sim_data:
282
+ return {}
283
+ return dict(entry[1])
284
+
285
+
286
+ # The columns pyorbiter computes with. Anything else in a polars frame is the
287
+ # user's own and never leaves polars.
288
+ _CORE_COLUMNS = ("id", "mass", "x", "y", "z", "vx", "vy", "vz", "time")
289
+ _ROW = "__pyorbiter_row__"
290
+
291
+
292
+ def _core_to_pandas(frame, settings: dict) -> pd.DataFrame:
293
+ """The columns pyorbiter uses, as pandas, with each row's position in ``frame``."""
294
+ core = [name for name in frame.columns if name in _CORE_COLUMNS]
295
+ out = pd.DataFrame({name: frame[name].to_numpy() for name in core})
296
+ out[_ROW] = np.arange(frame.height, dtype=float)
297
+ out.attrs = settings
298
+ return out
299
+
300
+
301
+ def _rows_to_polars(result: pd.DataFrame, original):
302
+ """Turn a result made of rows of ``original`` back into polars.
303
+
304
+ The user's own columns are picked up again from ``original`` by row, so
305
+ they keep their polars types exactly; rows pyorbiter added (as
306
+ :func:`continue_simulation` does) get nulls there. The columns pyorbiter
307
+ did compute are cast back to the types they arrived with.
308
+ """
309
+ pl = _polars()
310
+ out = to_polars(result)
311
+ out = out.with_columns(pl.col(_ROW).fill_nan(None).cast(pl.Int64))
312
+ extras = [name for name in original.columns if name not in result.columns]
313
+ if extras:
314
+ lookup = original.select(extras).with_columns(
315
+ pl.int_range(pl.len(), dtype=pl.Int64).alias(_ROW))
316
+ out = out.join(lookup, on=_ROW, how="left", maintain_order="left")
317
+ ordered = [name for name in original.columns if name in out.columns]
318
+ out = out.select(ordered + [name for name in out.columns
319
+ if name not in ordered and name != _ROW])
320
+ for name, dtype in original.schema.items():
321
+ if name in out.columns and out.schema[name] != dtype:
322
+ try:
323
+ out = out.with_columns(pl.col(name).cast(dtype))
324
+ except pl.exceptions.PolarsError:
325
+ pass # keep the computed type rather than fail
326
+ _record_run_settings(out, result.attrs)
327
+ return out
328
+
329
+
330
+ def accepts_frames(func):
331
+ """Let a function written for pandas take a polars frame as its first argument.
332
+
333
+ A polars DataFrame (or LazyFrame, which is collected) is converted on the
334
+ way in, and a DataFrame result is converted back to a polars DataFrame on
335
+ the way out. pandas input is passed straight through.
336
+ """
337
+ @functools.wraps(func)
338
+ def wrapper(sim_data, *args, **kwargs):
339
+ kind = _polars_kind(sim_data)
340
+ if kind is None:
341
+ return func(sim_data, *args, **kwargs)
342
+ settings = run_settings(sim_data)
343
+ original = sim_data.collect() if kind == "LazyFrame" else sim_data
344
+ out = func(_core_to_pandas(original, settings), *args, **kwargs)
345
+ if not isinstance(out, pd.DataFrame):
346
+ return out
347
+ if _ROW in out.columns:
348
+ return _rows_to_polars(out, original)
349
+ return to_polars(out)
350
+ return wrapper