-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathstarfix.py
More file actions
executable file
·3347 lines (2939 loc) · 128 KB
/
Copy pathstarfix.py
File metadata and controls
executable file
·3347 lines (2939 loc) · 128 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
''' A toolkit for celestial navigation, in particular sight reductions
© August Linnman, 2025, email: august@linnman.net
MIT License (see LICENSE file)
'''
from os import name as os_name
from sys import version_info
from math import pi, sin, cos, acos, sqrt, tan, atan2
from random import gauss
from datetime import datetime, date, timedelta, timezone
from types import NoneType
from typing import Optional
from collections.abc import Callable
import pathlib
import os
import socket
import time
import http.server
import socketserver
from threading import Thread
import webbrowser
from configparser import ConfigParser
################################################
# Testing switches
################################################
#pylint: disable=R0903
class Testing:
''' This is a switchboard used for testing only '''
# This flag disables all geocentric/geodetic mapping (for testing only)
disable_geodetics = False
# This flag disables all handling of refraction (for testing only)
disable_refraction_handling = False
# This flag is for shifting the GP calculation
GP_shift = None
#pylint: enable=R0903
################################################
# Debug Logger
################################################
class DebugLogger:
''' Simple debug utility to use when needed. Set enable_debug=True '''
enable_debug = False
output_stdout = False
def _output (self, message : str, level : str="INFO"):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
output_string = f"[{timestamp}] [{level}] {message}\n"
if self.output_stdout:
print (output_string)
with open(self.log_file, "a", encoding="utf-8") as f:
f.write(output_string)
f.flush()
def __init__(self):
if not DebugLogger.enable_debug:
return
self.log_file = os.path.join(os.getcwd(), "celeste_debug.txt")
try:
with open(self.log_file, "a", encoding="utf-8") as f:
f.write(f"=== Celeste Debug Log Started at {datetime.now()} ===\n")
#pylint: disable=W0702
except:
pass
#pylint: enable=W0702
@staticmethod
def enable (do_enable : bool, to_stdout : bool = False):
''' Modify debuglogger status '''
DebugLogger.enable_debug = do_enable
DebugLogger.output_stdout = to_stdout
def _log(self, message : str, level="INFO"):
''' Log a message'''
if not DebugLogger.enable_debug:
return
try:
#timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
#with open(self.log_file, "a", encoding="utf-8") as f:
# f.write(f"[{timestamp}] [{level}] {message}\n")
# f.flush()
self._output (message, level)
#pylint: disable=W0702
except:
pass # Don't crash if logging fails
#pylint: enable=W0702
def error(self, message):
''' Error log '''
self._log(message, "ERROR")
def info(self, message):
''' Info log '''
self._log(message, "INFO")
def debug(self, message):
''' Debug log '''
self._log(message, "DEBUG")
# Create global logger
debug_logger = DebugLogger()
################################################
# Metadata and file access
################################################
PANDAS_INITIALIZED = False
try:
#pylint: disable=W0611
import pandas
#pylint: enable=W0611
PANDAS_INITIALIZED = True
except ModuleNotFoundError:
pass
FOLIUM_INITIALIZED = False
FOLIUM_LOAD_ERROR = ""
try:
#pylint: disable=W0611
import folium
#pylint: enable=W0611
FOLIUM_INITIALIZED = True
except ModuleNotFoundError as mnfe:
FOLIUM_LOAD_ERROR = str(mnfe)
except ImportError as ie:
FOLIUM_LOAD_ERROR = str(ie)
def get_folium_load_error ():
''' Check for possible errors loading folium (mainly for the Android setup) '''
return FOLIUM_LOAD_ERROR
def check_folium ():
''' Check if folium is installed. Otherwise abort with exception '''
if not FOLIUM_INITIALIZED:
raise ValueError\
("Folium not available. Cannot generate maps. "+\
"Install folium with \"pip install folium\"")
def folium_initialized () -> bool:
''' Can be used to check if folium is initialized '''
return FOLIUM_INITIALIZED
def __version_warning (min_major_ver : int, min_minor_ver : int):
''' Check compatible Python version '''
def output_warning ():
print ("WARNING: You should use Python " +\
str(min_major_ver) + "." +str (min_minor_ver)+" for this toolkit!")
major_version = version_info[0]
if major_version < min_major_ver:
output_warning ()
elif major_version == min_major_ver:
minor_version = version_info[1]
if minor_version < min_minor_ver:
output_warning ()
__version_warning (3, 11)
################################################
# HTTP Server support
################################################
#pylint: disable=C0413
import threading
#pylint: enable=C0413
class MyTCPServer(socketserver.TCPServer):
''' A modified tcp server with correct connection parameters'''
def server_bind(self):
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(self.server_address)
server_address = ('', 8000)
MASTER_HTTPD = None
#pylint: disable=C0103
class MyHandler(http.server.SimpleHTTPRequestHandler):
''' A modified handler able to handle shutdown requests '''
# Track the last time ANY activity happened
last_activity_time = None # Change from time.time() to None
# last_activity_time = time.time()
def do_GET(self):
# ANY request counts as activity
# old_time = MyHandler.last_activity_time
MyHandler.last_activity_time = time.time()
#if self.path.startswith('/heartbeat'):
# if old_time is not None:
# debug_logger.info(f"Heartbeat received (was {time.time() - old_time:.1f}s ago)")
# else:
# debug_logger.info("Heartbeat received (first)")
# self.send_response(200)
# self.end_headers()
# return
#if self.path.startswith('/kill_server_delayed'):
# # Just acknowledge, don't actually schedule anything
# Real kill is based on sustained inactivity
# debug_logger.info("Kill request noted (but relying on inactivity timeout)")
# self.send_response(200)
# self.end_headers()
# return
#if self.path.startswith('/cancel_kill'):
# Reset activity timer
# MyHandler.last_activity_time = time.time()
# debug_logger.info("Activity detected")
# self.send_response(200)
# self.end_headers()
# return
#if self.path.startswith('/kill_server'):
# debug_logger.info("Server is going down, run it again manually!")
# def kill_me_please():
#pylint: disable=W0603
# global MASTER_HTTPD
#pylint: enable=W0603
# if MASTER_HTTPD and isinstance (MASTER_HTTPD, socketserver.TCPServer):
# #assert isinstance (MASTER_HTTPD, socketserver.TCPServer)
# try:
# MASTER_HTTPD.shutdown()
# MASTER_HTTPD = None
#pylint: disable=W0718
# except BaseException as _:
#pylint: enable=W0718
# pass
# t = threading.Thread(target=kill_me_please)
# t.start()
# self.send_response(200)
# self.end_headers()
# return
try:
# Only allowed requests are for these file formats
matched = False
for p in ["html", "css", "ico", "js", "png", "jpg", "jpeg", "json", "webp", "txt"]:
if self.path.lower().endswith(p):
matched = True
break
if not matched:
self.send_error(404, "Document not accessible")
super().do_GET()
debug_logger.info("GET " + self.path + " - OK")
#pylint: disable=W0718
except BaseException as be:
#pylint: enable=W0718
debug_logger.error("Http server failure : " + str(be))
#def do_POST(self):
# ''' Allow POST only for kill_server endpoints '''
# MyHandler.last_activity_time = time.time()
# if self.path.startswith('/kill_server_delayed'):
# debug_logger.info("Kill request noted (POST)")
# self.send_response(200)
# self.end_headers()
# elif self.path.startswith('/cancel_kill'):
# debug_logger.info("Activity detected (POST)")
# self.send_response(200)
# self.end_headers()
# elif self.path.startswith('/kill_server'):
# debug_logger.info("Server is going down (POST), run it again manually!")
# def kill_me_please():
# if isinstance (MASTER_HTTPD, socketserver.TCPServer):
# #assert isinstance(MASTER_HTTPD, socketserver.TCPServer)
# try:
# MASTER_HTTPD.shutdown()
#pylint: disable=W0718
# except BaseException as _:
#pylint: enable=W0718
# pass
# t = threading.Thread(target=kill_me_please)
# t.start()
# self.send_response(200)
# self.end_headers()
# else:
# self.send_error(405, "Method Not Allowed")
#pylint: enable=C0103
# def reset (self):
# self.last_activity_time = time.time()
#pylint: disable=C0103
running_http_server = None
#pylint: enable=C0103
def __run_http_server ():
port = 8000
Handler = MyHandler
try:
host_name = "127.0.0.1"
with MyTCPServer((host_name, port), Handler) as httpd:
#pylint: disable=W0603
global MASTER_HTTPD
#pylint: enable=W0603
MASTER_HTTPD = httpd
debug_logger.info("HTTP server started on port 8000")
#pylint: disable=C0415
import select
#pylint: enable=C0415
# In __run_http_server():
# Set socket to non-blocking mode
httpd.socket.setblocking(False)
# httpd.socket.settimeout (0.5)
# Manual polling loop with select
while MASTER_HTTPD is not None:
try:
# Use select to wait for incoming connection with timeout
readable, _, _ = select.select([httpd.socket], [], [], 0.5)
if readable:
debug_logger.info("Before handling a request")
httpd.handle_request()
debug_logger.info("After having handled a request")
else:
# No request pending - loop continues and checks MASTER_HTTPD
debug_logger.debug("Select timeout - checking shutdown flag")
#pylint: disable=W0718
except Exception as e:
#pylint: enable=W0718
debug_logger.error(f"HTTP request error: {e}")
debug_logger.info("HTTP server loop exited")
httpd.shutdown () # TODO Review
except OSError as ose:
if ose.errno != 98:
raise ose
debug_logger.error(f"OSError: {ose}")
#pylint: disable=W0718
except Exception as e:
#pylint: enable=W0718
debug_logger.error(f"Unexpected error in HTTP server: {e}")
finally:
debug_logger.info("HTTP server cleanup starting")
MASTER_HTTPD = None
#pylint: disable=W0603
global running_http_server
#pylint: enable=W0603
running_http_server = None
debug_logger.info("HTTP server thread terminated - running_http_server set to None")
def __run_http_server_2 ():
port = 8000
Handler = MyHandler
try:
host_name = "127.0.0.1"
with MyTCPServer((host_name, port), Handler) as httpd:
#pylint: disable=W0603
global MASTER_HTTPD
#pylint: enable=W0603
MASTER_HTTPD = httpd
debug_logger.info("HTTP server started on port 8000")
# Start the inactivity watchdog thread
#watchdog = threading.Thread(target=inactivity_watchdog, daemon=True)
#watchdog.start()
#debug_logger.info(f"Watchdog thread started: {watchdog}, daemon={watchdog.daemon}")
# httpd.serve_forever (poll_interval=0.5)
# Set socket timeout
httpd.socket.settimeout(0.5)
debug_logger.info("HTTP server started on port 8000")
# Manual polling loop instead of serve_forever
while MASTER_HTTPD is not None:
try:
debug_logger.info ("Before handling a request")
# Set socket timeout, again. TODO Review
httpd.socket.settimeout(0.5)
httpd.handle_request()
if MASTER_HTTPD is None:
debug_logger.info ("HTTP server got kill request")
else:
debug_logger.info ("After having handled a request")
except socket.timeout:
debug_logger.debug ("Socket timeout in polling loop")
continue
#pylint: disable=W0718
except Exception as e:
#pylint: enable=W0718
debug_logger.error(f"HTTP request error: {e}")
# debug_logger.info("serve_forever() exited")
debug_logger.info("HTTP server loop exited")
except OSError as ose:
if ose.errno != 98:
raise ose
debug_logger.error(f"OSError: {ose}")
#pylint: disable=W0718
except Exception as e:
#pylint: enable=W0718
debug_logger.error(f"Unexpected error in HTTP server: {e}")
finally:
debug_logger.info("HTTP server cleanup starting")
MASTER_HTTPD = None
#pylint: disable=W0603
global running_http_server
#pylint: enable=W0603
running_http_server = None
debug_logger.info("HTTP server thread terminated - running_http_server set to None")
def is_windows ():
''' Simple check for running under MS Windows '''
if os_name == 'nt':
return True
return False
def show_or_display_file (filename : str, protocol : str = "file",
kill_existing_server : bool = False) :
''' Used to display a file (typically a map) '''
if is_windows ():
protocol = "file"
cwd = os.getcwd()
absolute_path_string = cwd + "\\" + filename
filename = pathlib.Path(absolute_path_string).as_uri()
if protocol == "http":
debug_logger.debug ("Before start_http_server")
start_http_server (kill_existing=kill_existing_server)
debug_logger.debug ("After start_http_server")
# start_http_server () TODO Review
webbrowser.open ("http://localhost:8000/"+filename)
elif protocol == "file":
webbrowser.open (filename)
else:
raise ValueError ("Incorrect protocol <" + protocol + ">")
def __kill_http_server_if_running():
#pylint: disable=W0603
global running_http_server, MASTER_HTTPD
#pylint: enable=W0603
if running_http_server is not None:
if not running_http_server.is_alive ():
debug_logger.info ("HTTP server is already dead")
return
debug_logger.info("Stopping HTTP server")
MASTER_HTTPD = None
running_http_server.join(timeout=3.0)
if running_http_server is not None:
if running_http_server.is_alive():
debug_logger.error("HTTP server thread still alive")
running_http_server = None
else:
debug_logger.info ("HTTP server is already closed")
def start_http_server (kill_existing : bool = False): #TODO Maybe abolish kill_existing parameter
''' Start an http server for showing maps '''
#pylint: disable=W0603
global running_http_server
#pylint: enable=W0603
if is_windows():
return
try:
# TODO Review. Maybe unnecessary
if kill_existing:
if running_http_server is not None:
__kill_http_server_if_running ()
# TODO Review
if running_http_server is not None:
assert isinstance (running_http_server, Thread)
debug_logger.debug(f"running_http_server is a {str(type(debug_logger))}")
# debug_logger.info(f"Existing thread state: alive={running_http_server.is_alive()}")
# Check if server thread exists AND is still alive
old_server_alive = running_http_server is not None # and running_http_server.is_alive()
#if running_http_server is None or not running_http_server.is_alive():
if not old_server_alive:
#if running_http_server is not None:
# debug_logger.info("Old server thread dead, starting new one")
# Give the old thread a moment to fully clean up
# time.sleep(1)
#else:
debug_logger.info("No existing server thread, starting new one")
p = Thread (target=__run_http_server)
p.start()
running_http_server = p
debug_logger.info(f"New server thread started: {p}")
else:
debug_logger.info("Server thread already running and alive")
#pylint: disable=W0702
#pylint: disable=W0718
except Exception as e:
#pylint: enable=W0718
debug_logger.info(f"Error in start_http_server: {e}")
#pylint: enable=W0702
# __start_http_server ()
def http_server_running () -> bool:
''' Check if there is a http server running '''
return running_http_server is not None
# def exit_handler ():
def kill_http_server ():
''' Can be used on program/app exit '''
__kill_http_server_if_running ()
def is_online(timeout=3):
"""Check if internet is available by testing DNS resolution"""
try:
# Try to resolve a reliable hostname
socket.setdefaulttimeout(timeout)
socket.gethostbyname("google.com") # Google server
return True
except (socket.gaierror, socket.timeout, OSError):
return False
finally:
socket.setdefaulttimeout(None) # Reset to default
def is_online_safe(timeout=2):
"""
Check if internet is available
Uses dedicated socket to avoid global state mutation
Short timeout for reliability
"""
test_socket = None
try:
test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
test_socket.settimeout(timeout)
test_socket.connect(("8.8.8.8", 53))
# Shutdown before close (forces immediate cleanup)
try:
test_socket.shutdown(socket.SHUT_RDWR) # ← Force immediate shutdown
#pylint: disable=W0702
except:
pass # Already closed or not connected
#pylint: enable=W0702
test_socket.close()
return True
except (socket.timeout, socket.error, OSError):
return False
finally:
if test_socket is not None:
try:
# Shutdown first (non-blocking)
test_socket.shutdown(socket.SHUT_RDWR)
#pylint: disable=W0702
except:
pass # Socket not connected or already shut down
#pylint: enable=W0702
try:
test_socket.close()
#pylint: disable=W0702
except:
pass
#pylint: enable=W0702
################################################
# Basic generation of folium maps and tile handling
################################################
def get_folium_map_safe (location : list | tuple,
zoom_start_offline : int = 2,
zoom_start_online : int = 11,
max_zoom : int = 15) -> object:
'''
Generate a map object
Tries online first for detail, falls back to offline for reliability
'''
# pylint: disable=C0415
from folium import raster_layers, Map
# pylint: enable=C0415
# Try online first (with timeout on entire operation)
result: list[Optional[object]] = [None] # Use list for mutability in closure
def try_online_map():
try:
if is_online_safe(timeout=1):
the_map = Map(location=location,
zoom_start=zoom_start_online,
max_zoom=max_zoom)
result[0] = the_map
#pylint: disable=W0702
except:
pass
#pylint: enable=W0702
# Run with timeout (prevent Folium from hanging)
online_thread = threading.Thread(target=try_online_map, daemon=True)
online_thread.start()
online_thread.join(timeout=3.0) # Max 3 seconds for online map
if result[0] is not None:
return result[0] # Online map succeeded!
# Offline map (reliable fallback)
base_url = "http://localhost:8000/tiles"
tiles_url = f"{base_url}/{{z}}/{{x}}/{{y}}.png"
the_map = Map(location=location,
zoom_start=zoom_start_offline,
tiles=None,
max_zoom=max_zoom)
raster_layers.TileLayer(
tiles=tiles_url,
attr='Map data courtesy of U.S. Geological Survey | Offline tiles',
name='Offline Map',
overlay=False,
control=True,
max_native_zoom=zoom_start_offline,
max_zoom=max_zoom
).add_to(the_map)
return the_map
################################################
# Dimension of Earth
################################################
EARTH_CIRCUMFERENCE_EQUATORIAL = 40075.017
EARTH_CIRCUMFERENCE_MERIDIONAL = 40007.86
EARTH_CIRCUMFERENCE = (EARTH_CIRCUMFERENCE_EQUATORIAL*2 + EARTH_CIRCUMFERENCE_MERIDIONAL) / 3
EARTH_RADIUS = EARTH_CIRCUMFERENCE / (2 * pi)
WGS84_A = 6378.137 # km, semi-major axis
WGS84_F = 1.0 / 298.257223563 # flattening
WGS84_B = WGS84_A * (1 - WGS84_F) # semi-minor axis
WGS84_E2 = 2 * WGS84_F - WGS84_F**2 # First eccentricity squared
WGS84_EP2 = WGS84_E2 / (1 - WGS84_E2) # Second eccentricity squared
EARTH_RADIUS_GEODETIC_EQUATORIAL = WGS84_A
EARTH_RADIUS_GEODETIC_POLAR = WGS84_B
EARTH_FLATTENING = WGS84_F
################################################
# Basic maths
################################################
def acos2 (x : float, a : float) -> float:
""" A numerically stable routine for acos(cos(x)*a)"""
y = atan2(sqrt(1 - (cos(x) * a)**2), cos(x) * a)
return y
################################################
# Data types
################################################
class LatLon:
''' General baseclass for latlon coordinates '''
def __init__ (self, lat : float | int, lon : float | int):
if lat > 90 or lat < -90:
raise ValueError ("Latitude must be between -90 and 90.")
self.__lat = lat
self.__lon = mod_lon(lon)
def get_tuple (self) -> tuple[float | int, float | int] :
''' Used to simplify some code where tuples are more practical '''
return self.__lon, self.__lat
def get_lat (self) -> int | float:
''' Returns the latitude '''
return self.__lat
def get_lon (self) -> int | float:
''' Returns the longitude '''
return self.__lon
class LatLonGeocentric (LatLon):
''' Represents spherical coordinates on Earth '''
def __str__(self):
return "(Geocentric) LAT = " +\
str(round(self.get_lat(),4)) +\
"; LON = " + str(round(self.get_lon(),4))
################################################
# Utility routines (algrebraic, spheric geometry)
################################################
def add_vecs (vec1 : list[float], vec2 : list[float]) -> list[float]:
''' Performs addition of two cartesian vectors '''
assert len (vec1) == len (vec2)
retval = list [float] ()
for i, v in enumerate(vec1):
retval.append (v + vec2[i])
return retval
def subtract_vecs (vec1 : list[float], vec2 : list[float]) -> list [float]:
''' Performs subtraction of two cartesian vectors '''
assert len (vec1) == len (vec2)
return add_vecs (vec1, mult_scalar_vect(-1, vec2))
def mult_scalar_vect (scalar : int | float, vec : list [float]) -> list [float]:
''' Performs multiplication of a cartesian vector with a scalar '''
retval = list [float] ()
for v in vec:
retval.append (scalar*v)
return retval
def length_of_vect (vec : list [float]) -> float:
''' Returns the absolute value (length) of a vector '''
s = 0
for v in vec:
s += v*v
return sqrt (s)
def normalize_vect (vec : list [float]) -> list [float]:
''' Computes |vec| '''
len_v = length_of_vect (vec)
assert len_v > 0
return mult_scalar_vect (1/len_v, vec)
def cross_product (vec1 : list [float], vec2 : list [float]) -> list [float]:
''' Computes vec1 x vec2 (cross product) '''
assert len (vec1) == len (vec2) == 3
retval = [0.0, 0.0, 0.0]
retval [0] = vec1 [1]*vec2[2] - vec1[2]*vec2[1]
retval [1] = vec1 [2]*vec2[0] - vec1[0]*vec2[2]
retval [2] = vec1 [0]*vec2[1] - vec1[1]*vec2[0]
return retval
def dot_product (vec1 : list [float], vec2 : list [float]) -> float:
''' Computes vec1 * vec2 (dot product) '''
assert len (vec1) == len (vec2)
s = 0.0
for i, v1 in enumerate (vec1):
s += v1*vec2[i]
return s
def mod_lon (lon : int | float) -> int | float:
''' Transforms a longitude value to the range (-180,180) '''
x = lon + 180
x = x % 360
x = x - 180
return x
def deg_to_rad (deg : int | float) -> float:
''' Convert degrees to radians '''
return deg/(180.0/pi)
def rad_to_deg (rad : int | float) -> float:
''' Convert radians to degrees '''
return rad*(180.0/pi)
def to_latlon (vec : list [float]) -> LatLonGeocentric:
''' Convert cartesian coordinate to LatLon (spherical) '''
assert len (vec) == 3
vec = normalize_vect (vec)
theta = atan2 (vec[1],vec[0])
phi = acos (vec[2])
lon = rad_to_deg (theta)
lat = 90-rad_to_deg (phi)
return LatLonGeocentric (lat, mod_lon(lon))
def to_rectangular (latlon : LatLon) -> list [float]:
''' Convert LatLon (spherical) coordinate to cartesian '''
phi = deg_to_rad (90 - latlon.get_lat())
theta = deg_to_rad (latlon.get_lon())
a_vec = list [float] ()
a_vec.append (cos (theta) * sin (phi))
a_vec.append (sin (theta) * sin (phi))
a_vec.append (cos (phi))
a_vec = normalize_vect (a_vec)
return a_vec
def get_dms (angle : int | float) -> tuple[int, int, int | float]:
''' Convert an angle (in degrees) to a tuple of degrees, arc minutes and arc seconds '''
degrees = int (angle)
minutes = abs(int ((angle-degrees)*60))
seconds = abs((angle-degrees-minutes/60)*3600)
return degrees, minutes, seconds
def get_dm (angle : int | float) -> tuple[int, int | float]:
''' Convert an angle (in degrees) to a tuple of degrees and arc minutes '''
degrees = int (angle)
minutes = abs((angle-degrees)*60)
return degrees, minutes
def get_decimal_degrees (degrees : int | float, minutes : int | float, seconds : int | float)\
-> float:
''' Return decimal value for an angle (from degrees+minutes+seconds) '''
if degrees < 0:
minutes = -minutes
seconds = -seconds
return degrees + minutes/60 + seconds/3600
def get_decimal_degrees_from_tuple (t : tuple) -> float:
''' Return decimal value for an angle, represented as a tuple (degrees, minutes, seconds)'''
return get_decimal_degrees (t[0], t[1], t[2])
def rotate_vector_2 (vec : list [float], rot_vec : list [float],
angle_radians : float, tolerance : float =1e-15):
'''
Rotate a vector around a rotation vector. Based on Rodrigues formula.
https://en.wikipedia.org/wiki/Rodrigues%27_formula
'''
assert len(vec) == len(rot_vec) == 3
if abs(angle_radians) < tolerance:
return vec.copy()
# Ensure axis is normalized
axis_norm = normalize_vect(rot_vec)
cos_theta = cos(angle_radians)
sin_theta = sin(angle_radians)
# Rodrigues formula with explicit computation
axis_dot_vec = dot_product(axis_norm, vec)
cross_axis_vec = cross_product(axis_norm, vec)
result = [
vec[i] * cos_theta +
cross_axis_vec[i] * sin_theta +
axis_norm[i] * axis_dot_vec * (1.0 - cos_theta)
for i in range(3)
]
return result
def squeeze (val : float, min_val : float, max_val : float) -> float :
''' Used to limit a value in a range/interval '''
if val > max_val:
return max_val
if val < min_val:
return min_val
return val
################################################
# Course management
################################################
def mod_course (lon : int | float) -> float:
''' Transform a course angle into the compass range of (0,360) '''
x = lon % 360
return x
def takeout_course (latlon : LatLonGeocentric, course : int | float, speed_knots : int | float,
time_hours : int | float) -> LatLonGeocentric:
''' Calculates a trip movement. Simplified formula, not using great circles '''
distance = speed_knots * time_hours
distance_degrees = distance / 60
# The "stretch" is just taking care of narrowing longitudes on higher latitudes
stretch_at_start = cos (deg_to_rad (latlon.get_lat()))
diff_lat = cos (deg_to_rad(course))*distance_degrees
diff_lon = sin (deg_to_rad(course))*distance_degrees/stretch_at_start
return LatLonGeocentric (latlon.get_lat()+diff_lat, latlon.get_lon()+diff_lon)
def angle_b_points (latlon1 : LatLon, latlon2 : LatLon) -> float:
''' Calculates the angle between two points on Earth
Return : Angle in radians '''
normvec1 = to_rectangular (latlon1)
normvec2 = to_rectangular (latlon2)
dp = dot_product (normvec1, normvec2)
# Taking care of occasional rounding errors.
# acos breaks if the |dp| is something like 1.000000000000001
# Thanks to https://github.com/0dB for finding this bug.
dp = squeeze (dp, -1, 1)
angle = acos (dp)
return angle
def spherical_distance (latlon1 : LatLon, latlon2 : LatLon) -> float:
''' Calculate distance between two points in km. Using great circles '''
angle = angle_b_points (latlon1, latlon2)
distance = EARTH_RADIUS * angle
return distance
def km_to_nm (km : int | float) -> float:
''' Convert from kilometers to nautical miles '''
return (km / EARTH_CIRCUMFERENCE)*360*60
def nm_to_km (nm : int | float) -> float:
''' Convert from nautical miles to kilometers '''
return (nm/(360*60))*EARTH_CIRCUMFERENCE
################################################
# Sextant calibration
################################################
#pylint: disable=R0903
class Sextant:
''' This class represents a physical sextant, with various errors '''
def __init__ (self,
graduation_error : float = 1.0,
index_error : int | float = 0):
""" Parameters
graduation_error : ratio between read and actual altitude. (Linear relation)
Use 1.0 for the same values.
index_error : Error in arcminutes. (Fixed error)
"""
self.graduation_error = graduation_error
self.index_error = index_error
#pylint: enable=R0903
def angle_between_points (origin : LatLonGeocentric,
point1 : LatLonGeocentric, point2 : LatLonGeocentric) -> float:
''' Return the angle in degrees between two terrestrial targets (point1 and point2)
as seen from the observation point (origin) '''
origin_r = to_rectangular (origin)
point_1r = to_rectangular (point1)
point_2r = to_rectangular (point2)
point_1gc = normalize_vect (cross_product (origin_r, point_1r))
point_2gc = normalize_vect (cross_product (origin_r, point_2r))
dp = dot_product (point_1gc, point_2gc)
return acos (dp) * (180 / pi)
################################################
# Chronometer
################################################
class Chronometer: # pylint: disable=R0903
''' This class represents a chronometer (clock) with known error/drift '''
def __init__ (self, set_time : str, set_time_deviation_seconds : int | float,
drift_sec_per_day : int | float):
self.set_time = datetime.fromisoformat(set_time)
self.set_time_deviation_seconds = set_time_deviation_seconds
self.drift_sec_per_day = drift_sec_per_day
def get_corrected_time (self, measured_time : datetime) -> datetime:
''' Calculate proper time based on a measured time '''
st1 = int(self.set_time.timestamp())
mt1 = int(measured_time.timestamp())
diff_days = (mt1 - st1) / (24*3600)
drift = diff_days * self.drift_sec_per_day
mt_corr = mt1 - drift
return datetime.fromtimestamp (mt_corr, tz = measured_time.tzinfo)
# pylint: enable=R0903
################################################
# Horizon
################################################
def get_adjusted_earth_radius (temperature : float = 10,
dt_dh : float = -0.01, pressure : float = 101) -> float:
''' Calculate the modified earth radius as a result of refraction
Returns : The adjusted radius in km
'''
if Testing.disable_refraction_handling:
return EARTH_RADIUS
k_factor = 503*(pressure*10)*(1/((temperature+273)**2))*(0.0343 + dt_dh)
r = EARTH_RADIUS
return r / (1 - k_factor)
def get_dip_of_horizon (hm : int | float, temperature : float = 10,
dt_dh : float = -0.01, pressure : float = 101)\
-> float:
''' Calculate dip of horizon in arc minutes
Parameters:
hm : height in meters
temperature : temperature in degrees Celsius
dt_th : temperature gradient in degrees Celsius / meter
'''
rr = get_adjusted_earth_radius (temperature, dt_dh, pressure)
h = hm / 1000
the_dip = (acos (rr/(rr+h)))*(180/pi)*60
return the_dip
def get_line_of_sight (h1 : float, h2 : float, temperature : float = 10,
dt_dh : float = -0.01, pressure : float = 101) -> float:
''' Geometry for line-of-sight '''
rr = get_adjusted_earth_radius (temperature, dt_dh, pressure) * 1000
x1a = sqrt (((rr + h1)**2) - rr**2)
x1r = atan2 (x1a, rr)
x1 = x1r * rr
x2a = sqrt (((rr + h2)**2) - rr**2)
x2r = atan2 (x2a, rr)
x2 = x2r * rr
return x1 + x2