Files
spectrometer/test_wavelength_calibration.py
starcells ccc7c62569 统一默认输出目录命名
- 命名规则移入 spectro_core.default_output_directory(root, stem, indices)

- wavelength_calibration 默认改为 calibration_exports/<recording>_f<frame>,与 peak_exports 一致;输入为 peaks.json 时镜像其所在目录名

- 新增 3 项命名测试
2026-11-14 14:54:27 +08:00

204 lines
8.6 KiB
Python

"""Tests for wavelength_calibration: peaks in, calibration out."""
from __future__ import annotations
import csv
import json
import shutil
import os
import sys
import tempfile
import unittest
import uuid
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
TEST_TMP = os.environ.get('PEAK_FINDER_TEST_TMP')
def scratch():
"""Temporary directory that works inside restrictive sandboxes."""
base = Path(TEST_TMP) if TEST_TMP else Path(tempfile.gettempdir())
base.mkdir(parents=True, exist_ok=True)
path = base / f'wc_case_{uuid.uuid4().hex[:10]}'
path.mkdir()
return path
import wavelength_calibration as wc # noqa: E402
HG = {"P001": 404.6563, "P002": 435.8328, "P003": 546.0735,
"P004": 576.9598, "P005": 579.0663}
PIXELS = {"P001": 188.4, "P002": 302.5, "P003": 689.2, "P004": 802.1, "P005": 810.4}
def synthetic_peaks() -> list[dict]:
coeff = [0.2815541, 351.2738] # wavelength = coeff[0] * x + coeff[1]
peaks = []
for name, nm in HG.items():
x = (nm - coeff[1]) / coeff[0]
peaks.append({"id": name, "x": x, "fwhm_px": 8.0, "snr": 100.0,
"saturated": False, "channels": "G"})
return peaks
class LoadTests(unittest.TestCase):
def setUp(self):
self.dir = scratch()
def tearDown(self):
shutil.rmtree(self.dir, ignore_errors=True)
def test_json_roundtrip(self):
path = self.dir / "peaks.json"
path.write_text(json.dumps({
"recording": "some/recording", "frames": [0], "roi": [0, 426, 1270, 1396],
"full_size": [2028, 1520], "peaks": [
{"id": name, "sensor_x_px": x, "fwhm_px": 7.5, "snr": 42.0,
"saturated": False, "channels": "G"}
for name, x in PIXELS.items()]}), encoding="utf-8")
peaks, context = wc.read_peaks(path)
self.assertEqual([peak["id"] for peak in peaks], list(PIXELS))
self.assertAlmostEqual(peaks[2]["x"], 689.2, places=6)
self.assertEqual(context["full_size"], [2028, 1520])
self.assertEqual(context["roi"], [0, 426, 1270, 1396])
def test_csv_roundtrip_keeps_roi(self):
path = self.dir / "selected_peaks.csv"
with path.open("w", newline="", encoding="utf-8") as handle:
writer = csv.writer(handle)
writer.writerow(["id", "sensor_x_px", "fwhm_px", "snr", "saturated",
"channels", "roi_x0", "roi_y0", "roi_x1", "roi_y1"])
for name, x in PIXELS.items():
writer.writerow([name, x, 7.5, 42.0, 0, "G", 0, 426, 1270, 1396])
peaks, context = wc.read_peaks(path)
self.assertEqual(len(peaks), 5)
self.assertEqual(context["roi"], [0, 426, 1270, 1396])
self.assertFalse(peaks[0]["saturated"])
def test_csv_without_id_column_is_rejected(self):
path = self.dir / "bad.csv"
path.write_text("name,x\nP001,1\n", encoding="utf-8")
with self.assertRaises(ValueError):
wc.read_peaks(path)
def test_empty_json_is_rejected(self):
path = self.dir / "empty.json"
path.write_text(json.dumps({"peaks": []}), encoding="utf-8")
with self.assertRaises(ValueError):
wc.read_peaks(path)
class AssignTests(unittest.TestCase):
def setUp(self):
self.peaks = synthetic_peaks()
def test_parses_ids_and_wavelengths(self):
confirmed = wc.parse_assign("P001:404.6563,P003:546.0735", self.peaks, 1)
self.assertEqual([peak["id"] for peak in confirmed], ["P001", "P003"])
self.assertAlmostEqual(confirmed[1]["wavelength_nm"], 546.0735)
def test_lowercase_ids_are_accepted(self):
confirmed = wc.parse_assign("p002:435.8328,p003:546.0735", self.peaks, 1)
self.assertEqual([peak["id"] for peak in confirmed], ["P002", "P003"])
def test_unknown_id_names_the_available_ones(self):
with self.assertRaises(ValueError) as raised:
wc.parse_assign("P999:500", self.peaks, 1)
self.assertIn("P001", str(raised.exception))
def test_duplicate_id_is_rejected(self):
with self.assertRaises(ValueError):
wc.parse_assign("P001:404.6,P001:435.8", self.peaks, 1)
def test_non_monotonic_wavelengths_are_rejected(self):
# x rises 188 -> 303 -> 689 but the wavelengths go 404 -> 579 -> 546
with self.assertRaises(ValueError):
wc.parse_assign("P001:404.6563,P002:579.0663,P003:546.0735", self.peaks, 1)
def test_too_few_points_for_the_order(self):
with self.assertRaises(ValueError):
wc.parse_assign("P001:404.6563,P002:435.8328", self.peaks, 2)
class FitTests(unittest.TestCase):
def test_recovers_a_linear_calibration(self):
confirmed = wc.parse_assign("P001:404.6563,P002:435.8328,P003:546.0735,"
"P004:576.9598,P005:579.0663", synthetic_peaks(), 1)
coeff, residual = wc.fit(confirmed, 1, 2028)
self.assertAlmostEqual(coeff[0], 0.2815541, places=6)
self.assertAlmostEqual(coeff[1], 351.2738, places=3)
self.assertLess(float(np.max(np.abs(residual))), 1e-6)
def test_non_monotonic_mapping_is_rejected(self):
# a quadratic through these points turns over inside the sensor width
confirmed = wc.parse_assign("P001:546.0735,P002:500.0,P003:470.0",
synthetic_peaks(), 1)
with self.assertRaises(ValueError):
wc.fit(confirmed, 2, 2028)
class OutputTests(unittest.TestCase):
def test_writes_calibration_json_and_tables(self):
tmp = scratch()
if True:
peaks = synthetic_peaks()
confirmed = wc.parse_assign("P001:404.6563,P002:435.8328,P003:546.0735,"
"P004:576.9598,P005:579.0663", peaks, 1)
coeff, residual = wc.fit(confirmed, 1, 2028)
args = wc.build_parser().parse_args(["--peaks", "x.json", "--order", "1",
"--output", str(tmp)])
context = {"source": "test", "full_size": [2028, 1520], "roi": [0, 426, 1270, 1396]}
info = wc.write_outputs(args, peaks, confirmed, coeff, residual, context)
out = Path(tmp)
self.assertTrue((out / "calibration.json").is_file())
self.assertTrue((out / "residuals.csv").is_file())
self.assertTrue((out / "pixel_wavelength.csv").is_file())
self.assertTrue((out / "calibration.png").is_file())
saved = json.loads((out / "calibration.json").read_text(encoding="utf-8"))
self.assertEqual(saved["order"], 1)
self.assertEqual(len(saved["confirmed"]), 5)
self.assertLess(saved["rms_nm"], 1e-6)
self.assertEqual(saved["calibrated_pixel_range"],
[min(peak["x"] for peak in confirmed), max(peak["x"] for peak in confirmed)])
self.assertEqual(info["roi"], [0, 426, 1270, 1396])
rows = list(csv.DictReader((out / "pixel_wavelength.csv").open(encoding="utf-8")))
self.assertEqual(len(rows), 2028)
def test_parser_requires_exactly_one_input(self):
parser = wc.build_parser()
args = parser.parse_args(["--peaks", "a.json"])
with self.assertRaises(OSError):
wc.run(args) # the file does not exist
args = parser.parse_args(["--peaks", "a.json", "--input", "rec"])
with self.assertRaises(ValueError):
wc.run(args)
class NamingTests(unittest.TestCase):
"""The calibration folder must follow the same rule as peak_exports/."""
def test_peaks_inside_an_export_folder_mirrors_its_name(self):
path = Path(r"C:\\x\\peak_exports\\hq_20261112_200710_f0000\\peaks.json")
out = wc.default_output_directory(peaks=str(path))
self.assertEqual(out.parent.name, "calibration_exports")
self.assertEqual(out.name, "hq_20261112_200710_f0000")
def test_single_frame_and_stack_names(self):
out = wc.default_output_directory(recording=r"C:\\rec\\hq_20261112_200710", frames=[7])
self.assertEqual(out.name, "hq_20261112_200710_f0007")
out = wc.default_output_directory(recording=r"C:\\rec\\hq_20261112_200710", frames=[5, 6, 7])
self.assertEqual(out.name, "hq_20261112_200710_f0005-0007_avg3")
def test_moved_peaks_file_falls_back_to_its_recording(self):
out = wc.default_output_directory(
peaks=r"C:\\tmp\\peaks.json",
context={"recording": r"C:\\rec\\hq_20261112_195107", "frames": [0]})
self.assertEqual(out.name, "hq_20261112_195107_f0000")
if __name__ == "__main__":
unittest.main()