sidereel 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,110 @@
1
+ Metadata-Version: 2.4
2
+ Name: sidereel
3
+ Version: 0.1.0
4
+ Summary: Sidereel, an interactive N-body sandbox with a Qt desktop.
5
+ Author: Nate Bosma
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/AllHailSeizure/sidereel
8
+ Project-URL: Repository, https://github.com/AllHailSeizure/sidereel
9
+ Project-URL: Issues, https://github.com/AllHailSeizure/sidereel/issues
10
+ Keywords: n-body,astronomy,simulation,pyqt
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: X11 Applications :: Qt
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Topic :: Scientific/Engineering :: Astronomy
19
+ Classifier: Topic :: Scientific/Engineering :: Physics
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: numpy>=1.24
24
+ Requires-Dist: matplotlib>=3.8
25
+ Requires-Dist: pillow>=10
26
+ Requires-Dist: PyQt6>=6.5
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=7.4; extra == "dev"
29
+ Requires-Dist: ruff==0.17.3; extra == "dev"
30
+ Dynamic: license-file
31
+
32
+ # Sidereel
33
+
34
+ A planar N-body sandbox. Build a system, watch gravity work, keep the picture.
35
+
36
+ ![Sun, Earth, and Jupiter through one year](docs/orbit.gif)
37
+
38
+ One year of the Sun, Earth, and Jupiter, rendered by `sidereel-cli`.
39
+
40
+ ## Features
41
+
42
+ - Unsoftened Newtonian gravity in the plane. Masses pull on each other. Test particles only fall.
43
+ - A fixed-step Yoshida integrator. A close encounter halts the run and keeps the last good state.
44
+ - A PyQt6 window filled by the sky. Menu, or M, lays a sidebar over the scene. The view stays put.
45
+ - Four starting experiments: the Solar System, a star at twice the Sun's mass, Earth and the Moon, 32 asteroids in a ring at 3.2 AU.
46
+ - A CLI that integrates the system and writes a PNG. No display required.
47
+ - Starting setups saved as JSON. Calculate a recording, then play the samples.
48
+ - An isolated planet holds its period to a relative 1e-7. At 1 AU, solar gravity sits about 30 ppm above JPL's GM, inside a 1e-4 bound.
49
+
50
+ ## Prerequisites and installation
51
+
52
+ Python 3.10 or newer.
53
+
54
+ ```bash
55
+ pipx install sidereel
56
+ ```
57
+
58
+ `sidereel` opens the desktop. `sidereel-cli` renders.
59
+
60
+ The project is not on PyPI yet. Until the first release, install from git:
61
+
62
+ ```bash
63
+ pipx install git+https://github.com/AllHailSeizure/sidereel
64
+ ```
65
+
66
+ From a checkout:
67
+
68
+ ```bash
69
+ pip install -e .
70
+ ```
71
+
72
+ On Debian and Ubuntu the desktop also needs `libegl1` and `libopengl0`.
73
+
74
+ ## Usage
75
+
76
+ Open the GUI:
77
+
78
+ ```bash
79
+ sidereel
80
+ ```
81
+
82
+ You get the experiment list. `sidereel-cli` with no arguments opens the same window.
83
+
84
+ Render the year in the picture:
85
+
86
+ ```bash
87
+ sidereel-cli --star sun --planet earth --planet jupiter --years 1 --output output/sidereel.png
88
+ ```
89
+
90
+ Starting positions only. The default is the Sun, Earth, and Jupiter:
91
+
92
+ ```bash
93
+ sidereel-cli --output output/start.png
94
+ ```
95
+
96
+ Inner planets, half a year:
97
+
98
+ ```bash
99
+ sidereel-cli --star sun --planet mercury --planet venus --planet earth --years 0.5 --output output/inner.png
100
+ ```
101
+
102
+ `--star` is `proxima`, `sun`, `sirius`, or `rigel`. Repeat `--planet` for each body: `mercury`, `venus`, `earth`, `mars`, `jupiter`, `saturn`, `uranus`, `neptune`, `pluto`, `ceres`.
103
+
104
+ `--years` works only with `--output`. So do `--sample-stride` and `--max-recording-mib`. Name bodies without `--output` and the Matplotlib window opens instead.
105
+
106
+ In a checkout, `python -m simulations.star_system` is the same program. `sidereel-cli --help` lists every flag.
107
+
108
+ ## License
109
+
110
+ MIT. Copyright 2026 Nate Bosma. See [LICENSE](LICENSE).
@@ -0,0 +1,32 @@
1
+ sidereel-0.1.0.dist-info/licenses/LICENSE,sha256=o5Ezg9RBpp9bKdwk432u1GPuwjfHYMGcRE-wI38Pfac,1067
2
+ simulations/__init__.py,sha256=PEgJceebHRsZxGE8cA9X2edQZugL7WzQH4EwRNoaCbo,44
3
+ simulations/star_system/__init__.py,sha256=bwQ0ch5Aforv6Rpq5v-VpyUBh416KLGmlV_3MEElwAc,75
4
+ simulations/star_system/__main__.py,sha256=QXHKHHmI8CNEb1Ei8hn6ZsJHlRX9e7rPLmlTk5o_ggo,5426
5
+ simulations/star_system/authoring.py,sha256=yCTuaN7lRbtAMcVPeNRacLZ1I4bSHJTOpXOX51uIefw,18881
6
+ simulations/star_system/catalog-sources.json,sha256=PSjkBqZSax63IQUyv1M8maqhVxtepzsnOxXC4J60C5g,37215
7
+ simulations/star_system/collisions.py,sha256=doQM59f6o3a44z3u3UpJfYlldSohE8kfdjfS_0vOLdI,16619
8
+ simulations/star_system/context.py,sha256=nABJGv7reA2cOurF76q59wfF8u7C6lNN-1NHmgHgz1o,2407
9
+ simulations/star_system/core.py,sha256=-BB1WsxjtOMlkF53B8uT6ofv2lxYERwYr7b08Ps9lOQ,5693
10
+ simulations/star_system/data.py,sha256=lXMDITvBpM7_ey9ucnyeULqZbZQFXkbmUds1dJIifVA,2690
11
+ simulations/star_system/desktop.py,sha256=J1QS_4jDrDI_52PBWfiAAxeNrSzlna0boLtYHu61pTo,56431
12
+ simulations/star_system/desktop_panels.py,sha256=Xw2HoNjByCj91czEqebVYjd2bRbu9mqc2h2tRtiTC64,13569
13
+ simulations/star_system/experiments.py,sha256=kZivxADLheicH7RJLO9HKa1xtK5zHrM1-gL0jCuGyuE,4933
14
+ simulations/star_system/frames.py,sha256=DUMJhC3dIDGmJbdBU2TprRMVNwMN60or6fghtKswV7s,4930
15
+ simulations/star_system/history.py,sha256=JRA5kJqwYMg0KBWM8H_Rrx4TSlYONU6XD3IckXU0GYA,2803
16
+ simulations/star_system/initialization.py,sha256=-4uJBuykKmUXyP--G_fU8aRbOM5C4mgIUd28XpnLouY,10762
17
+ simulations/star_system/model.py,sha256=mm94UhTCGsY0fwxZR4_j8LHf-MmF4YhnLQWnxgUvnh0,7530
18
+ simulations/star_system/persistence.py,sha256=5XfWItFKM63YwzSU20S-TvmTzKDdr0wbnUk98DCzB9I,12373
19
+ simulations/star_system/playback.py,sha256=NyAYdQT5W3dOhdvNzZrvOCIVNM8DYXyj91M56HJRRdA,1424
20
+ simulations/star_system/plotting.py,sha256=tmQ2j9_VQ0Th8JHHX-jMTqtvp_jtGuN-0QffcgyAT94,40853
21
+ simulations/star_system/population_editor.py,sha256=fEHo0o7-c8pX2ZlimQ4H8liq1yeY0IhqzcFJPiNJVAE,10455
22
+ simulations/star_system/populations.py,sha256=bV5gomiHH66y8bEUtCnDcmTn7SfoqZOFLhmwN9v-gqc,3859
23
+ simulations/star_system/recording.py,sha256=6jhAS6jEgW9RbiivUpIBwkmMv5MUloEcBMDPmmqyqSs,10448
24
+ simulations/star_system/rendering.py,sha256=PHUFhIY0JKUP9WoOflAKtykOjCqLjqnY_ied8Z1Bots,23307
25
+ simulations/star_system/scenarios.py,sha256=coxyfnUKzf-nSVZYd3GHg95z8Z2aPUaK6LsR6rqujlw,8641
26
+ simulations/star_system/sidebar.py,sha256=_cSLhsz7KmOlKlpH_PnvOGHYX34EREVfTQUKb--UVTY,25511
27
+ simulations/star_system/templates.py,sha256=vXQo1PngadqgoegjShZvTxj3XvzdTsDG6H1VEL3jgSo,7746
28
+ sidereel-0.1.0.dist-info/METADATA,sha256=MI4HFCNv4d8EFypnCrSLrIBrYNy8sXcGbFMVy1ikxxo,3634
29
+ sidereel-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
30
+ sidereel-0.1.0.dist-info/entry_points.txt,sha256=s64PGeUZCerdMhvr64j_fKECIM3FFSBGXY4CcJErfAU,134
31
+ sidereel-0.1.0.dist-info/top_level.txt,sha256=-2tKl0vmHje1FojAWdmRw1WPVvjKcK80VVRpb4c_vW8,12
32
+ sidereel-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,5 @@
1
+ [console_scripts]
2
+ sidereel-cli = simulations.star_system.__main__:main
3
+
4
+ [gui_scripts]
5
+ sidereel = simulations.star_system.desktop:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nate Bosma
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ simulations
@@ -0,0 +1 @@
1
+ """Small, checkable physics simulations."""
@@ -0,0 +1 @@
1
+ """Interactive stellar sandbox with a display-independent physics core."""
@@ -0,0 +1,95 @@
1
+ """Default: Qt desktop starting menu. Explicit flags: legacy Matplotlib GUI or headless PNG (--output)."""
2
+ import argparse
3
+ import math
4
+ import sys
5
+ from pathlib import Path
6
+ from .core import make_system, SOLAR_RADIUS_AU
7
+ from .data import STARS, PLANETS
8
+ from .populations import Population, with_population
9
+
10
+
11
+ def main(argv=None):
12
+ arguments = list(sys.argv[1:] if argv is None else argv)
13
+ if not arguments:
14
+ from .desktop import main as desktop_main
15
+ return desktop_main()
16
+ parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False)
17
+ parser.add_argument('--star', choices=STARS, default='sun')
18
+ parser.add_argument('--load', type=Path, help='Load a versioned starting setup JSON')
19
+ parser.add_argument('--planet', choices=PLANETS, action='append')
20
+ parser.add_argument('--output', type=Path, help='Save a still image instead of opening the GUI')
21
+ parser.add_argument('--years', type=float, default=0., help='With --output: evolve before saving the PNG (nonnegative; default 0)')
22
+ parser.add_argument('--sample-stride', type=int, default=10, help='With --output: recording output stride in physics steps (default 10)')
23
+ parser.add_argument('--max-recording-mib', type=int, default=256, help='With --output: in-memory recording budget (default 256 MiB)')
24
+ parser.add_argument('--population', choices=('ring', 'disk', 'belt'))
25
+ parser.add_argument('--count', type=int, default=200, help='Massless particles (1-2000)')
26
+ parser.add_argument('--inner', type=float, default=2., help='Inner population radius in AU from star')
27
+ parser.add_argument('--outer', type=float, help='Outer radius in AU; defaults to inner for rings, 3.5 otherwise')
28
+ parser.add_argument('--seed', type=int, default=0, help='Nonnegative population seed')
29
+ parser.add_argument('--angles', choices=('random', 'even'), default='random')
30
+ args = parser.parse_args(arguments)
31
+ recording_only = ('--sample-stride', '--max-recording-mib')
32
+ if not args.output:
33
+ if args.years:
34
+ parser.error('--years applies only with --output; interactive GUIs open in PREP at t=0')
35
+ if any(argument.split('=', 1)[0] in recording_only for argument in arguments):
36
+ parser.error('--sample-stride and --max-recording-mib apply only with --output')
37
+ construction = {'--star', '--planet', '--population', '--count', '--inner', '--outer', '--seed', '--angles'}
38
+ if args.load is not None and any(argument.split('=', 1)[0] in construction for argument in arguments):
39
+ parser.error('--load cannot be combined with explicit body/population construction flags')
40
+ planets = args.planet or ['earth','jupiter']
41
+ import matplotlib
42
+ if args.output:
43
+ matplotlib.use('Agg')
44
+ from .plotting import App, draw_system
45
+ import matplotlib.pyplot as plt
46
+ try:
47
+ if not math.isfinite(args.years) or args.years < 0:
48
+ raise ValueError('--years must be nonnegative')
49
+ population = None
50
+ loaded = None
51
+ if args.load is not None:
52
+ from .persistence import load_setup
53
+ from .initialization import build_system
54
+ loaded = load_setup(args.load)
55
+ if args.population:
56
+ outer = args.outer if args.outer is not None else args.inner if args.population == 'ring' else 3.5
57
+ population = Population(args.population, args.count, args.inner, outer, args.seed, args.angles)
58
+ # Validate before opening a window, as well as on each rebuild.
59
+ with_population(make_system(args.star, planets), population,
60
+ STARS[args.star].radius*SOLAR_RADIUS_AU)
61
+ if args.output:
62
+ from .initialization import build_system, legacy_setup
63
+ from .recording import Calculation, CalculationRequest
64
+ setup = loaded if loaded is not None else legacy_setup(args.star, planets, population=population)
65
+ prepared = build_system(setup)
66
+ result = None
67
+ if args.years:
68
+ calc = Calculation(setup, CalculationRequest(args.years, args.sample_stride, args.max_recording_mib*1048576))
69
+ while not calc.done:
70
+ calc.advance(150)
71
+ prepared, result = calc.prepared, calc.result
72
+ fig,ax = plt.subplots(figsize=(9,9))
73
+ scene = draw_system(ax, prepared, result.frames if result else ())
74
+ ax.set_title(setup.name, color='#edf4f7')
75
+ if result:
76
+ scene.result_info.set_text(f'{result.status.upper()} / {result.completed_steps:,} steps\n'
77
+ f'Requested {result.requested_end_time:.8g} yr / actual {result.actual_end_time:.8g} yr\n'
78
+ f'Source {result.setup_digest[:12]}\n{result.reason}')
79
+ args.output.parent.mkdir(parents=True,exist_ok=True)
80
+ fig.savefig(args.output,dpi=150)
81
+ plt.close(fig)
82
+ if result is not None and result.status != 'complete':
83
+ print(f'{result.status}: {result.reason}', file=sys.stderr)
84
+ return 2
85
+ else:
86
+ # Keep callbacks and animation alive until the GUI closes.
87
+ _app = App(args.star,planets, population=population, setup=loaded)
88
+ plt.show()
89
+ return 0
90
+ except (ValueError, OSError) as exc:
91
+ parser.error(str(exc))
92
+ return 0
93
+
94
+ if __name__ == '__main__':
95
+ raise SystemExit(main())
@@ -0,0 +1,357 @@
1
+ """Shared draft body editor. Scene placement and velocity use distinct transforms."""
2
+ from dataclasses import replace
3
+ from uuid import uuid4
4
+ from textwrap import fill
5
+ import time
6
+ import numpy as np
7
+ from matplotlib.widgets import TextBox, Button, RadioButtons
8
+ from matplotlib.patches import FancyArrowPatch
9
+ from .data import CATALOG, AU_KM
10
+ from .model import BodySpec, InitialBody, PropertySource
11
+ from .initialization import build_system, insert_body, circular_relative_velocity, recommended_moon_step
12
+ from .rendering import PANEL, TEXT, MUTED, ACCENT
13
+
14
+ VELOCITY_PIXELS_PER_AUYR = 12.
15
+
16
+
17
+ def reference_ids(bodies, exclude=None, world=False, kind=None):
18
+ """Stable choices shared by body placement and initial population drafts."""
19
+ keys = [key for key, spec in bodies if spec.mass is not None and spec.mass > 0 and key != exclude and (kind is None or spec.kind == kind)]
20
+ return keys + (['world'] if world else [])
21
+
22
+
23
+ class BodyEditor:
24
+ """Drafts never mutate the active trajectory before successful confirmation."""
25
+ def __init__(self, app, body_id=None):
26
+ self.app, self.body_id = app, body_id
27
+ self.was_paused, self.finished, self.dragging = app.paused, False, False
28
+ self.axes, self.widgets, self.fields = [], [], {}
29
+ self._filling_spec = False
30
+ self.spec = CATALOG['earth']
31
+ initial = next((b for b in app.initial_setup.bodies if b.id == body_id), None)
32
+ if initial is not None:
33
+ self.spec = initial.spec
34
+ selected = app.prepared.body_ids[app.selected_index]
35
+ reference = selected if app.prepared.body_specs[app.selected_index].mass > 0 else ''
36
+ if initial is not None:
37
+ reference = initial.reference_id or 'world'
38
+ self.panel = self._axes((0, .005, .31, .89))
39
+ self.panel.set_xticks([])
40
+ self.panel.set_yticks([])
41
+ self.panel.text(.05, .985, ('Edit starting body' if body_id else 'Add body') + (' / preparation' if app.preparing else ' / live insertion'), color=TEXT, fontsize=12, va='top')
42
+ self.notice = self.panel.text(.05, .94, '', color=MUTED, fontsize=8, va='top', wrap=True)
43
+ self.category = RadioButtons(self._axes((.02,.727,.27,.065)), ['star','planet','moon','asteroid','custom'], active=(['star','planet','moon','asteroid'].index(self.spec.kind) if self.spec.catalog_key else 4), activecolor=ACCENT, useblit=False)
44
+ for label in self.category.labels:
45
+ label.set_color(TEXT)
46
+ label.set_fontsize(8)
47
+ self.widgets.append(self.category)
48
+ self.category.on_clicked(self.change_category)
49
+ def field(key, label, value, y):
50
+ widget = TextBox(self._axes((.118,y,.17,.026)), label+' ', initial=str(value), color='#1b3044', hovercolor='#294b60')
51
+ widget.label.set_color(TEXT)
52
+ widget.label.set_fontsize(8)
53
+ widget.text_disp.set_color(TEXT)
54
+ widget.text_disp.set_fontsize(8)
55
+ self.fields[key] = widget
56
+ self.widgets.append(widget)
57
+ return widget
58
+ field('catalog','Catalog key',self.spec.catalog_key or 'custom',.688).on_submit(self.load_catalog)
59
+ self.previous = self._button((.02,.652,.065,.026),'<', lambda e:self.browse(-1))
60
+ self.load = self._button((.09,.652,.125,.026),'Load definition',lambda e:self.load_catalog(self.fields['catalog'].text))
61
+ self.next = self._button((.22,.652,.065,.026),'>',lambda e:self.browse(1))
62
+ for key,label,value,y in [('name','Name',self.spec.name,.614),('kind','Kind',self.spec.kind,.579),('mass','Mass (solar)',self.spec.mass,.544),('radius','Radius (AU)',self.spec.radius,.509),('temperature','Star temp (K)',self.spec.temperature,.474),('reference','Reference ID',reference,.425),('x','x (AU)',initial.r[0] if initial else 1.,.387),('y','y (AU)',initial.r[1] if initial else 0.,.352),('vx','vx (AU/yr)',initial.v[0] if initial else 0.,.309),('vy','vy (AU/yr)',initial.v[1] if initial else 0.,.275),('separation','Separation (km)','',.237),('dt','Fixed dt (yr)',app.initial_setup.dt if app.preparing else app.system.dt,.203)]:
63
+ field(key,label,'' if value is None else value,y)
64
+ self.fields['dt'].set_active(app.preparing)
65
+ if not app.preparing:
66
+ self.fields['dt'].label.set_text('dt auto <= (yr) ')
67
+ self.reference_next = self._button((.02,.164,.27,.026),'Reference: next massive / world',self.cycle_reference)
68
+ self.circular = self._button((.02,.119,.27,.03),'Circular aid about reference',self.circular_aid)
69
+ self.confirm = self._button((.02,.079,.13,.032),'Confirm',self.commit)
70
+ self.cancel = self._button((.16,.079,.13,.032),'Cancel',lambda e:self.finish())
71
+ self.error = self.panel.text(.05,.065,'',color='#efb17b',fontsize=8,va='top',wrap=True)
72
+ self.marker, = app.ax.plot([], [], 'o', color=ACCENT, markersize=7, zorder=20)
73
+ self.arrow = FancyArrowPatch((0,0),(0,0),arrowstyle='->',shrinkA=0,shrinkB=0,mutation_scale=14,color=ACCENT,linewidth=1.5,zorder=21)
74
+ app.ax.add_patch(self.arrow)
75
+ self.legend = app.ax.text(.975,.91,'',transform=app.ax.transAxes,color=ACCENT,fontsize=9,ha='right',va='top',zorder=21)
76
+ self.artists = [self.marker,self.arrow,self.legend]
77
+ for key in ('reference','x','y','vx','vy'):
78
+ self.fields[key].on_text_change(lambda text:self.preview())
79
+ self.fields['separation'].on_submit(self.set_separation)
80
+ self.fields['kind'].on_text_change(self.kind_changed)
81
+ self.fields['mass'].on_text_change(lambda text:self.preview())
82
+ self.kind_changed()
83
+ self._describe()
84
+ self.preview()
85
+
86
+ def _axes(self, bounds):
87
+ ax = self.app.fig.add_axes(bounds,zorder=30,facecolor=PANEL)
88
+ for spine in ax.spines.values():
89
+ spine.set_visible(False)
90
+ self.axes.append(ax)
91
+ return ax
92
+
93
+ def _button(self,bounds,label,callback):
94
+ widget = Button(self._axes(bounds),label,color='#1b3044',hovercolor='#294b60',useblit=False)
95
+ widget.label.set_color(TEXT)
96
+ widget.label.set_fontsize(8)
97
+ widget.on_clicked(callback)
98
+ self.widgets.append(widget)
99
+ return widget
100
+
101
+ def _describe(self):
102
+ unknown = [key for key in (('mass','radius','temperature') if self.spec.kind == 'star' else ('mass','radius')) if getattr(self.spec,key) is None]
103
+ status = '; '.join(f'{k}: {v.status}' for k,v in self.spec.sources.items() if v.status not in ('measurement','rounded legacy measurement'))
104
+ text = self.spec.name + (' — unknown '+', '.join(unknown)+'. Supply custom values when needed.' if unknown else '')
105
+ self.notice.set_text(fill(text,width=49)+'\n'+fill(status[:110],width=49))
106
+
107
+ @property
108
+ def is_moon(self):
109
+ return self.fields['kind'].text.strip() == 'moon'
110
+
111
+ def kind_changed(self, text=None):
112
+ if self._filling_spec:
113
+ return
114
+ moon = self.is_moon
115
+ self.reference_next.label.set_text('Parent: next planet' if moon else 'Reference: next massive / world')
116
+ self.fields['reference'].label.set_text('Planet ID ' if moon else 'Reference ID ')
117
+ if moon and self.body_id is None:
118
+ p = self.app.prepared
119
+ choices = reference_ids(zip(p.body_ids,p.body_specs), kind='planet')
120
+ if self.fields['reference'].text.strip() not in choices:
121
+ selected = self.app.selected_id
122
+ self.fields['reference'].set_val(selected if selected in choices else '')
123
+ self.preview()
124
+
125
+ def set_separation(self, text):
126
+ try:
127
+ distance = float(text)/AU_KM
128
+ if not np.isfinite(distance) or distance <= 0:
129
+ raise ValueError('Separation must be finite and positive in km.')
130
+ r, _ = self.vectors()
131
+ r = r/np.linalg.norm(r)*distance if np.linalg.norm(r) else np.array([distance,0.])
132
+ for key,value in zip(('x','y'),r):
133
+ self.fields[key].set_val(f'{value:.16g}')
134
+ self.error.set_text('')
135
+ except ValueError as exc:
136
+ self.error.set_text(fill(str(exc),width=49))
137
+ self.preview()
138
+
139
+ def change_category(self, category):
140
+ if category == 'custom':
141
+ self.spec = BodySpec('Custom body','planet',None,None)
142
+ self._fill_spec()
143
+ return
144
+ keys = [k for k,s in CATALOG.items() if s.kind == category]
145
+ self.load_catalog(keys[0])
146
+
147
+ def browse(self, delta):
148
+ keys = [k for k,s in CATALOG.items() if s.kind == self.category.value_selected]
149
+ if keys:
150
+ current = self.fields['catalog'].text
151
+ self.load_catalog(keys[((keys.index(current) if current in keys else -1)+delta)%len(keys)])
152
+
153
+ def load_catalog(self, key):
154
+ key = key.strip().lower()
155
+ if key not in CATALOG:
156
+ self.error.set_text('Unknown catalog key. Use category and < / > to browse.')
157
+ self.app.painter.paint()
158
+ return
159
+ self.spec = CATALOG[key]
160
+ self._fill_spec()
161
+
162
+ def _fill_spec(self):
163
+ self._filling_spec=True
164
+ for key in ('name','kind','mass','radius','temperature'):
165
+ value=getattr(self.spec,key)
166
+ self.fields[key].set_val('' if value is None else str(value))
167
+ self.fields['catalog'].eventson=False
168
+ self.fields['catalog'].set_val(self.spec.catalog_key or 'custom')
169
+ self.fields['catalog'].eventson=True
170
+ self._filling_spec=False
171
+ self.kind_changed()
172
+ self.error.set_text('')
173
+ self._describe()
174
+ self.preview()
175
+
176
+ def cycle_reference(self,event=None):
177
+ p=self.app.prepared
178
+ keys=reference_ids(zip(p.body_ids,p.body_specs), exclude=self.body_id, world=not self.is_moon, kind='planet' if self.is_moon else None)
179
+ if not keys:
180
+ self.error.set_text('Add a planet before authoring a moon.')
181
+ self.app.painter.paint()
182
+ return
183
+ current=self.fields['reference'].text.strip()
184
+ self.fields['reference'].set_val(keys[(keys.index(current)+1)%len(keys)] if current in keys else keys[0])
185
+ self.preview()
186
+
187
+ def reference_state(self):
188
+ key=self.fields['reference'].text.strip()
189
+ if key == 'world' and not self.is_moon:
190
+ return np.zeros(2),np.zeros(2),None
191
+ p=self.app.prepared
192
+ if not key or key not in p.body_ids:
193
+ if self.is_moon:
194
+ raise ValueError('Choose an existing planet ID as the moon parent.')
195
+ raise ValueError('Choose a massive reference ID from the body list, or enter world.')
196
+ if key == self.body_id:
197
+ raise ValueError('A body cannot reference itself.')
198
+ i=p.body_ids.index(key)
199
+ if self.is_moon and p.body_specs[i].kind != 'planet':
200
+ raise ValueError('A moon parent must be a planet with positive mass.')
201
+ if p.system.masses[i] <= 0:
202
+ raise ValueError('Choose a massive reference body.')
203
+ return p.system.r[i],p.system.v[i],key
204
+
205
+ def vectors(self):
206
+ try:
207
+ r=np.array([float(self.fields[k].text) for k in ('x','y')])
208
+ v=np.array([float(self.fields[k].text) for k in ('vx','vy')])
209
+ except ValueError:
210
+ raise ValueError('Position and velocity components must be numbers.') from None
211
+ if not np.isfinite([r,v]).all():
212
+ raise ValueError('Position and velocity must be finite.')
213
+ return r,v
214
+
215
+ def preview(self):
216
+ if self.finished or self._filling_spec:
217
+ return
218
+ try:
219
+ r,v=self.vectors()
220
+ rr,vv,key=self.reference_state()
221
+ anchor=self.app.scene.world_to_display(r+rr)
222
+ pixel=self.app.ax.transData.transform(anchor)
223
+ displayed_v=self.app.scene.transform.vectors(v)
224
+ tip=self.app.ax.transData.inverted().transform(pixel+displayed_v*VELOCITY_PIXELS_PER_AUYR)
225
+ self.marker.set_data([anchor[0]],[anchor[1]])
226
+ self.arrow.set_positions(anchor,tip)
227
+ self.anchor, self.velocity_tip=anchor,tip
228
+ reference = 'world' if key is None else f'{self.app.prepared.body_specs[self.app.prepared.body_ids.index(key)].name} [{key}]'
229
+ label = 'Parent' if self.is_moon else 'Reference'
230
+ distance = np.linalg.norm(r)
231
+ separation = self.fields['separation']
232
+ distance_text=f'{distance*AU_KM:.10g}'
233
+ if separation.text != distance_text:
234
+ separation.eventson=False
235
+ separation.set_val(distance_text)
236
+ separation.eventson=True
237
+ text = (f'{label}: {reference} / '+('initial' if self.app.preparing else 'current')+' reference state\n'
238
+ f'relative r = ({r[0]:.6g}, {r[1]:.6g}) AU / {distance:.6g} AU = {distance*AU_KM:,.7g} km\n'
239
+ f'relative v = ({v[0]:.6g}, {v[1]:.6g}) AU/yr / speed {np.linalg.norm(v):.6g}\n'
240
+ f'system r = ({(r+rr)[0]:.6g}, {(r+rr)[1]:.6g}) AU\n'
241
+ f'system v = ({(v+vv)[0]:.6g}, {(v+vv)[1]:.6g}) AU/yr\n'
242
+ f'Physical reference-relative inertial velocity; displayed axes only rotate.\n'
243
+ f'Click to place; drag velocity tip / linear {VELOCITY_PIXELS_PER_AUYR:g} px per AU/yr')
244
+ if self.is_moon and self.fields['mass'].text.strip():
245
+ step=recommended_moon_step(r,self.app.system.masses[self.app.prepared.body_ids.index(key)],float(self.fields['mass'].text))
246
+ if self.app.preparing and float(self.fields['dt'].text)>step:
247
+ self.fields['dt'].set_val(f'{step:.16g}')
248
+ text += f'\nMoon fixed dt <= {step:.9g} yr / initial relative period / 600'
249
+ if self.app.preparing:
250
+ text += f'\nDraft fixed dt: {self.fields["dt"].text} yr'
251
+ text += '\nInitial aid only; no forced binding or reattachment.'
252
+ self.legend.set_text(text)
253
+ for a in self.artists:
254
+ a.set_visible(True)
255
+ except ValueError as exc:
256
+ self.marker.set_visible(False)
257
+ self.arrow.set_visible(False)
258
+ self.legend.set_text(fill(str(exc),width=65))
259
+ self.legend.set_visible(True)
260
+ if hasattr(self.app,'painter'):
261
+ self.app.painter.paint()
262
+
263
+ def on_press(self,event):
264
+ if event.button != 1 or event.inaxes != self.app.ax or self.app.sidebar.contains_event(event) or event.xdata is None:
265
+ return
266
+ tip=self.app.ax.transData.transform(getattr(self,'velocity_tip',(np.inf,np.inf)))
267
+ if np.linalg.norm(tip-(event.x,event.y)) < 15:
268
+ self.dragging=True
269
+ return
270
+ rr,_,_=self.reference_state()
271
+ world=self.app.scene.display_to_world((event.xdata,event.ydata))
272
+ r=world-rr
273
+ for key,value in zip(('x','y'),r):
274
+ self.fields[key].set_val(f'{value:.16g}')
275
+ self.preview()
276
+
277
+ def on_motion(self,event):
278
+ if not self.dragging or event.x is None:
279
+ return
280
+ displayed_v=(np.array([event.x,event.y])-self.app.ax.transData.transform(self.anchor))/VELOCITY_PIXELS_PER_AUYR
281
+ v=self.app.scene.transform.inverse_vectors(displayed_v)
282
+ for key,value in zip(('vx','vy'),v):
283
+ self.fields[key].set_val(f'{value:.16g}')
284
+ self.preview()
285
+
286
+ def circular_aid(self,event=None):
287
+ try:
288
+ r,_=self.vectors()
289
+ _,_,key=self.reference_state()
290
+ if key is None:
291
+ raise ValueError('Circular aid requires a massive reference body, not world.')
292
+ mass=float(self.fields['mass'].text)
293
+ ref_mass=self.app.system.masses[self.app.prepared.body_ids.index(key)]
294
+ v=circular_relative_velocity(r,ref_mass,mass)
295
+ for key,value in zip(('vx','vy'),v):
296
+ self.fields[key].set_val(f'{value:.16g}')
297
+ self.error.set_text('Two-body prograde initial aid; no stability guarantee.')
298
+ except ValueError as exc:
299
+ self.error.set_text(fill(str(exc),width=49))
300
+ self.preview()
301
+
302
+ def draft_body(self):
303
+ r,v=self.vectors()
304
+ _,_,reference=self.reference_state()
305
+ values={key:(float(self.fields[key].text) if self.fields[key].text.strip() else None) for key in ('mass','radius','temperature')}
306
+ overrides={key:value for key,value in values.items() if value != getattr(self.spec,key)}
307
+ sources=dict(self.spec.sources)
308
+ for key,value in overrides.items():
309
+ sources[key]=PropertySource('user://override','user input','',value,{'mass':'solar masses','radius':'AU','temperature':'K'}[key],'identity',status='user-authored override')
310
+ spec=replace(self.spec,name=self.fields['name'].text,kind=self.fields['kind'].text.strip(),**values,sources=sources,
311
+ provenance='user overrides of '+str(self.spec.catalog_key or 'custom definition') if (overrides or self.fields['name'].text != self.spec.name or self.fields['kind'].text.strip() != self.spec.kind) else self.spec.provenance)
312
+ return InitialBody(self.body_id or (spec.catalog_key or 'custom')+'-'+uuid4().hex[:10],spec,tuple(r),tuple(v),reference)
313
+
314
+ def commit(self,event=None):
315
+ try:
316
+ body=self.draft_body()
317
+ if self.app.preparing:
318
+ bodies=tuple(body if b.id == self.body_id else b for b in self.app.initial_setup.bodies)
319
+ if self.body_id is None:
320
+ bodies += (body,)
321
+ setup=replace(self.app.initial_setup,bodies=bodies,dt=float(self.fields['dt'].text))
322
+ prepared=build_system(setup)
323
+ else:
324
+ prepared=insert_body(self.app.prepared,body)
325
+ except ValueError as exc:
326
+ self.error.set_text(fill(str(exc),width=49))
327
+ self.app.painter.paint()
328
+ return
329
+ preparing = self.app.preparing
330
+ self.finish(confirmed=True)
331
+ if preparing:
332
+ self.app._legacy_configuration=False
333
+ self.app.initial_setup=setup
334
+ self.app._install_prepared(prepared,reset=preparing)
335
+ if not preparing:
336
+ self.app.status.set_text(prepared.events[-1].message)
337
+ self.app._refresh()
338
+
339
+ def finish(self,confirmed=False):
340
+ if self.finished:
341
+ return
342
+ self.finished=True
343
+ self.app.body_editor=None
344
+ for w in self.widgets:
345
+ w.disconnect_events()
346
+ for ax in self.axes:
347
+ ax.set_animated(False)
348
+ ax.remove()
349
+ for artist in self.artists:
350
+ if artist in self.app.ax.get_children():
351
+ artist.remove()
352
+ self.app.paused=True if confirmed else self.was_paused
353
+ self.app.pending=0.
354
+ self.app.last=time.monotonic()
355
+ self.app._sync_painter()
356
+ self.app.sidebar._sync()
357
+ self.app._refresh()