Skip to content

Commit 2fa90af

Browse files
DocAtPromptclaude
andcommitted
geometry: every blade's output read back out of a finished PDF (§ 13.2)
`test_dimensional.py` builds a PDF, parses it and checks the coordinates against what the definition asked for — and § 13.2 calls that the most important test in the suite. It only ever covered `lines`. Everything else rested on tests written beside the code, which inherit the code's assumptions; reading the artefact back does not. `tests/test_geometry_readback.py` extends the discipline to the rest. The rule it is written under is stated at the top of the file and matters more than any single assertion: **every expected number comes from the definition, or from a property the specification states in words, and never from the implementation.** What is now measured out of real PDFs: - **`tiling`** — the strongest of them. § 7.7 says `size` is the edge length for every shape, so every single stroke on the sheet must be 10 mm long. Checked for hex, tri, square, rhombus and octagon; and no inner edge is stroked twice, which is § 7.7's load-bearing sentence. - **`polar`** — ring radii against the cumulative series 12, 24, 48, 60 … that `base_radius: 12mm` with `radius: [1, 1, 2]` spells out on paper; twelve 30° spokes measured from the centre the *circles* give, and the twelfth lands back on 0° (§ 3.3's reason for micro-degrees). - **`mandala`** — rotate the whole drawing by a twelfth of a turn and it must map onto itself. A property of the result; no arithmetic of the blade is consulted. - **`perspective`** — every ray of a fan, extended to the horizon, crosses it within a millimetre of one point. Concurrency is checkable without the blade. - **`form`** — § 7.8's central claim, both halves: the same definition rules 8 mm on A4 *and* on A5, while the field itself does change size. Either half alone would prove nothing. - **`dots`** (an exact 5 mm lattice, 35 × 52 of them, both counts from § 8.1's arithmetic), **`grid`** (10×10 cells are 11×11 equal lines, and square on a page that is not), **`staves`** (5 lines 2 mm apart, six times, and `system_gap` measured as a *gap* and not a pitch), **`maze`** (every wall one cell long and on the lattice, the grid 10×14), **`net`** (a tray of 80×50×20 mm is 120×90 mm flat, and creases are dashed where cuts are not). `pdfread` grew a subpath reader for this — polygons and circles, on-curve points only, because the Bézier control points are the writer's business and a test that asserted on them would be checking reportlab. **One real finding, and it came from writing the definitions out of the specification rather than off the presets.** § 7.10 ends with "`labels: none` unterdrückt die Beschriftung ganz". `tiling` took it; `grid` and `polar` refused it with `Input should be a valid dictionary or instance of GridLabels` — an internal class name, in answer to a definition copied straight out of the spec. Omitting the key always worked, so nothing was unlabellable; the documented way of saying it simply was not there. Now all three take it. Three of the four first failures were **my** probes, not the code: `labels: none` was the fourth. A tray has eight creases and not four — four floor-to-wall and four where a glue tab meets its wall — and I had forgotten the tabs; the comment now counts them off § 7.14 rather than trusting the number that came out. 1219 tests green (27 new), ruff clean, every committed example byte-identical. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
1 parent 9b8c82d commit 2fa90af

4 files changed

Lines changed: 557 additions & 4 deletions

File tree

‎ctrlgrid/generators/grid.py‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,9 @@
2626
from __future__ import annotations
2727

2828
from collections.abc import Iterator
29-
from typing import Literal
29+
from typing import Any, Literal
3030

31-
from pydantic import BaseModel, ConfigDict, Field
31+
from pydantic import BaseModel, ConfigDict, Field, model_validator
3232

3333
from ctrlgrid.axes import AxisPeriod
3434
from ctrlgrid.errors import DefinitionError
@@ -72,7 +72,21 @@ class GridConfig(BaseModel):
7272
header_row: bool = False
7373
font: FontSpec = FontSpec(size="8pt")
7474

75-
75+
@model_validator(mode="before")
76+
@classmethod
77+
def _labels_none_is_the_documented_spelling(cls, data: Any) -> Any:
78+
"""§ 7.10: "`labels: none` unterdrückt die Beschriftung ganz."
79+
80+
Leaving the key out has always done that, but the spelling the
81+
specification documents met pydantic's "Input should be a valid
82+
dictionary or instance of ...LabelS" — an internal class name in answer
83+
to a definition copied out of § 7.10. `none` is one of the keywords
84+
§ 5.1 lists as standing where a value could, so it is accepted here and
85+
means exactly what an absent key means.
86+
"""
87+
if isinstance(data, dict) and data.get("labels") == "none":
88+
data = {key: value for key, value in data.items() if key != "labels"}
89+
return data
7690
class GridGenerator:
7791
name = "grid"
7892
config_model = GridConfig

‎ctrlgrid/generators/polar.py‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232

3333
import math
3434
from collections.abc import Iterator
35-
from typing import Literal
35+
from typing import Any, Literal
3636

3737
from pydantic import BaseModel, ConfigDict, Field, model_validator
3838

@@ -165,6 +165,21 @@ class PolarConfig(BaseModel):
165165
spokes: Spokes | None = None
166166
labels: PolarLabels | None = None
167167

168+
@model_validator(mode="before")
169+
@classmethod
170+
def _labels_none_is_the_documented_spelling(cls, data: Any) -> Any:
171+
"""§ 7.10: "`labels: none` unterdrückt die Beschriftung ganz."
172+
173+
Leaving the key out has always done that, but the spelling the
174+
specification documents met pydantic's "Input should be a valid
175+
dictionary or instance of ...LabelS" — an internal class name in answer
176+
to a definition copied out of § 7.10. `none` is one of the keywords
177+
§ 5.1 lists as standing where a value could, so it is accepted here and
178+
means exactly what an absent key means.
179+
"""
180+
if isinstance(data, dict) and data.get("labels") == "none":
181+
data = {key: value for key, value in data.items() if key != "labels"}
182+
return data
168183
@model_validator(mode="after")
169184
def _something_has_to_be_drawn(self) -> PolarConfig:
170185
if self.rings is None and self.spokes is None:

‎tests/pdfread.py‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,3 +94,63 @@ def dash_arrays(path: Path, page: int = 0) -> list[list[float]]:
9494

9595
def text_on(path: Path, page: int = 0) -> str:
9696
return PdfReader(str(path)).pages[page].extract_text()
97+
98+
99+
_TOKEN = re.compile(rb"(-?(?:\d+\.?\d*|\.\d+))|([A-Za-z']+)")
100+
101+
102+
def subpaths_um(path: Path, page: int = 0) -> list[list[tuple[float, float]]]:
103+
"""Every subpath on a page as its **on-curve** points, in micrometres.
104+
105+
A segment comes back as two points, a polygon as its vertices, and a circle
106+
as the five points reportlab's four Bézier quarters begin and end at. That is
107+
enough to measure what a definition declares — an edge length, a radius, a
108+
rotation — without the test knowing how the writer chose to draw it.
109+
110+
Deliberately ignores the Bézier control points: they are the writer's
111+
business, and a test that asserted on them would be checking reportlab.
112+
"""
113+
stream = PdfReader(str(path)).pages[page].get_contents().get_data()
114+
paths: list[list[tuple[float, float]]] = []
115+
current: list[tuple[float, float]] = []
116+
numbers: list[float] = []
117+
for match in _TOKEN.finditer(stream):
118+
number, operator = match.group(1), match.group(2)
119+
if number is not None:
120+
numbers.append(float(number))
121+
continue
122+
op = operator.decode()
123+
if op == "m":
124+
if len(current) > 1:
125+
paths.append(current)
126+
current = [(um(numbers[-2]), um(numbers[-1]))] if len(numbers) >= 2 else []
127+
elif (op == "l" and len(numbers) >= 2) or (op == "c" and len(numbers) >= 6):
128+
# A `c`'s last pair is its on-curve endpoint; the four before it are
129+
# control points and belong to the writer, not to the geometry.
130+
current.append((um(numbers[-2]), um(numbers[-1])))
131+
elif op in ("S", "f", "B", "b", "s", "n"):
132+
if len(current) > 1:
133+
paths.append(current)
134+
current = []
135+
numbers = []
136+
if len(current) > 1:
137+
paths.append(current)
138+
return paths
139+
140+
141+
def length_um(a: tuple[float, float], b: tuple[float, float]) -> float:
142+
return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5
143+
144+
145+
def circle_um(points: list[tuple[float, float]]) -> tuple[float, float, float]:
146+
"""Centre and radius of a subpath that is a circle, from its on-curve points.
147+
148+
Fitted from the extremes rather than from any one quarter, so a rounding in
149+
the writer's Bézier endpoints cannot decide the answer alone.
150+
"""
151+
xs = [x for x, _ in points]
152+
ys = [y for _, y in points]
153+
cx = (min(xs) + max(xs)) / 2
154+
cy = (min(ys) + max(ys)) / 2
155+
radius = sum(length_um((cx, cy), point) for point in points) / len(points)
156+
return cx, cy, radius

0 commit comments

Comments
 (0)