import csv import json import os import tempfile import unittest from pathlib import Path from types import SimpleNamespace import numpy as np import peak_finder as pf import spectro_core as core HERE = Path(__file__).resolve().parent TEST_TMP = os.environ.get("PEAK_FINDER_TEST_TMP") def _find_recording(name: str) -> Path: """Look for recordings/ here and one or two levels up. The recordings often live beside the program folder (Light/recordings vs Light/Programs), so a fixed path would silently skip the end-to-end tests. """ for base in (HERE, HERE.parent, HERE.parent.parent): candidate = base / "recordings" / name if candidate.is_dir(): return candidate return HERE / "recordings" / name # Optional overrides let the end-to-end tests run against a recording kept elsewhere. RECORDING = Path(os.environ.get("PEAK_FINDER_TEST_RECORDING", _find_recording("hq_20261101_114417"))) CALIBRATION = Path(os.environ.get("PEAK_FINDER_TEST_CALIBRATION", HERE / "wavelength_calibration" / "calibration.json")) MODULE_DIR = Path(os.environ.get("PEAK_FINDER_TEST_MODULE_DIR", HERE)) AVAILABLE = RECORDING.is_dir() and CALIBRATION.is_file() def read_rows(path) -> list[dict]: with open(path, newline="", encoding="utf-8") as handle: return list(csv.DictReader(handle)) class temp_directory: """Scratch directory context manager; PEAK_FINDER_TEST_TMP overrides the location. A plain ``mkdir`` is used instead of ``tempfile.mkdtemp`` so the directory keeps the parent's permissions, which matters inside restrictive sandboxes. """ def __init__(self): import shutil import uuid self._shutil = shutil base = Path(TEST_TMP) if TEST_TMP else Path(tempfile.gettempdir()) base.mkdir(parents=True, exist_ok=True) self.path = base / f"pf_case_{uuid.uuid4().hex[:10]}" self.path.mkdir() def __enter__(self) -> str: return str(self.path) def __exit__(self, *exc_info) -> bool: self._shutil.rmtree(self.path, ignore_errors=True) return False def gaussian(x, amplitude, center, sigma, base=0.0, slope=0.0, xref=None): xref = float(np.mean(x)) if xref is None else xref return base + slope * (x - xref) + amplitude * np.exp(-0.5 * ((x - center) / sigma) ** 2) def make_peak(center, height, fwhm, snr, channel="G", **extra): peak = { "channel": channel, "sample_index": int(round(center / 2.0)), "sensor_x_px": float(round(center / 2.0) * 2.0), "center_px": float(center), "center_source": "fit", "center_parabola_px": float(center) + 0.3, "center_fit_px": float(center), "sigma_px": fwhm / 2.3548200450309493, "fwhm_px": fwhm, "fwhm_halfmax_px": fwhm * 1.02, "height_net_adu": height, "prominence_adu": height * 0.9, "raw_adu": height + 100.0, "baseline_adu": 10.0, "snr": snr, "area_net_adu_px": height * fwhm, "saturated": False, "fit_ok": True, "fit_rms_adu": height * 0.02, "fit_shape": "gauss", "fit_params": [height, float(center), fwhm / 2.3548200450309493, 10.0, 0.0], "fit_xref": float(center), "window_lo_px": float(center) - 20.0, "window_hi_px": float(center) + 20.0, "window_lo_sample": 0, "window_hi_sample": 10, } peak.update(extra) return peak def make_lines(): wavelengths = [404.7, 435.8, 546.1, 577.0, 579.1] return [ {"id": f"P{index:03d}", "wavelength_nm": value, "sensor_x_px": 200.0 + 100.0 * index, "snr": float(10 * index), "center_spread_px": 0.5, "extrapolated": False} for index, value in enumerate(wavelengths, 1) ] class EstimatorTests(unittest.TestCase): def test_baseline_follows_continuum_not_peaks(self): x = np.arange(0, 600, 2.0) y = 100.0 + 0.05 * x + gaussian(x, 500.0, 300.0, 5.0) baseline = pf.estimate_baseline(y, 50, lambda values, width: values) error = np.abs(baseline - (100.0 + 0.05 * x))[60:-60] self.assertLess(float(np.max(error)), 5.0) def test_baseline_disabled_returns_zero(self): y = np.arange(10.0) np.testing.assert_array_equal(pf.estimate_baseline(y, 0, lambda v, w: v), np.zeros(10)) def test_noise_proxy_of_white_noise(self): rng = np.random.default_rng(7) y = rng.normal(0.0, 7.0, 4000) self.assertAlmostEqual(pf.estimate_noise(y), 7.0, delta=0.5) def test_parabola_and_half_max_width(self): x = np.arange(0, 200, 2.0) y = gaussian(x, 1000.0, 101.0, 4.0) index = int(np.argmax(y)) self.assertAlmostEqual(pf.parabola_center(x, y, index), 101.0, delta=0.5) left, right = pf.half_max_crossings(x, y, index, 40) self.assertAlmostEqual(right - left, 2.3548200450309493 * 4.0, delta=0.6) class FitTests(unittest.TestCase): def test_gaussian_fit_recovers_parameters(self): rng = np.random.default_rng(11) x = np.arange(600.0, 700.0, 2.0) truth = gaussian(x, 1200.0, 651.7, 3.4, base=40.0, slope=0.8, xref=650.0) y = truth + rng.normal(0.0, 8.0, x.size) bounds = [(0.0, 20000.0), (580.0, 720.0), (0.8, 40.0), (-2000.0, 2000.0), (-100.0, 100.0)] fit = pf.fit_profile(x, y, [1000.0, 650.0, 4.0, 0.0, 0.0], "gauss", bounds) self.assertTrue(fit["ok"]) self.assertAlmostEqual(fit["center"], 651.7, delta=0.4) self.assertAlmostEqual(fit["fwhm"], 2.3548200450309493 * 3.4, delta=0.6) self.assertAlmostEqual(fit["amplitude"], 1200.0, delta=120.0) def test_lorentzian_fit_recovers_width(self): rng = np.random.default_rng(3) x = np.arange(0.0, 120.0, 2.0) y = 900.0 / (1.0 + ((x - 61.2) / 3.0) ** 2) + rng.normal(0.0, 5.0, x.size) bounds = [(0.0, 10000.0), (20.0, 100.0), (1.0, 20.0), (-500.0, 500.0), (-50.0, 50.0)] fit = pf.fit_profile(x, y, [900.0, 60.0, 3.0, 0.0, 0.0], "lorentz", bounds) self.assertTrue(fit["ok"]) self.assertAlmostEqual(fit["fwhm"], 6.0, delta=0.6) def test_model_values_round_trip(self): x = np.arange(0.0, 10.0) params = [5.0, 4.0, 1.5, 1.0, 0.0] model = pf.model_values(x, params, 4.0, "gauss") self.assertAlmostEqual(float(np.max(model)), 6.0, delta=1e-6) self.assertTrue(np.all(np.isfinite(model))) class DetectionTests(unittest.TestCase): def test_three_peaks_found_in_continuum(self): rng = np.random.default_rng(5) x = np.arange(0.0, 800.0, 2.0) y = (0.02 * x + gaussian(x, 1000.0, 200.0, 4.0) + gaussian(x, 400.0, 400.0, 6.0) + gaussian(x, 120.0, 600.0, 3.0) + rng.normal(0.0, 2.0, x.size)) baseline = pf.estimate_baseline(y, 50, lambda values, width: values) net = y - baseline noise = pf.estimate_noise(net) candidates = pf.find_peak_candidates(net, 4, 20.0, 20.0, 10) centers = sorted(x[item["sample"]] for item in candidates) self.assertEqual(len(centers), 3) for found, expected in zip(centers, (200.0, 400.0, 600.0)): self.assertAlmostEqual(found, expected, delta=4.0) self.assertLess(noise, 5.0) def test_refined_centres_are_sub_sample(self): rng = np.random.default_rng(9) x = np.arange(0.0, 200.0, 2.0) y = gaussian(x, 800.0, 97.3, 2.6) + rng.normal(0.0, 4.0, x.size) baseline = pf.estimate_baseline(y, 40, lambda values, width: values) net = y - baseline noise = pf.estimate_noise(net) candidate = pf.find_peak_candidates(net, 4, 20.0, 20.0, 4)[0] peak = pf.refine_peak(x, net, y, candidate, noise, 2.0, 30, 0, "gauss", False) self.assertAlmostEqual(peak["center_px"], 97.3, delta=0.6) self.assertAlmostEqual(peak["fwhm_px"], 2.3548200450309493 * 2.6, delta=0.8) self.assertTrue(peak["fit_ok"]) def test_silent_profile_has_no_candidates(self): net = np.zeros(50) self.assertEqual(pf.find_peak_candidates(net, 4, 1.0, 1.0, 5), []) class BlendTests(unittest.TestCase): def test_failed_fit_falls_back_to_the_measured_maximum(self): from unittest.mock import patch x = np.arange(400.0, 700.0, 2.0) net = (gaussian(x, 10000.0, 542.0, 15.0) + 4000.0 * np.exp(-np.clip(x - 542.0, 0.0, None) / 120.0)) candidate = {"sample": int(np.argmax(net)), "height_adu": float(net.max()), "base_adu": 0.0, "prominence_adu": float(net.max())} with patch.object(core, "fit_profile", return_value={"ok": False}): peak = pf.refine_peak(x, net, net, candidate, 1.0, 2.0, 30, 0, "gauss", False) self.assertEqual(peak["center_source"], "apex") self.assertAlmostEqual(peak["center_px"], 542.0, delta=1.0) def test_flat_top_falls_back_to_the_sampled_maximum(self): from unittest.mock import patch x = np.arange(0.0, 60.0, 2.0) net = np.full(x.size, 100.0) net[10:16] = 1000.0 # saturated flat top candidate = {"sample": 12, "height_adu": 1000.0, "base_adu": 100.0, "prominence_adu": 900.0} with patch.object(core, "fit_profile", return_value={"ok": False}): peak = pf.refine_peak(x, net, net, candidate, 1.0, 2.0, 30, 0, "gauss", False) self.assertEqual(peak["center_source"], "sample") self.assertAlmostEqual(peak["center_px"], 24.0) # x[12] def test_topographic_prominence_rejects_a_shoulder(self): net = np.array([0.0, 100.0, 200.0, 500.0, 300.0, 400.0, 200.0, 0.0]) prominence, base = pf.peak_prominence(net, 5) self.assertAlmostEqual(prominence, 100.0) self.assertAlmostEqual(base, 300.0) prominence, _ = pf.peak_prominence(net, 3) self.assertAlmostEqual(prominence, 500.0) def test_resolved_doublet_survives_detection(self): rng = np.random.default_rng(21) x = np.arange(780.0, 830.0, 2.0) net = (gaussian(x, 3600.0, 800.0, 2.5) + gaussian(x, 4300.0, 808.0, 2.5) + rng.normal(0.0, 20.0, x.size)) candidates = pf.find_peak_candidates(net, 2, 200.0, 100.0, 10) self.assertEqual(len(candidates), 2) self.assertEqual(sorted(round(float(x[item["sample"]]), 1) for item in candidates), [800.0, 808.0]) def test_doublet_is_deblended_with_one_shared_width(self): rng = np.random.default_rng(22) x = np.arange(780.0, 830.0, 2.0) net = (gaussian(x, 3600.0, 800.0, 2.5) + gaussian(x, 4300.0, 808.0, 2.5) + rng.normal(0.0, 20.0, x.size)) noise = pf.estimate_noise(net) candidates = pf.find_peak_candidates(net, 2, 200.0, 100.0, 10) peaks = [pf.refine_peak(x, net, net, item, noise, 2.0, 30, 0, "gauss", False) for item in candidates] deduped = pf.dedupe_channel_peaks(peaks, 4.0) self.assertEqual(len(deduped), 2) merged = pf.deblend_close_peaks(x, net, deduped, "gauss", 2.0, noise) self.assertEqual(len(merged), 2) self.assertTrue(all(peak["deblended"] for peak in merged)) centres = sorted(peak["center_px"] for peak in merged) self.assertAlmostEqual(centres[0], 800.0, delta=0.8) self.assertAlmostEqual(centres[1], 808.0, delta=0.8) self.assertEqual(len({round(peak["fwhm_px"], 6) for peak in merged}), 1) self.assertAlmostEqual(merged[0]["fwhm_px"], 2.3548200450309493 * 2.5, delta=0.8) for peak in merged: self.assertTrue(np.isfinite(peak["center_err_px"])) def test_coincident_weak_lines_are_merged(self): first = pf.summarise_line({"B": make_peak(912.0, 430.0, 9.2, 75.0, "B")}) second = pf.summarise_line({"R": make_peak(917.0, 70.0, 8.0, 15.0, "R")}) first["id"] = second["id"] = "" lines = [dict(first, sensor_x_px=912.0), dict(second, sensor_x_px=917.0)] self.assertEqual(len(pf.merge_coincident_lines(lines, 1.5)), 2) lines[1]["sensor_x_px"] = 912.4 combined = pf.merge_coincident_lines(lines, 1.5) self.assertEqual(len(combined), 1) self.assertEqual(combined[0]["channel_names"], "RB") class GroupingTests(unittest.TestCase): def test_same_line_in_three_channels_merges(self): peaks = { "R": [make_peak(500.0, 300.0, 9.0, 40.0, "R")], "G": [make_peak(501.0, 1200.0, 10.0, 200.0, "G")], "B": [make_peak(499.5, 800.0, 11.0, 90.0, "B")], } lines = pf.group_channels(peaks, 4.0) self.assertEqual(len(lines), 1) line = lines[0] self.assertEqual(line["channel_names"], "RGB") self.assertEqual(line["primary_channel"], "G") self.assertEqual(line["id"], "P001") self.assertAlmostEqual(line["sensor_x_px"], (300 * 500 + 1200 * 501 + 800 * 499.5) / 2300, places=6) self.assertAlmostEqual(line["center_spread_px"], 1.5, places=6) def test_distinct_lines_stay_separate(self): peaks = {"G": [make_peak(500.0, 100.0, 8.0, 20.0), make_peak(520.0, 90.0, 8.0, 18.0)]} lines = pf.group_channels(peaks, 4.0) self.assertEqual([line["id"] for line in lines], ["P001", "P002"]) def test_channel_duplicate_is_dropped(self): peaks = {"G": [make_peak(500.0, 300.0, 9.0, 50.0), make_peak(500.4, 900.0, 9.0, 90.0)]} lines = pf.group_channels(peaks, 4.0) self.assertEqual(len(lines), 1) self.assertEqual(lines[0]["height_net_adu"], 900.0) def test_dedupe_keeps_neighbours_further_than_distance(self): peaks = [make_peak(100.0, 500.0, 8.0, 40.0), make_peak(112.0, 400.0, 8.0, 30.0), make_peak(103.0, 300.0, 8.0, 20.0)] kept = pf.dedupe_channel_peaks(peaks, 12.0) self.assertEqual([peak["center_px"] for peak in kept], [100.0, 112.0]) class OutputNamingTests(unittest.TestCase): def test_default_output_names_the_frame(self): single = pf.default_output_directory(r"C:\raw\hq_20261112_200710", [7]) self.assertEqual(single.name, "hq_20261112_200710_f0007") stacked = pf.default_output_directory(r"C:\raw\hq_20261112_200710", [5, 6, 7]) self.assertEqual(stacked.name, "hq_20261112_200710_f0005-0007_avg3") self.assertEqual(stacked.parent.name, "peak_exports") class SelectionTests(unittest.TestCase): def setUp(self): self.lines = make_lines() def test_all_and_none(self): self.assertEqual(len(pf.parse_selection("all", self.lines)), 5) self.assertEqual(pf.parse_selection("none", self.lines), set()) self.assertEqual(pf.parse_selection("ALL", self.lines), pf.parse_selection("*", self.lines)) def test_ids_and_ranges(self): self.assertEqual(pf.parse_selection("2", self.lines), {"P002"}) self.assertEqual(pf.parse_selection("1-2", self.lines), {"P001", "P002"}) self.assertEqual(pf.parse_selection("id:4", self.lines), {"P004"}) def test_wavelength_ranges(self): self.assertEqual(pf.parse_selection("nm:540-560", self.lines), {"P003"}) self.assertEqual(pf.parse_selection("540-560", self.lines), {"P003"}) self.assertEqual(pf.parse_selection("546.0", self.lines), {"P003"}) self.assertEqual(pf.parse_selection("nm:430-440", self.lines), {"P002"}) def test_top_n_and_union(self): self.assertEqual(pf.parse_selection("top:2", self.lines), {"P004", "P005"}) self.assertEqual(pf.parse_selection("1,nm:540-560", self.lines), {"P001", "P003"}) def test_bad_tokens_raise(self): for token in ("9", "0", "abc", "id:3-9", "nm:"): with self.assertRaises(ValueError): pf.parse_selection(token, self.lines) def test_wavelength_selection_needs_calibration(self): lines = [dict(line, wavelength_nm=float("nan")) for line in self.lines] with self.assertRaises(ValueError): pf.parse_selection("nm:500-600", lines) self.assertEqual(pf.parse_selection("2", lines), {"P002"}) class CalibrationTests(unittest.TestCase): def write(self, payload): handle = tempfile.NamedTemporaryFile("w", suffix=".json", delete=False, encoding="utf-8", dir=TEST_TMP) handle.write(json.dumps(payload)) handle.close() return handle.name def test_scale_offset_and_inverse(self): path = self.write({"coefficients_descending": [0.285, 349.45], "calibrated_pixel_range": [304.0, 808.5]}) calibration = pf.Calibration(path, offset_nm=0.5) calibration.set_width(2028) self.assertAlmostEqual(float(calibration(600.0)), 0.285 * 600 + 349.45 + 0.5, places=6) self.assertAlmostEqual(float(calibration.dispersion(600.0)), 0.285, places=9) self.assertAlmostEqual(float(calibration.inverse(calibration(600.0))), 600.0, delta=1.0) self.assertAlmostEqual(calibration.nm_span[0], 0.285 * 304 + 349.95, places=6) def test_invalid_calibrations(self): for payload in ({"coefficients_descending": [0.0, 1.0], "calibrated_pixel_range": [1, 2]}, {"coefficients_descending": [1.0], "calibrated_pixel_range": [1, 2]}, {"coefficients_descending": [1.0, 2.0], "calibrated_pixel_range": [3, 2]}, {"coefficients_descending": [1.0, 2.0]}): with self.assertRaises(ValueError): pf.Calibration(self.write(payload)) def test_geometry_checks(self): path = self.write({"coefficients_descending": [0.285, 349.45], "calibrated_pixel_range": [304.0, 808.5]}) calibration = pf.Calibration(path) source = SimpleNamespace(full_size=(2028, 1520), pattern="BGGR") calibration.validate_geometry(source, lambda *a, **k: None) bad = pf.Calibration(self.write({"coefficients_descending": [0.001, -2.0, 900.0], "calibrated_pixel_range": [304.0, 808.5]})) with self.assertRaises(ValueError): bad.validate_geometry(source, lambda *a, **k: None) class LineTableTests(unittest.TestCase): def test_match_nearest_within_tolerance(self): table = [{"wavelength_nm": 546.0, "species": "Hg I", "label": "546"}, {"wavelength_nm": 579.1, "species": "Hg I", "label": "579"}] lines = [{"id": "P001", "wavelength_nm": 546.4, "sensor_x_px": 1.0}, {"id": "P002", "wavelength_nm": 600.0, "sensor_x_px": 2.0}] pf.match_lines(lines, table, 1.5) self.assertEqual(lines[0]["match_species"], "Hg I") self.assertAlmostEqual(lines[0]["match_delta_nm"], 0.4, places=6) self.assertEqual(lines[1]["match_species"], "") self.assertTrue(np.isnan(lines[1]["match_delta_nm"])) def test_csv_table_with_flexible_columns(self): with temp_directory() as folder: path = Path(folder) / "lines.csv" path.write_text("nm,element\n546.0735,Hg I\n435.8328,Hg I\n", encoding="utf-8") table = pf.load_line_table(path) self.assertEqual([entry["wavelength_nm"] for entry in table], [435.8328, 546.0735]) def build_spectrum_and_lines(): """Run the pipeline up to detection, for tests that need real peaks.""" hq = pf.load_hq(str(MODULE_DIR)) args = pf.build_parser().parse_args(["--input", str(RECORDING), "--output", "unused", "--quiet"]) source = hq.RecordingSource(str(RECORDING)) source.start() image, original, indices, frame_meta = pf.read_frames(hq, source, args, lambda *a, **k: None) roi = hq.detect_auto_roi(hq.make_preview(original, source.pattern), *source.full_size) source.close() meta = dict(source.base_meta) meta.update({key: value for key, value in frame_meta.items() if not str(key).startswith("_")}) black, full = hq.resolve_levels(meta, source.bit_depth, args.black, args.full_scale) spectrum = pf.SpectrumData(hq, source, image, original, indices, roi, args, black, full) lines = pf.group_channels(spectrum.detect(), args.group_tol) pf.attach_wavelength(lines, None) return spectrum, lines @unittest.skipUnless(AVAILABLE, "recordings or calibration not available") class PickerTests(unittest.TestCase): def test_hover_previews_and_click_selects(self): import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.backend_bases import KeyEvent, MouseEvent spectrum, lines = build_spectrum_and_lines() self.assertGreaterEqual(len(lines), 3) target = lines[2] seen = {} def fake_show(block=True): figure = plt.gcf() canvas = figure.canvas axes = figure.axes[0] x_display = float(axes.transData.transform((target["x_plot"], 0.0))[0]) y_display = float(axes.transAxes.transform((0.0, 0.5))[1]) canvas.callbacks.process( "motion_notify_event", MouseEvent("motion_notify_event", canvas, x_display, y_display)) seen["axes"] = len(figure.axes) seen["images"] = len(figure.axes[1].images) seen["curves"] = len(figure.axes[2].lines) seen["title"] = figure.axes[2].get_title() canvas.callbacks.process( "button_press_event", MouseEvent("button_press_event", canvas, x_display, y_display, button=1)) canvas.callbacks.process( "key_press_event", KeyEvent("key_press_event", canvas, key="e")) real_show = plt.show plt.show = fake_show try: chosen = pf.pick_peaks(spectrum, lines, None, set()) finally: plt.show = real_show self.assertEqual(chosen, {target["id"]}) self.assertEqual(seen["axes"], 3) # spectrum + RAW patch + zoom self.assertGreaterEqual(seen["images"], 1) # RAW patch rendered self.assertGreaterEqual(seen["curves"], 3) # R/G/B profiles drawn self.assertIn(target["id"], seen["title"]) @unittest.skipUnless(AVAILABLE, "recordings or calibration not available") class EndToEndTests(unittest.TestCase): def test_export_selected_peaks(self): with temp_directory() as folder: code = pf.main(["--input", str(RECORDING), "--calibration", str(CALIBRATION), "--output", folder, "--select", "nm:530-560", "--no-images", "--quiet", "--module-dir", str(MODULE_DIR)]) self.assertEqual(code, 0) output = Path(folder) rows = read_rows(output / "selected_peaks.csv") self.assertTrue(rows) for row in rows: self.assertGreaterEqual(float(row["wavelength_nm"]), 530.0) self.assertLessEqual(float(row["wavelength_nm"]), 560.0) self.assertTrue(0 <= float(row["patch_x0"]) < float(row["patch_x1"]) <= 2028) self.assertTrue(0 <= float(row["patch_y0"]) < float(row["patch_y1"]) <= 1520) self.assertTrue(0 <= float(row["sensor_x_px"])) self.assertTrue((output / row["shape_csv"]).is_file()) manifest = json.loads((output / "peaks.json").read_text(encoding="utf-8")) all_rows = read_rows(output / "peaks_all.csv") self.assertGreaterEqual(len(all_rows), len(manifest["peaks"])) self.assertEqual(manifest["calibration"]["wavelength_offset_nm"], 0.0) self.assertTrue(manifest["coordinate_convention"]["sensor_x_px"]) def test_without_calibration_only_pixels_are_exported(self): with temp_directory() as folder: code = pf.main(["--input", str(RECORDING), "--output", folder, "--select", "top:1", "--no-images", "--quiet", "--module-dir", str(MODULE_DIR)]) self.assertEqual(code, 0) row = read_rows(Path(folder) / "selected_peaks.csv")[0] self.assertEqual(row["wavelength_nm"], "") self.assertGreater(float(row["sensor_x_px"]), 0.0) manifest = json.loads((Path(folder) / "peaks.json").read_text(encoding="utf-8")) self.assertIsNone(manifest["calibration"]) def test_bad_frame_is_rejected(self): code = pf.main(["--input", str(RECORDING), "--frame", "100000", "--quiet", "--output", str(Path(tempfile.gettempdir()) / "pf_unused"), "--no-images", "--module-dir", str(MODULE_DIR)]) self.assertEqual(code, 2) def test_wavelength_offset_shifts_the_scale(self): with temp_directory() as folder: code = pf.main(["--input", str(RECORDING), "--calibration", str(CALIBRATION), "--wavelength-offset", "-10", "--output", folder, "--select", "top:1", "--no-images", "--quiet", "--module-dir", str(MODULE_DIR)]) self.assertEqual(code, 0) row = read_rows(Path(folder) / "selected_peaks.csv")[0] 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()