-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathneocp_explorer.py
More file actions
2559 lines (2197 loc) · 102 KB
/
Copy pathneocp_explorer.py
File metadata and controls
2559 lines (2197 loc) · 102 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import html
import os
import sys
import requests
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import scrolledtext, messagebox, font, filedialog
import re
import logging
import threading
import math
import time
from datetime import datetime
import pandas as pd
try:
from cartes_du_ciel import slew_telescope_via_cdc, load_observing_list_in_cdc, CartesDuCielError
CDC_AVAILABLE = True
except Exception:
slew_telescope_via_cdc = None
load_observing_list_in_cdc = None
CartesDuCielError = Exception
CDC_AVAILABLE = False
# Optional: used only to compute topocentric Alt/Az from Project Pluto RA/Dec.
# The application still runs without astropy; Alt/Az will simply be unavailable.
try:
from astropy.coordinates import SkyCoord, EarthLocation, AltAz
from astropy.time import Time
import astropy.units as u
ASTROPY_AVAILABLE = True
except Exception:
ASTROPY_AVAILABLE = False
# Configure logging to log to both file and console
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Avoid duplicate log entries if this module is reloaded in an IDE/session.
if not logger.handlers:
file_handler = logging.FileHandler('app.log')
file_handler.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(console_handler)
# ---------------------------------------------------------------------------
# Colour palette — neutral professional dark
# ---------------------------------------------------------------------------
C = {
'bg': '#1e1e1e',
'panel': '#252526',
'panel_alt': '#2d2d2d',
'border': '#3c3c3c',
'accent': '#0078d4',
'accent_dark': '#005a9e',
'fg': '#d4d4d4',
'fg_dim': '#8a8a8a',
'fg_header': '#ffffff',
'entry_bg': '#3c3c3c',
'entry_fg': '#d4d4d4',
'row_even': '#2a2a2a',
'row_odd': '#252526',
'row_sel': '#094771',
'status_bg': '#007acc',
'status_fg': '#ffffff',
'error': '#5a1a1a',
'success': '#4ec9b0',
'warning': '#dcdcaa',
}
class Tooltip:
"""Creates tooltips for Tkinter widgets."""
def __init__(self, widget, text):
self.widget = widget
self.text = text
self.tooltip_window = None
widget.bind("<Enter>", self.show_tooltip)
widget.bind("<Leave>", self.hide_tooltip)
def show_tooltip(self, event=None):
if self.tooltip_window or not self.text:
return
x = self.widget.winfo_rootx() + (event.x if event else 10)
y = self.widget.winfo_rooty() + self.widget.winfo_height() + 4
self.tooltip_window = tw = tk.Toplevel(self.widget)
tw.wm_overrideredirect(True)
tw.wm_geometry(f"+{x}+{y}")
label = tk.Label(tw, text=self.text, background='#3c3c3c',
foreground=C['fg'], relief='solid', borderwidth=1,
font=('Segoe UI', 9))
label.pack(ipadx=4, ipady=2)
def hide_tooltip(self, event=None):
tw = self.tooltip_window
if tw:
tw.destroy()
self.tooltip_window = None
# ---------------------------------------------------------------------------
# Project Pluto remote ephemeris provider
# ---------------------------------------------------------------------------
PROJECT_PLUTO_URL = "https://www.projectpluto.com/cgi-bin/fo/fo_serve.cgi"
APP_VERSION = "3.1.1"
LD_PER_AU = 389.17 # mean lunar distances per astronomical unit
HTTP_HEADERS = {
"User-Agent": (
f"NEOCP Explorer/{APP_VERSION} "
"(https://github.com/Anduin-source/NEOCP_Explorer)"
)
}
RETRYABLE_HTTP_STATUS = {429, 502, 503, 504}
NEOCP_CACHE_TTL_SECONDS = 300
NEOCP_MIN_REFRESH_SECONDS = 30
def _service_get(url, *, timeout, params=None):
"""GET a public service with identification and one bounded retry."""
for attempt in range(2):
response = requests.get(
url,
params=params,
headers=HTTP_HEADERS,
timeout=timeout,
)
if response.status_code not in RETRYABLE_HTTP_STATUS or attempt == 1:
response.raise_for_status()
return response
retry_after = response.headers.get("Retry-After", "1")
try:
delay = float(retry_after)
except (TypeError, ValueError):
delay = 1.0
time.sleep(max(0.5, min(delay, 5.0)))
raise requests.exceptions.RequestException("External service request failed.")
def resource_path(relative_path):
"""Return absolute path to a bundled resource.
Works both in normal Python execution and in PyInstaller --onefile builds.
"""
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def project_pluto_uncertainty_to_degrees(value):
"""Convert Project Pluto/Find_Orb ephemeris uncertainty to degrees.
Project Pluto may report the ephemeris uncertainty with different suffixes:
- d : degrees, for very large uncertainties, e.g. 40d
- m : arcminutes, e.g. 3.6m
- " : arcseconds, e.g. 2728"
- no suffix: treated as arcseconds, which is how some pseudo-MPEC
text appears after HTML conversion/parsing.
The UI displays a single normalized unit, degrees, to avoid mixing
values like 40d and 2728" in the same column.
"""
if value is None:
return None
s = str(value).strip()
if not s or s.upper() == 'N/A':
return None
# Normalize typographic prime characters that may appear in copied HTML.
s = s.replace('″', '"').replace('”', '"').replace('′', "'").replace('’', "'")
try:
lower = s.lower()
if lower.endswith('d'):
return float(lower[:-1])
if lower.endswith('m') or lower.endswith("'"):
return float(lower[:-1]) / 60.0
if lower.endswith('s') or lower.endswith('"'):
return float(lower[:-1]) / 3600.0
# Project Pluto often emits bare numeric values for arcseconds.
return float(lower) / 3600.0
except ValueError:
return None
def format_uncertainty_degrees(value):
"""Return uncertainty normalized to degrees for table display."""
deg = project_pluto_uncertainty_to_degrees(value)
if deg is None:
return str(value).strip() if value is not None else ''
if deg >= 10:
return f"{deg:.1f}"
if deg >= 1:
return f"{deg:.2f}"
return f"{deg:.3f}"
class ProjectPlutoError(Exception):
"""Raised when Project Pluto returns a page that cannot be used as an ephemeris."""
def fetch_project_pluto_ephemeris(target_object, obs_code="X93", eph_steps=10, step_size="1h"):
"""
Fetches ephemerides from Project Pluto's online Find_Orb server.
Works for both NEOCP tracklets and known minor-planet designations.
This is the only calculation engine used by this no-local-Find_Orb build.
"""
params = {
"obj_name": target_object,
"year": "now",
"n_steps": int(eph_steps),
"stepsize": step_size,
"mpc_code": obs_code,
"faint_limit": 99,
"ephem_type": 0,
"sigmas": "on",
# Force heliocentric (Sun-centered) elements. With the "automatic"
# setting (-2) Find_Orb returns GEOCENTRIC elements for short-arc
# near-Earth objects ("Perigee"/"(J2000 equator)"), whose eccentricity
# is relative to Earth (e >> 1 for any flyby) and has no semi-major
# axis. That produced spurious "hyperbolic/interstellar" flags and made
# the orbit incomparable to the MPC. 0 = Sun keeps every object
# heliocentric, matching the MPC.
"element_center": 0,
"epoch": "default",
"resids": 0,
"language": "e",
"file_no": 0,
}
headers = HTTP_HEADERS
try:
response = requests.get(
PROJECT_PLUTO_URL,
params=params,
headers=headers,
timeout=30,
)
response.raise_for_status()
except requests.exceptions.RequestException as e:
logger.error(f"Project Pluto request error: {e}")
raise requests.exceptions.RequestException(
f"Project Pluto request error: {e}"
)
return response.text
def _extract_html_comments(html_text):
"""Extracts hidden Project Pluto metadata comments from the HTML."""
return "\n".join(
c.strip() for c in re.findall(r"<!--(.*?)-->", html_text, flags=re.S)
if c.strip()
)
# Observatory coordinates used for local Alt/Az after Project Pluto returns RA/Dec.
# Longitude is degrees East. 313.6047 E = 46.3953 W.
# Add more observatories here later if needed.
OBSERVATORY_COORDS = {
"X93": {
"name": "Munhoz Observatory",
"lat_deg": -22.628914,
"lon_deg": 313.6047,
"height_m": 1078.766,
},
}
def _html_to_readable_text(html_text):
"""Converts Project Pluto's simple HTML pseudo-MPEC into readable visible text."""
# Remove hidden comments from visible text. They are kept separately as
# advanced metadata, not mixed into the main orbital-elements display.
text = re.sub(r"<!--.*?-->", "", html_text, flags=re.S)
text = re.sub(r"(?i)<br\s*/?>", "\n", text)
text = re.sub(r"(?i)</p\s*>", "\n", text)
text = re.sub(r"(?i)</pre\s*>", "\n", text)
text = re.sub(r"(?i)<li\s*>", "\n- ", text)
text = re.sub(r"<[^>]+>", "", text)
text = html.unescape(text)
text = "\n".join(line.rstrip() for line in text.splitlines())
return text
def _clean_project_pluto_error_excerpt(readable_text):
"""Returns a compact, user-facing excerpt from a failed Project Pluto page.
Project Pluto/Find_Orb may return HTTP 200 with an HTML page describing
the problem instead of a machine-readable error. The visible text can also
include CSS/style artifacts. This helper removes those artifacts and keeps
the operational message, usually beginning with 'Problem reading
observations'.
"""
lines = []
skip_css = False
for raw in readable_text.splitlines():
line = raw.strip()
if not line:
continue
lower = line.lower()
# Drop common CSS/style artifacts that can appear after stripping tags.
if lower.startswith(('.neocp', '.whtext')) or '{' in line or '}' in line:
skip_css = True
if '}' in line:
skip_css = False
continue
if skip_css:
if '}' in line:
skip_css = False
continue
# Drop generic headings/navigation that are not useful in an error box.
if lower in {'ephemeris generator', 'pseudo-mpec'}:
continue
if lower.startswith('click here') or lower.startswith('orbit simulator'):
continue
lines.append(line)
# Prefer the actual Find_Orb/Project Pluto error paragraph when present.
start_idx = 0
for i, line in enumerate(lines):
if 'problem reading observations' in line.lower():
start_idx = i
break
if 'no objects found' in line.lower():
start_idx = i
break
useful = lines[start_idx:start_idx + 12]
cleaned = []
for line in useful:
if len(line) > 180:
line = line[:177] + '...'
cleaned.append(line)
return "\n".join(cleaned) or "No readable server message returned."
def _section_between(text, start_marker, end_marker=None):
"""Returns a text section from start_marker up to end_marker."""
start = text.find(start_marker)
if start == -1:
return ""
if end_marker:
end = text.find(end_marker, start + len(start_marker))
if end != -1:
return text[start:end].strip()
return text[start:].strip()
def _parse_project_pluto_ephemeris_rows(eph_text):
"""Parse Project Pluto ephemeris rows into dictionaries.
Project Pluto can return two slightly different visible formats:
Daily step:
YYYY MM DD RA_h RA_m RA_s Dec_d Dec_m Dec_s delta r elong mag sig PA
Hourly/sub-day step:
YYYY MM DD HH RA_h RA_m RA_s Dec_d Dec_m Dec_s delta r elong mag sig PA
The previous v3 parser only handled the daily form and a HH:MM token. With
stepsize=1h, Project Pluto emits a standalone HH column, so RA/Dec were
shifted and Alt/Az could not be computed. This parser detects that form.
"""
rows = []
for line in eph_text.splitlines():
stripped = line.strip()
if not re.match(r"^\d{4}\s+\d{2}\s+\d{2}\s+", stripped):
continue
parts = stripped.split()
if len(parts) < 15:
continue
try:
year, month, day = parts[0], parts[1], parts[2]
idx = 3
time_utc = "00:00"
# Case A: explicit HH:MM or HH:MM:SS token.
if idx < len(parts) and re.match(r"^\d{1,2}:\d{2}(:\d{2})?$", parts[idx]):
time_utc = parts[idx][:5]
idx += 1
# Case B: Project Pluto hourly output has a standalone HH column.
# Example:
# 2026 05 31 18 19 01 52.377 -40 12 50.42 ...
# If parts[7] starts with +/-, then parts[4:7] are RA and parts[7]
# is Dec degrees; therefore parts[3] is the hour.
elif (
len(parts) >= 16
and re.match(r"^\d{1,2}$", parts[3])
and parts[7][0] in "+-"
):
hour = int(parts[3])
if 0 <= hour <= 23:
time_utc = f"{hour:02d}:00"
idx = 4
ra = f"{parts[idx]} {parts[idx+1]} {parts[idx+2]}"
dec = f"{parts[idx+3]} {parts[idx+4]} {parts[idx+5]}"
delta = float(parts[idx+6])
r = float(parts[idx+7])
elong = float(parts[idx+8])
mag = float(parts[idx+9])
sig = parts[idx+10]
pa = int(float(parts[idx+11]))
rows.append({
"date": f"{year}-{month}-{day}",
"time": time_utc,
"ra": ra,
"dec": dec,
"delta": delta,
"r": r,
"elong": elong,
"mag": mag,
"sig": sig,
"pa": pa,
"alt": None,
"az": None,
"airmass": None,
"rate": None,
"motion_pa": None,
})
except Exception as e:
logger.debug(f"Could not parse Project Pluto ephemeris line: {line!r}; {e}")
continue
return rows
def _compute_altaz_for_rows(rows, obs_code):
"""Adds Alt/Az/Airmass to Project Pluto rows when astropy and coordinates exist."""
if not ASTROPY_AVAILABLE:
return "Alt/Az not computed: astropy is not installed."
code = (obs_code or "").strip().upper()
info = OBSERVATORY_COORDS.get(code)
if not info:
return f"Alt/Az not computed: coordinates for observatory {code} are not in the local table."
location = EarthLocation(
lat=info["lat_deg"] * u.deg,
lon=info["lon_deg"] * u.deg,
height=info["height_m"] * u.m,
)
for row in rows:
try:
# Convert RA/Dec strings to astropy coordinates.
rah, ram, ras = row["ra"].split()
decd, decm, decs = row["dec"].split()
coord = SkyCoord(
f"{rah}h{ram}m{ras}s {decd}d{decm}m{decs}s",
frame="icrs",
)
t = Time(f"{row['date']}T{row['time']}", scale="utc")
altaz = coord.transform_to(AltAz(obstime=t, location=location))
row["alt"] = float(altaz.alt.deg)
row["az"] = float(altaz.az.deg)
# sec(z) approximation is acceptable for display; avoid values
# below/near the horizon.
if row["alt"] > 5:
z_rad = math.radians(90.0 - row["alt"])
row["airmass"] = 1.0 / math.cos(z_rad)
except Exception as e:
logger.debug(f"Could not compute Alt/Az for row {row}: {e}")
return None
def _ra_to_degrees(ra_text):
"""Convert RA string 'HH MM SS.s' to decimal degrees."""
h, m, s = [float(x) for x in str(ra_text).split()]
return 15.0 * (h + m / 60.0 + s / 3600.0)
def _dec_to_degrees(dec_text):
"""Convert Dec string '+DD MM SS.s' or '-DD MM SS.s' to decimal degrees."""
d_s, m_s, s_s = str(dec_text).split()
sign = -1.0 if d_s.startswith('-') else 1.0
d = abs(float(d_s))
m = float(m_s)
s = float(s_s)
return sign * (d + m / 60.0 + s / 3600.0)
def _row_datetime_utc(row):
"""Return a naive UTC datetime for an ephemeris row."""
return datetime.strptime(f"{row['date']} {row['time']}", "%Y-%m-%d %H:%M")
def _angular_sep_and_pa(ra1_deg, dec1_deg, ra2_deg, dec2_deg):
"""Return angular separation in arcsec and position angle in degrees.
PA is measured east of north, matching the usual astronomical convention
used for apparent motion PA in ephemerides.
"""
ra1 = math.radians(ra1_deg)
dec1 = math.radians(dec1_deg)
ra2 = math.radians(ra2_deg)
dec2 = math.radians(dec2_deg)
dra = ra2 - ra1
# Great-circle separation.
cos_sep = (
math.sin(dec1) * math.sin(dec2)
+ math.cos(dec1) * math.cos(dec2) * math.cos(dra)
)
cos_sep = max(-1.0, min(1.0, cos_sep))
sep_rad = math.acos(cos_sep)
# Position angle from point 1 to point 2, east of north.
y = math.sin(dra) * math.cos(dec2)
x = (
math.cos(dec1) * math.sin(dec2)
- math.sin(dec1) * math.cos(dec2) * math.cos(dra)
)
pa_deg = (math.degrees(math.atan2(y, x)) + 360.0) % 360.0
return math.degrees(sep_rad) * 3600.0, pa_deg
def _compute_apparent_motion_for_rows(rows):
"""Add apparent sky motion to ephemeris rows.
Project Pluto's pseudo-MPEC table used here provides the ephemeris
uncertainty and its PA, but not the apparent motion rate. We compute the
apparent motion from successive RA/Dec positions. Interior rows use a
centered difference; the first and last rows use forward/backward
differences. Units are arcsec/min.
"""
if len(rows) < 2:
return
try:
coords = [(_ra_to_degrees(r['ra']), _dec_to_degrees(r['dec'])) for r in rows]
times = [_row_datetime_utc(r) for r in rows]
except Exception as e:
logger.debug(f"Could not prepare apparent-motion calculation: {e}")
return
for i, row in enumerate(rows):
try:
if i == 0:
j1, j2 = 0, 1
elif i == len(rows) - 1:
j1, j2 = len(rows) - 2, len(rows) - 1
else:
j1, j2 = i - 1, i + 1
dt_min = abs((times[j2] - times[j1]).total_seconds()) / 60.0
if dt_min <= 0:
continue
sep_arcsec, pa_deg = _angular_sep_and_pa(
coords[j1][0], coords[j1][1], coords[j2][0], coords[j2][1]
)
rate = sep_arcsec / dt_min
row['rate'] = rate
row['motion_pa'] = pa_deg
except Exception as e:
logger.debug(f"Could not compute apparent motion for row {row}: {e}")
continue
def _format_project_pluto_ephemeris(eph_raw, obs_code):
"""Builds a clean ephemeris table enhanced with Alt/Az and apparent motion."""
rows = _parse_project_pluto_ephemeris_rows(eph_raw)
if not rows:
return eph_raw
altaz_note = _compute_altaz_for_rows(rows, obs_code)
_compute_apparent_motion_for_rows(rows)
title = "Project Pluto ephemerides"
m = re.search(r"Ephemerides for.*", eph_raw)
if m:
title = m.group(0).strip()
lines = []
lines.append(title)
if altaz_note:
lines.append(altaz_note)
else:
lines.append(f"Alt/Az computed locally for observatory {obs_code.upper()}.")
lines.append("Apparent motion computed locally from successive RA/Dec positions.")
lines.append("")
lines.append(
"Date UTC Time RA Dec delta r elong mag rate motPA unc_deg uncPA Alt Az Air"
)
lines.append(
"--------- ----- ------------ ------------ ------- ------ ------ ---- ------ ----- ------- ----- ----- ----- ----"
)
for row in rows:
alt = f"{row['alt']:5.1f}" if row["alt"] is not None else " N/A"
az = f"{row['az']:5.1f}" if row["az"] is not None else " N/A"
air = f"{row['airmass']:4.2f}" if row["airmass"] is not None else " N/A"
unc_deg = format_uncertainty_degrees(row['sig'])
rate = f"{row['rate']:6.2f}" if row.get('rate') is not None else " N/A"
mot_pa = f"{row['motion_pa']:5.1f}" if row.get('motion_pa') is not None else " N/A"
lines.append(
f"{row['date']} {row['time']:<5} "
f"{row['ra']:<12} {row['dec']:<12} "
f"{row['delta']:7.5f} {row['r']:6.4f} {row['elong']:6.1f} "
f"{row['mag']:4.1f} {rate} {mot_pa} "
f"{unc_deg:>7} {row['pa']:5d} {alt} {az} {air}"
)
return "\n".join(lines)
def _parse_project_pluto_station_names(station_text):
"""Builds {MPC_code: station_name} from Project Pluto Station data."""
names = {}
for line in station_text.splitlines():
line = line.strip()
m = re.match(r"^\(([A-Za-z0-9]{3})\)\s+(.+?)(?:\s+\([NS][\d.]+\s+[EW][\d.]+\)|\s{2,}|$)", line)
if m:
code = m.group(1).upper()
name = " ".join(m.group(2).split())
names[code] = name
return names
def _format_project_pluto_observations(obs_raw, station_text):
"""Appends the observatory name beside each OBS80 astrometry line."""
station_names = _parse_project_pluto_station_names(station_text)
if not obs_raw.strip():
return obs_raw
out = []
for line in obs_raw.splitlines():
raw = line.rstrip()
stripped = raw.strip()
if not stripped or stripped.lower().startswith("astrometry"):
out.append(raw)
continue
# In the readable Project Pluto pseudo-MPEC, the reporting MPC code is
# normally the final 3 alphanumeric characters of each astrometry line.
m = re.search(r"([A-Za-z0-9]{3})\s*$", stripped)
if m:
code = m.group(1).upper()
station = station_names.get(code)
if station:
out.append(f"{raw} [{code} — {station}]")
continue
out.append(raw)
if station_names:
out.append("")
out.append("Observatory codes:")
for code in sorted(station_names):
out.append(f" {code} — {station_names[code]}")
return "\n".join(out)
def split_project_pluto_output(html_text, obs_code="X93"):
"""Splits Project Pluto pseudo-MPEC into UI blocks.
Returns:
elements_content - clean orbital elements + residuals, without hidden dump
eph_content - clean/enhanced ephemeris table
obs_content - astrometry only
advanced_content - hidden Project Pluto metadata for optional display
"""
readable = _html_to_readable_text(html_text)
hidden_metadata = _extract_html_comments(html_text)
if "Ephemerides for" not in readable:
logger.error("Project Pluto response did not contain an ephemeris table.")
logger.debug("Project Pluto response snippet:\n%s", readable[:2000])
# Project Pluto/Find_Orb usually returns HTTP 200 even for search
# failures; the failure is described in the HTML/text itself. Keep a
# compact, readable snippet for the user and the full text in app.log.
server_msg = _clean_project_pluto_error_excerpt(readable)
raise ProjectPlutoError(
"Project Pluto did not return an ephemeris table.\n\n"
"Possible causes:\n"
"• object designation was not found in MPC/NEOCP data;\n"
"• object exists, but Project Pluto could not retrieve valid observations;\n"
"• observatory code is invalid;\n"
"• Project Pluto/MPC service is temporarily unavailable.\n\n"
f"Server message excerpt:\n{server_msg}"
)
obs_raw = _section_between(readable, "Astrometry:", "Station data:")
station_content = _section_between(readable, "Station data:", "Orbital elements:")
obs_content = _format_project_pluto_observations(obs_raw, station_content)
elements_content = _section_between(
readable,
"Orbital elements:",
"Residuals in arcseconds:"
)
residuals_content = _section_between(
readable,
"Residuals in arcseconds:",
"Ephemerides for"
)
eph_raw = _section_between(readable, "Ephemerides for")
if residuals_content:
elements_content = (elements_content + "\n\n" + residuals_content).strip()
eph_content = _format_project_pluto_ephemeris(eph_raw, obs_code)
advanced_content = ""
if hidden_metadata:
advanced_content = "Hidden Project Pluto metadata:\n" + hidden_metadata
return elements_content, eph_content, obs_content, advanced_content
def infer_object_category(target_object, obs_content="", advanced_content="", neocp_designations=None):
"""Infer whether the submitted object is a current NEOCP candidate or a known object."""
target = (target_object or "").strip().upper()
neocp_set = {str(x).strip().upper() for x in (neocp_designations or set())}
if target and target in neocp_set:
return "NEOCP candidate (current MPC NEOCP list)"
combined = f"{obs_content}\n{advanced_content}"
if "NEOCP" in combined:
return "NEOCP candidate"
return "Known object / MPC designation"
def parse_summary(elements_content, eph_content, target_object, object_category="Unknown"):
"""
Parses Find_Orb / Project Pluto elements and ephemeris output to produce
a human-readable summary.
This version supports both:
- local Find_Orb output, with altitude/azimuth columns;
- Project Pluto pseudo-MPEC output, without altitude/azimuth but with
useful hidden metadata in HTML comments.
"""
def _get(pattern, text, group=1, default='N/A', flags=0):
m = re.search(pattern, text, flags)
return m.group(group).strip() if m else default
metadata_text = elements_content + "\n" + eph_content
# Detect a geocentric (Earth-centered) elements block. Find_Orb falls back
# to this for some short-arc near-Earth objects: it prints "Perigee" and
# "(J2000 equator)" instead of "Perihelion"/"(J2000 ecliptic)", and the
# eccentricity is then relative to Earth (e >> 1 for any flyby), with no
# semi-major axis. We request heliocentric elements (element_center=0), so
# this should not happen, but guard against it to avoid false interstellar
# flags if the server ever returns a geocentric solution.
geocentric = bool(
re.search(r'J2000\s+equator', elements_content)
or re.search(r'^\s*Perigee\b', elements_content, re.MULTILINE)
)
# ------------------------------------------------------------------ #
# 1. Parse orbital / physical metadata
# ------------------------------------------------------------------ #
diameter = _get(r'Diameter\s+([\d.]+)\s+meters', metadata_text)
enc_vel = _get(r'Earth encounter velocity\s+([\d.]+)\s+km/s', metadata_text)
moid = _get(r'Earth MOID[:\s]+([\d.]+)', metadata_text)
score = _get(r'Score:\s+([\d.]+)', metadata_text)
perihelion = _get(r'Perihelion\s+(\d{4}\s+\w+\s+[\d.]+)', elements_content)
ecc = _get(r'\be\s+([\d.]+)', elements_content)
# Eccentricity 1-sigma uncertainty (may be in scientific notation, e.g.
# "1.26e-8"). A short observation arc leaves e essentially unconstrained,
# which Find_Orb reports as a large sigma here.
ecc_sigma = _get(r'\be\s+[\d.]+\s+\+/-\s+([0-9.eE+-]+)', elements_content)
incl = _get(r'Incl\.\s+([\d.]+)', elements_content)
a_au = _get(r'\ba\s+(-?[\d.]+)', elements_content)
tisserand = _get(r'Tisserand relative to Earth:\s+([\d.]+)', metadata_text)
tisserand_jup = _get(r'Tisserand relative to Jupiter:\s+([\d.]+)', metadata_text)
h_mag = _get(r'\bH\s+([\d.]+)', elements_content)
# Observations: local Find_Orb and Project Pluto use different wording.
obs_used = _get(r'(\d+)\s+of\s+\d+\s+observations', elements_content)
obs_total = _get(r'\d+\s+of\s+(\d+)\s+observations', elements_content)
obs_arc = _get(r'\d+\s+of\s+\d+\s+observations\s+[\d\w. ]+\(([\d.]+\s+hr)\)',
elements_content)
if obs_used == 'N/A':
obs_used = _get(r'From\s+(\d+)\s+observations', elements_content)
obs_total = obs_used
obs_arc = _get(r'From\s+\d+\s+observations\s+.*?\(([\d.]+\s+min)\)',
elements_content)
# ------------------------------------------------------------------ #
# 2. Find closest approach in ephemeris table
# ------------------------------------------------------------------ #
closest_date = 'N/A'
closest_delta = None
closest_mag = 'N/A'
closest_alt = 'N/A'
closest_rate = 'N/A'
closest_mot_pa = 'N/A'
first_date = 'N/A'
first_delta = None
first_r = 'N/A'
first_elong = 'N/A'
# Project Pluto enhanced table generated by _format_project_pluto_ephemeris:
# YYYY-MM-DD HH:MM RA_h RA_m RA_s Dec_d Dec_m Dec_s delta r elong mag sig PA alt az air
# Local Find_Orb table:
# YYYY MM DD HH RA_h RA_m RA_s Dec_d Dec_m Dec_s delta r mag motion PA alt az
for line in eph_content.splitlines():
sline = line.strip()
if not sline:
continue
try:
if re.match(r'^\d{4}-\d{2}-\d{2}\s+', sline):
# Enhanced Project Pluto table.
parts = sline.split()
if len(parts) >= 19:
date_str = f"{parts[0]} {parts[1]} UTC"
# Enhanced v15 columns:
# date time RA(3) Dec(3) delta r elong mag rate motPA unc PA alt az air
delta = float(parts[8])
r_val = parts[9]
elong_val = parts[10]
mag = parts[11]
apparent_rate = parts[12]
motion_pa = parts[13]
alt = parts[16]
elif len(parts) >= 17:
date_str = f"{parts[0]} {parts[1]} UTC"
# Enhanced v14 columns:
# date time RA(3) Dec(3) delta r elong mag unc PA alt az air
delta = float(parts[8])
r_val = parts[9]
elong_val = parts[10]
mag = parts[11]
apparent_rate = 'N/A'
motion_pa = 'N/A'
alt = parts[14]
else:
continue
elif re.match(r'^\d{4}\s+\d{2}\s+\d{2}\s+\d{2}', sline):
# Local Find_Orb table from '-E 3,5,24'.
parts = sline.split()
if len(parts) < 17:
continue
tail = parts[-7:] # [delta, r, mag, motion, PA, alt, az]
delta = float(tail[0])
r_val = tail[1]
elong_val = 'N/A'
mag = tail[2]
apparent_rate = tail[3]
motion_pa = tail[4]
alt = tail[5]
date_str = f"{parts[0]}-{parts[1]}-{parts[2]} {parts[3]}h UTC"
elif re.match(r'^\d{4}\s+\d{2}\s+\d{2}\s+', sline):
# Raw Project Pluto pseudo-MPEC table, kept as fallback.
parts = sline.split()
if len(parts) < 15:
continue
delta = float(parts[9])
r_val = parts[10]
elong_val = parts[11]
mag = parts[12]
apparent_rate = 'N/A'
motion_pa = 'N/A'
alt = 'N/A'
date_str = f"{parts[0]}-{parts[1]}-{parts[2]} UTC"
else:
continue
if first_delta is None:
first_date = date_str
first_delta = delta
first_r = r_val
first_elong = elong_val
if closest_delta is None or delta < closest_delta:
closest_delta = delta
closest_date = date_str
closest_mag = mag
closest_alt = alt
closest_rate = apparent_rate
closest_mot_pa = motion_pa
except (ValueError, IndexError):
continue
closest_delta_str = 'N/A'
if closest_delta is not None:
ld = closest_delta * LD_PER_AU
closest_delta_str = f"{closest_delta:.5f} AU ({ld:.1f} LD)"
first_delta_str = 'N/A'
if first_delta is not None:
first_delta_str = f"{first_delta:.5f} AU ({first_delta * LD_PER_AU:.1f} LD)"
try:
first_r_str = f"{float(first_r):.4f} AU"
except (TypeError, ValueError):
first_r_str = 'N/A'
try:
first_elong_str = f"{float(first_elong):.1f}°"
except (TypeError, ValueError):
first_elong_str = 'N/A'
# ------------------------------------------------------------------ #
# 3. Classification
# ------------------------------------------------------------------ #
EARTH_Q = 1.017 # Earth aphelion (AU)
EARTH_q = 0.983 # Earth perihelion (AU)
neo_subclass = "Unknown"
try:
a_val = float(a_au)
e_val = float(ecc)
q = a_val * (1.0 - e_val)
Q = a_val * (1.0 + e_val)
if not geocentric and e_val >= 1.0:
# Hyperbolic heliocentric orbit: a is negative and Q is meaningless,
# so the Aten/Atira (a < 1) branches below must not be reached.
neo_subclass = "Hyperbolic / unbound orbit (e ≥ 1)"
elif a_val < 1.0 and Q < EARTH_q:
neo_subclass = "Atira (orbit interior to Earth's)"
elif a_val < 1.0:
neo_subclass = "Aten (a < 1 AU, crosses Earth's orbit)"
elif q < EARTH_Q:
neo_subclass = "Apollo (a > 1 AU, crosses Earth's orbit)"
elif q < 1.3:
neo_subclass = "Amor (a > 1 AU, approaches but does not cross)"
else:
neo_subclass = "Outside NEO criterion (q > 1.3 AU)"
except ValueError:
neo_subclass = "Unknown"
try:
tj = float(tisserand_jup)
if tj < 2:
dyn_class = "Halley-type / long-period comet (T_J < 2)"
elif tj < 3:
dyn_class = "Jupiter-family comet (2 <= T_J < 3)"
else:
dyn_class = "Asteroid (T_J >= 3)"
except ValueError:
dyn_class = "Unavailable (T_J not reported)"
# ------------------------------------------------------------------ #
# 4. Flags
# ------------------------------------------------------------------ #
try:
pha = float(moid) < 0.05 and float(h_mag) < 22
except ValueError:
pha = False
# A large sigma on e means the orbit is poorly constrained (typically a
# very short observation arc), so the eccentricity value is not meaningful.
try:
sig_e = float(ecc_sigma)
poorly_constrained = sig_e >= 0.1
except ValueError:
sig_e = None
poorly_constrained = False
# Only a heliocentric eccentricity >= 1 indicates a (possibly interstellar)
# hyperbolic orbit. A geocentric solution always has e >> 1 and says nothing
# about heliocentric dynamics, so never flag it as hyperbolic. A short-arc
# fit with a huge sigma can land at e >= 1 by chance, so only call it a
# *significant* (possible interstellar) hyperbolic orbit when e exceeds 1 by
# more than 3 sigma.
try:
e_val_flag = (not geocentric) and float(ecc)