reflection-method 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,820 @@
1
+ """Core reflection-method algorithm.
2
+
3
+ All functions operate on linear time units (JD, HJD, MJD, phase, minutes, etc.).
4
+ The library performs no time conversion or I/O.
5
+
6
+ This module implements the reflection method for finding minima of eclipsing
7
+ binary light curves. The method exploits the symmetry of the light curve about
8
+ the minimum: reflecting all points about a trial minimum and measuring the
9
+ residual variance of a spline fit to the combined (original + reflected) data.
10
+ The trial point that minimizes this variance is the estimated minimum.
11
+
12
+ References
13
+ ----------
14
+ - Kwee, K. K., & van Woerden, H. (1956). Bull. Astron. Inst. Netherlands, 12, 327.
15
+ - Andronov, I. L. (2003). Odessa Astron. Publ., 16, 55.
16
+ """
17
+
18
+ from typing import Optional
19
+ import warnings
20
+ import numpy as np
21
+ from scipy.interpolate import LSQUnivariateSpline
22
+
23
+ from .result import MinimumResult
24
+
25
+
26
+ def fit_spline(
27
+ x: np.ndarray,
28
+ y: np.ndarray,
29
+ pts_per_knot: int = 10,
30
+ degree: int = 3,
31
+ w: Optional[np.ndarray] = None,
32
+ ) -> LSQUnivariateSpline:
33
+ """Fit a least-squares B-spline to the data.
34
+
35
+ Fits a B-spline using `scipy.interpolate.LSQUnivariateSpline` with
36
+ automatically placed knots. The number of knots is determined by
37
+ ``pts_per_knot`` (target number of data points per knot). The spline
38
+ is fitted with `ext=3`, meaning evaluation outside the knot range
39
+ raises a `ValueError` rather than extrapolating.
40
+
41
+ Parameters
42
+ ----------
43
+ x : np.ndarray
44
+ Independent variable (abscissae). Must be 1-D array. Will be sorted
45
+ internally if not already monotonic.
46
+ y : np.ndarray
47
+ Dependent variable (ordinates). Must be 1-D array of same length as ``x``.
48
+ pts_per_knot : int, optional
49
+ Target number of data points per interior knot. The actual number of
50
+ knots is ``max(1, len(x) // pts_per_knot)``, capped at
51
+ ``len(x) - degree - 1``. Default is 10.
52
+ degree : int, optional
53
+ Degree of the spline (1 to 5). Cubic (3) is default and recommended
54
+ for most light curves. Use lower degree for noisy/sparse data.
55
+ w : np.ndarray or None, optional
56
+ Weights for weighted least squares. If provided, must be same length
57
+ as ``x``. Typically ``1 / sigma`` where ``sigma`` are measurement
58
+ uncertainties. Default is None (equal weights).
59
+
60
+ Returns
61
+ -------
62
+ LSQUnivariateSpline
63
+ Fitted spline object. Can be called like a function to evaluate at
64
+ arbitrary ``x`` values within the knot range.
65
+
66
+ Raises
67
+ ------
68
+ ValueError
69
+ If ``x`` and ``y`` have different lengths, or too few points for the
70
+ given degree, or if the fit fails (e.g., due to degenerate knots).
71
+
72
+ Notes
73
+ -----
74
+ The number of interior knots is chosen adaptively: starting from the
75
+ target based on ``pts_per_knot``, it is halved until the fit succeeds.
76
+ This handles cases where the data is too sparse for the requested knot
77
+ density.
78
+
79
+ The spline uses ``ext=3`` (raise on extrapolation) to prevent silent
80
+ extrapolation beyond the data range. This is a safety feature; the caller
81
+ should ensure evaluation points are within the data range.
82
+
83
+ Repeated abscissae are allowed and are kept as separate observations. In
84
+ the reflection method a reflected point can land exactly on another
85
+ measurement, giving two points at the same ``x`` with different ``y``.
86
+ ``LSQUnivariateSpline`` accepts non-decreasing ``x`` (scipy >= 1.10, the
87
+ minimum supported version) and fits such points as ordinary weighted
88
+ least-squares rows.
89
+
90
+ Examples
91
+ --------
92
+ >>> import numpy as np
93
+ >>> from reflection_method import fit_spline
94
+ >>> x = np.linspace(0, 1, 50)
95
+ >>> y = np.sin(2 * np.pi * x) + np.random.normal(0, 0.1, 50)
96
+ >>> spl = fit_spline(x, y, pts_per_knot=10, degree=3)
97
+ >>> y_fit = spl(np.linspace(0, 1, 100))
98
+ """
99
+ if not isinstance(x, np.ndarray) or not isinstance(y, np.ndarray):
100
+ raise ValueError("x and y must be numpy arrays")
101
+ if len(x) != len(y):
102
+ raise ValueError("x and y must have the same length")
103
+ n = len(x)
104
+ if n < degree + 2:
105
+ raise ValueError(f"Too few points ({n}) for spline degree {degree}.")
106
+
107
+ # Ensure x is sorted (spline requires non-decreasing x)
108
+ order = np.argsort(x)
109
+ x_sorted = x[order]
110
+ y_sorted = y[order]
111
+ w_sorted = w[order] if w is not None else None
112
+
113
+ xmin, xmax = float(x_sorted.min()), float(x_sorted.max())
114
+ n_inner = max(1, int(n / pts_per_knot))
115
+ n_inner = min(n_inner, max(1, n - degree - 1))
116
+
117
+ orig_n_inner = n_inner
118
+ while n_inner >= 1:
119
+ knots = np.linspace(xmin, xmax, n_inner + 2)[1:-1]
120
+ try:
121
+ spl = LSQUnivariateSpline(x_sorted, y_sorted, knots, k=degree, w=w_sorted, ext=3)
122
+ if n_inner < orig_n_inner:
123
+ warnings.warn(
124
+ f"Reduced spline knots from {orig_n_inner} to {n_inner} "
125
+ f"(data too sparse for pts_per_knot={pts_per_knot})",
126
+ UserWarning, stacklevel=2
127
+ )
128
+ return spl
129
+ except ValueError:
130
+ n_inner //= 2
131
+
132
+ raise ValueError("Failed to fit the spline — too few points.")
133
+
134
+
135
+ def spline_variance(
136
+ spl: LSQUnivariateSpline,
137
+ x: np.ndarray,
138
+ y: np.ndarray,
139
+ w: Optional[np.ndarray] = None,
140
+ ) -> float:
141
+ """Compute the (optionally weighted) mean squared residual of a fit.
142
+
143
+ With ``w=None`` this is ``mean((y - spl(x))**2)``. With weights the
144
+ result is ``sum((w * r)**2) / sum(w**2)`` for ``r = y - spl(x)``, using
145
+ the convention ``w = 1 / sigma``. This is invariant to a global rescaling
146
+ of the errors and reduces to the unweighted mean for constant sigma.
147
+
148
+ Parameters
149
+ ----------
150
+ spl : LSQUnivariateSpline
151
+ Fitted spline object.
152
+ x : np.ndarray
153
+ Abscissae at which to evaluate.
154
+ y : np.ndarray
155
+ Observed ordinates.
156
+ w : np.ndarray or None, optional
157
+ Weights ``1 / sigma``, same length as ``x`` and ``y``. Must be finite
158
+ and positive. Default None (equal weights).
159
+
160
+ Returns
161
+ -------
162
+ float
163
+ Mean squared residual, weighted when ``w`` is given. Callers take the
164
+ square root to obtain σ₁/σ₂.
165
+
166
+ Raises
167
+ ------
168
+ ValueError
169
+ If ``w`` has the wrong shape or contains non-finite or non-positive
170
+ values.
171
+ """
172
+ r = y - spl(x)
173
+ if w is None:
174
+ return float(np.mean(r ** 2))
175
+ w = np.asarray(w, dtype=float)
176
+ if w.shape != r.shape:
177
+ raise ValueError(f"w must have shape {r.shape}, got {w.shape}")
178
+ if not np.all(np.isfinite(w)) or np.any(w <= 0):
179
+ raise ValueError("w must be finite and positive (convention: w = 1/sigma)")
180
+ return float(np.sum((w * r) ** 2) / np.sum(w ** 2))
181
+
182
+
183
+ def combine(
184
+ x: np.ndarray,
185
+ y: np.ndarray,
186
+ x0: float,
187
+ w: Optional[np.ndarray] = None,
188
+ ) -> tuple[np.ndarray, np.ndarray, Optional[np.ndarray]]:
189
+ """Combine original and reflected points about a trial minimum ``x0``.
190
+
191
+ For each point ``(x_i, y_i)``, the reflected point is ``(2*x0 - x_i, y_i)``.
192
+ The combined dataset is sorted by the abscissa.
193
+
194
+ Parameters
195
+ ----------
196
+ x : np.ndarray
197
+ Original abscissae.
198
+ y : np.ndarray
199
+ Original ordinates.
200
+ x0 : float
201
+ Trial reflection point (abscissa of symmetry axis).
202
+ w : np.ndarray or None, optional
203
+ Weights for original points. If provided, weights are duplicated for
204
+ reflected points. Default is None.
205
+
206
+ Returns
207
+ -------
208
+ tuple[np.ndarray, np.ndarray, np.ndarray or None]
209
+ ``(x_all, y_all, w_all)`` where all arrays are sorted by ``x_all``.
210
+ ``w_all`` is None if ``w`` is None.
211
+
212
+ Examples
213
+ --------
214
+ >>> x = np.array([1, 2, 3])
215
+ >>> y = np.array([1, 2, 1])
216
+ >>> x_all, y_all, _ = combine(x, y, x0=2.0)
217
+ >>> print(x_all)
218
+ [1. 1. 2. 2. 3. 3.]
219
+ """
220
+ x_all = np.concatenate([x, 2 * x0 - x])
221
+ y_all = np.concatenate([y, y])
222
+ if w is not None:
223
+ w_all = np.concatenate([w, w])
224
+ else:
225
+ w_all = None
226
+
227
+ order = np.argsort(x_all)
228
+ return x_all[order], y_all[order], (w_all[order] if w_all is not None else None)
229
+
230
+
231
+ class _CenteredPoly1D:
232
+ """Polynomial fitted in centered coordinates, evaluates in original coordinates.
233
+
234
+ Wraps a polynomial fitted to (x - x_center) and transparently shifts
235
+ inputs by x_center on evaluation. Behaves like np.poly1d for callers.
236
+ """
237
+ def __init__(self, coeffs: np.ndarray, x_center: float):
238
+ self._poly = np.poly1d(coeffs)
239
+ self._center = float(x_center)
240
+ # Expose common poly1d attributes for compatibility
241
+ self.coeffs = self._poly.coeffs
242
+ self.order = self._poly.order
243
+ self.roots = self._poly.roots
244
+
245
+ def __call__(self, x):
246
+ return self._poly(x - self._center)
247
+
248
+ def __repr__(self):
249
+ return f"_CenteredPoly1D({self._poly}, center={self._center})"
250
+
251
+ def deriv(self, m=1):
252
+ return self._poly.deriv(m)
253
+
254
+ def __getattr__(self, name):
255
+ # Delegate any other attributes to underlying poly1d
256
+ return getattr(self._poly, name)
257
+
258
+
259
+ def refine_x0_minimum(
260
+ x0_grid: np.ndarray,
261
+ sigma2: np.ndarray,
262
+ parabola_window: float = 0.05,
263
+ ) -> tuple[float, np.poly1d, float, float]:
264
+ """Refine the σ₂(x₀) minimum with a local polynomial fit.
265
+
266
+ The σ₂(x₀) curve is smooth near the minimum but not exactly parabolic,
267
+ so a quartic polynomial is fitted to the grid points inside a narrow
268
+ window around the grid minimum — a parabola only when fewer than five
269
+ points fall in the window, and the grid minimum itself when fewer than
270
+ three do. Fitting a polynomial to a few local points avoids the
271
+ unstable minima that interpolating splines produce when the σ₂ curve is
272
+ flat. The minimum of the polynomial is located analytically from the
273
+ roots of its derivative (or from the vertex formula for the parabola)
274
+ and clamped to the scan bounds.
275
+
276
+ Parameters
277
+ ----------
278
+ x0_grid : np.ndarray
279
+ Scan grid of trial reflection points.
280
+ sigma2 : np.ndarray
281
+ σ₂ values at each grid point, same length as ``x0_grid``.
282
+ parabola_window : float, optional
283
+ Fraction of the scan range around the grid minimum used for the
284
+ polynomial fit. Default 0.05 (5%).
285
+
286
+ Returns
287
+ -------
288
+ tuple[float, np.poly1d, float, float]
289
+ ``(x0_opt, poly, window_lo, window_hi)`` where ``x0_opt`` is the
290
+ refined minimum, ``poly`` the fitted polynomial (a constant equal to
291
+ the median σ₂ when the fit is not possible), and ``window_lo`` /
292
+ ``window_hi`` the bounds of the fitted window in the same units as
293
+ ``x0_grid`` (useful for plotting).
294
+
295
+ Notes
296
+ -----
297
+ The fit centers x on the grid minimum to avoid ill-conditioning when the
298
+ abscissae are large (e.g., minutes from epoch ~100), which eliminates
299
+ numerical warnings from high-order polynomial fits.
300
+ """
301
+ idx_min = int(np.argmin(sigma2))
302
+ hw = parabola_window * (x0_grid[-1] - x0_grid[0])
303
+ mask = np.abs(x0_grid - x0_grid[idx_min]) <= hw
304
+ x_fit = x0_grid[mask]
305
+ y_fit = sigma2[mask]
306
+ window_lo = float(x_fit[0])
307
+ window_hi = float(x_fit[-1])
308
+
309
+ # Center x on the grid minimum to avoid ill-conditioning when x is large
310
+ # (e.g., minutes from epoch ~100). This eliminates the RankWarning
311
+ # that would otherwise occur with high-order polynomial fits on large abscissae.
312
+ x_center = float(x0_grid[idx_min])
313
+ x_fit_c = x_fit - x_center
314
+
315
+ # Actual centered window bounds — use these (not hw) for root filtering
316
+ # and endpoint evaluation to avoid extrapolating beyond fitted data.
317
+ c_lo = window_lo - x_center
318
+ c_hi = window_hi - x_center
319
+
320
+ if len(x_fit) >= 5:
321
+ coeffs_c = np.polyfit(x_fit_c, y_fit, 4)
322
+ # Quartic must have a minimum in the fitted window. Check by evaluating
323
+ # the polynomial at the stationary points and endpoints within the window.
324
+ deriv = np.polyder(coeffs_c)
325
+ roots = np.roots(deriv)
326
+ in_range = (roots.real >= c_lo) & (roots.real <= c_hi) & np.isreal(roots)
327
+ candidates = roots[in_range].real
328
+ if len(candidates) > 0:
329
+ eval_points = np.concatenate([candidates, [c_lo, c_hi]])
330
+ vals = np.polyval(coeffs_c, eval_points)
331
+ x0_opt_c = float(eval_points[np.argmin(vals)])
332
+ x0_opt = x0_opt_c + x_center
333
+ x0_opt = max(x0_grid[0], min(x0_grid[-1], x0_opt))
334
+ return x0_opt, _CenteredPoly1D(coeffs_c, x_center), window_lo, window_hi
335
+ elif len(x_fit) >= 3:
336
+ coeffs_c = np.polyfit(x_fit_c, y_fit, 2)
337
+ # A flat curve can fit a tiny positive coefficient; its vertex is noise.
338
+ curve = np.polyval(coeffs_c, np.linspace(c_lo, c_hi, 5))
339
+ if coeffs_c[0] > 0 and np.ptp(curve) > 1e-12 * max(1.0, float(np.max(np.abs(y_fit)))):
340
+ x0_opt_c = float(-coeffs_c[1] / (2 * coeffs_c[0]))
341
+ x0_opt = x0_opt_c + x_center
342
+ x0_opt = max(x0_grid[0], min(x0_grid[-1], x0_opt))
343
+ return x0_opt, _CenteredPoly1D(coeffs_c, x_center), window_lo, window_hi
344
+
345
+ return float(x0_grid[idx_min]), _CenteredPoly1D(np.array([0.0, 0.0, float(np.median(sigma2))]), 0.0), window_lo, window_hi
346
+
347
+
348
+ def find_x0(
349
+ x: np.ndarray,
350
+ y: np.ndarray,
351
+ pts_per_knot: int = 10,
352
+ degree: int = 3,
353
+ w: Optional[np.ndarray] = None,
354
+ n_scan: int = 200,
355
+ x0_window: float = 0.1,
356
+ x0_initial_guess: Optional[float] = None,
357
+ find_peak: bool = False,
358
+ parabola_window: float = 0.05,
359
+ ) -> tuple[float, np.ndarray, np.ndarray]:
360
+ """Scan trial reflection points to find the minimum of σ₂(x₀).
361
+
362
+ The function evaluates the residual standard deviation σ₂ of a spline
363
+ fitted to the combined (original + reflected) data for a grid of trial
364
+ reflection points ``x0``. The grid is centered on an initial guess and
365
+ spans a window of width ``x0_window * (xmax - xmin)``. The minimum is
366
+ refined with a local polynomial fit to the ``σ₂(x₀)`` curve (see
367
+ :func:`refine_x0_minimum`).
368
+
369
+ Parameters
370
+ ----------
371
+ x : np.ndarray
372
+ Abscissae (time, phase, etc.). 1-D array.
373
+ y : np.ndarray
374
+ Ordinates (flux, magnitude, etc.). 1-D array, same length as ``x``.
375
+ pts_per_knot : int, optional
376
+ Points per knot for spline fits. Default 10.
377
+ degree : int, optional
378
+ Spline degree (1-5). Default 3.
379
+ w : np.ndarray or None, optional
380
+ Weights for weighted least squares. Default None.
381
+ n_scan : int, optional
382
+ Number of trial ``x0`` values in the scan grid. Default 200.
383
+ x0_window : float, optional
384
+ Fraction of the total ``x`` range to scan around the initial guess.
385
+ The scan window is ``x0_window * (xmax - xmin)``. Default 0.1 (10%).
386
+ find_peak : bool, optional
387
+ If True, the eclipsing feature is a *peak* (maximum) of ``y`` rather
388
+ than a dip — as when working directly in magnitudes, where the eclipse
389
+ minimum is the largest magnitude. The initial guess for the scan is
390
+ then the maximum of the initial spline instead of the minimum.
391
+ Default False.
392
+ x0_initial_guess : float or None, optional
393
+ Initial guess for the minimum location. If None (default), the minimum
394
+ (or maximum when ``find_peak=True``) of a coarse spline fit to the
395
+ original data is used (evaluated on a 2001-point grid).
396
+ parabola_window : float, optional
397
+ Fraction of the scan range to use for polynomial refinement around the
398
+ grid minimum. Default 0.05 (5% of scan range). Must be positive.
399
+ A smaller window uses fewer points for the fit; larger includes more
400
+ of the curve. The fitted minimum is clamped to the scan bounds.
401
+
402
+ Returns
403
+ -------
404
+ tuple[float, np.ndarray, np.ndarray]
405
+ ``(x0_opt, x0_grid, sigma2_grid)`` where:
406
+ - ``x0_opt`` : float, the refined minimum location
407
+ - ``x0_grid`` : np.ndarray, the scan grid points
408
+ - ``sigma2_grid`` : np.ndarray, σ₂ values at each grid point
409
+
410
+ Raises
411
+ ------
412
+ ValueError
413
+ If the scan fails (e.g., insufficient data, spline fit fails).
414
+
415
+ Notes
416
+ -----
417
+ The scan window is clamped to the data range ``[xmin, xmax]``. The
418
+ ``σ₂`` values are computed as the square root of the mean squared
419
+ residual of the spline fitted to the combined (original + reflected)
420
+ data at each trial ``x0``. A floor of 1e-6 is applied to avoid numerical
421
+ issues.
422
+
423
+ The refinement fits a quartic polynomial to σ₂ values within
424
+ ``parabola_window`` of the grid minimum — a parabola when fewer than five
425
+ points fall in the window, and the grid minimum itself when fewer than
426
+ three do. The polynomial minimum is found analytically and clamped to the
427
+ scan bounds. The local fit avoids the unstable minima that interpolating
428
+ splines produce when the σ₂ curve is flat.
429
+
430
+ Examples
431
+ --------
432
+ >>> import numpy as np
433
+ >>> from reflection_method import find_x0
434
+ >>> phase = np.linspace(0, 1, 200)
435
+ >>> flux = 1 - 0.5 * np.exp(-((phase - 0.5)**2) / 0.001)
436
+ >>> x0_opt, x0_grid, sigma2 = find_x0(phase, flux, pts_per_knot=10, n_scan=200)
437
+ >>> print(f"Minimum at x0 = {x0_opt:.4f}")
438
+ """
439
+ # Initial spline on original data
440
+ spl1 = fit_spline(x, y, pts_per_knot, degree, w)
441
+
442
+ xmin, xmax = float(x.min()), float(x.max())
443
+ if x0_initial_guess is None:
444
+ x_fine = np.linspace(xmin, xmax, 2001)
445
+ if find_peak:
446
+ x0_initial_guess = float(x_fine[int(np.argmax(spl1(x_fine)))])
447
+ else:
448
+ x0_initial_guess = float(x_fine[int(np.argmin(spl1(x_fine)))])
449
+
450
+ window_width = x0_window * (xmax - xmin)
451
+ lo = max(xmin, x0_initial_guess - window_width / 2)
452
+ hi = min(xmax, x0_initial_guess + window_width / 2)
453
+
454
+ x0_grid = np.linspace(lo, hi, n_scan)
455
+ sigma2 = np.empty(n_scan)
456
+
457
+ for i, x0 in enumerate(x0_grid):
458
+ xs, ys, ws = combine(x, y, x0, w)
459
+ spl_refit = fit_spline(xs, ys, 2 * pts_per_knot, degree, ws)
460
+ sigma2[i] = np.sqrt(spline_variance(spl_refit, xs, ys, ws))
461
+
462
+ sigma2 = np.maximum(sigma2, 1e-6)
463
+
464
+ x0_opt, _, _, _ = refine_x0_minimum(x0_grid, sigma2, parabola_window)
465
+
466
+ return x0_opt, x0_grid, sigma2
467
+
468
+
469
+ def bootstrap_x0(
470
+ x: np.ndarray,
471
+ y: np.ndarray,
472
+ x0_opt: float,
473
+ spl1: LSQUnivariateSpline,
474
+ pts_per_knot: int,
475
+ degree: int,
476
+ w: Optional[np.ndarray],
477
+ n_bootstrap: int = 60,
478
+ n_scan_boot: int = 80,
479
+ x0_window: float = 0.1,
480
+ rng: Optional[np.random.Generator] = None,
481
+ return_samples: bool = False,
482
+ find_peak: bool = False,
483
+ parabola_window: float = 0.05,
484
+ ) -> tuple[float, float, float] | tuple[float, float, float, np.ndarray]:
485
+ """Estimate uncertainty of x0 via residual bootstrap.
486
+
487
+ Performs a residual bootstrap to estimate the sampling distribution of
488
+ the minimum location ``x0``. Residuals from the initial spline fit are
489
+ resampled with replacement to generate bootstrap samples. For each
490
+ bootstrap sample, the full ``find_x0`` scan is repeated (at reduced
491
+ resolution for speed). The empirical distribution of bootstrap estimates
492
+ provides standard error and confidence intervals.
493
+
494
+ Parameters
495
+ ----------
496
+ x : np.ndarray
497
+ Original abscissae.
498
+ y : np.ndarray
499
+ Original ordinates.
500
+ x0_opt : float
501
+ Optimal ``x0`` from ``find_x0``.
502
+ spl1 : LSQUnivariateSpline
503
+ Initial spline fit to the original data (without reflection).
504
+ pts_per_knot : int
505
+ Points per knot for spline fits.
506
+ degree : int
507
+ Spline degree.
508
+ w : np.ndarray or None
509
+ Weights (same as passed to ``find_x0``). When given, the bootstrap
510
+ switches from pooled to wild residual resampling.
511
+ n_bootstrap : int, optional
512
+ Number of bootstrap iterations. Default 60. Use larger values (100-200)
513
+ for more precise confidence intervals.
514
+ n_scan_boot : int, optional
515
+ Grid resolution for each bootstrap iteration's scan. Default 80
516
+ (coarser than main scan for speed).
517
+ x0_window : float, optional
518
+ Scan window fraction, same as in ``find_x0``. Default 0.1. It must stay
519
+ wide enough to contain the minimum for every resampled sample, whose
520
+ coarse initial guess is itself noisy: narrowing it biases the
521
+ bootstrap distribution.
522
+ find_peak : bool, optional
523
+ If True, the eclipsing feature is a peak (maximum) of ``y`` rather
524
+ than a dip — as when working directly in magnitudes. The per-iteration
525
+ initial guess then uses the maximum of the bootstrap spline instead of
526
+ the minimum. Must match the ``find_peak`` value used in ``find_x0``.
527
+ Default False.
528
+ parabola_window : float, optional
529
+ Fraction of the per-iteration scan range for polynomial refinement.
530
+ Default 0.05 (5%). Same behavior as in ``find_x0``.
531
+ rng : np.random.Generator or None, optional
532
+ Random number generator. If None, a new PCG64 generator is created.
533
+ Pass a seeded generator for reproducible results.
534
+ return_samples : bool, optional
535
+ If True, additionally return the raw bootstrap estimates ``x0_boot``
536
+ (e.g. for plotting the bootstrap distribution). Default False.
537
+
538
+ Returns
539
+ -------
540
+ tuple[float, float, float] or tuple[float, float, float, np.ndarray]
541
+ ``(x0_std, x0_lo, x0_hi)`` where:
542
+ - ``x0_std`` : float, bootstrap standard error (sample std, ddof=1)
543
+ - ``x0_lo`` : float, 16th percentile (lower bound of 68% CI)
544
+ - ``x0_hi`` : float, 84th percentile (upper bound of 68% CI)
545
+ If ``return_samples`` is True, a fourth element ``x0_boot`` (the array
546
+ of ``n_bootstrap`` individual estimates) is appended.
547
+
548
+ Notes
549
+ -----
550
+ With ``w=None`` the bootstrap pools residuals: they are resampled with
551
+ replacement and added back to the fitted values. With weights, a **wild
552
+ bootstrap** is used instead: each point keeps its own residual, multiplied
553
+ by a random sign. This avoids attaching a noisy point's residual to a
554
+ precise one. Both variants preserve the fitted model under the null
555
+ hypothesis; only the weighted path needs per-point error information.
556
+
557
+ The per-iteration scan uses a coarser grid (``n_scan_boot``) and the same
558
+ window fraction ``x0_window``. The initial guess for each bootstrap
559
+ iteration is the minimum of a coarse spline fit to the bootstrap sample.
560
+ Each iteration's minimum is refined with the same local polynomial fit as
561
+ in :func:`find_x0`.
562
+
563
+ For reproducibility, pass a seeded generator:
564
+ ``rng = np.random.default_rng(42)``.
565
+
566
+ References
567
+ ----------
568
+ Efron, B., & Tibshirani, R. J. (1993). *An Introduction to the Bootstrap*.
569
+ Chapman & Hall.
570
+ """
571
+ if rng is None:
572
+ rng = np.random.default_rng()
573
+
574
+ residuals = y - spl1(x)
575
+ n = len(x)
576
+ x0_boot = np.empty(n_bootstrap)
577
+
578
+ xmin, xmax = float(x.min()), float(x.max())
579
+ window_width = x0_window * (xmax - xmin)
580
+
581
+ for k in range(n_bootstrap):
582
+ if w is None:
583
+ y_boot = spl1(x) + residuals[rng.integers(0, n, n)]
584
+ else:
585
+ # Wild bootstrap: each point keeps its own residual magnitude.
586
+ signs = rng.integers(0, 2, n) * 2 - 1
587
+ y_boot = spl1(x) + residuals * signs
588
+ spl_boot = fit_spline(x, y_boot, pts_per_knot, degree, w)
589
+
590
+ # Coarse scan for this bootstrap sample
591
+ x_fine = np.linspace(xmin, xmax, 1001)
592
+ if find_peak:
593
+ center = float(x_fine[int(np.argmax(spl_boot(x_fine)))])
594
+ else:
595
+ center = float(x_fine[int(np.argmin(spl_boot(x_fine)))])
596
+ lo = max(xmin, center - window_width / 2)
597
+ hi = min(xmax, center + window_width / 2)
598
+
599
+ grid = np.linspace(lo, hi, n_scan_boot)
600
+ sig = np.empty(len(grid))
601
+
602
+ for i, x0 in enumerate(grid):
603
+ xs, ys, ws = combine(x, y_boot, x0, w)
604
+ sp = fit_spline(xs, ys, 2 * pts_per_knot, degree, ws)
605
+ sig[i] = np.sqrt(spline_variance(sp, xs, ys, ws))
606
+
607
+ sig = np.maximum(sig, 1e-6)
608
+
609
+ x0_boot[k], _, _, _ = refine_x0_minimum(grid, sig, parabola_window)
610
+ # Guard against outliers: if bootstrap estimate is far from main x0,
611
+ # fall back to that iteration's grid minimum
612
+ fit_hw = parabola_window * (grid[-1] - grid[0])
613
+ if abs(x0_boot[k] - x0_opt) > 3 * fit_hw:
614
+ x0_boot[k] = float(grid[int(np.argmin(sig))])
615
+
616
+ x0_std = float(x0_boot.std(ddof=1))
617
+ x0_lo = float(np.percentile(x0_boot, 16))
618
+ x0_hi = float(np.percentile(x0_boot, 84))
619
+
620
+ if return_samples:
621
+ return x0_std, x0_lo, x0_hi, x0_boot
622
+ return x0_std, x0_lo, x0_hi
623
+
624
+
625
+ def prepare_plot_data(
626
+ x: np.ndarray,
627
+ y: np.ndarray,
628
+ w: Optional[np.ndarray],
629
+ x0_opt: float,
630
+ x0_grid: np.ndarray,
631
+ sigma2: np.ndarray,
632
+ pts_per_knot: int,
633
+ degree: int,
634
+ parabola_window: float,
635
+ ) -> dict:
636
+ """Build the intermediate arrays needed by :func:`plot_all`.
637
+
638
+ Parameters
639
+ ----------
640
+ x, y : np.ndarray
641
+ Original data.
642
+ w : np.ndarray or None
643
+ Weights used in the fit.
644
+ x0_opt : float
645
+ Optimal reflection point from the main scan.
646
+ x0_grid, sigma2 : np.ndarray
647
+ Scan grid and its σ₂ values, from the same run as ``x0_opt``.
648
+ pts_per_knot, degree : int
649
+ Spline settings used for the fit.
650
+ parabola_window : float
651
+ Fraction of the scan range used for the polynomial refinement.
652
+
653
+ Returns
654
+ -------
655
+ dict
656
+ Keys ``spl1``, ``spl2``, ``xr``, ``spl_sigma``, ``fit_window_lo`` and
657
+ ``fit_window_hi``, ready to pass to ``plot_all`` alongside the grid.
658
+ """
659
+ spl1 = fit_spline(x, y, pts_per_knot, degree, w)
660
+ _, spl_sigma, fit_lo, fit_hi = refine_x0_minimum(x0_grid, sigma2, parabola_window)
661
+ xr = 2 * x0_opt - x
662
+ x_all, y_all, w_all = combine(x, y, x0_opt, w)
663
+ spl2 = fit_spline(x_all, y_all, 2 * pts_per_knot, degree, w_all)
664
+ return {
665
+ "spl1": spl1,
666
+ "spl2": spl2,
667
+ "xr": xr,
668
+ "spl_sigma": spl_sigma,
669
+ "fit_window_lo": fit_lo,
670
+ "fit_window_hi": fit_hi,
671
+ }
672
+
673
+
674
+ def find_minimum(
675
+ x: np.ndarray,
676
+ y: np.ndarray,
677
+ pts_per_knot: int = 10,
678
+ degree: int = 3,
679
+ w: Optional[np.ndarray] = None,
680
+ n_scan: int = 200,
681
+ x0_window: float = 0.1,
682
+ n_bootstrap: int = 60,
683
+ n_scan_boot: int = 80,
684
+ rng: Optional[np.random.Generator] = None,
685
+ return_samples: bool = False,
686
+ find_peak: bool = False,
687
+ parabola_window: float = 0.05,
688
+ return_scan: bool = False,
689
+ ) -> MinimumResult | tuple[MinimumResult, np.ndarray] | tuple:
690
+ """Full pipeline: find the light-curve minimum and its uncertainty.
691
+
692
+ High-level function that runs the complete reflection-method pipeline:
693
+ 1. Scans trial ``x0`` values to find the minimum of σ₂(x₀) (``find_x0``).
694
+ 2. Estimates uncertainty via residual bootstrap (``bootstrap_x0``).
695
+ 3. Returns a ``MinimumResult`` containing the minimum location,
696
+ uncertainties, and diagnostics.
697
+
698
+ Parameters
699
+ ----------
700
+ x : np.ndarray
701
+ Abscissae (time in any linear units: JD, HJD, MJD, phase, minutes,
702
+ etc.). 1-D array.
703
+ y : np.ndarray
704
+ Ordinates (flux, magnitude, etc.). 1-D array, same length as ``x``.
705
+ pts_per_knot : int, optional
706
+ Points per knot for spline fits. Default 10. Typical range: 5-20.
707
+ degree : int, optional
708
+ Spline degree (1-5). Default 3 (cubic).
709
+ w : np.ndarray or None, optional
710
+ Weights (typically ``1 / sigma``). If None, equal weights. Default None.
711
+ n_scan : int, optional
712
+ Scan resolution for main search. Default 200.
713
+ x0_window : float, optional
714
+ Scan window as fraction of ``x`` range. Default 0.1 (10%).
715
+ n_bootstrap : int, optional
716
+ Number of bootstrap iterations. Default 60. Increase for more
717
+ precise confidence intervals.
718
+ n_scan_boot : int, optional
719
+ Grid resolution per bootstrap iteration. Default 80.
720
+ find_peak : bool, optional
721
+ If True, the eclipsing feature is a peak (maximum) of ``y`` rather
722
+ than a dip — as when working directly in magnitudes, where the eclipse
723
+ minimum is the largest magnitude value. This changes the initial-guess
724
+ step of the scan (and of each bootstrap iteration) from the minimum to
725
+ the maximum of the spline fit. Default False.
726
+ parabola_window : float, optional
727
+ Fraction of the scan range for polynomial refinement in both the main
728
+ scan and each bootstrap iteration. Default 0.05 (5%).
729
+ rng : np.random.Generator or None, optional
730
+ Random number generator for bootstrap. Pass a seeded generator for
731
+ reproducibility. Default is a new PCG64 generator.
732
+ return_samples : bool, optional
733
+ If True, additionally return the raw bootstrap estimates ``x0_boot``
734
+ (e.g. for plotting the bootstrap distribution). Default False.
735
+ return_scan : bool, optional
736
+ If True, additionally return ``x0_grid`` and ``sigma2`` from the main
737
+ scan, so callers can build diagnostic plots without running the scan
738
+ twice. Combined with ``return_samples``, the order is
739
+ ``(result, x0_boot, x0_grid, sigma2)``. Default False.
740
+
741
+ Returns
742
+ -------
743
+ MinimumResult or tuple
744
+ ``MinimumResult`` with fields:
745
+ - ``x0`` : float, optimal reflection point (same units as input ``x``)
746
+ - ``x0_std`` : float, bootstrap standard error
747
+ - ``x0_lo`` : float, 16th percentile (lower 68% CI)
748
+ - ``x0_hi`` : float, 84th percentile (upper 68% CI)
749
+ - ``sigma_min`` : float, minimum σ₂ value
750
+ - ``n_points`` : int, number of data points
751
+ - ``n_bootstrap`` : int, bootstrap iterations used
752
+ If ``return_samples`` is True, a tuple ``(result, x0_boot)`` is
753
+ returned instead, where ``x0_boot`` is the array of ``n_bootstrap``
754
+ individual bootstrap estimates.
755
+
756
+ Raises
757
+ ------
758
+ ValueError
759
+ If input arrays are invalid, spline fitting fails, or scan fails.
760
+
761
+ Examples
762
+ --------
763
+ Basic usage with synthetic data:
764
+
765
+ >>> import numpy as np
766
+ >>> from reflection_method import find_minimum
767
+ >>> rng = np.random.default_rng(42)
768
+ >>> phase = np.sort(rng.uniform(0, 1, 300))
769
+ >>> flux = 1 - 0.5 * np.exp(-((phase - 0.5)**2) / 0.001) + rng.normal(0, 0.01, 300)
770
+ >>> result = find_minimum(phase, flux, n_bootstrap=100, rng=np.random.default_rng(42))
771
+ >>> print(f"Minimum at x0 = {result.x0:.4f} ± {result.x0_std:.4f}")
772
+ Minimum at x0 = 0.5000 ± 0.0002
773
+
774
+ With weights and reproducibility:
775
+
776
+ >>> w = 1 / np.full_like(flux, 0.01) # constant uncertainty
777
+ >>> result = find_minimum(phase, flux, w=w, n_bootstrap=200,
778
+ ... rng=np.random.default_rng(42))
779
+ >>> print(f"68% CI: [{result.x0_lo:.4f}, {result.x0_hi:.4f}]")
780
+ 68% CI: [0.4997, 0.5003]
781
+ """
782
+ if rng is None:
783
+ rng = np.random.default_rng()
784
+
785
+ # Main scan
786
+ x0_opt, x0_grid, sigma2 = find_x0(
787
+ x, y, pts_per_knot, degree, w, n_scan, x0_window,
788
+ find_peak=find_peak,
789
+ parabola_window=parabola_window,
790
+ )
791
+
792
+ # Initial spline for bootstrap
793
+ spl1 = fit_spline(x, y, pts_per_knot, degree, w)
794
+
795
+ # Bootstrap
796
+ x0_std, x0_lo, x0_hi, x0_boot = bootstrap_x0(
797
+ x, y, x0_opt, spl1, pts_per_knot, degree, w,
798
+ n_bootstrap, n_scan_boot, x0_window, rng, True,
799
+ find_peak=find_peak,
800
+ parabola_window=parabola_window,
801
+ )
802
+
803
+ sigma_min = float(np.min(sigma2))
804
+
805
+ result = MinimumResult(
806
+ x0=x0_opt,
807
+ x0_std=x0_std,
808
+ x0_lo=x0_lo,
809
+ x0_hi=x0_hi,
810
+ sigma_min=sigma_min,
811
+ n_points=len(x),
812
+ n_bootstrap=n_bootstrap,
813
+ )
814
+ if return_scan:
815
+ if return_samples:
816
+ return result, x0_boot, x0_grid, sigma2
817
+ return result, x0_grid, sigma2
818
+ if return_samples:
819
+ return result, x0_boot
820
+ return result