Files
spectrometer/test_geometry.py
T
starcells 1294d979b3 预处理阶段:几何一次定义,其余工具复用
- spectro_prep.py: 自动 ROI + 测谱线倾角 + 反斜切,产出 geometry.json 与预览图

- spectro_core.Geometry / shear_planes / measure_tilt: 裁剪与反斜切的共享实现

- peak_finder --roi 接受 geometry.json,降维前反斜切,几何写进 peaks.json

- test_geometry.py: 8 项(往返、裁剪/文件解析、合成斜线、倾角复原)

- 文档与 .gitignore(geometry/ 为产物)
2026-11-14 14:43:14 +08:00

133 lines
5.1 KiB
Python

"""Tests for the geometry stage: crop + de-tilt + provenance."""
from __future__ import annotations
import json
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))
import spectro_core as core # noqa: E402
TEST_TMP = os.environ.get("PEAK_FINDER_TEST_TMP")
def scratch() -> Path:
base = Path(TEST_TMP) if TEST_TMP else Path(tempfile.gettempdir())
base.mkdir(parents=True, exist_ok=True)
path = base / f"geo_case_{uuid.uuid4().hex[:10]}"
path.mkdir()
return path
def tilted_plane(rows: int, cols: int, slope_px_per_row: float, black: float = 4096.0,
amplitude: float = 9000.0, sigma: float = 1.6) -> np.ndarray:
"""A Gaussian line whose centre moves by slope_px_per_row per sensor row."""
plane = np.zeros((rows, cols))
columns = np.arange(cols)
for index in range(rows):
row = 2.0 * index # sensor row of this plane row
centre = 0.4 * cols + slope_px_per_row * (row - rows) / 2.0
plane[index] = amplitude * np.exp(-0.5 * ((columns - centre) / sigma) ** 2) + black
return plane
class GeometryTests(unittest.TestCase):
def test_roundtrip_json(self):
directory = scratch()
try:
geometry = core.Geometry((24, 474, 1558, 964), 0.031, row_origin_px=719.0,
source="rec", method="test", tilt_deg=1.2)
path = directory / "geometry.json"
core.write_json(path, {**geometry.as_dict(), "frame": 0})
loaded = core.Geometry.load(path)
self.assertEqual(loaded.roi, (24, 474, 1558, 964))
self.assertAlmostEqual(loaded.shear, 0.031, places=6)
self.assertAlmostEqual(loaded.row_origin, 719.0, places=3)
self.assertAlmostEqual(loaded.tilt_deg, 1.2, places=3)
finally:
import shutil
shutil.rmtree(directory, ignore_errors=True)
def test_from_spec_accepts_crop_and_file(self):
directory = scratch()
try:
path = directory / "g.json"
path.write_text(json.dumps({"format": "spectro-geometry",
"roi": [10, 20, 100, 200],
"shear_px_per_row": 0.02}), encoding="utf-8")
loaded = core.Geometry.from_spec(str(path), (2028, 1520), lambda: None)
self.assertEqual(loaded.roi, (10, 20, 100, 200))
self.assertAlmostEqual(loaded.shear, 0.02, places=6)
crop = core.Geometry.from_spec("0,100,500,900", (2028, 1520), lambda: None)
self.assertEqual(crop.roi, (0, 100, 500, 900))
self.assertEqual(crop.shear, 0.0)
finally:
import shutil
shutil.rmtree(directory, ignore_errors=True)
def test_invalid_roi_is_rejected(self):
with self.assertRaises(ValueError):
core.Geometry((100, 200, 100, 300))
with self.assertRaises(ValueError):
core.Geometry.from_spec("1,2,3", (2028, 1520), lambda: None)
def test_shear_removes_a_known_tilt(self):
rows, cols = 120, 200
slope = 0.05 # px per sensor row
plane = tilted_plane(rows, cols, slope)
def drift(data):
columns = np.arange(cols)
centres = []
for row in data:
weight = np.clip(row.astype(float) - 4096.0, 0.0, None)
centres.append(float((weight * columns).sum() / max(weight.sum(), 1e-9)))
return centres
before = drift(plane)
geometry = core.Geometry((0, 0, 2 * cols, 2 * rows), slope, row_origin_px=rows)
fixed = core.shear_planes({"G": plane}, geometry, 2.0, 0)["G"]
after = drift(fixed)
self.assertGreater(abs(before[-1] - before[0]), 5.0)
self.assertLess(abs(after[-1] - after[0]), 1.0)
def test_shear_of_zero_returns_the_input(self):
plane = np.zeros((10, 20))
geometry = core.Geometry((0, 0, 40, 20))
self.assertIs(core.shear_planes({"G": plane}, geometry)["G"], plane)
class TiltTests(unittest.TestCase):
def test_measure_tilt_recovers_a_known_slope(self):
rows, cols = 240, 160
slope = 0.06
plane = tilted_plane(rows, cols, slope)
result = core.measure_tilt({"G": plane}, 64, 12, 4096.0)
self.assertAlmostEqual(result["slope"], slope, delta=0.01)
self.assertAlmostEqual(result["angle_deg"], np.degrees(np.arctan(slope)), delta=0.6)
self.assertGreater(result["sharpness_ratio"], 1.05)
def test_measure_tilt_reports_no_tilt_for_a_vertical_line(self):
plane = tilted_plane(240, 160, 0.0)
result = core.measure_tilt({"G": plane}, 64, 12, 4096.0)
self.assertAlmostEqual(result["slope"], 0.0, delta=0.01)
self.assertLess(result["sharpness_ratio"], 1.05)
def test_measure_tilt_needs_rows(self):
plane = tilted_plane(8, 160, 0.05)
with self.assertRaises(ValueError):
core.measure_tilt({"G": plane}, 64, 12, 4096.0)
if __name__ == "__main__":
unittest.main()