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
//! Brent–Dekker solver for the universal Kepler equation.
//!
//! This module provides a bracket-based root-finding approach as an alternative
//! to the Newton–Raphson solver in [`newton_solver`](crate::kepler::newton_solver).
//! The Brent–Dekker method guarantees convergence when a valid bracket is
//! supplied, making it more robust than Newton's method in pathological cases
//! (e.g., near-parabolic orbits, large eccentricities).
//!
//! # Algorithm overview
//!
//! 1. **Bracket construction** ([`bracket_kepler_root`]) — finds an interval
//! $ [\psi_a, \psi_b] $ such that $ f(\psi_a) \cdot f(\psi_b) < 0 $ , where
//!
//! $ f(\psi) = r_0 \cdot s_1(\psi, \alpha) + \sigma_0 \cdot s_2(\psi, \alpha)
//! + \mu \cdot s_3(\psi, \alpha) - \Delta t $
//!
//! 2. **Root isolation** ([`solve_kepuni_brent_dekker`]) — applies the
//! Brent–Dekker iteration within that bracket to converge on $ \psi^* $ .
//!
//! # Supported regimes
//!
//! * **Elliptic** ( $ \alpha < 0 $ ) and **Hyperbolic** ( $ \alpha > 0 $ ) motions.
//! * **Parabolic** ( $ \alpha = 0 $ ) is not handled and returns `None`.
use crateUniversalKeplerSolution;
use UniversalKeplerParams;
use s_funct;
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/// Maximum number of iterations for the bracket expansion phase.
const MAX_BRACKET_ITERATIONS: usize = 60;
/// Maximum number of iterations for the Brent–Dekker root-finding phase.
const MAX_BRENT_ITERATIONS: usize = 100;
/// Golden ratio $ \phi \approx 1.618 $ , used as the geometric expansion factor
/// during bracket construction.
const PHI: f64 = 1.618_033_988_749_895;
// ---------------------------------------------------------------------------
// Residual evaluation
// ---------------------------------------------------------------------------
/// Evaluate the universal Kepler residual $ f(\psi) $ .
///
/// $ f(\psi) = r_0 \cdot s_1(\psi,\alpha) + \sigma_0 \cdot s_2(\psi,\alpha)
/// + \mu \cdot s_3(\psi,\alpha) - \Delta t $
///
/// A root of this function corresponds to the universal anomaly $ \psi^* $ at
/// time $ \Delta t $ .
// ---------------------------------------------------------------------------
// Bracket construction
// ---------------------------------------------------------------------------
/// Compute the initial half-width of the bracket search interval.
///
/// When $ |\psi_0| $ is large enough, the half-width is set proportional to
/// $ |\psi_0| $ to scale the search with the magnitude of the guess. Otherwise
/// an absolute fallback of $ 1.0 $ is used to avoid a degenerate zero-width
/// interval.
/// Expand the bracket endpoint whose residual magnitude is smaller.
///
/// The side with the smaller $ |f| $ is closer to a root, so expanding it
/// biases the search toward the most promising direction. The expansion
/// grows the interval by a factor $ \phi $ (golden ratio) at each call.
///
/// Returns the updated `(psi_lo, f_lo, psi_hi, f_hi)` tuple.
/// Return `true` if `(psi_lo, psi_hi)` is a valid bracket, i.e. the residuals
/// at both endpoints have opposite signs (or one is exactly zero).
/// Find an interval $ [\psi_a, \psi_b] $ that brackets a root of the universal
/// Kepler residual.
///
/// # Strategy
///
/// Starting from an initial guess $ \psi_0 $ (from [`prelim_kepuni`](crate::kepler::UniversalKeplerParams::prelim_kepuni) or the
/// caller), the algorithm expands the search interval geometrically until a
/// sign change is detected:
///
/// - The interval is grown by a factor $ \phi $ (golden ratio, $ \approx 1.618 $ )
/// at each step, alternating the expansion direction to remain centered on
/// the initial guess.
/// - If the initial guess already brackets the root (one side negative, one
/// positive), the interval is returned immediately.
///
/// # Arguments
///
/// * `psi0` – Initial guess for $ \psi $ (center of the search).
/// * `params` – Orbital parameters (used to evaluate the residual).
///
/// # Return
///
/// * `Some((psi_lo, psi_hi))` such that $ f(\psi_{lo}) \cdot f(\psi_{hi}) \leq 0 $ .
/// * `None` if no bracket is found within [`MAX_BRACKET_ITERATIONS`].
// ---------------------------------------------------------------------------
// Brent–Dekker state and step logic
// ---------------------------------------------------------------------------
/// Internal state of the Brent–Dekker iteration.
///
/// By convention, `b` is always the *better* approximation, i.e.
/// $ |f(b)| \leq |f(a)| $ is maintained as an invariant throughout the
/// iteration.
/// Attempt an inverse quadratic interpolation (IQI) step using the three
/// points $ (a, f_a) $ , $ (b, f_b) $ , $ (c, f_c) $ .
///
/// IQI fits a parabola through the three points in the $ f $ -direction and
/// evaluates it at $ f = 0 $ . It provides superlinear convergence when the
/// function is smooth near the root.
///
/// Returns `None` if any two of the three $ f $ -values are too close to
/// distinguish (the denominator would be numerically zero).
/// Compute a secant step using the two points $ (a, f_a) $ and $ (b, f_b) $ .
///
/// The secant method interpolates linearly between the two points and
/// evaluates the interpolant at $ f = 0 $ .
/// Compute a bisection step between `a` and `b`.
/// Return `true` if the interpolation candidate `s` falls strictly inside the
/// interval $ (3a/4 + b/4,\; b) $ , i.e. within the inner three-quarters of the
/// bracket $ [a, b] $ .
///
/// This condition prevents the interpolation step from landing too close to
/// `a`, which would give poor progress.
/// Return `true` if the interpolation candidate `s` is making sufficient
/// progress compared to the reference step length.
///
/// The interpolation step is accepted only when $ |s - b| < \text{reference} / 2 $ .
/// Otherwise the method falls back to bisection to guarantee monotone bracket
/// shrinkage.
/// Select the next $ \psi $ candidate and update the bisection flag.
///
/// The interpolation step (IQI or secant) is used only when it:
///
/// 1. Falls strictly inside the bracket (`is_candidate_inside_bracket`), and
/// 2. Makes sufficient progress over the previous step (`is_candidate_making_progress`).
///
/// Otherwise the method falls back to bisection.
///
/// Returns `(next_psi, was_bisection)`.
/// Update the bracket endpoints after evaluating the residual at `next_psi`.
///
/// The endpoint whose residual has the same sign as `f_next` is replaced by
/// `next_psi`. Then the invariant $ |f(b)| \leq |f(a)| $ is restored by
/// swapping `a` and `b` if necessary.
// ---------------------------------------------------------------------------
// Public solver
// ---------------------------------------------------------------------------
/// Solve the **universal Kepler equation** using the Brent–Dekker method.
///
/// # Goal
///
/// Find the universal anomaly $\psi^*$ such that the residual
///
/// $$f(\psi) = r_0 \cdot s_1(\psi, \alpha) + \sigma_0 \cdot s_2(\psi, \alpha)
/// + \mu \cdot s_3(\psi, \alpha) - \Delta t = 0$$
///
/// vanishes. The universal anomaly $\psi$ parametrises the along-track
/// progress of a body regardless of orbit type, unifying the classical
/// anomalies (eccentric, hyperbolic, parabolic) into a single variable.
///
/// # Scientific background
///
/// See [`newton_solver`](crate::kepler::newton_solver) for the physical
/// interpretation of $\psi$, $\alpha$, and the Stumpff functions
/// $(s_0, s_1, s_2, s_3)$.
///
/// The energy parameter $\alpha = -\mu / (2a)$ encodes the orbit type:
///
/// | Regime | Condition | Shape |
/// |---|---|---|
/// | Elliptic | $\alpha < 0$ | Closed orbit |
/// | Parabolic | $\alpha = 0$ | Escape at exact escape velocity |
/// | Hyperbolic | $\alpha > 0$ | Open, unbound trajectory |
///
/// # Numerical strategy
///
/// The solver pipeline proceeds in four steps:
///
/// 1. **Tolerance** — defaults to $100\varepsilon$ if not provided.
/// 2. **Orbit-type guard** — parabolic orbits ($\alpha = 0$) are rejected
/// immediately.
/// 3. **Bracket construction** ([`bracket_kepler_root`]) — starting from the
/// heuristic guess $\psi_0$ returned by [`prelim_kepuni`](crate::kepler::UniversalKeplerParams::prelim_kepuni), the search
/// interval is expanded geometrically (by factor $\phi$, the golden ratio)
/// until a sign change is detected:
/// $$f(\psi_\text{lo}) \cdot f(\psi_\text{hi}) \leq 0$$
/// 4. **Brent–Dekker iteration** ([`run_brent_dekker`]) — within the bracket,
/// each step selects between:
/// - **Inverse quadratic interpolation (IQI)** — superlinear convergence
/// when three distinct points are available and the step falls inside the
/// bracket.
/// - **Secant step** — used when IQI is not applicable.
/// - **Bisection** — fallback when interpolation fails to make sufficient
/// progress, guaranteeing that the bracket width decreases monotonically.
///
/// # Comparison with Newton–Raphson
///
/// | Property | Newton–Raphson | Brent–Dekker |
/// |---|---|---|
/// | Convergence guarantee | No (can diverge) | Yes (within bracket) |
/// | Convergence rate | Quadratic (near root) | Superlinear |
/// | Requires derivative | Yes | No |
/// | Requires bracket | No | Yes |
///
/// Brent–Dekker is preferred when robustness matters more than raw speed, or
/// as a fallback when Newton's method fails to converge (e.g., near-parabolic
/// orbits, large eccentricities, or ill-conditioned initial conditions).
///
/// # Arguments
///
/// * `params` – Packed orbital parameters for the universal-variable
/// formulation:
/// - `r0` — initial radius $r_0$,
/// - `sig0` — radial velocity proxy $\sigma_0 = \mathbf{r}_0 \cdot \dot{\mathbf{r}}_0 / \sqrt{\mu}$,
/// - `mu` — gravitational parameter $\mu$,
/// - `alpha` — energy parameter $\alpha$,
/// - `dt` — time of flight $\Delta t$.
/// * `convergency` – Optional absolute tolerance on $|f(\psi^*)|$ and
/// $|\psi_b - \psi_a|$ (default: $100\varepsilon \approx 2.2 \times 10^{-14}$).
///
/// # Return
///
/// * `Some(UniversalKeplerSolution)` — the converged universal anomaly
/// $\psi^*$ together with the evaluated Stumpff functions
/// $(s_0, s_1, s_2, s_3)$ at $\psi^*$.
/// * `None` if any of the following conditions occur:
/// - the orbit is parabolic ($\alpha = 0$),
/// - [`prelim_kepuni`](crate::kepler::UniversalKeplerParams::prelim_kepuni) fails to produce a finite initial guess,
/// - no sign change is found within [`MAX_BRACKET_ITERATIONS`] expansions,
/// - the Brent–Dekker loop exhausts [`MAX_BRENT_ITERATIONS`] without
/// meeting `tolerance`.
///
/// # See also
///
/// * [`bracket_kepler_root`] – Bracket construction helper.
/// * [`run_brent_dekker`] – Core iteration loop.
/// * [`s_funct`](crate::kepler::s_funct) – Stumpff auxiliary functions.
/// * [`prelim_kepuni`](crate::kepler::UniversalKeplerParams::prelim_kepuni) – Initial guess used to
/// seed the bracket search.
/// * [`solve_kepuni_newton`](crate::kepler::newton_solver::solve_kepuni_newton) –
/// Alternative Newton–Raphson solver.
// ---------------------------------------------------------------------------
// Internal pipeline steps
// ---------------------------------------------------------------------------
/// Run the core Brent–Dekker iteration loop starting from the bracket
/// `(psi_lo, psi_hi)`.
///
/// Returns `Some(UniversalKeplerSolution)` on convergence, or `None` if
/// [`MAX_BRENT_ITERATIONS`] is exhausted without meeting `tolerance`.
/// Build a [`UniversalKeplerSolution`] from the converged universal anomaly
/// `psi_star`.
///
/// Recomputes the Stumpff functions at $\psi^*$ to populate the solution
/// fields.