firmament: read LED positions files
Assisted-by: Claude Opus 5.5 via Claude Code
change wqqnpwnmlzxoyvxwnslppsqrptyuuzwp
commit d85bd89222d3e1a7c96dc828e1925621f0d2fd86
author Alpha Chen <alpha@kejadlen.dev>
date
parent zwtstypx
diff --git a/firmament/src/firmament/positions.py b/firmament/src/firmament/positions.py
new file mode 100644
index 0000000..940d58b
--- /dev/null
+++ b/firmament/src/firmament/positions.py
@@ -0,0 +1,52 @@
+"""Read LED positions, as defined in SPEC.md (LED positions)."""
+
+import csv
+import math
+from dataclasses import dataclass
+from pathlib import Path
+
+from firmament.codes import MAX_LEDS
+from firmament.pattern import MIN_LEDS
+
+COLUMNS = ("index", "x", "y", "z", "views")
+
+
+@dataclass(frozen=True)
+class Led:
+    index: int
+    x: float
+    y: float
+    z: float
+    views: int
+
+
+def read_leds(path: Path) -> list[Led]:
+    """Read `leds.csv`, raising ValueError with the line number of the first problem."""
+    with open(path, newline="", encoding="utf-8") as f:
+        reader = csv.DictReader(f)
+        missing = [c for c in COLUMNS if c not in (reader.fieldnames or [])]
+        if missing:
+            raise ValueError(f"{path}: missing column {', '.join(missing)}")
+        leds = [_led(row, reader.line_num, path) for row in reader]
+    for expected, led in enumerate(leds):
+        if led.index != expected:
+            raise ValueError(f"{path}: expected LED {expected} next, found {led.index}")
+    if not MIN_LEDS <= len(leds) <= MAX_LEDS:
+        raise ValueError(f"{path}: {len(leds)} LEDs is outside {MIN_LEDS} to {MAX_LEDS}")
+    return leds
+
+
+def _led(row: dict[str, str], line: int, path: Path) -> Led:
+    try:
+        index, views = int(row["index"]), int(row["views"])
+        x, y, z = (float(row[c]) for c in "xyz")
+    except (TypeError, ValueError):
+        raise ValueError(
+            f"{path}, line {line}: expected whole numbers for index and views, "
+            "and numbers for x, y, and z"
+        ) from None
+    if not all(math.isfinite(v) for v in (x, y, z)):
+        raise ValueError(f"{path}, line {line}: x, y, and z must be finite")
+    if views < 0:
+        raise ValueError(f"{path}, line {line}: views must be 0 or more")
+    return Led(index, x, y, z, views)
diff --git a/firmament/tests/test_positions.py b/firmament/tests/test_positions.py
new file mode 100644
index 0000000..f5855d8
--- /dev/null
+++ b/firmament/tests/test_positions.py
@@ -0,0 +1,38 @@
+import pytest
+
+from firmament.positions import Led, read_leds
+
+
+def _write(tmp_path, text):
+    path = tmp_path / "leds.csv"
+    path.write_text(text)
+    return path
+
+
+def test_reads_each_led_in_order(tmp_path):
+    path = _write(tmp_path, "index,x,y,z,views\n0,0.1,0.2,0.3,2\n1,-1,0,1.5,0\n")
+    assert read_leds(path) == [Led(0, 0.1, 0.2, 0.3, 2), Led(1, -1.0, 0.0, 1.5, 0)]
+
+
+def test_finds_columns_by_name_and_ignores_extras(tmp_path):
+    path = _write(tmp_path, "views,confidence,z,y,x,index\n1,0.9,3,2,1,0\n0,0.1,6,5,4,1\n")
+    assert read_leds(path) == [Led(0, 1.0, 2.0, 3.0, 1), Led(1, 4.0, 5.0, 6.0, 0)]
+
+
+@pytest.mark.parametrize(
+    ("text", "match"),
+    [
+        ("index,x,y,views\n0,1,2,0\n1,1,2,0\n", "missing column z"),
+        ("index,x,y,z,views\n0,0,0,0,0\n2,0,0,0,0\n", "expected LED 1 next, found 2"),
+        ("index,x,y,z,views\n0,0,0,0,0\n0,0,0,0,0\n", "expected LED 1 next, found 0"),
+        ("index,x,y,z,views\n0,0,0,0,0\n1,a,0,0,0\n", "line 3: expected whole numbers"),
+        ("index,x,y,z,views\n0,0,0,0,0\n1,0,0,0\n", "line 3: expected whole numbers"),
+        ("index,x,y,z,views\n0,0,0,0,0\n1,0,nan,0,0\n", "line 3: x, y, and z must be finite"),
+        ("index,x,y,z,views\n0,0,0,0,-1\n1,0,0,0,0\n", "line 2: views must be 0 or more"),
+        ("index,x,y,z,views\n0,0,0,0,0\n", "1 LEDs is outside 2 to 500"),
+        ("", "missing column index"),
+    ],
+)
+def test_rejects_malformed_files(tmp_path, text, match):
+    with pytest.raises(ValueError, match=match):
+        read_leds(_write(tmp_path, text))