From 6b4e86cebd36706faecc24b58d69b6e9750128ba Mon Sep 17 00:00:00 2001 From: StarCells Date: Sat, 14 Nov 2026 15:28:26 +0800 Subject: [PATCH] =?UTF-8?q?pick=20=E7=AA=97=E5=8F=A3=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E6=89=8B=E5=8A=A8=E5=90=88=E5=B9=B6/=E6=8B=86=E5=88=86?= =?UTF-8?q?=EF=BC=88m=20/=20s=20/=20u=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 选中多条按 m 合并:中心按峰高加权,保留最小 id,记录 merged_from - s 拆回、u 撤销;合并结果直接作用于本次导出 - apply_merges 为纯函数,新增 3 项单元测试 --- peak_finder.py | 105 +++++++++++++++++++++++++++++++++++++++----- test_peak_finder.py | 34 ++++++++++++++ 2 files changed, 128 insertions(+), 11 deletions(-) diff --git a/peak_finder.py b/peak_finder.py index e7dff69..522a0b0 100644 --- a/peak_finder.py +++ b/peak_finder.py @@ -1054,6 +1054,51 @@ def fit_window_to_screen(fig, width_fraction: float = 0.94, pass +def apply_merges(lines: list[dict], merges: list[list[str]], calibration) -> list[dict]: + """Merge manually chosen lines; the smallest id survives the merge. + + The centre is the height-weighted mean of the member centres, and each channel + keeps its strongest member. Two lines that both peak in G are one merged line + with one G entry, so the ids are recorded separately in `merged_from`. + """ + + if not merges: + return list(lines) + by_id = {line["id"]: line for line in lines} + consumed: set[str] = set() + merged_lines: list[dict] = [] + for group in merges: + members = [by_id[name] for name in group if name in by_id and name not in consumed] + if len(members) < 2: + continue + weights = np.array([max(0.0, item["height_net_adu"]) for item in members]) + positions = np.array([item["sensor_x_px"] for item in members]) + centre = (float(np.dot(weights, positions) / weights.sum()) + if weights.sum() > 0 else float(positions.mean())) + strongest = max(members, key=lambda item: item["height_net_adu"]) + channels: dict[str, dict] = {} + for member in members: + for channel, peak in member["channels"].items(): + kept = channels.get(channel) + if kept is None or peak["height_net_adu"] > kept["height_net_adu"]: + channels[channel] = dict(peak) + consumed.add(member["id"]) + merged = dict(strongest) + merged.update({ + "id": members[0]["id"], + "sensor_x_px": centre, + "center_spread_px": float(positions.max() - positions.min()), + "channels": channels, + "channel_names": "".join(c for c in ("R", "G", "B") if c in channels), + "merged_from": [member["id"] for member in members], + }) + merged_lines.append(merged) + result = merged_lines + [line for line in lines if line["id"] not in consumed] + attach_wavelength(result, calibration) + result.sort(key=lambda item: item["sensor_x_px"]) + return result + + def pick_peaks(spectrum: SpectrumData, lines: list[dict], calibration, selected: set[str]) -> Optional[set[str]]: """Browse peaks with a live RAW/zoom preview. @@ -1090,20 +1135,34 @@ def pick_peaks(spectrum: SpectrumData, lines: list[dict], calibration, ax_over.legend(loc="upper right", fontsize=8) preview = frame_preview(spectrum) - by_id = {line["id"]: line for line in lines} + base_lines = list(lines) state = {"selected": set(selected), - "focus": lines[0]["id"] if lines else None, - "export": False} + "focus": base_lines[0]["id"] if base_lines else None, + "export": False, + "merges": [], + "view": list(base_lines)} def nearest(x_value: float): found, best = None, float("inf") - for line in lines: + for line in state["view"]: distance = abs(line["x_plot"] - x_value) if distance < best: found, best = line, distance span = abs(ax_over.get_xlim()[1] - ax_over.get_xlim()[0]) return found if found is not None and best <= 0.02 * span else None + def rebuild_view() -> None: + state["view"] = apply_merges(base_lines, state["merges"], calibration) + for handle in handles.values(): + handle.remove() + handles.clear() + for line in state["view"]: + handles[line["id"]] = ax_over.axvline(line["x_plot"], lw=1.0) + ids = {line["id"] for line in state["view"]} + state["selected"] &= ids + if state["focus"] not in ids: + state["focus"] = state["view"][0]["id"] if state["view"] else None + def refresh() -> None: for key, handle in handles.items(): chosen = key in state["selected"] @@ -1113,10 +1172,11 @@ def pick_peaks(spectrum: SpectrumData, lines: list[dict], calibration, chosen = sorted(state["selected"]) ax_over.set_title("Selected: " + (", ".join(chosen) if chosen else "none") + " | hover = preview, click = toggle, a = all, n = none, " + "m = merge selected, s = split, u = undo, " "e = export, q = cancel", fontsize=9) ax_raw.clear() ax_zoom.clear() - line = by_id.get(state["focus"]) + line = {item["id"]: item for item in state["view"]}.get(state["focus"]) if line is not None: draw_preview_panel(ax_raw, spectrum, line, preview) low, high = zoom_range(spectrum, line) @@ -1154,8 +1214,29 @@ def pick_peaks(spectrum: SpectrumData, lines: list[dict], calibration, refresh() def on_key(event) -> None: - if event.key == "a": - state["selected"] = {line["id"] for line in lines} + if event.key == "m": + group = sorted(state["selected"]) + if len(group) >= 2: + state["merges"].append(group) + rebuild_view() + state["selected"] = {state["view"][0]["id"]} if False else {group[0]} + state["focus"] = group[0] + refresh() + elif event.key == "u": + if state["merges"]: + state["merges"].pop() + rebuild_view() + refresh() + elif event.key == "s": + focused = {line["id"]: line for line in state["view"]}.get(state["focus"]) + if focused is not None and focused.get("merged_from"): + for group in list(state["merges"]): + if focused["id"] in group: + state["merges"].remove(group) + rebuild_view() + refresh() + elif event.key == "a": + state["selected"] = {line["id"] for line in state["view"]} refresh() elif event.key == "n": state["selected"] = set() @@ -1173,7 +1254,8 @@ def pick_peaks(spectrum: SpectrumData, lines: list[dict], calibration, plt.show(block=True) if not state["export"]: return None - return state["selected"] + return {"selected": state["selected"], "merges": state["merges"], + "lines": state["view"]} # --------------------------------------------------------------------------- @@ -1362,13 +1444,14 @@ def run(args) -> int: if matplotlib.get_backend().lower() in ("agg", "pdf", "svg", "ps", "cairo", "template"): raise ValueError("--pick needs an interactive Matplotlib backend; use --select instead") try: - chosen = pick_peaks(spectrum, lines, calibration, set()) + picked = pick_peaks(spectrum, lines, calibration, set()) except Exception as exc: # no usable display, missing Tk, ... raise ValueError(f"--pick could not open a window ({exc}); use --select instead") from exc - if chosen is None: + if picked is None: tell("Selection cancelled; nothing exported.") return 1 - selected = chosen + lines = picked["lines"] # manual merges applied + selected = picked["selected"] elif not lines: selected = set() else: diff --git a/test_peak_finder.py b/test_peak_finder.py index 490d2b2..6e8f634 100644 --- a/test_peak_finder.py +++ b/test_peak_finder.py @@ -539,6 +539,40 @@ class EndToEndTests(unittest.TestCase): self.assertAlmostEqual(float(row["wavelength_nm"]), 545.8237 - 10.0, delta=0.2) +class ManualMergeTests(unittest.TestCase): + """Manual merges chosen in the picker: smallest id survives.""" + + def _line(self, ident, x, height): + peak = {"center_px": x, "sensor_x_px": x, "height_net_adu": height, + "snr": height, "fwhm_px": 6.0, "area_net_adu_px": height * 6.0, + "saturated": False, "center_spread_px": 0.0, "fit_ok": True, + "center_err_px": float("nan"), "channel": "G", + "sample_index": int(x / 2), "center_parabola_px": x, + "center_fit_px": x, "fwhm_halfmax_px": 6.0, "prominence_adu": height, + "fit_rms_adu": 1.0, "fit_params": None, "window_lo_px": x - 6.0, + "window_hi_px": x + 6.0, "fit_xref": 0.0, "center_source": "fit", + "sigma_px": 2.5, "undersampled": False} + line = pf.summarise_line({"G": dict(peak)}) + line["id"] = ident + return line + + def test_merge_takes_the_weighted_centre_and_keeps_the_first_id(self): + lines = [self._line("P001", 910.0, 1000.0), self._line("P002", 920.0, 1000.0)] + merged = pf.apply_merges(lines, [["P001", "P002"]], None) + self.assertEqual([line["id"] for line in merged], ["P001"]) + self.assertAlmostEqual(merged[0]["sensor_x_px"], 915.0, places=3) + self.assertEqual(merged[0]["merged_from"], ["P001", "P002"]) + + def test_no_merge_returns_the_original_order(self): + lines = [self._line("P001", 910.0, 1000.0), self._line("P002", 920.0, 1000.0)] + self.assertEqual([line["id"] for line in pf.apply_merges(lines, [], None)], + ["P001", "P002"]) + + def test_single_member_group_is_ignored(self): + lines = [self._line("P001", 910.0, 1000.0)] + self.assertEqual(len(pf.apply_merges(lines, [["P001"]], None)), 1) + + if __name__ == "__main__": unittest.main()