-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdistlink.py
More file actions
1532 lines (1354 loc) · 56.1 KB
/
Copy pathdistlink.py
File metadata and controls
1532 lines (1354 loc) · 56.1 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
"""Minimum orbit intersection distance and linking coefficients.
This is a source-level Python translation of ``distlink-cpp/distlink.cpp`` by
R. V. Baluev and D. V. Mikryukov (2018-2020). The original and this port are
distributed under the MIT license reproduced below.
Copyright (c) 2018-2020 R.V. Baluev and D.V. Mikryukov
Copyright (c) 2026 Troy D. Rockwood (Python translation and modifications)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
The public names intentionally follow the C++ API. Python ``float`` is used
throughout and therefore corresponds to the C++ ``double`` instantiation.
"""
from __future__ import annotations
from dataclasses import dataclass
import cmath
import math
import sys
import time
from typing import Callable, Sequence
DIM = 21
DEG = 16
_PI = math.pi
_CIRC = 2.0 * math.pi
_EPS = sys.float_info.epsilon
_EXPS = tuple(cmath.rect(1.0, 2.0 * j * math.pi / DIM) for j in range(DIM))
_UINT64_MASK = (1 << 64) - 1
class _DeterministicRandom:
"""SplitMix64 stream matching the C++ implementation exactly."""
__slots__ = ("state",)
def __init__(self) -> None:
self.state = 0x243F6A8885A308D3
def next(self) -> float:
self.state = (self.state + 0x9E3779B97F4A7C15) & _UINT64_MASK
value = self.state
value = ((value ^ (value >> 30)) * 0xBF58476D1CE4E5B9) & _UINT64_MASK
value = ((value ^ (value >> 27)) * 0x94D049BB133111EB) & _UINT64_MASK
value ^= value >> 31
return (value >> 11) * (2.0 ** -53)
def _sqr(x):
return x * x
def _sign(x: float) -> int:
return int(x > 0.0) - int(x < 0.0)
def _safe_asin(x: float) -> float:
return math.asin(max(min(x, 1.0), -1.0))
def _safe_sqrt(x: float) -> float:
return math.sqrt(max(x, 0.0))
def _safe_acosh(x: float) -> float:
return math.acosh(max(x, 1.0))
def _sqrt_ieee(x: float) -> float:
"""Return sqrt with the NaN-on-negative behavior of C++ libm."""
return math.sqrt(x) if x >= 0.0 else math.nan
def _float_divide(numerator: float, denominator: float) -> float:
"""Emulate ordinary IEEE-754 division where Python would raise on zero."""
if denominator != 0.0:
return numerator / denominator
if numerator == 0.0 or math.isnan(numerator):
return math.nan
sign = math.copysign(1.0, numerator) * math.copysign(1.0, denominator)
return math.copysign(math.inf, sign)
def _log_abs(x: float) -> float:
return -math.inf if x == 0.0 else math.log(abs(x))
def _atan2h(y: float, x: float) -> float:
return (_log_abs(x + y) - _log_abs(x - y)) / 2.0
def _atan2_smart(y: float, x: float, trig: bool) -> float:
return math.atan2(y, x) if trig else _atan2h(y, x)
def _dot(a: Sequence[float], b: Sequence[float]) -> float:
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def _cross(a: Sequence[float], b: Sequence[float]) -> tuple[float, float, float]:
return (
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
)
def _vnorm(a: Sequence[float]) -> float:
return _dot(a, a)
def _cnorm(z: complex) -> float:
return z.real * z.real + z.imag * z.imag
def _inverse(z: complex) -> complex:
return z.conjugate() / _cnorm(z)
def _angle_wrap(x: float) -> float:
x = math.fmod(x + _PI, _CIRC)
return x + _PI if x < 0.0 else x - _PI
def detect_suitable_options() -> tuple[float, float, float]:
"""Return ``(max_root_error, min_root_error, max_anom_error)``.
This is the Python-float equivalent of the C++ template function.
"""
return math.sqrt(_EPS), 2.0 * _EPS, 1000.0 * _EPS
class COrbitData:
"""Keplerian elements and the associated orthonormal P/Q vectors."""
__slots__ = ("_a", "_e", "_i", "_w", "_Om", "_P", "_Q")
def __init__(
self,
a: float = 1.0,
e: float = 0.0,
i: float = 0.0,
w: float = 0.0,
Om: float = 0.0,
) -> None:
self.set_data(a, e, i, w, Om)
def set_data(self, a: float, e: float, i: float, w: float, Om: float) -> None:
a, e, i, w, Om = (float(value) for value in (a, e, i, w, Om))
if not all(math.isfinite(value) for value in (a, e, i, w, Om)):
raise ValueError("orbital elements must be finite")
if a == 0.0:
raise ValueError("semimajor axis must be nonzero")
if e < 0.0:
raise ValueError("eccentricity must be nonnegative")
if e == 1.0:
raise ValueError("parabolic orbits (e == 1) are unsupported")
self._a = abs(a) if e < 1.0 else -abs(a)
self._e, self._i, self._w, self._Om = e, i, w, Om
self._set_vectors()
def _set_vectors(self) -> None:
cw, sw = math.cos(self._w), math.sin(self._w)
cO, sO = math.cos(self._Om), math.sin(self._Om)
ci, si = math.cos(self._i), math.sin(self._i)
self._P = (
cw * cO - ci * sw * sO,
cw * sO + ci * sw * cO,
si * sw,
)
self._Q = (
-sw * cO - ci * cw * sO,
ci * cw * cO - sw * sO,
si * cw,
)
def get_data(self) -> tuple[float, float, float, float, float]:
return self._a, self._e, self._i, self._w, self._Om
def get_a(self) -> float:
return self._a
def get_e(self) -> float:
return self._e
def get_i(self) -> float:
return self._i
def get_w(self) -> float:
return self._w
def get_Om(self) -> float:
return self._Om
def vectorP(self) -> tuple[float, float, float]:
return self._P
def vectorQ(self) -> tuple[float, float, float]:
return self._Q
def get_vectors(self) -> tuple[tuple[float, float, float], tuple[float, float, float]]:
return self._P, self._Q
def __repr__(self) -> str:
values = ", ".join(repr(v) for v in self.get_data())
return f"COrbitData({values})"
def test_peri_apo(O1: COrbitData, O2: COrbitData, limit: float) -> bool:
a1, e1 = O1.get_a(), O1.get_e()
a2, e2 = O2.get_a(), O2.get_e()
rp1, ra1 = a1 * (1.0 - e1), a1 * (1.0 + e1)
rp2, ra2 = a2 * (1.0 - e2), a2 * (1.0 + e2)
return rp1 - ra2 < limit and rp2 - ra1 < limit
@dataclass(slots=True)
class SMOIDResult:
good: bool = True
distance: float = -1.0
distance_error: float = 0.0
u1: float = math.nan
u1_error: float = 0.0
u2: float = math.nan
u2_error: float = 0.0
root_count: int = 0
min_delta: float = -1.0
iter_count: int = 0
iter_count_2D: int = 0
time: float = 0.0
@dataclass(slots=True)
class SLCResult:
I: float = -1.0
l: float = 0.0
lmod: float = 0.0
l2: float = 0.0
class _AuxData:
__slots__ = (
"e1", "e2", "a1", "a2", "alpha1", "alpha2", "K",
"Pp", "Ps", "Sp", "Ss", "p1", "p2", "w1", "w2", "I",
"abs_w", "P1w", "P2w", "Q1w", "Q2w", "P1", "P2", "Q1", "Q2",
)
def __init__(self, O1: COrbitData, O2: COrbitData) -> None:
self.e1, self.e2 = O1.get_e(), O2.get_e()
self.a1, self.a2 = O1.get_a(), O2.get_a()
self.w1, self.w2 = O1.get_w(), O2.get_w()
self.p1 = self.a1 * (1.0 - self.e1 * self.e1)
self.p2 = self.a2 * (1.0 - self.e2 * self.e2)
self.alpha1, self.alpha2 = self.a1 / self.a2, self.a2 / self.a1
self.K = self.alpha2 * self.e2 * self.e2
eta1 = math.sqrt(abs(1.0 - self.e1 * self.e1))
eta2 = math.sqrt(abs(1.0 - self.e2 * self.e2))
i1, i2 = O1.get_i(), O2.get_i()
Om1, Om2 = O1.get_Om(), O2.get_Om()
c1, s1 = math.cos(i1), math.sin(i1)
c2, s2 = math.cos(i2), math.sin(i2)
wv = (
c1 * s2 * math.cos(Om2) - s1 * c2 * math.cos(Om1),
c1 * s2 * math.sin(Om2) - s1 * c2 * math.sin(Om1),
s1 * s2 * math.sin(Om2 - Om1),
)
self.abs_w = math.sqrt(_vnorm(wv))
cosI = c1 * c2 + s1 * s2 * math.cos(Om2 - Om1)
self.I = _safe_asin(self.abs_w) if cosI > 0.0 else _PI - _safe_asin(self.abs_w)
self.P1, self.P2 = O1.vectorP(), O2.vectorP()
self.Q1, self.Q2 = O1.vectorQ(), O2.vectorQ()
self.Pp = _dot(self.P1, self.P2)
self.Ps = _dot(self.P1, self.Q2) * eta2
self.Sp = _dot(self.Q1, self.P2) * eta1
self.Ss = _dot(self.Q1, self.Q2) * eta1 * eta2
self.P1w, self.P2w = _dot(self.P1, wv), _dot(self.P2, wv)
self.Q1w, self.Q2w = _dot(self.Q1, wv), _dot(self.Q2, wv)
def _l2(data: _AuxData) -> float:
f1 = data.p2 * (data.abs_w + data.e1 * data.P1w) - data.p1 * (
data.abs_w + data.e2 * data.P2w
)
f2 = data.p2 * (data.abs_w - data.e1 * data.P1w) - data.p1 * (
data.abs_w - data.e2 * data.P2w
)
return f1 * f2
def _l1(data: _AuxData) -> tuple[float, float]:
costheta1 = _float_divide(data.P1w, data.abs_w)
costheta2 = _float_divide(data.P2w, data.abs_w)
rr = data.p1 / (1.0 + data.e1 * costheta1) - data.p2 / (
1.0 + data.e2 * costheta2
)
RR = data.p1 / (1.0 - data.e1 * costheta1) - data.p2 / (
1.0 - data.e2 * costheta2
)
product = rr * RR
smaller = RR if abs(RR) < abs(rr) else rr
return product, smaller * smaller * _sign(product)
def _l3(data: _AuxData) -> float:
return (
data.a1 * data.p1
+ data.a2 * data.p2
- 2.0
* data.a1
* data.a2
* (1.0 - data.e1 * data.e2 * math.cos(data.w1 - data.w2))
)
def LC(O1: COrbitData, O2: COrbitData, min_mut_incl: float) -> SLCResult:
if not math.isfinite(min_mut_incl) or min_mut_incl < 0.0:
raise ValueError("minimum mutual inclination must be finite and nonnegative")
data = _AuxData(O1, O2)
result = SLCResult(I=data.I, l2=_l2(data))
if data.I < min_mut_incl or data.abs_w <= math.sqrt(_EPS):
result.l = _l3(data)
else:
result.l, result.lmod = _l1(data)
return result
def _radius_vector(
branch: bool,
P: Sequence[float],
Q: Sequence[float],
a: float,
e: float,
u: float,
) -> tuple[float, float, float]:
if e <= 1.0:
p, q = math.cos(u), math.sin(u) * math.sqrt(1.0 - e * e)
else:
tmp = math.exp(abs(u))
p = (tmp + 1.0 / tmp) / 2.0
q = (1.0 / tmp - tmp) / 2.0 * _sign(u) * math.sqrt(e * e - 1.0)
if not branch:
p, q = -p, -q
p -= e
return tuple(a * (P[k] * p + Q[k] * q) for k in range(3)) # type: ignore[return-value]
def _radius_vector_valder(
branch: bool,
P: Sequence[float],
Q: Sequence[float],
a: float,
e: float,
u: float,
) -> tuple[tuple[float, float, float], tuple[float, float, float]]:
if e <= 1.0:
x, y = math.cos(u), math.sin(u)
eta = math.sqrt(1.0 - e * e)
h = x * eta
else:
tmp = math.exp(abs(u))
x, y = (tmp + 1.0 / tmp) / 2.0, (1.0 / tmp - tmp) / 2.0 * _sign(u)
eta = math.sqrt(e * e - 1.0)
h = -x * eta
if not branch:
x, y, h = -x, -y, -h
p, q = x - e, y * eta
r = tuple(a * (P[k] * p + Q[k] * q) for k in range(3))
rd = tuple(-P[k] * y + Q[k] * h for k in range(3))
return r, rd # type: ignore[return-value]
def _radius_vector_valder2(
branch: bool,
P: Sequence[float],
Q: Sequence[float],
a: float,
e: float,
u: float,
) -> tuple[
tuple[float, float, float],
tuple[float, float, float],
tuple[float, float, float],
]:
if e <= 1.0:
x, y = math.cos(u), math.sin(u)
eta = math.sqrt(1.0 - e * e)
h = x * eta
else:
tmp = math.exp(abs(u))
x, y = (tmp + 1.0 / tmp) / 2.0, (1.0 / tmp - tmp) / 2.0 * _sign(u)
eta = math.sqrt(e * e - 1.0)
h = -x * eta
if not branch:
x, y, h = -x, -y, -h
p, q = x - e, y * eta
r = tuple(a * (P[k] * p + Q[k] * q) for k in range(3))
rd = tuple(-P[k] * y + Q[k] * h for k in range(3))
rdd = tuple(P[k] * x + Q[k] * q for k in range(3))
if e <= 1.0:
rdd = tuple(-v for v in rdd)
return r, rd, rdd # type: ignore[return-value]
def _distance_between(data: _AuxData, br1: bool, br2: bool, u1: float, u2: float) -> float:
r1 = _radius_vector(br1, data.P1, data.Q1, data.a1, data.e1, u1)
r2 = _radius_vector(br2, data.P2, data.Q2, data.a2, data.e2, u2)
dr = tuple(r2[k] - r1[k] for k in range(3))
return math.sqrt(_vnorm(dr))
def _sqdist_vg(
data: _AuxData, br1: bool, br2: bool, u1: float, u2: float
) -> tuple[float, list[float]]:
r1, rd1 = _radius_vector_valder(br1, data.P1, data.Q1, data.a1, data.e1, u1)
r2, rd2 = _radius_vector_valder(br2, data.P2, data.Q2, data.a2, data.e2, u2)
dr = tuple(r2[k] - r1[k] for k in range(3))
g = [-_dot(dr, rd1) / data.a2, _dot(dr, rd2) / data.a1]
return _vnorm(dr) / (2.0 * data.a1 * data.a2), g
def _sqdist_vgH(
data: _AuxData, br1: bool, br2: bool, u1: float, u2: float
) -> tuple[float, list[float], list[float]]:
r1, rd1, rdd1 = _radius_vector_valder2(
br1, data.P1, data.Q1, data.a1, data.e1, u1
)
r2, rd2, rdd2 = _radius_vector_valder2(
br2, data.P2, data.Q2, data.a2, data.e2, u2
)
dr = tuple(r2[k] - r1[k] for k in range(3))
g = [-_dot(dr, rd1) / data.a2, _dot(dr, rd2) / data.a1]
H = [
(-_dot(dr, rdd1) + _vnorm(rd1) * data.a1) / data.a2,
(_dot(dr, rdd2) + _vnorm(rd2) * data.a2) / data.a1,
-_dot(rd1, rd2),
]
return _vnorm(dr) / (2.0 * data.a1 * data.a2), g, H
def _eliminated_anomaly(
data: _AuxData, u1: float, coefficient_error: float | None = None
) -> tuple[bool, float, float, float | None]:
if data.e1 <= 1.0:
x, y = math.cos(u1), math.sin(u1)
x_ = x - data.e1
M = data.Sp * y + data.Pp * x_ + data.alpha2 * data.e2
N = -data.Ss * y - data.Ps * x_
else:
tmp = math.exp(abs(u1))
x, y = (tmp + 1.0 / tmp) / 2.0, (tmp - 1.0 / tmp) / 2.0 * _sign(u1)
x_ = x - data.e1
M = -data.Sp * y + data.Pp * x_ + data.alpha2 * data.e2
N = data.Ss * y - data.Ps * x_
A = data.Ps * y - data.Ss * x
B = data.Pp * y - data.Sp * x
C = data.e2 * B - data.alpha1 * data.e1 * y * (1.0 - data.e1 * x)
if data.e2 <= 1.0:
V, D = A * A + B * B, A * A + B * B - C * C
else:
V, D = B * B - A * A, C * C - (B * B - A * A)
negative_discriminant = D < 0.0
if negative_discriminant:
D = 0.0
if data.e2 <= 1.0:
u2 = math.atan2(A, B) if C > 0.0 else math.atan2(-A, -B)
else:
u2 = _atan2h(A, B)
u2_other = u2
else:
D = math.sqrt(D)
AC, BD = A * C, B * D
y1, y2 = (AC - BD) / V, (AC + BD) / V
if not data.e2 <= 1.0:
y1, y2 = y2, y1
BC, AD = B * C, A * D
x1, x2 = (BC + AD) / V, (BC - AD) / V
if data.e2 <= 1.0:
u2, u2_other = math.atan2(y1, x1), math.atan2(y2, x2)
else:
if not x1 > 0.0 and x2 > 0.0:
x1, x2, y1, y2 = x2, x1, y2, y1
u2, u2_other = _atan2h(y1, x1), _atan2h(y2, x2)
err = M * y1 + N * x1 - data.K * y1 * x1
err_other = M * y2 + N * x2 - data.K * y2 * x2
if not abs(err) < abs(err_other) and (data.e2 <= 1.0 or x2 > 0.0):
u2, u2_other = u2_other, u2
if coefficient_error is not None:
sigma = coefficient_error * math.sqrt(
1.0 + data.e2 * data.e2 + _sqr(data.alpha1 * data.e1)
)
coefficient_error = sigma / math.sqrt(D * D + abs(C) * sigma / 2.0)
return negative_discriminant, u2, u2_other, coefficient_error
def _min_distance_for(
data: _AuxData, u1: float, coefficient_error: float | None = None
) -> tuple[float, float, float | None]:
failed, u2, u2_other, coefficient_error = _eliminated_anomaly(
data, u1, coefficient_error
)
if failed:
return -_distance_between(data, True, True, u1, u2), u2, coefficient_error
d = _distance_between(data, True, True, u1, u2)
d_other = _distance_between(data, True, True, u1, u2_other)
return (d, u2, coefficient_error) if d < d_other else (
d_other,
u2_other,
coefficient_error,
)
def _sqdist_2Diter(
data: _AuxData, br1: bool, br2: bool, u1: float, u2: float
) -> tuple[float, float, float, list[float], list[float], float]:
rho, g, H = _sqdist_vgH(data, br1, br2, u1, u2)
detH = H[0] * H[1] - H[2] * H[2]
if detH == 0.0:
return u1, u2, 0.0, g, H, detH
du1 = -(H[1] * g[0] - H[2] * g[1]) / detH
du2 = -(H[0] * g[1] - H[2] * g[0]) / detH
return u1 + du1, u2 + du2, du1 * du1 + du2 * du2, g, H, detH
def _newton_sqdist(
data: _AuxData, u1: float, u2: float, eps: float, maxcount: int
) -> tuple[int, float, float, float, float, float, int, list[float], list[float]]:
err2 = math.inf
iter_count = 0
detH = math.nan
H = [math.nan, math.nan, math.nan]
g = [math.nan, math.nan]
while True:
u1, u2, next_err2, g, H, detH = _sqdist_2Diter(data, True, True, u1, u2)
if data.e1 <= 1.0 and abs(u1) > _PI:
u1 = _angle_wrap(u1)
if data.e2 <= 1.0 and abs(u2) > _PI:
u2 = _angle_wrap(u2)
if detH == 0.0:
break
derr2 = err2 - next_err2
err2 = next_err2
iter_count += 1
if not (derr2 > _EPS * err2 and err2 > eps * eps and iter_count <= maxcount):
break
rho, g = _sqdist_vg(data, True, True, u1, u2)
if detH == 0.0:
u1_error = u2_error = rho_error = 0.0
if H[0] > 0.0 or H[1] > 0.0:
sign_H = 1
elif H[0] < 0.0 or H[1] < 0.0:
sign_H = -1
else:
sign_H = 0
else:
u1_error = abs((H[1] * g[0] - H[2] * g[1]) / detH)
u2_error = abs((H[0] * g[1] - H[2] * g[0]) / detH)
rho_error = abs(
(H[1] * g[0] * g[0] + H[0] * g[1] * g[1] - 2.0 * H[2] * g[0] * g[1])
/ (2.0 * detH)
)
if detH > 0.0 and H[0] > 0.0:
sign_H = 2
elif detH > 0.0 and H[0] < 0.0:
sign_H = -2
else:
sign_H = 0
return sign_H, u1, u2, u1_error, u2_error, rho, rho_error, iter_count, g, H
def _restrict_search_range_aux(data: _AuxData) -> list[tuple[float, float]]:
if data.abs_w <= math.sqrt(_EPS):
if data.e1 < 1.0:
return [(-_PI, _PI)]
raise ValueError("cannot bound a coplanar hyperbolic anomaly range")
theta1, theta2 = math.atan2(data.Q1w, data.P1w), math.atan2(data.Q2w, data.P2w)
costheta1, costheta2 = math.cos(theta1), math.cos(theta2)
rp = data.p1 / (1.0 + data.e1 * costheta1)
rm = data.p1 / (1.0 - data.e1 * costheta1)
Rp = data.p2 / (1.0 + data.e2 * costheta2)
Rm = data.p2 / (1.0 - data.e2 * costheta2)
distances = (abs(rp - Rp), abs(rp + Rm), abs(rm + Rp), abs(rm - Rm))
flags = (rp > 0.0 and Rp > 0.0, rp > 0.0 and Rm > 0.0,
rm > 0.0 and Rp > 0.0, rm > 0.0 and Rm > 0.0)
dO = -1.0
for valid, distance in zip(flags, distances):
if valid and (dO > distance or dO < 0.0):
dO = distance
A = math.sqrt(abs(1.0 - _sqr(data.e1 * costheta1)))
k = _float_divide(dO, A * data.abs_w * abs(data.a1))
sintheta1 = math.sin(theta1)
eta1 = math.sqrt(abs(1.0 - data.e1 * data.e1))
phi = _atan2_smart(sintheta1, costheta1 * eta1, data.e1 <= 1.0)
esth = _float_divide(data.e1 * sintheta1, A)
if data.e1 <= 1.0:
if min(abs(esth), 1.0) <= abs(1.0 - k):
if k < 1.0:
tmpm, tmpp = _safe_asin(esth - k), _safe_asin(esth + k)
first = (phi - tmpp, phi - tmpm)
phi += _PI
return [first, (phi + tmpm, phi + tmpp)]
return [(-_PI, _PI)]
if esth > 0.0:
tmpm = _safe_asin(esth - k)
first = [phi + tmpm, phi + _PI - tmpm]
if first[0] > first[1]:
first = [phi + _PI / 2.0] * 2
else:
tmpp = _safe_asin(esth + k)
first = [phi - tmpp, phi + _PI + tmpp]
if first[0] > first[1]:
first = [phi - _PI / 2.0] * 2
return [(first[0], first[1])]
if abs(costheta1) * eta1 <= abs(sintheta1):
if sintheta1 < 0.0:
esth = -esth
tmpm, tmpp = _safe_acosh(esth - k), _safe_acosh(esth + k)
if tmpm > 0.0:
return [(-tmpp - phi, -tmpm - phi), (tmpm - phi, tmpp - phi)]
return [(-tmpp - phi, tmpp - phi)]
if costheta1 < 0.0:
esth = -esth
return [(math.asinh(esth - k) - phi, math.asinh(esth + k) - phi)]
def restrict_search_range(
O1: COrbitData, O2: COrbitData
) -> tuple[tuple[float, float], ...]:
"""Return the one or two ranges selected by the C++ range restriction."""
return tuple(_restrict_search_range_aux(_AuxData(O1, O2)))
def _search_in_segment(
data: _AuxData, a: float, b: float, count: int
) -> tuple[int, float]:
min_value = -1.0
min_index = 0
for index in range(count + 1):
u1 = (a * (count - index) + b * index) / count
distance, _, _ = _min_distance_for(data, u1)
if distance < 0.0:
continue
if distance < min_value or min_value < 0.0:
min_value, min_index = distance, index
return min_index, min_value
def MOID_direct_search(
O1: COrbitData,
O2: COrbitData,
densities: Sequence[int] | None,
max_dist_error: float,
max_anom_error: float,
) -> SMOIDResult:
"""Calculate MOID by the C++ implementation's scan-and-refine method."""
if not math.isfinite(max_dist_error) or max_dist_error <= 0.0:
raise ValueError("maximum distance error must be finite and positive")
if not math.isfinite(max_anom_error) or max_anom_error <= 0.0:
raise ValueError("maximum anomaly error must be finite and positive")
started = time.perf_counter()
results = [SMOIDResult(), SMOIDResult()]
data = _AuxData(O1, O2)
other_data = _AuxData(O2, O1)
if data.abs_w <= math.sqrt(_EPS):
if data.e1 > 1.0 and data.e2 > 1.0:
raise ValueError("direct search cannot bound a coplanar hyperbolic pair")
swapped = data.e1 > 1.0
if swapped:
data = other_data
ranges = _restrict_search_range_aux(data)
else:
ranges = _restrict_search_range_aux(data)
other_ranges = _restrict_search_range_aux(other_data)
length = sum(max(b - a, 0.0) for a, b in ranges)
other_length = sum(max(b - a, 0.0) for a, b in other_ranges)
swapped = other_length < length
if swapped:
data, ranges = other_data, other_ranges
for range_index, (a0, b0) in enumerate(ranges):
h = (b0 - a0) / 2.0
a, b = a0, b0
if h > 0.0:
min_value = math.nan
delta = math.inf
using_densities = densities is not None
density = 3
iteration = 0
while iteration < 1 or h > max_anom_error or abs(delta) > max_dist_error:
if using_densities:
if iteration < len(densities) and densities[iteration] != 0:
density = (
int(densities[iteration])
if iteration > 0
else math.ceil(h * densities[iteration] / _PI)
)
else:
using_densities = False
if density < 3:
density = 3
h = 2.0 * h / density
min_index, next_min = _search_in_segment(data, a, b, density)
a += h * min_index
b, a = a + h, a - h
if iteration > 0:
delta = next_min - min_value
min_value = next_min
iteration += 1
results[range_index].u1_error = h
else:
results[range_index].u1_error = 0.0
results[range_index].u1 = (a + b) / 2.0
distance, results[range_index].u2, _ = _min_distance_for(
data, results[range_index].u1
)
results[range_index].distance = abs(distance)
result = results[0] if len(ranges) < 2 or results[0].distance <= results[1].distance else results[1]
eps = math.sqrt(_EPS)
distance, u2, _ = _min_distance_for(data, result.u1 + eps)
distance = abs(distance)
result.distance_error = abs(distance - result.distance) * _sqr(result.u1_error / eps)
result.u2_error = abs(u2 - result.u2) * result.u1_error / eps
if swapped:
result.u1, result.u2 = result.u2, result.u1
result.u1_error, result.u2_error = result.u2_error, result.u1_error
result.good = result.good and result.distance_error < max_dist_error
result.time = time.perf_counter() - started
return result
def _polynomial_val(
degree: int, coefficients: Sequence[complex], z: complex, forward: bool = True
) -> complex:
if forward:
value = coefficients[degree]
for index in range(degree - 1, -1, -1):
value = value * z + coefficients[index]
else:
value = coefficients[0]
for index in range(1, degree + 1):
value = value * z + coefficients[index]
return value
def _polynomial_valder(
degree: int, coefficients: Sequence[complex], z: complex, forward: bool
) -> tuple[complex, complex]:
if forward:
value = coefficients[degree]
derivative = coefficients[degree] * degree
for index in range(degree - 1, 1, -1):
value = value * z + coefficients[index]
derivative = derivative * z + coefficients[index] * index
if degree > 1:
value = value * z + coefficients[1]
derivative = derivative * z + coefficients[1]
if degree > 0:
value = value * z + coefficients[0]
else:
value = coefficients[0]
derivative = coefficients[0] * degree
for index in range(1, degree - 1):
value = value * z + coefficients[index]
derivative = derivative * z + coefficients[index] * (degree - index)
if degree > 1:
value = value * z + coefficients[degree - 1]
derivative = derivative * z + coefficients[degree - 1]
if degree > 0:
value = value * z + coefficients[degree]
return value, derivative
def _polynomial_valder2(
degree: int, coefficients: Sequence[complex], z: complex, forward: bool
) -> tuple[complex, complex, complex]:
if forward:
value = coefficients[degree]
derivative = coefficients[degree] * degree
derivative2 = coefficients[degree] * (degree * (degree - 1))
for index in range(degree - 1, 2, -1):
value = value * z + coefficients[index]
derivative = derivative * z + coefficients[index] * index
derivative2 = derivative2 * z + coefficients[index] * (index * (index - 1))
if degree > 2:
value = value * z + coefficients[2]
derivative = derivative * z + coefficients[2] * 2
derivative2 = derivative2 * z + coefficients[2] * 2
if degree > 1:
value = value * z + coefficients[1]
derivative = derivative * z + coefficients[1]
if degree > 0:
value = value * z + coefficients[0]
else:
value = coefficients[0]
derivative = coefficients[0] * degree
derivative2 = coefficients[0] * (degree * (degree - 1))
for index in range(1, degree - 2):
value = value * z + coefficients[index]
derivative = derivative * z + coefficients[index] * (degree - index)
derivative2 = derivative2 * z + coefficients[index] * (
(degree - index) * (degree - index - 1)
)
if degree > 2:
value = value * z + coefficients[degree - 2]
derivative = derivative * z + coefficients[degree - 2] * 2
derivative2 = derivative2 * z + coefficients[degree - 2] * 2
if degree > 1:
value = value * z + coefficients[degree - 1]
derivative = derivative * z + coefficients[degree - 1]
if degree > 0:
value = value * z + coefficients[degree]
return value, derivative, derivative2
def _ratio1(degree: int, coefficients: Sequence[complex], z: complex, forward: bool) -> complex:
value, derivative = _polynomial_valder(degree, coefficients, z, forward)
return value / derivative
def _ratio2(coefficients: Sequence[complex], z: complex, forward: bool) -> complex:
if forward:
return ((coefficients[2] * z + coefficients[1]) * z + coefficients[0]) / (
2.0 * coefficients[2] * z + coefficients[1]
)
return ((coefficients[0] * z + coefficients[1]) * z + coefficients[2]) / (
2.0 * coefficients[0] * z + coefficients[1]
)
def _ratio4(coefficients: Sequence[complex], z: complex, forward: bool) -> complex:
if forward:
return (
(((coefficients[4] * z + coefficients[3]) * z + coefficients[2]) * z + coefficients[1])
* z
+ coefficients[0]
) / (
((4.0 * coefficients[4] * z + 3.0 * coefficients[3]) * z + 2.0 * coefficients[2])
* z
+ coefficients[1]
)
return (
(((coefficients[0] * z + coefficients[1]) * z + coefficients[2]) * z + coefficients[3])
* z
+ coefficients[4]
) / (
((4.0 * coefficients[0] * z + 3.0 * coefficients[1]) * z + 2.0 * coefficients[2])
* z
+ coefficients[3]
)
def _newton_polynomial(
degree: int,
coefficients: Sequence[complex],
initial: complex,
max_error: float,
min_error: float,
max_count: int,
restart_count: int,
random: _DeterministicRandom,
) -> tuple[complex, int]:
z = initial
max_error, min_error = abs(max_error), abs(min_error)
z1 = z2 = z
if not max_error >= 2.0 * min_error:
max_error = 2.0 * min_error
if not max_error >= 2.0 * _EPS:
max_error = 2.0 * _EPS
iteration = 0
error2 = 0.0
nrm = 0.0
inner = True
while True:
iteration += 1
cycled = (
iteration > 2 and _cnorm(z - z2) < _cnorm(z - z1) * 1.0e-6
) or iteration % max_count == 0
multiplier = (
cmath.rect((2.0 * random.next() + 1.0) / 3.0, random.next() * _CIRC)
if cycled
else 1.0 + 0.0j
)
nrm = _cnorm(z)
if inner:
if nrm > 5.0:
inner = False
elif 2.0 * nrm < 1.0:
inner = True
z2, z1 = z1, z
if inner:
dz = _ratio1(degree, coefficients, z, True)
z -= dz * multiplier
else:
nrm = 1.0 / nrm
dz = _ratio1(degree, coefficients, z.conjugate() * nrm, False)
z /= 1.0 - z * dz * multiplier
error2 = _cnorm(dz)
if not (error2 > max_error * max_error * nrm and iteration < max_count * restart_count):
break
if error2 > min_error * min_error * nrm:
extra_iterations = 0
while True:
nrm = _cnorm(z)
if inner:
dz = _ratio1(degree, coefficients, z, True)
z -= dz
else:
nrm = 1.0 / nrm
dz = _ratio1(degree, coefficients, z.conjugate() * nrm, False)
z /= 1.0 - z * dz
next_error2 = _cnorm(dz)
improvement = error2 - next_error2
error2 = next_error2
extra_iterations += 1
if not (
improvement > _EPS * error2
and error2 > min_error * min_error * nrm
and extra_iterations <= max_count
):
break
iteration += extra_iterations
return z, iteration
def _extract_linear_factor(
degree: int, coefficients: list[complex], root: complex
) -> list[complex]:
if _cnorm(root) <= 1.0:
for index in range(degree - 1, 0, -1):
coefficients[index] += coefficients[index + 1] * root
return coefficients[1:]
inverse_root = _inverse(root)
for index in range(1, degree):
coefficients[index] += coefficients[index - 1] * inverse_root
return coefficients
def _solve_quadratic(coefficients: Sequence[complex]) -> list[complex]:
discriminant = cmath.sqrt(
coefficients[1] * coefficients[1] - 4.0 * coefficients[2] * coefficients[0]
)
same_half_plane = (
coefficients[1].real * discriminant.real
+ coefficients[1].imag * discriminant.imag
>= 0.0
)
tmp = -coefficients[1] - discriminant if same_half_plane else -coefficients[1] + discriminant
roots = [tmp / (2.0 * coefficients[2]), (2.0 * coefficients[0]) / tmp]
for index, root in enumerate(roots):
if _cnorm(root) <= 1.0:
roots[index] -= _ratio2(coefficients, root, True)
else:
roots[index] /= 1.0 - root * _ratio2(coefficients, _inverse(root), False)
return roots
def _solve_quartic(c: Sequence[complex]) -> list[complex]:
r = 4.0 * c[4]
p = 2.0 * r * c[2] - 3.0 * c[3] * c[3]
q = 2.0 * c[3] * (c[3] * c[3] - r * c[2]) + r * r * c[1]
D0 = c[2] * c[2] - 3.0 * c[3] * c[1] + 3.0 * c[0] * r
D1 = (
2.0 * c[2] * c[2] * c[2]
- 9.0 * c[3] * c[2] * c[1]
+ 27.0 * c[3] * c[3] * c[0]
+ 27.0 * c[1] * c[1] * c[4]
- 18.0 * r * c[2] * c[0]
)
tmp = cmath.sqrt(D1 * D1 - 4.0 * D0 * D0 * D0)
Qc = (D1 + tmp) / 2.0 if D1.real * tmp.real + D1.imag * tmp.imag >= 0.0 else (D1 - tmp) / 2.0
Qabs, Qarg = abs(Qc) ** (1.0 / 3.0), cmath.phase(Qc) / 3.0