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.
- reflection_method/__init__.py +47 -0
- reflection_method/cli.py +210 -0
- reflection_method/core.py +820 -0
- reflection_method/io.py +221 -0
- reflection_method/plot.py +459 -0
- reflection_method/result.py +140 -0
- reflection_method-0.3.0.dist-info/METADATA +370 -0
- reflection_method-0.3.0.dist-info/RECORD +12 -0
- reflection_method-0.3.0.dist-info/WHEEL +5 -0
- reflection_method-0.3.0.dist-info/entry_points.txt +2 -0
- reflection_method-0.3.0.dist-info/licenses/LICENSE +674 -0
- reflection_method-0.3.0.dist-info/top_level.txt +1 -0
reflection_method/io.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Input helpers for AAVSO-style photometry files.
|
|
2
|
+
|
|
3
|
+
The core algorithm is I/O-free; all file parsing lives here. Weights follow
|
|
4
|
+
the convention ``w = 1 / sigma``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def parse_datetime_column(values: list[str]) -> tuple[np.ndarray, np.datetime64]:
|
|
12
|
+
"""Parse ISO datetime strings to minutes elapsed from the first timestamp.
|
|
13
|
+
|
|
14
|
+
Accepts ISO-8601 timestamps with either a space or ``T`` separator
|
|
15
|
+
(e.g. AAVSO ``DATE-OBS`` values like ``2026-08-08 20:43:16.427``).
|
|
16
|
+
Timestamps are treated as naive UTC, following the AAVSO convention.
|
|
17
|
+
|
|
18
|
+
Parameters
|
|
19
|
+
----------
|
|
20
|
+
values : list[str]
|
|
21
|
+
ISO datetime strings to parse.
|
|
22
|
+
|
|
23
|
+
Returns
|
|
24
|
+
-------
|
|
25
|
+
tuple[np.ndarray, np.datetime64]
|
|
26
|
+
``(x_minutes, t0_utc)`` where ``x_minutes`` is the time of each point
|
|
27
|
+
in minutes relative to the earliest timestamp, and ``t0_utc`` is that
|
|
28
|
+
earliest timestamp as ``datetime64[ms]`` (UTC).
|
|
29
|
+
|
|
30
|
+
Raises
|
|
31
|
+
------
|
|
32
|
+
ValueError
|
|
33
|
+
If any value cannot be parsed as an ISO datetime.
|
|
34
|
+
"""
|
|
35
|
+
import datetime
|
|
36
|
+
|
|
37
|
+
timestamps = []
|
|
38
|
+
for v in values:
|
|
39
|
+
try:
|
|
40
|
+
v_clean = v.strip().replace(" ", "T")
|
|
41
|
+
dt = datetime.datetime.fromisoformat(v_clean)
|
|
42
|
+
timestamps.append(dt)
|
|
43
|
+
except (ValueError, TypeError):
|
|
44
|
+
raise ValueError(f"Cannot parse datetime: {v}")
|
|
45
|
+
|
|
46
|
+
ts = np.array([np.datetime64(dt, "ms") for dt in timestamps])
|
|
47
|
+
t0 = ts.min()
|
|
48
|
+
x_minutes = ((ts - t0) / np.timedelta64(1, "m")).astype(float)
|
|
49
|
+
return x_minutes, t0
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def parse_jd_column(values: list[str]) -> np.ndarray:
|
|
53
|
+
"""Parse a Julian Date column to floats."""
|
|
54
|
+
return np.array([float(v) for v in values], dtype=float)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _weights_from_errors(err: np.ndarray, col: str) -> np.ndarray:
|
|
58
|
+
"""Build weights under the ``w = 1 / sigma`` convention.
|
|
59
|
+
|
|
60
|
+
Non-finite or non-positive errors are rejected with row context; silently
|
|
61
|
+
clamping them would let a single bad row dominate the fit.
|
|
62
|
+
"""
|
|
63
|
+
for i, value in enumerate(err):
|
|
64
|
+
if not np.isfinite(value) or value <= 0:
|
|
65
|
+
raise ValueError(
|
|
66
|
+
f"Row {i+1}, column '{col}': error must be finite and positive, "
|
|
67
|
+
f"got {value}"
|
|
68
|
+
)
|
|
69
|
+
return 1.0 / err
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _read_rows(
|
|
73
|
+
path: str,
|
|
74
|
+
required_cols: list[str],
|
|
75
|
+
) -> tuple[list[str], list[dict[str, str]]]:
|
|
76
|
+
"""Find the header and data rows of an AAVSO-style CSV file.
|
|
77
|
+
|
|
78
|
+
The header is normally in a comment line like
|
|
79
|
+
``#NAME,DATE-OBS,MAG,MAG_ERR,...``; the first non-comment line is used as
|
|
80
|
+
a fallback.
|
|
81
|
+
|
|
82
|
+
Raises
|
|
83
|
+
------
|
|
84
|
+
ValueError
|
|
85
|
+
If no header or no data rows are found, or a requested column is
|
|
86
|
+
missing.
|
|
87
|
+
"""
|
|
88
|
+
import csv
|
|
89
|
+
|
|
90
|
+
with open(path, encoding="utf-8") as f:
|
|
91
|
+
lines = f.readlines()
|
|
92
|
+
|
|
93
|
+
header_line = None
|
|
94
|
+
data_start = 0
|
|
95
|
+
for i, line in enumerate(lines):
|
|
96
|
+
stripped = line.strip()
|
|
97
|
+
if stripped.startswith("#") and "," in stripped and "=" not in stripped[1:]:
|
|
98
|
+
header_line = stripped[1:].strip()
|
|
99
|
+
data_start = i + 1
|
|
100
|
+
break
|
|
101
|
+
|
|
102
|
+
if header_line is None:
|
|
103
|
+
for i, line in enumerate(lines):
|
|
104
|
+
if line.strip() and not line.strip().startswith("#"):
|
|
105
|
+
header_line = line.strip()
|
|
106
|
+
data_start = i + 1
|
|
107
|
+
break
|
|
108
|
+
|
|
109
|
+
if header_line is None:
|
|
110
|
+
raise ValueError("No header found in file")
|
|
111
|
+
|
|
112
|
+
fieldnames = [c.strip() for c in header_line.split(",")]
|
|
113
|
+
|
|
114
|
+
data_lines = [
|
|
115
|
+
line for line in lines[data_start:]
|
|
116
|
+
if line.strip() and not line.strip().startswith("#")
|
|
117
|
+
]
|
|
118
|
+
if not data_lines:
|
|
119
|
+
raise ValueError("No data rows found")
|
|
120
|
+
|
|
121
|
+
rows = list(csv.DictReader(data_lines, fieldnames=fieldnames))
|
|
122
|
+
if not rows:
|
|
123
|
+
raise ValueError("No data rows found")
|
|
124
|
+
|
|
125
|
+
for col in required_cols:
|
|
126
|
+
if col not in fieldnames:
|
|
127
|
+
raise ValueError(f"Column '{col}' not found. Available: {fieldnames}")
|
|
128
|
+
|
|
129
|
+
return fieldnames, rows
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _float_column(rows: list[dict[str, str]], col: str) -> np.ndarray:
|
|
133
|
+
"""Convert a column to floats, reporting the row and column on failure."""
|
|
134
|
+
values = []
|
|
135
|
+
for i, row in enumerate(rows):
|
|
136
|
+
try:
|
|
137
|
+
values.append(float(row[col]))
|
|
138
|
+
except (ValueError, TypeError):
|
|
139
|
+
raise ValueError(
|
|
140
|
+
f"Row {i+1}, column '{col}': cannot convert '{row[col]}' to float"
|
|
141
|
+
)
|
|
142
|
+
return np.array(values)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def read_csv_file(
|
|
146
|
+
path: str,
|
|
147
|
+
x_col: str,
|
|
148
|
+
y_col: str,
|
|
149
|
+
w_col: str | None,
|
|
150
|
+
time_format: str,
|
|
151
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray | None, np.datetime64 | None]:
|
|
152
|
+
"""Read a CSV file and extract ``x``, ``y`` and optional weights.
|
|
153
|
+
|
|
154
|
+
Handles AAVSO-style extended format where the column header is in a
|
|
155
|
+
comment line like ``#NAME,DATE-OBS,MAG,MAG_ERR,...``. The ordinate column
|
|
156
|
+
(typically ``MAG``) is used as-is, on the logarithmic magnitude scale:
|
|
157
|
+
for an eclipsing binary the eclipse minimum is therefore a *maximum* of
|
|
158
|
+
``y``, so the caller should use ``find_peak=True``.
|
|
159
|
+
|
|
160
|
+
Parameters
|
|
161
|
+
----------
|
|
162
|
+
path : str
|
|
163
|
+
Path to the CSV file.
|
|
164
|
+
x_col, y_col : str
|
|
165
|
+
Names of the time and ordinate columns.
|
|
166
|
+
w_col : str or None
|
|
167
|
+
Name of the measurement-error column, or None.
|
|
168
|
+
time_format : str
|
|
169
|
+
``"iso"`` (DATE-OBS to minutes and UTC) or ``"jd"``. Heliocentric
|
|
170
|
+
and barycentric corrections are out of scope.
|
|
171
|
+
|
|
172
|
+
Returns
|
|
173
|
+
-------
|
|
174
|
+
tuple[np.ndarray, np.ndarray, np.ndarray or None, np.datetime64 or None]
|
|
175
|
+
``(x, y, w, t0_utc)``. For ``"iso"``, ``x`` is minutes from the first
|
|
176
|
+
timestamp and ``t0_utc`` is that timestamp; for ``"jd"``, ``x`` is the
|
|
177
|
+
Julian Date and ``t0_utc`` is None.
|
|
178
|
+
"""
|
|
179
|
+
_, rows = _read_rows(path, [x_col, y_col] + ([w_col] if w_col else []))
|
|
180
|
+
y = _float_column(rows, y_col)
|
|
181
|
+
w = _weights_from_errors(_float_column(rows, w_col), w_col) if w_col else None
|
|
182
|
+
|
|
183
|
+
x_raw = [row[x_col] for row in rows]
|
|
184
|
+
t0_utc = None
|
|
185
|
+
if time_format == "iso":
|
|
186
|
+
x, t0_utc = parse_datetime_column(x_raw)
|
|
187
|
+
elif time_format == "jd":
|
|
188
|
+
x = parse_jd_column(x_raw)
|
|
189
|
+
else:
|
|
190
|
+
raise ValueError(f"Unknown time_format: {time_format}")
|
|
191
|
+
|
|
192
|
+
return x, y, w, t0_utc
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def load_aavso(
|
|
196
|
+
path: str,
|
|
197
|
+
x_col: str = "DATE-OBS",
|
|
198
|
+
y_col: str = "MAG",
|
|
199
|
+
err_col: str = "MAG_ERR",
|
|
200
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.datetime64, str, np.ndarray]:
|
|
201
|
+
"""Read an AAVSO extended-format file into arrays.
|
|
202
|
+
|
|
203
|
+
Returns
|
|
204
|
+
-------
|
|
205
|
+
tuple[np.ndarray, np.ndarray, np.ndarray, np.datetime64, str, np.ndarray]
|
|
206
|
+
``(x_minutes, y_mag, w, t0_utc, star_name, mag_err)`` where ``x`` is
|
|
207
|
+
the time in minutes from the first observation, ``y`` the magnitude
|
|
208
|
+
as reported (logarithmic scale), ``w`` the weights ``1 / MAG_ERR``,
|
|
209
|
+
``t0_utc`` the first timestamp, ``star_name`` the value of the
|
|
210
|
+
``NAME`` column and ``mag_err`` the photometric error of each point
|
|
211
|
+
in magnitudes (the ``MAG_ERR`` column as-is).
|
|
212
|
+
"""
|
|
213
|
+
_, rows = _read_rows(path, [x_col, y_col, err_col])
|
|
214
|
+
|
|
215
|
+
star_name = rows[0]["NAME"]
|
|
216
|
+
x, t0 = parse_datetime_column([row[x_col] for row in rows])
|
|
217
|
+
y = _float_column(rows, y_col)
|
|
218
|
+
err = _float_column(rows, err_col)
|
|
219
|
+
w = _weights_from_errors(err, err_col)
|
|
220
|
+
|
|
221
|
+
return x, y, w, t0, star_name, err
|
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
"""Plotting utilities for reflection-method (optional `[plot]` extra).
|
|
2
|
+
|
|
3
|
+
Uses matplotlib. All functions accept an optional `ax` parameter for subplot
|
|
4
|
+
embedding. The main function `plot_all` creates the standard 4-panel composite
|
|
5
|
+
figure matching the notebook visualization.
|
|
6
|
+
|
|
7
|
+
Dependencies
|
|
8
|
+
------------
|
|
9
|
+
Requires the `[plot]` extra: ``pip install "reflection-method[plot]"``.
|
|
10
|
+
This installs matplotlib as a dependency.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from typing import Optional
|
|
14
|
+
import numpy as np
|
|
15
|
+
import matplotlib.pyplot as plt
|
|
16
|
+
from matplotlib.axes import Axes
|
|
17
|
+
from matplotlib.figure import Figure
|
|
18
|
+
from matplotlib.dates import AutoDateLocator, DateFormatter
|
|
19
|
+
|
|
20
|
+
from .core import LSQUnivariateSpline
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _minutes_to_datetime64(t0: np.datetime64, minutes: np.ndarray) -> np.ndarray:
|
|
24
|
+
"""Convert array of minutes-from-t0 to matplotlib-compatible datetime64."""
|
|
25
|
+
return t0 + (minutes * 60_000).astype("timedelta64[ms]")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _utc_label(t0: np.datetime64, x0_minutes: float) -> str:
|
|
29
|
+
"""ISO-8601 UTC string for an ``x0`` expressed in minutes from ``t0``."""
|
|
30
|
+
ts = t0 + np.timedelta64(int(round(x0_minutes * 60)), "s")
|
|
31
|
+
return np.datetime_as_string(ts, unit="s", timezone="UTC")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def plot_original_spline(
|
|
35
|
+
x: np.ndarray,
|
|
36
|
+
y: np.ndarray,
|
|
37
|
+
spl1: LSQUnivariateSpline,
|
|
38
|
+
x0_opt: float,
|
|
39
|
+
x0_std: float,
|
|
40
|
+
xlabel: str = "Time",
|
|
41
|
+
ylabel: str = "magnitude",
|
|
42
|
+
x_unit: str = "",
|
|
43
|
+
invert_y: bool = False,
|
|
44
|
+
utc0: Optional[np.datetime64] = None,
|
|
45
|
+
ax: Optional[Axes] = None,
|
|
46
|
+
) -> Axes:
|
|
47
|
+
"""Plot original data, initial spline fit, and the optimal ``x₀`` line.
|
|
48
|
+
|
|
49
|
+
Parameters
|
|
50
|
+
----------
|
|
51
|
+
x : np.ndarray
|
|
52
|
+
Original abscissae (time, phase, etc.).
|
|
53
|
+
y : np.ndarray
|
|
54
|
+
Original ordinates (flux, magnitude, etc.).
|
|
55
|
+
spl1 : LSQUnivariateSpline
|
|
56
|
+
Initial spline fit to the original data (without reflection).
|
|
57
|
+
x0_opt : float
|
|
58
|
+
Optimal reflection point found by the reflection method.
|
|
59
|
+
x0_std : float
|
|
60
|
+
Bootstrap standard error of ``x0_opt``.
|
|
61
|
+
xlabel : str, optional
|
|
62
|
+
Label for the x-axis (without unit). Default "Time".
|
|
63
|
+
ylabel : str, optional
|
|
64
|
+
Label for the y-axis. Default "magnitude".
|
|
65
|
+
x_unit : str, optional
|
|
66
|
+
Unit string for the x-axis (e.g., "min", "JD", "phase"). Appended to
|
|
67
|
+
the xlabel in brackets. Default "" (no unit).
|
|
68
|
+
invert_y : bool, optional
|
|
69
|
+
If True, invert the y-axis so that smaller values are on top — the
|
|
70
|
+
standard convention when plotting magnitudes (brighter stars up).
|
|
71
|
+
Default False.
|
|
72
|
+
utc0 : np.datetime64 or None, optional
|
|
73
|
+
Origin timestamp for the abscissae, which are then interpreted as
|
|
74
|
+
minutes from ``utc0`` and the x-axis is labelled with UTC clock times.
|
|
75
|
+
Default None (numeric x-axis, ``x_unit`` used for the label).
|
|
76
|
+
ax : matplotlib.axes.Axes or None, optional
|
|
77
|
+
Axes to plot on. If None, a new figure and axes are created.
|
|
78
|
+
|
|
79
|
+
Returns
|
|
80
|
+
-------
|
|
81
|
+
matplotlib.axes.Axes
|
|
82
|
+
The axes object with the plot.
|
|
83
|
+
|
|
84
|
+
Examples
|
|
85
|
+
--------
|
|
86
|
+
>>> from reflection_method import fit_spline, find_x0
|
|
87
|
+
>>> from reflection_method.plot import plot_original_spline
|
|
88
|
+
>>> import matplotlib.pyplot as plt
|
|
89
|
+
>>> spl1 = fit_spline(x, y, pts_per_knot=10)
|
|
90
|
+
>>> x0_opt, _, _ = find_x0(x, y)
|
|
91
|
+
>>> ax = plot_original_spline(x, y, spl1, x0_opt, 0.01, xlabel="Phase", x_unit="")
|
|
92
|
+
>>> plt.show()
|
|
93
|
+
"""
|
|
94
|
+
if ax is None:
|
|
95
|
+
fig, ax = plt.subplots(figsize=(8, 4))
|
|
96
|
+
|
|
97
|
+
if utc0 is not None:
|
|
98
|
+
x_plot = _minutes_to_datetime64(utc0, x)
|
|
99
|
+
xs = np.linspace(x.min(), x.max(), 600)
|
|
100
|
+
xs_plot = _minutes_to_datetime64(utc0, xs)
|
|
101
|
+
x0_opt_plot = _minutes_to_datetime64(utc0, np.array([x0_opt]))[0]
|
|
102
|
+
else:
|
|
103
|
+
x_plot = x
|
|
104
|
+
xs = np.linspace(x.min(), x.max(), 600)
|
|
105
|
+
xs_plot = xs
|
|
106
|
+
x0_opt_plot = x0_opt
|
|
107
|
+
|
|
108
|
+
ax.scatter(x_plot, y, s=8, alpha=0.6, label="data", color="C0", edgecolors="none")
|
|
109
|
+
ax.plot(xs_plot, spl1(xs), label="original spline", color="royalblue", linewidth=1.5)
|
|
110
|
+
|
|
111
|
+
y_min, y_max = float(y.min()), float(y.max())
|
|
112
|
+
if utc0 is not None:
|
|
113
|
+
x0_label = f"x₀ = {_utc_label(utc0, x0_opt)} ± {x0_std * 60:.0f} s"
|
|
114
|
+
else:
|
|
115
|
+
x0_label = f"x₀ = {x0_opt:.2f} ± {x0_std:.2f}"
|
|
116
|
+
if x_unit:
|
|
117
|
+
x0_label += f" {x_unit}"
|
|
118
|
+
ax.axvline(x0_opt_plot, color="red", linewidth=1.5, label=x0_label)
|
|
119
|
+
|
|
120
|
+
if utc0 is not None:
|
|
121
|
+
ax.set_xlabel(f"{xlabel} [UTC]")
|
|
122
|
+
ax.xaxis.set_major_locator(AutoDateLocator())
|
|
123
|
+
ax.xaxis.set_major_formatter(DateFormatter("%H:%M"))
|
|
124
|
+
else:
|
|
125
|
+
ax.set_xlabel(f"{xlabel} [{x_unit}]" if x_unit else xlabel)
|
|
126
|
+
ax.set_ylabel(ylabel)
|
|
127
|
+
ax.set_title("Light curve and original spline with x₀")
|
|
128
|
+
ax.legend(loc="lower left", framealpha=0.7)
|
|
129
|
+
ax.grid(True, alpha=0.3)
|
|
130
|
+
|
|
131
|
+
if invert_y:
|
|
132
|
+
ax.invert_yaxis()
|
|
133
|
+
|
|
134
|
+
return ax
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def plot_scan(
|
|
138
|
+
x0_grid: np.ndarray,
|
|
139
|
+
sigma1: np.ndarray,
|
|
140
|
+
sigma2: np.ndarray,
|
|
141
|
+
spl_sigma: np.poly1d,
|
|
142
|
+
x0_opt: float,
|
|
143
|
+
x0_grid_idx_min: int,
|
|
144
|
+
xlabel: str = "x₀",
|
|
145
|
+
ylabel: str = "residual σ",
|
|
146
|
+
x_unit: str = "",
|
|
147
|
+
ax: Optional[Axes] = None,
|
|
148
|
+
) -> Axes:
|
|
149
|
+
"""Plot σ₁, σ₂, and the polynomial fit to σ₂ with vertical lines at minima.
|
|
150
|
+
|
|
151
|
+
Parameters
|
|
152
|
+
----------
|
|
153
|
+
x0_grid : np.ndarray
|
|
154
|
+
Grid of trial reflection points.
|
|
155
|
+
sigma1 : np.ndarray
|
|
156
|
+
σ values with respect to the original spline (σ₁).
|
|
157
|
+
sigma2 : np.ndarray
|
|
158
|
+
σ values with respect to the refitted spline (σ₂).
|
|
159
|
+
spl_sigma : np.poly1d
|
|
160
|
+
Polynomial fit (np.poly1d) to the σ₂ curve.
|
|
161
|
+
x0_opt : float
|
|
162
|
+
Optimal reflection point from the refined minimum.
|
|
163
|
+
x0_grid_idx_min : int
|
|
164
|
+
Index of the minimum ``sigma2`` on the grid (before refinement).
|
|
165
|
+
xlabel : str, optional
|
|
166
|
+
Label for the x-axis. Default "x₀".
|
|
167
|
+
ylabel : str, optional
|
|
168
|
+
Label for the y-axis. Default "residual σ".
|
|
169
|
+
x_unit : str, optional
|
|
170
|
+
Unit string for the x-axis. Default "".
|
|
171
|
+
ax : matplotlib.axes.Axes or None, optional
|
|
172
|
+
Axes to plot on. If None, a new figure and axes are created.
|
|
173
|
+
|
|
174
|
+
Returns
|
|
175
|
+
-------
|
|
176
|
+
matplotlib.axes.Axes
|
|
177
|
+
The axes object with the plot.
|
|
178
|
+
"""
|
|
179
|
+
if ax is None:
|
|
180
|
+
fig, ax = plt.subplots(figsize=(8, 4))
|
|
181
|
+
|
|
182
|
+
xs = np.linspace(x0_grid[0], x0_grid[-1], 200)
|
|
183
|
+
|
|
184
|
+
ax.plot(x0_grid, sigma1, label="σ w.r.t. original spline", color="royalblue", linewidth=1)
|
|
185
|
+
ax.plot(x0_grid, sigma2, label="σ w.r.t. refitted spline", color="mediumseagreen", linewidth=1)
|
|
186
|
+
ax.plot(xs, spl_sigma(xs), label="polynomial fit to σ₂", color="darkgreen", linestyle=":", linewidth=1.5)
|
|
187
|
+
|
|
188
|
+
ax.axvline(x0_grid[x0_grid_idx_min], color="royalblue", linestyle="--", linewidth=1, alpha=0.7)
|
|
189
|
+
x0_label = f"x₀ = {x0_opt:.2f}"
|
|
190
|
+
if x_unit:
|
|
191
|
+
x0_label += f" {x_unit}"
|
|
192
|
+
ax.axvline(x0_opt, color="red", linewidth=1.5, label=x0_label)
|
|
193
|
+
|
|
194
|
+
ax.set_xlabel(f"{xlabel} [{x_unit}]" if x_unit else xlabel)
|
|
195
|
+
ax.set_ylabel(ylabel)
|
|
196
|
+
ax.set_title("σ (standard deviation of residual) as a function of the reflection point x₀")
|
|
197
|
+
ax.legend(loc="upper left", framealpha=0.7)
|
|
198
|
+
ax.grid(True, alpha=0.3)
|
|
199
|
+
|
|
200
|
+
return ax
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def plot_all(
|
|
204
|
+
x: np.ndarray,
|
|
205
|
+
y: np.ndarray,
|
|
206
|
+
spl1: LSQUnivariateSpline,
|
|
207
|
+
xr: np.ndarray,
|
|
208
|
+
spl2: LSQUnivariateSpline,
|
|
209
|
+
x0_opt: float,
|
|
210
|
+
x0_std: float,
|
|
211
|
+
x0_grid: np.ndarray,
|
|
212
|
+
sigma2: np.ndarray,
|
|
213
|
+
spl_sigma: np.poly1d,
|
|
214
|
+
x0_boot: np.ndarray,
|
|
215
|
+
xlabel: str = "Time",
|
|
216
|
+
ylabel: str = "magnitude",
|
|
217
|
+
x_unit: str = "",
|
|
218
|
+
invert_y: bool = False,
|
|
219
|
+
utc0: Optional[np.datetime64] = None,
|
|
220
|
+
fit_window_lo: Optional[float] = None,
|
|
221
|
+
fit_window_hi: Optional[float] = None,
|
|
222
|
+
**kwargs,
|
|
223
|
+
) -> Figure:
|
|
224
|
+
"""Create the standard 4-panel reflection-method diagnostic figure.
|
|
225
|
+
|
|
226
|
+
Produces a 2×2 figure with the following panels:
|
|
227
|
+
|
|
228
|
+
1. **Main (left, full height)**: Light curve with original data, reflected
|
|
229
|
+
points, original spline, refitted spline (data + reflection), and
|
|
230
|
+
the optimal ``x₀`` vertical line with uncertainty.
|
|
231
|
+
2. **σ₂ scan (top right)**: The ``σ₂(x₀)`` curve as data points with the
|
|
232
|
+
polynomial fit (drawn only over the window used for the fit), and the
|
|
233
|
+
optimal ``x₀`` line. X-axis limited to ``±3σ`` around the optimum for
|
|
234
|
+
consistency with the histogram.
|
|
235
|
+
3. **Bootstrap histogram (bottom right)**: Distribution of bootstrap
|
|
236
|
+
``x₀`` estimates with the optimal ``x₀`` line. Same x-axis limits
|
|
237
|
+
as the σ₂ scan.
|
|
238
|
+
|
|
239
|
+
Parameters
|
|
240
|
+
----------
|
|
241
|
+
x : np.ndarray
|
|
242
|
+
Original abscissae.
|
|
243
|
+
y : np.ndarray
|
|
244
|
+
Original ordinates.
|
|
245
|
+
spl1 : LSQUnivariateSpline
|
|
246
|
+
Initial spline fit to original data.
|
|
247
|
+
xr : np.ndarray
|
|
248
|
+
Reflected abscissae (``2 * x0_opt - x``).
|
|
249
|
+
spl2 : LSQUnivariateSpline
|
|
250
|
+
Spline fit to combined (original + reflected) data.
|
|
251
|
+
x0_opt : float
|
|
252
|
+
Optimal reflection point.
|
|
253
|
+
x0_std : float
|
|
254
|
+
Bootstrap standard error of ``x0_opt``.
|
|
255
|
+
x0_grid : np.ndarray
|
|
256
|
+
Scan grid of trial ``x₀`` values.
|
|
257
|
+
sigma2 : np.ndarray
|
|
258
|
+
``σ₂`` values at each grid point.
|
|
259
|
+
spl_sigma : np.poly1d
|
|
260
|
+
Polynomial fit (``np.poly1d``) to ``(x0_grid, sigma2)``, as returned
|
|
261
|
+
by :func:`reflection_method.core.refine_x0_minimum`.
|
|
262
|
+
x0_boot : np.ndarray
|
|
263
|
+
Array of bootstrap ``x₀`` estimates (length = ``n_bootstrap``).
|
|
264
|
+
xlabel : str, optional
|
|
265
|
+
Label for the main x-axis (e.g., "Time", "Phase"). Default "Time".
|
|
266
|
+
ylabel : str, optional
|
|
267
|
+
Label for the y-axis (e.g., "magnitude", "Flux"). Default
|
|
268
|
+
"magnitude".
|
|
269
|
+
x_unit : str, optional
|
|
270
|
+
Unit for the x-axis (e.g., "min", "JD", "HJD", "phase"). Appended
|
|
271
|
+
to axis labels and ``x₀`` labels. Default "".
|
|
272
|
+
invert_y : bool, optional
|
|
273
|
+
If True, invert the y-axis of the main panel so that smaller values
|
|
274
|
+
are on top — the standard convention when plotting magnitudes
|
|
275
|
+
(brighter stars up). Default False.
|
|
276
|
+
utc0 : np.datetime64 or None, optional
|
|
277
|
+
Origin timestamp for the abscissae, which are then interpreted as
|
|
278
|
+
minutes from ``utc0``. The main panel is then labelled with UTC
|
|
279
|
+
clock times instead of the raw numeric axis, and the ``x₀`` label on
|
|
280
|
+
the main panel shows the UTC time of the minimum. The right-hand
|
|
281
|
+
panels (σ₂ scan and histogram) always use relative minutes from x₀
|
|
282
|
+
to show precision. Default None (numeric x-axis, ``x_unit`` used
|
|
283
|
+
for the labels).
|
|
284
|
+
fit_window_lo : float or None, optional
|
|
285
|
+
Lower bound of the window used for the polynomial fit of ``σ₂``,
|
|
286
|
+
in the same units as ``x0_grid``. The fit curve is drawn only over
|
|
287
|
+
this window (the points actually used for the fit). Default None
|
|
288
|
+
(draw over the whole scan range).
|
|
289
|
+
fit_window_hi : float or None, optional
|
|
290
|
+
Upper bound of the fit window, same convention as
|
|
291
|
+
``fit_window_lo``. Default None.
|
|
292
|
+
**kwargs : dict
|
|
293
|
+
Additional keyword arguments (currently unused, for forward
|
|
294
|
+
compatibility).
|
|
295
|
+
|
|
296
|
+
Returns
|
|
297
|
+
-------
|
|
298
|
+
matplotlib.figure.Figure
|
|
299
|
+
The created figure object. Call ``fig.savefig("output.png")`` to save.
|
|
300
|
+
|
|
301
|
+
Notes
|
|
302
|
+
-----
|
|
303
|
+
- The right-hand panels (σ₂ scan and histogram) share the same x-axis
|
|
304
|
+
limits: ``x₀ ± 3 * x0_std``. This ensures consistent visual comparison.
|
|
305
|
+
- The σ₂ scan y-limits are automatically set to the range of the points
|
|
306
|
+
visible within the ``±3σ`` window, with a 10% padding.
|
|
307
|
+
- The σ₂ scan uses a polynomial fit to the curve (quartic by default);
|
|
308
|
+
the fit curve is drawn only over the window that was actually used for
|
|
309
|
+
the fit (``fit_window_lo`` … ``fit_window_hi``), so the fit can be
|
|
310
|
+
judged against the points it was fitted to.
|
|
311
|
+
- The figure size is 10×8 inches with width ratios 0.62:0.38 and
|
|
312
|
+
height ratios 0.5:0.5.
|
|
313
|
+
- The layout uses ``plt.tight_layout()`` for automatic spacing.
|
|
314
|
+
|
|
315
|
+
Examples
|
|
316
|
+
--------
|
|
317
|
+
>>> from reflection_method import find_minimum, find_x0, fit_spline, combine
|
|
318
|
+
>>> from reflection_method.plot import plot_all
|
|
319
|
+
>>> from reflection_method.core import refine_x0_minimum
|
|
320
|
+
>>> import matplotlib.pyplot as plt
|
|
321
|
+
>>>
|
|
322
|
+
>>> result = find_minimum(x, y)
|
|
323
|
+
>>> x0_opt, x0_grid, sigma2 = find_x0(x, y)
|
|
324
|
+
>>> _, spl_sigma, fit_lo, fit_hi = refine_x0_minimum(x0_grid, sigma2)
|
|
325
|
+
>>> spl1 = fit_spline(x, y)
|
|
326
|
+
>>> xr = 2 * x0_opt - x
|
|
327
|
+
>>> spl2 = fit_spline(*combine(x, y, x0_opt))
|
|
328
|
+
>>> # Bootstrap samples needed for the histogram:
|
|
329
|
+
>>> from reflection_method import bootstrap_x0
|
|
330
|
+
>>> *_, x0_boot = bootstrap_x0(x, y, x0_opt, spl1, 10, 3, None, 60, 80, 0.1,
|
|
331
|
+
... return_samples=True)
|
|
332
|
+
>>>
|
|
333
|
+
>>> fig = plot_all(x, y, spl1, xr, spl2, x0_opt, result.x0_std,
|
|
334
|
+
... x0_grid, sigma2, spl_sigma, x0_boot,
|
|
335
|
+
... xlabel="Time", ylabel="Flux", x_unit="min",
|
|
336
|
+
... fit_window_lo=fit_lo, fit_window_hi=fit_hi)
|
|
337
|
+
>>> fig.savefig("output.png", dpi=150, bbox_inches="tight")
|
|
338
|
+
"""
|
|
339
|
+
fig = plt.figure(figsize=(10, 8))
|
|
340
|
+
gs = fig.add_gridspec(2, 2, width_ratios=[0.62, 0.38], height_ratios=[0.5, 0.5])
|
|
341
|
+
ax_main = fig.add_subplot(gs[:, 0])
|
|
342
|
+
ax_sigma = fig.add_subplot(gs[0, 1])
|
|
343
|
+
ax_hist = fig.add_subplot(gs[1, 1])
|
|
344
|
+
|
|
345
|
+
# Determine x0 range for right panels (±3σ)
|
|
346
|
+
x0_range = 3 * x0_std
|
|
347
|
+
x0_xlim = (x0_opt - x0_range, x0_opt + x0_range)
|
|
348
|
+
|
|
349
|
+
# --- Panel 1: Main ---
|
|
350
|
+
xs = np.linspace(x.min(), x.max(), 600)
|
|
351
|
+
xs2 = np.linspace(min(x.min(), xr.min()), max(x.max(), xr.max()), 600)
|
|
352
|
+
|
|
353
|
+
if utc0 is not None:
|
|
354
|
+
x_plot = _minutes_to_datetime64(utc0, x)
|
|
355
|
+
xr_plot = _minutes_to_datetime64(utc0, xr)
|
|
356
|
+
xs_plot = _minutes_to_datetime64(utc0, xs)
|
|
357
|
+
xs2_plot = _minutes_to_datetime64(utc0, xs2)
|
|
358
|
+
x0_opt_plot = _minutes_to_datetime64(utc0, np.array([x0_opt]))[0]
|
|
359
|
+
else:
|
|
360
|
+
x_plot = x
|
|
361
|
+
xr_plot = xr
|
|
362
|
+
xs_plot = xs
|
|
363
|
+
xs2_plot = xs2
|
|
364
|
+
x0_opt_plot = x0_opt
|
|
365
|
+
|
|
366
|
+
ax_main.scatter(x_plot, y, s=8, alpha=0.6, label="original data", color="C0", edgecolors="none")
|
|
367
|
+
ax_main.scatter(xr_plot, y, s=8, alpha=0.5, label="reflected points", color="orange", edgecolors="none")
|
|
368
|
+
ax_main.plot(xs_plot, spl1(xs), label="original spline", color="royalblue", linewidth=1.5)
|
|
369
|
+
ax_main.plot(xs2_plot, spl2(xs2), label="refitted spline (data + reflection)", color="darkgreen", linestyle="--", linewidth=1.5)
|
|
370
|
+
|
|
371
|
+
y_min, y_max = float(y.min()), float(y.max())
|
|
372
|
+
if utc0 is not None:
|
|
373
|
+
x0_label = f"x₀ = {_utc_label(utc0, x0_opt)} ± {x0_std * 60:.0f} s"
|
|
374
|
+
else:
|
|
375
|
+
x0_label = f"x₀ = {x0_opt:.2f} ± {x0_std:.2f}"
|
|
376
|
+
if x_unit:
|
|
377
|
+
x0_label += f" {x_unit}"
|
|
378
|
+
ax_main.axvline(x0_opt_plot, color="red", linewidth=1.5, label=x0_label)
|
|
379
|
+
|
|
380
|
+
if utc0 is not None:
|
|
381
|
+
ax_main.set_xlabel(f"{xlabel} [UTC]")
|
|
382
|
+
ax_main.xaxis.set_major_locator(AutoDateLocator())
|
|
383
|
+
ax_main.xaxis.set_major_formatter(DateFormatter("%H:%M"))
|
|
384
|
+
else:
|
|
385
|
+
ax_main.set_xlabel(f"{xlabel} [{x_unit}]" if x_unit else xlabel)
|
|
386
|
+
ax_main.set_ylabel(ylabel)
|
|
387
|
+
ax_main.set_title(f"Reflected light curve; {x0_label}")
|
|
388
|
+
ax_main.legend(loc="upper right", fontsize=8, framealpha=0.7)
|
|
389
|
+
ax_main.grid(True, alpha=0.3)
|
|
390
|
+
|
|
391
|
+
if invert_y:
|
|
392
|
+
ax_main.invert_yaxis()
|
|
393
|
+
|
|
394
|
+
# --- Panel 2: σ₂ ---
|
|
395
|
+
# Show fitted window points; X-limits match histogram (±3σ) for direct comparison.
|
|
396
|
+
x0_rel = x0_grid - x0_opt
|
|
397
|
+
xlim_lo, xlim_hi = -3 * x0_std, 3 * x0_std
|
|
398
|
+
|
|
399
|
+
if fit_window_lo is not None and fit_window_hi is not None:
|
|
400
|
+
in_fit = (x0_grid >= fit_window_lo) & (x0_grid <= fit_window_hi)
|
|
401
|
+
ax_sigma.plot(x0_rel[in_fit], sigma2[in_fit], 'o',
|
|
402
|
+
label="σ₂(x₀) — fitted window",
|
|
403
|
+
color="mediumseagreen", markersize=4, alpha=0.9, linewidth=0)
|
|
404
|
+
# Show other scan points in background within ±3σ
|
|
405
|
+
in_view = (x0_rel >= xlim_lo) & (x0_rel <= xlim_hi)
|
|
406
|
+
ax_sigma.plot(x0_rel[in_view & ~in_fit], sigma2[in_view & ~in_fit], 'o',
|
|
407
|
+
label="σ₂(x₀) — other scan points",
|
|
408
|
+
color="lightgrey", markersize=3, alpha=0.4, linewidth=0)
|
|
409
|
+
|
|
410
|
+
fit_lo_rel = fit_window_lo - x0_opt
|
|
411
|
+
fit_hi_rel = fit_window_hi - x0_opt
|
|
412
|
+
xs_fit_rel = np.linspace(fit_lo_rel, fit_hi_rel, 300)
|
|
413
|
+
ax_sigma.plot(xs_fit_rel, spl_sigma(xs_fit_rel + x0_opt),
|
|
414
|
+
label="polynomial fit to σ₂", color="darkgreen", linestyle="-", linewidth=1.5)
|
|
415
|
+
else:
|
|
416
|
+
in_view = (x0_rel >= xlim_lo) & (x0_rel <= xlim_hi)
|
|
417
|
+
ax_sigma.plot(x0_rel[in_view], sigma2[in_view], 'o', label="σ₂(x₀)",
|
|
418
|
+
color="mediumseagreen", markersize=3, alpha=0.7, linewidth=0)
|
|
419
|
+
xs_fit_rel = np.linspace(xlim_lo, xlim_hi, 300)
|
|
420
|
+
ax_sigma.plot(xs_fit_rel, spl_sigma(xs_fit_rel + x0_opt),
|
|
421
|
+
label="polynomial fit to σ₂", color="darkgreen", linestyle="-", linewidth=1.5)
|
|
422
|
+
|
|
423
|
+
ax_sigma.axvline(0, color="red", linewidth=1.5)
|
|
424
|
+
|
|
425
|
+
# X-limits match histogram (±3σ)
|
|
426
|
+
ax_sigma.set_xlim(xlim_lo, xlim_hi)
|
|
427
|
+
|
|
428
|
+
# Y-limits from points within ±3σ with 10% padding
|
|
429
|
+
in_view = (x0_rel >= xlim_lo) & (x0_rel <= xlim_hi)
|
|
430
|
+
sigma_min = float(sigma2[in_view].min())
|
|
431
|
+
sigma_max = float(sigma2[in_view].max())
|
|
432
|
+
y_pad = 0.1 * (sigma_max - sigma_min) if sigma_max > sigma_min else 0.01
|
|
433
|
+
ax_sigma.set_ylim(sigma_min - y_pad, sigma_max + y_pad)
|
|
434
|
+
|
|
435
|
+
ax_sigma.set_ylabel("σ₂")
|
|
436
|
+
ax_sigma.set_title("σ₂(x₀) scan")
|
|
437
|
+
ax_sigma.legend(fontsize=8, framealpha=0.7)
|
|
438
|
+
ax_sigma.grid(True, alpha=0.3)
|
|
439
|
+
ax_sigma.tick_params(labelbottom=False)
|
|
440
|
+
|
|
441
|
+
# --- Panel 3: Histogram ---
|
|
442
|
+
# Plot relative to x0_opt (in minutes) to show precision
|
|
443
|
+
x0_boot_rel = x0_boot - x0_opt
|
|
444
|
+
hist_counts, hist_bins, _ = ax_hist.hist(x0_boot_rel, bins=15, color=(120/255, 120/255, 170/255, 0.6), edgecolor="none", alpha=0.7, label="bootstrap distribution")
|
|
445
|
+
hist_max = float(hist_counts.max())
|
|
446
|
+
ax_hist.axvline(0, color="red", linewidth=1.5)
|
|
447
|
+
|
|
448
|
+
# Same x-limits as σ₂ panel (±3σ)
|
|
449
|
+
x0_rel_xlim = (-3 * x0_std, 3 * x0_std)
|
|
450
|
+
ax_hist.set_xlim(x0_rel_xlim)
|
|
451
|
+
|
|
452
|
+
ax_hist.set_xlabel(f"Δx₀ [{x_unit}]" if x_unit else "Δx₀")
|
|
453
|
+
ax_hist.set_ylabel("count")
|
|
454
|
+
ax_hist.set_title("Bootstrap distribution of x₀")
|
|
455
|
+
ax_hist.legend(fontsize=8, framealpha=0.7)
|
|
456
|
+
ax_hist.grid(True, alpha=0.3)
|
|
457
|
+
|
|
458
|
+
plt.tight_layout()
|
|
459
|
+
return fig
|