From 429b823b44c4642895c9fd9ba186bd4d6c473ceb Mon Sep 17 00:00:00 2001 From: StarCells Date: Sat, 14 Nov 2026 16:11:23 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20--stability=20N=EF=BC=9A?= =?UTF-8?q?=E5=A4=9A=E5=B8=A7=E9=87=8D=E5=A4=8D=E6=B5=8B=E9=87=8F=E5=B3=B0?= =?UTF-8?q?=E5=BF=83=E4=B8=8E=20FWHM=20=E7=9A=84=E6=A0=87=E5=87=86?= =?UTF-8?q?=E5=B7=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 连续分析 N 帧,按最近邻匹配同一条线(默认 1.5x 参考 FWHM) - 导出 peak_summary.csv: id, n_frames, x_mean_px, x_std_px, fwhm_mean_px, fwhm_std_px, wavelength_nm - 控制台打印 x ± s_x 与 FWHM ± s_FWHM 简表 --- peak_finder.py | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/peak_finder.py b/peak_finder.py index a4165de..c2c3679 100644 --- a/peak_finder.py +++ b/peak_finder.py @@ -836,6 +836,44 @@ def _clean_output(directory: Path) -> None: stale.unlink() +def summarise_repeats(runs: list[list[dict]], tolerance_px: float = 0.0) -> list[dict]: + """Mean and standard deviation of each line over repeated frames. + + Cross-frame matching uses the nearest centre within `tolerance` (default + 1.5 x the reference FWHM), so a line that drifts by more than that is left as + a missing sample instead of being matched to its neighbour. + """ + + if not runs: + return [] + reference = runs[0] + summary = [] + for line in reference: + width = line["fwhm_px"] if np.isfinite(line["fwhm_px"]) else 8.0 + limit = tolerance_px if tolerance_px > 0 else max(2.0, 1.5 * width) + centres, widths = [], [] + for run in runs: + match = None + for candidate in run: + distance = abs(candidate["sensor_x_px"] - line["sensor_x_px"]) + if distance <= limit and (match is None or distance < abs( + match["sensor_x_px"] - line["sensor_x_px"])): + match = candidate + if match is None: + continue + centres.append(match["sensor_x_px"]) + if np.isfinite(match["fwhm_px"]): + widths.append(match["fwhm_px"]) + entry = {"id": line["id"], "n": len(centres), + "x_mean": float(np.mean(centres)) if centres else float("nan"), + "x_std": float(np.std(centres, ddof=1)) if len(centres) > 1 else float("nan"), + "fwhm_mean": float(np.mean(widths)) if widths else float("nan"), + "fwhm_std": float(np.std(widths, ddof=1)) if len(widths) > 1 else float("nan"), + "wavelength_nm": line.get("wavelength_nm", float("nan"))} + summary.append(entry) + return summary + + def export_all(hq, spectrum: SpectrumData, lines: list[dict], calibration, selected: set[str], args, meta: dict) -> dict: import matplotlib @@ -1313,6 +1351,8 @@ def build_parser() -> argparse.ArgumentParser: detect.add_argument("--fit-window", type=float, default=0.0, metavar="PX", help="half-width of the fit window in sensor px; 0 = automatic") detect.add_argument("--shape", choices=SHAPES, default="gauss", help="line-shape model") + detect.add_argument("--stability", type=int, default=1, metavar="N", + help="also analyse N consecutive frames and report centre/FWHM scatter") export = parser.add_argument_group("selection and export") export.add_argument("--select", default="all", metavar="TOKENS", @@ -1338,6 +1378,8 @@ def build_parser() -> argparse.ArgumentParser: def validate_arguments(args) -> None: if args.average < 1: raise ValueError("--average must be >= 1") + if args.stability < 1: + raise ValueError("--stability must be >= 1") if args.max_peaks < 1: raise ValueError("--max-peaks must be >= 1") if args.peak_distance <= 0 or args.baseline_window < 0 or args.fwhm_span <= 0: @@ -1457,12 +1499,44 @@ def run(args) -> int: else: selected = parse_selection(args.select, lines) + summary = None + if getattr(args, "stability", 1) > 1: + base_frame, runs = args.frame, [lines] + try: + for step in range(1, args.stability): + args.frame, args.average = base_frame + step, 1 + try: + runs.append(analyse(args, tell=lambda *a, **k: None).lines) + except (ValueError, RuntimeError, OSError): + break + finally: + args.frame = base_frame + if len(runs) > 1: + summary = summarise_repeats(runs) + if args.output is None: args.output = str(default_output_directory(args.input, indices)) meta_out = {"created": _timestamp(), "recording": str(Path(args.input).expanduser().resolve())} result = export_all(hq, spectrum, lines, calibration, selected, args, meta_out) + if summary: + write_csv(result["output"] / "peak_summary.csv", + ["id", "n_frames", "x_mean_px", "x_std_px", "fwhm_mean_px", + "fwhm_std_px", "wavelength_nm"], + ([row["id"], row["n"], _num(row["x_mean"], 4), _num(row["x_std"], 4), + _num(row["fwhm_mean"], 4), _num(row["fwhm_std"], 4), + _num(row["wavelength_nm"], 7)] for row in summary)) + tell("") + tell(f"centre/width scatter over {args.stability} frame(s):") + tell(f"{'id':6s}{'n':>3s}{'x_px':>11s}{'s_x':>8s}{'FWHM':>9s}{'s_FWHM':>8s}") + for row in summary: + def _f(value, width, digits): + return f"{'nan':>{width}s}" if not np.isfinite(value) else f"{value:{width}.{digits}f}" + tell(f"{row['id']:6s}{row['n']:3d}{_f(row['x_mean'], 11, 3)}" + f"{_f(row['x_std'], 9, 3)}{_f(row['fwhm_mean'], 9, 3)}" + f"{_f(row['fwhm_std'], 9, 3)}") + tell("") tell(f"{'':2s}{'id':4s}{'nm':>10s}{'x_px':>10s}{'ch':>4s}{'SNR':>9s}{'height':>9s}" f"{'FWHM px':>9s}{'FWHM nm':>9s}{'slit y':>9s} flags")