diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bce0c77b..31f95a23 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -59,7 +59,7 @@ jobs: - name: gate's own tests run: >- python -m unittest bench/tests/test_gate_stats.py bench/tests/test_ci_gate.py - bench/tests/test_gate_scoring.py bench/tests/test_gt_diff.py + bench/tests/test_gate_scoring.py bench/tests/test_gt_diff.py bench/tests/test_design.py bench/tests/test_cases_ratchet.py - name: hard cases, Quality run: python bench/cases.py --exe target/release/inkvec --ratchet quality diff --git a/.github/workflows/formal.yml b/.github/workflows/formal.yml new file mode 100644 index 00000000..d12fe92b --- /dev/null +++ b/.github/workflows/formal.yml @@ -0,0 +1,65 @@ +name: formal + +# Machine-checks formal/InkvecTheory (Lean 4 + Mathlib): every proof, then the axiom audit, +# which must report only Lean's three standard axioms, then that the checkers generated from +# the Lean definitions (crates/inkvec-verified/src/generated) are exactly what those +# definitions print, so the Rust cannot drift from the proofs. Runs when either changes; the +# Mathlib build comes from its prebuilt cache (`lake exe cache get`). + +on: + push: + branches: [main, master] + paths: ["formal/**", "crates/inkvec-verified/**", ".github/workflows/formal.yml"] + pull_request: + paths: ["formal/**", "crates/inkvec-verified/**", ".github/workflows/formal.yml"] + +permissions: + contents: read + +concurrency: + group: formal-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + lean: + runs-on: ubuntu-latest + defaults: + run: + working-directory: formal/InkvecTheory + steps: + - uses: actions/checkout@v4 + - name: Install elan + run: | + curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain none + echo "$HOME/.elan/bin" >> "$GITHUB_PATH" + - name: Fetch prebuilt Mathlib + run: lake exe cache get + - name: Build every proof + run: lake build + - name: Axiom audit + run: | + lake build InkvecTheory.Audit 2>&1 | tee audit.log + n=$(grep -c "depends on axioms" audit.log || true) + expected=$(grep -c "^#print axioms" InkvecTheory/Audit.lean) + if [ "$n" -ne "$expected" ]; then + echo "the audit printed $n axiom reports, expected $expected" >&2 + exit 1 + fi + if grep "depends on axioms" audit.log | grep -v "\[propext, Classical.choice, Quot.sound\]"; then + echo "a theorem depends on an axiom beyond Lean's standard three" >&2 + exit 1 + fi + if grep -rnE "\bsorry\b|^axiom |\badmit\b" InkvecTheory --include=*.lean | grep -v "Audit.lean"; then + echo "sorry, admit or a new axiom in the development" >&2 + exit 1 + fi + - name: Generated checkers match the Lean definitions + run: | + lake env lean InkvecTheory/Gen/Emit.lean + git diff --exit-code -- ../../crates/inkvec-verified/src/generated + untracked=$(git ls-files --others --exclude-standard -- ../../crates/inkvec-verified/src/generated) + if [ -n "$untracked" ]; then + echo "generated files not committed: $untracked" >&2 + exit 1 + fi diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3596e387..f4639a9f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -226,7 +226,8 @@ jobs: Logolabs/inkvec-denoiser-001 (https://huggingface.co/Logolabs/inkvec-denoiser-001). 2. Place it next to this binary, or in a `models/` directory next to this binary, or point INKVEC_RESTORE_ONNX at its path. - 3. Run inkvec with --restore auto (or on). + 3. Quality mode (the default) then runs it as --restore auto by itself; in + fast or balanced mode, pass --restore auto (or on). See the project README for the other restorer backends (restore-burn, restore-wgpu), which are not part of this pre-built archive. diff --git a/CHANGELOG.md b/CHANGELOG.md index fd160311..a2b47fb9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,62 @@ API in particular should be treated as unstable release to release). ## [Unreleased] +### Changed + +- **`--restore auto` is the default in Quality mode.** `Args::restore` is now an `Option`: unset, `Args::restore_mode` resolves it to `auto` in Quality mode when the build can restore (the network compiled in, or `--restore-command`) and to `off` in Fast and balanced and in a build with nothing to restore with, which then traces exactly as `--restore off` does; a given `--restore` always wins. On a clean input `auto` makes no probe without a sign of compression, so the default costs a clean PNG the ringing score alone (about 2.7 ms at 512 px); the gate's builds carry no network and its numbers do not move. +- **Quality mode takes the codec's damage out of its labels on a lossy intake.** The MDL palette founded the codec's tints of an ink as inks of their own (on `openmoji/E056`, three tinted blacks beside black: 674 faces, 41 colours, 250 subpaths where the artist drew four colours), and the halos Fast's pass removes cut Quality's strokes into fragments. On an opaque lossy intake the despeckled labels now go through Fast's halo pass, in a strict form that holds every thin component to the strip rule and the segment test, through its soft merge of thin variants, and through a merge of codec variants of its own: an ink within 8 levels of a heavier one in luma-weighted YCbCr, and within the soft floor, is that ink (`fast/codec.rs`). `quality-web` against the build before (246 icons, the gate's distance axes): dE00 −6.83 %, `turning_gap` −36.57 %, `ratio_gap` −11.89 %, geom −3.73 %; openmoji's colours and subpaths per icon 10.6 and 38.0 → 5.7 and 12.8 (artists: 3.9 and 11.7). A clean intake is byte-identical, and Fast's output is unchanged. A restored image (`--restore`) does not take it: the restorer took the damage out, and on the restored path it read dE00 +0.24 %; `ColorOptions::restored` (set by the CLI's restorer pre-pass) says so. +- **Counters are cut out of their glyph, and square rectangles share their paint's path (all modes).** On an opaque page, the counter of a letter O was a page-coloured element painted over a solid disc, and every rectangle was an element of its own (`material-icons/border_left`: seventeen `` where the artist has one path). Now: + - A face in exactly the page's colour that fills a hole of a glyph on the page is dropped and written into the glyph as a hole (`emit/holes.rs`). As under `--no-background`, only a glyph whose children are all page-coloured is cut. A counter or glyph written as a circle, ellipse or rounded rectangle stays painted over, since a hole costs more numbers. + - A square-cornered rectangle joins the compound path of its same-coloured siblings: three lines are the six numbers of a ``. So does a rectangle the completion stage produced. + - The picture is unchanged by construction (`Design/Layers.lean`, `cut_hole`). + - **Regression gate** (246 icons, all 8 conditions, against the previous build). Every verdict is identical or non-inferior; fast-128ss and fast-512ss are byte-identical. + - quality-512ssop: dE00 −0.15 %, turning_gap −0.06 %, ratio_gap −0.15 %, geom −0.0001 %. + - quality-web: −0.0008 %, −0.05 %, −0.10 %, geom unchanged. + - quality-128ss and quality-512ss: ratio_gap −0.05 % and −0.06 %; the other axes within 2·10⁻⁶ %. + - Two point estimates are worse, each from one icon: quality-512ss turning_gap +3·10⁻⁷ (`material-icons/qr_code`, a completion corner moved by 0.01 px) and fast-512ssop geom +7.8·10⁻⁷ (`material-icons/admin_panel_settings`, the renderer's coverage of a hole's edge pixels). + - **Closer to how the artists draw** (`bench/human_stats.py`, 246 icons, divergence from the artist's file). The composite falls 3.1 % on quality-512ssop and 1.9 % on quality-web. On 512ssop: primitives −24.7 %, elements −14.5 %, nested −12.7 %, stacked −10.3 %. material-icons' nested share goes 0 → 0.13 (artist 0.42) and its stacked share 0.47 → 0.28 (artist 0). + - `INKVEC_CUT_HOLES=0` paints counters over, as before. +- **Nodes at a curve's extrema, where the fit's own objective prefers them (Quality).** Type designers and icon artists put a curve's points where it runs horizontal or vertical, with the handles there on the axis (Adobe, *Type 1 Font Format*, 1990, §4.1 "Points at Extremes" and §4.2 "Tangent Continuity"; font editors check it). The dynamic program can only put a node on a measured point, with the estimated direction, so it never proposed one there. A new pass after the merge (`inkvec_fit::extrema`) offers each smooth run of the fit the same run with its nodes at the extrema and every join smooth: the cheapest chain through the extrema and the old nodes, each node then refined by a compass search and the arms polished on every point. It replaces the run only when the fit's own objective, `½χ² + λ·params`, prefers it, with one parameter credited per anchored node (the direction it no longer writes), and only when it writes exactly as many numbers. Stroke centrelines are left alone (`extrema::without`), so the stroke decision is unchanged. + - Regression gate, 246 icons (change; icons better / worse). On the tree before the completion stage, against the baseline: quality-512ssop dE00 −0.04 % (23/22), `turning_gap` −0.01 % (40/38), `ratio_gap` −0.01 % (2/0), geom −0.03 % (26/15); quality-128ss dE00 −0.03 % (26/24), `turning_gap` −0.40 % (41/20), `ratio_gap` identical, geom −0.02 % (19/16); quality-web dE00 −0.10 % (56/25), `turning_gap` −0.15 % (63/40), `ratio_gap` −0.00 % (1/0), geom −0.03 % (46/27); quality-512ss dE00 +0.002 % (25/20), `turning_gap` −0.18 % (51/15), `ratio_gap` +0.002 % (0/1), geom −0.02 % (18/20). With the completion stage, against that tree: quality-512ssop dE00 −0.05 % (24/22), `turning_gap` +0.05 % (40/36), `ratio_gap` −0.01 % (2/0), geom −0.03 % (26/15); quality-web dE00 −0.11 % (64/23), `turning_gap` −0.07 % (58/43), `ratio_gap` −0.00 % (1/0), geom −0.05 % (50/23). The rises are one icon each, through later stages: the crossing repair refits an edge next to a re-noded one differently (`noto-emoji/emoji_u1f9d1_1f3fc_200d_1f37c`, two numbers more), and the seam underlap gave up on a run holding one of the new cubics (`noto-emoji/emoji_u1f3c4_1f3fe`; fixed, see *Fixed*). Fast mode is byte-identical. + - Human battery, quality-512ssop, divergence from the artist's file: `smooth` −3.1 % (51 icons closer, 3 further), `kinked` −6.1 % (19, 1), `handle_axis` −3.3 % (39, 4), `extremum` −1.3 % (33, 27), all with 95 % intervals clear of zero; composite 0.9937. +- **`--editability` writes curves the way drawing tools do.** Every circular arc is written as cubics cut at its x and y extrema, handles on the axes and `4/3·tan(Δ/4)·r` long (Riškus 2006, *Information Technology and Control* 35(4): 2.7e-4 of the radius for a quarter), a stroke's centreline included; no cut within 1 px of an arc's end. Smooth runs are re-noded at their extrema with three parameters credited per node and the count free. Every join that turns by at most 30° is made smooth, next to a line along the line, and joins between two edges at a junction too (`editable/junctions.rs`); a smooth node's two handles snap to an axis together or not at all; two lines meeting within 0.5° become one. A boundary with no junction on it, handed over as an open edge ending where it starts, now has its closing join edited like any other. Every change is held to the mode's guard, as before. Human battery, `--editability` against the default trace, quality-512ssop: composite 0.9185 (it was 0.9925); divergence from the artist `kinked` −44.2 % (92 icons closer, 21 further), `handle_axis` −37.1 %, `handle_length` −30.2 %, `extremum` −25.6 %, `smooth` −22.3 %, `ties` −13.3 %, `kinds` −12.8 %, `collinear` −4.0 % (it was +15.3 %); further: `segment_lengths` +13.3 %, `nodes_per_subpath` +6.4 % and `sweep` +12.0 % (not significant), the price of cutting arcs at quarter turns. +- **On a lossy intake the carve stage leaves the codec's band alone.** A codec's error sits at the edges and its ringing is a rim of residual just inside every region, which `carve_residual_features` cut into extra regions along the edges. On a lossy intake a pixel is now carved only when it lies two pixels or more inside its region (`gradient::carve::CODEC_BAND`). `quality-web` (246 icons, the gate's distance axes): dE00 −0.01 %, `turning_gap` −5.38 %, `ratio_gap` −0.80 %, geom −0.10 %, 18 icons changed; 1 px read dE00 +0.21 % and 3 px geom +0.08 %. A clean intake is byte-identical. `carve_residual_features_with_detail_noise` takes the band as a new last argument. +- **The strip reading's corner test scales with the intake's noise on a soft Quality intake.** A vertex is declined as a corner only beyond `max(SIDE_TOL, 3·√(70 V)/12)`, three standard deviations of the one-sided fourth difference, with `V` from the trace's measured noise over the edge's contrast. The front end's soft-intake decision (wide edges, ringing or a lossy container) now reaches the sub-pixel refinement (`RefineCtx::soft`). Clean intakes keep `SIDE_TOL` and their bytes on all six clean gate conditions, and Fast, which measures no noise, is unchanged too. On `quality-web` 111 icons change and every gated axis improves at its point estimate (dE00 −0.14 %, `turning_gap` −0.02 %, `ratio_gap` −0.03 %, geom −0.03 %; `docs/theory/chain-boundary.md`, "`strip.rs`: a statistical side test on soft intakes"). +- **`--restore auto` and `--sr auto` act only on input that shows damage of its own.** Both decided on one signal, the input's residual against its own probe trace where the trace claims to be flat, and that reads smooth shading in clean art as damage: on the gate's clean opaque 512 px tier `--restore auto` restored 7 of 246 icons (all shaded Noto emoji) and read dE00 +4.49 %, geom +13.9 %. A restore now also needs a lossy container or JPEG ringing around the edges (`coverage::ringing_score` above the palette's gate, for a JPEG re-saved as PNG); SR's clean-up also accepts edges wider than a native render's. These are the soft intake's three signals. They are asked first, and the residual (which renders the probe at full size, the costly half: 16.5 ms of CPU on a 31 ms Fast trace at 512 px) only when one of them fires; both are needed, so the order changes no decision. Without one, `--restore auto` makes no probe and traces as `--restore off` does, and in Fast mode the sign is the container alone (the ringing score would add 2.5 ms to a 31 ms trace at 512 px). JPEG input decides as before (`crates/inkvec-cli/src/damage.rs`). A probe `auto` keeps also reports what the plain trace reports, its stage log and lambda; it used to print only the `restore` or `sr` line. +- **Faces are completed behind what is painted over them (Quality).** A face partly hidden by a face or stroke painted after it was written as the crescent it shows: every edge of its cover traced again. It is now written as the cheapest shape in its painter's interval, `V ⊆ E ⊆ V ∪ U` (what it shows; that and what covers it). Within that interval every visible pixel stays as it was. The candidates are a circle, ellipse or rectangle; the face's own rings with each covered run replaced by the corner its owned lines meet at; a chord a margin under the cover; the run offset under the cover; a bulge; a corner cut (a chamfer a blur left, dropped and its lines extended under the cover); or a bridge (one G1 cubic continuing the visible boundary across the run). A completion that would fill the image's frame is never proposed: which face is the page is the emitter's decision. The lower bound reaches half a pixel under the cover, as the seams' underlap did, so a completed face needs no underlap. + - **Verification.** The interval is proved in Lean (`Design/Layers.lean`, `painter_interval_iff`). A completion is accepted only by a checker generated into `inkvec-verified` (`span_within`, `span_link`; `Gen/Design.lean`, `chain_cover`, `line_cover`), on the solver's certificate of span covers on every scan line, in outward-rounded intervals. + - **Regression gate** (246 icons, all 8 conditions, against the baseline, `--no-tighten`). + - quality-128ss: dE00 −0.18 %, turning_gap −8.61 %, ratio_gap −0.12 %, geom −0.07 %. + - quality-512ss: −0.94 %, −10.77 %, −3.64 %, −0.02 %. + - quality-512ssop: −1.51 %, −4.34 %, −8.66 %, −0.01 %. + - quality-web: −0.31 %, −3.84 %, −5.08 %, −0.00 %. + - Fast output is unchanged. + - **Canary.** `openmoji` England flag at 512 px goes from 54 to 20 parameters, the artist's count. + - **Against the artists' hidden geometry** (`bench/theory/amodal_eval.py`, 121 emoji). A completed face's IoU with the artist's full element rises in 60 % of cases and falls in 19 % (median 0.49 → 0.52). The bridge gains most (median 0.59 → 0.75). + - `INKVEC_COMPLETION=0` switches the stage off; `INKVEC_COMPLETION_DEBUG` reports it. +- **Fast mode gives a JPEG's halos back to the inks they lie between (lossy intake only).** A JPEG stores colour at half resolution, so an edge comes back with a band two or three pixels wide whose chroma has bled across independently of its luma: off the line between the two inks in sRGB (0.08-0.09, twice the blend tolerance), so Fast's palette founded it as an ink and its clean-up kept it, and one ink came back split into variants a few dE00 apart (an outline as #010101, #010009 and #080000). On a lossy intake (`ColorOptions::lossy_intake`) of an opaque image, two passes now run in the clean-up (`fast/faces/halos.rs`): + - **Halos.** In JPEG's own colour space (BT.601 YCbCr) a thin component (no 5 × 5 window of its own) whose mean colour lies, channel by channel, between two inks around it or 20 % beyond them, is their halo, and each of its pixels goes to the ink it covers more of, read mostly from luma; a thin component of an ink that owns an area elsewhere must also be a strip lying within 0.04 of the line between them, which keeps a real four-pixel rim (`twemoji/1faa3`). Flecks of a halo ink inside a single ink go to it. + - **Ink variants.** A component with no 5 × 5 interior merges into a neighbouring ink within 5 dE00 (the soft floor Quality's palette uses on the same intakes); one with an interior keeps the clean 1.5. + - Regression gate, `fast-web` (246 icons): dE00 −11.8 %, turning −50.5 %, parameter ratio −42.8 % (7.22 → 4.13), geom −6.8 %, all demonstrable gains; openmoji's ratio 13.2 → 3.9, twemoji's 8.9 → 3.7. `twemoji/1f1fa`: 4 inks and 215 faces → 2 inks and 3 paths, dE00 0.242 → 0.144. The six clean conditions are byte-identical: neither pass runs on a clean intake, and neither costs anything there. +- **The regression gate is faster, with the same numbers.** Icons whose SVG is byte-identical to the baseline's are traced but no longer scored (their numbers were the baseline's anyway; `--rescore` scores them, to check the scorer). What the artist's file contributes is cached by its hash in `bench/data/_cache` (the artist's side of `geom`: its flat render's palette, labels, edge length and near-edge mask; its design profile), dE00 converts only the sampled pixels where the two renders differ (an equal pixel's CIEDE2000 is exactly 0), the trace's flat render is labelled run by run, no render is saved when DISTS is off, and one process pool serves every condition. CPU per icon on the full set: quality-512ssop 3.99 s before, 2.84 s with a cold cache, 2.15 s warm, 1.43 s when every icon matches the baseline; fast-web 1.75, 1.03, 0.64 and 0.35 s (113 icons changed). The gate's own scoring of a changed 512 px icon fell from 2.58 to 0.72 s; the rest is the tracer. Every number is unchanged: old and new scorers on the same binary gave identical per-icon rows, summaries and verdicts on both conditions, cold and warm. Each condition's line now says where its CPU went (tracer, scoring, design battery) and how many icons were reused. +- **Stroke detection is on by default (Quality).** Faces drawn as a centreline and one width are written as stroked paths wherever that is the shorter description at as good a fit; `--no-detect-strokes` (`detect_strokes: false`) turns it off, and `INKVEC_RIBBONS=0` does for benchmark builds. It had stayed opt-in for its time, which is now 1.16× the trace at 512 px over the screen set (1.23-1.31× on lucide, material-icons, openmoji and simple-icons; the worst icon 0.8 s more). Two changes came with it: + - **Merges.** After its splits, the stroke solve runs them backwards: every joint of a centreline is offered the line through its outer ends, an arc on either neighbour's circle (both's when they turn alike, or the three points'), and the cubic with the outer tangents; every cubic and arc the line on its chord; a closed path of arcs on one circle that circle. A merge is kept when the face's description length falls, unsolved or after a short solve, and the strokes stay within the decision's fidelity bound (`ribbon/refine/merge.rs`). The fitter's arcs stop at 120°, so an artist's 270° arc came back as three arcs and a short line at each cap; lucide `closed-caption` and `iteration-ccw` now carry exactly the artist's structure. A merged arc near a half turn is written as the half circle on its chord, and the solve refuses arcs within 15° of a half turn otherwise, where rounding the radius would move the drawn arc. + - **Faces that leave with a stroke.** On an opaque page the inside of a stroked ring is its own face, painted the page's colour over the ring's disc. A face the stroke face alone encloses, painted exactly the colour of what lies beneath, now leaves the document with it and counts in the decision: a ring on white is one stroke over the page, not a black disc under a white one. + - Regression gate against the stage off (246 icons, all demonstrable gains): dE00 −8.18 % quality-128ss, −8.57 % quality-512ss, −11.35 % quality-512ssop; parameters against the artist's 1.495 → 0.954, 1.728 → 1.168, 1.967 → 1.414; turning −6.1 %, −6.0 %, −5.6 %. Fast mode is unchanged. + - `fit_face` takes the fidelity bound its merges keep (`chi2_cap`). +- **Sub-pixel boundaries are read from exact column sums (all modes).** A pixel's coverage is the area of the shape inside it, so a column's coverages, summed from a pixel wholly in one face to a pixel wholly in the other, are exactly the boundary's mean height over the column, whatever its slope or curvature; four adjacent column means fix a unique cubic, which is the boundary wherever the boundary is a cubic. Stage 07 now slides each vertex between two flat fills onto that cubic (`planar/strip.rs`) before trying the per-vertex probes, which needed a normal they could only estimate from the lattice and read two-probe brackets at the ½-crossing, a reading biased by up to 3/2 − √2 ≈ 0.086 px even on a straight edge. A corner, a junction or a third colour in a column makes the strip reading decline, and the probes decide as before. + - Stage-07 points on exactly known shapes (`bench/theory`): 0.073 → 0.011 px mean error on exact-area renders, 0.073 → 0.016 px on 8x8 supersampled ones; p99 0.32 → 0.18–0.19 px. + - Regression gate (246 icons, against `main`): dE00 −10.96 % fast-128ss, −8.70 % fast-512ss, −9.83 % fast-512ssop, −4.51 % quality-128ss, −1.89 % quality-512ss, −1.36 % quality-512ssop (non-inferior); turning better in Fast and level in Quality; parameters −2.7 % fast-128ss, +1.9 % quality-128ss, within margin elsewhere. `bench/cases` Fast passes `edge_axis` too (28/42); Quality stays 42/42. + - Time unchanged: whole-process median on 40 corpus icons at 512 px, Fast 22.3 → 22.7 ms, Quality 538 → 529 ms. + - The theorems behind it are machine-checked (see *Added*); the reading's rational constants are proved exact (`histopolate_cubic`, `strip_reading_exact`). + - `probe_chord` moved to `planar/chord.rs`, unchanged but for the seam fix below. + - `crates/inkvec/tests/api.rs` `restored_pixels_are_traced_with_soft_intake` ripples at 12 levels instead of 9: at 9 the plain and the forced trace differed only by a 0.01 px centre error on the forced one, which the column sums no longer make; at 12 forcing soft intake changes the palette, which is what the test is for. + ### Fixed +- **The seam underlap no longer gives up on a curve that turns far (all modes).** Whether a moved edge cut into the lower face was asked of the nesting's polygon of that face, four points per curve, whose chords stray from a long curve that turns far by more than the half-pixel reach: 0.55 px at the middle of a cubic turning 74° over 78 px. Where the curve bulged into the lower face, an edge moved the full reach outward still read as cutting into it, the whole run between two junctions went unmoved and the seam showed. The test now reads the lower face's own outline, flattened to within 0.01 px of its curves (`seams.rs`, `fine_ring`). A cubic between two extrema turns up to 90°, so this mattered more once the fit put nodes there (`noto-emoji/emoji_u1f3c4_1f3fe` at quality-512ss: dE00 0.0650, 0.0686 with nodes at extrema and the old test). Regression gate, against the tree with nodes at extrema and the completion stage (change; icons better / worse): quality-512ssop dE00 −1.31 % (43/1), `turning_gap` +0.10 % (28/33), `ratio_gap` +0.02 % (3/7), geom −0.01 % (5/0); quality-web dE00 −0.22 % (50/0), `turning_gap` +0.01 % (30/34), `ratio_gap` +0.02 % (11/11); fast-512ss dE00 −0.46 % (34/0), fast-512ssop −0.49 % (38/1), fast-web −0.11 % (26/2), fast-128ss −0.01 % (4/1), with `ratio_gap` up to +0.01 % and `turning_gap` up to +0.02 % in Fast: the runs that now move gain the underlap's taper vertices. +- **`--editability`'s G1 pass turned the wrong handle.** Since it was written, at each join it turned the incoming cubic's first control point, at that cubic's far end, instead of the one at the join. Within the old 3° window the harm was small; with the window at 30° (above), a join it smoothed kept its kink and the far end gained one (`material-icons/dining`: 0.45 of its joins between curves kinked before the fix, 0 after). Node alignment also moved nodes without their handles, so a handle a pixel long turned by up to 15° for a 0.3 px move and a smooth node became a kink; a moved node now carries its handles. +- **The seam vertex of every closed ring is refined (all modes).** A closed edge stores its first point once, and the lattice normal clamped its neighbours at the ends of the edge, so the seam took a one-sided chord: on a ring whose seam lies on a horizontal run, a horizontal normal on a horizontal boundary, and the vertex stayed on the lattice, 0.30 px off on an exact disc. Quality's boundary solve repaired it; Fast kept it. The chord now wraps round the seam. Within noise on the gate (the corpus's rings mostly start at a junction or a corner). - **Thin strokes on a transparent ground keep their ink (Quality).** A stroke narrower than about two pixels covers few or no pixels completely, so the palette met its anti-aliasing before its ink, or never met the ink at all: - A 1-1.5 px line split across two rows (every pixel translucent) was dropped entirely. Such a colour, at least half opaque and refused only for having no interior, is now read as a hairline of its opaque version. - A 2 px diagonal came out as a translucent band around opaque specks, because its 0.83-covered pixels outnumbered its core and were accepted first. After the walk, a translucent ink whose opaque version is also an ink is weighed again as a blend of the two and dropped when it is coverage; a translucent wash with an interior of its own stays. @@ -20,6 +74,17 @@ API in particular should be treated as unstable release to release). ### Added +- **Human statistics: how a trace is drawn, against the artist's file** (`bench/inkvec_bench/design.py`, `bench/human_stats.py`; reported, not gated). A battery of statistics of a file's construction, read on the trace and on the artist's own file, each as a per-icon divergence (zero for a trace drawn as the artist drew it): the segment-kind mix, smooth (G1) joins, nodes at the x/y extrema, cubic handles on the axes, kinked joins (3-30°), the share of corners, right angles and the corner angles, lines on the axes and on the diagonals, collinear nodes, each curve's sweep, handle lengths, symmetric handles, coordinates on the artist's half-unit grid, repeated values, mirror-symmetric nodes, primitives, strokes and repeated stroke widths, elements, subpaths, nodes per subpath, closed subpaths, segment lengths, colours, nested subpaths and shapes stacked over others, and as an artefact signal the share of numbers on the raster's half-pixel grid. 29 statistics are kept of 36 candidates: those correlated beyond |Spearman rho| 0.7 with one kept, over the screen set at quality-512ssop and quality-web, were dropped (`design.DROPPED` says which and why), and none of the kept reaches 0.57 with a gate axis. The gate takes it on every icon it traces (about 10 ms each), prints each statistic's family-macro divergence per condition and writes every icon's values to `--report-json` and `--artifact-dir` (`human-.json`). `bench/human_stats.py` traces without rendering and prints the per-family picture and the oddities, or compares two builds or flag sets icon by icon with a paired bootstrap per statistic and one composite to tune against (`--exe ... --extra-args "--editability" --base-args ""`). It is the one implementation of what the representation and node-placement work's own `design_stats.py` and `node_stats.py` counted; `bench/theory/human_gap.py` keeps only its per-face match, its turning and parameter gaps being the gate's own axes. +- **A machine-checked theory of inverting box-filter rasterisation** (`formal/InkvecTheory`, Lean 4 + Mathlib, `docs/theory/README.md`): coverage defined as Lebesgue area; the column-sum theorem; the exact null space of the box filter (the layer-cake fibre of a column, and the zigzag as the one invisible deformation of a border-vertex polyline: the boundary solve's "sawtooth"); identifiability of polynomial boundaries from as many columns as coefficients; the cell-mean-to-point correction exact for cubics; the sharp 3/2 − √2 bias of the ½-crossing; minimax lower bounds for tracers that threshold or quantise first (½ px for thresholding); exact inversion of sub-pixel strokes that straddle a border and the bias of the coverage centroid; noise and supersampling versions. No `sorry` and no axiom beyond Lean's three standard ones (`lake build InkvecTheory.Audit`); a `formal` CI workflow checks both. A literature survey of the mathematics behind reversing rasterisation, and what of it had been formalised (nothing), is in the theory page. +- **Checkers generated from the proofs** (`crates/inkvec-verified`, `formal/InkvecTheory/InkvecTheory/Gen/`). The engine's solvers stay free; a result a theorem speaks about is now accepted only by a checker generated from the Lean definition the theorem is about, in exact rationals or outward-rounded intervals, and CI regenerates the checkers and fails on any difference, so the code cannot drift from the proofs (`docs/theory/verification.md` compares six ways of linking them). Soundness is proved once for the expression language (`evalQ_sound`, `evalI_sound`). First kernels: `strip.rs`'s cubic stencil is now generated (bit for bit the formula it replaced; output unchanged), and every vertex the strip reading moves must be proved to lie on the cubic the column sums determine (`stripResidual_on_cubic`) or it goes to the probes. +- **A geometric match to the artist's file in the regression gate** (`geom`, gated at 2 %; `geom_far` reported). Both files are drawn flat at four times the input's size, every pixel takes the nearest of the artist's colours, and the area where they disagree, divided by the length of the artist's edges, is the mean distance between the trace's edges and the artist's, in input pixels (`bench/inkvec_bench/geomatch.py`). An edge moved by `δ` reads `δ` in any colour: a disc grown by 0.1 px reads 0.097 in dark red and in pale grey, where dE00 reads 0.021 and 0.0018 (`bench/theory/geom_calibration.py`). `geom_far` is the part more than an input pixel from any artist edge: missing or extra features. Current build: Quality 0.056 px at 128 px, 0.093 at 512 px, 0.097 at 512 px opaque; Fast 0.15, 0.32, 0.28 (about half of it `geom_far`). The baseline is re-recorded in format 2 (scorer version 4) for this axis; every other number in it is unchanged. +- **The gate judges turning and parameters as distances from the artist's file** (`turning_gap`, `ratio_gap`, replacing the raw `turning` and `ratio` axes, same margins). Lower is not better everywhere: per canvas side the artists' files turn more than the traces of lucide, material-icons and simple-icons (3.35, 6.71 and 8.73 against 2.65, 4.70 and 6.89 at 512 px), and noto-emoji on the noisy tier writes fewer numbers than its artists, so a trace moving toward the artist used to read as a regression. `turning_gap` is |the trace's turning per raster side − the artist's per canvas side|, `ratio_gap` is |ln(parameters / the artist's)|, both family-macro means. They are derived from the stored per-icon rows, so the baselines kept every icon's numbers; only their summaries were recomputed. The raw values stay reported. +- **A noisy condition in the regression gate** (`quality-web`, `fast-web`). The gate's other rasters are exact renders, noiseless but for 8-bit rounding; the `web` tier is each screen icon as logos usually reach a tracer: flattened onto white, resized from 512 to 400 px with bicubic interpolation (blur and overshoot at every edge) and saved as a quality-80 JPEG with 4:2:0 chroma (8×8 block quantisation, colour at half resolution), after the practical degradation model of Zhang et al. (2021, arXiv 2103.14006) fixed at one setting. `bench/build_web_tier.py` writes it; the 246 JPEG files (3.3 MB) are committed so every machine scores the same bytes. The scorer reads a `.jpg` intake and judges a file with no alpha channel over white, as an opaque tier. +- **Naturality, proved** (`formal/InkvecTheory/InkvecTheory/Naturality.lean`): when a merge keeps the true boundary drawable, the merged least-squares fit is at least as close to the truth for every noise realisation (`natural_model_closer`), the gain is exactly the noise in the removed directions (`natural_model_gain`), the merge test reads only that noise (`merge_chi2_increase`), and each parameter keeps one unit of noise variance (`noise_absorbed`: `Σᵢ ‖P bᵢ‖² = dim K`). +- **`bench/theory`**: `attribution.py` (where each icon's dE00 comes from: edge band by smooth, corner and junction, interior flat, shaded, blobs), `params_diag.py` (where the parameters go, against the artist's file) and `naturality_diag.py` (parameters an artist would not write: collinear vertices, straight cubics, co-circular arcs, broken continuations). +- **Noise measured at the edges, per image (Quality, soft or lossy intakes only).** Where the colour path finds an intake soft or lossy (wide edges, ringing, a lossy container), the boundary evidence now measures the intake's noise from its own edges: rounding as the base, replica windows counted once, the rest from the fourth differences of consecutive window sums (winsorised, geometry gated out, per class), the tail as Student-t degrees of freedom, a point-sampling renderer's lattice read from axis-aligned edges. Above three levels of edge noise `ColorTrace::noise` carries the result as `inkvec_core::noise::NoiseModel` for the representation chain; below it, and on every clean intake, it is `NoiseModel::clean()`. Nothing in the pipeline reads it yet, so traced files are byte-identical to the previous build on all eight gate conditions; a clean intake does not even take the measurement. Folding it into each boundary point's `σ` is opt-in (`INKVEC_NOISE_FOLD=1`) until the fitter reads it with a robust loss: with today's fitter it trades fidelity for simplicity on `web` (dE00 +2.8 %, geom +1.7 %, turning −5 %, parameters −1.4 %). On a lossy intake the windows read luma (4:2:0 chroma bleeds), their inks are plateau medians, and they span the observed ramp. The truth's score on the `web` tier falls from `χ²/M` 150 to 3.1 (1.8 under Huber). The evaluator gains the blur forward model (`½ μ₂ A''`, `window_sum_resampled` and two companions proved in `Windows.lean`), Huber's robust cost, stroke bands and per-layer compositing at junctions (A2), and `EdgeScorer`, the dynamic program's window partition by point index (`docs/theory/chain-boundary.md`, "Phase 2, milestone 2"). +- **The boundary evidence and its likelihood** (`inkvec_core::likelihood`, `inkvec_trace::evidence`; not yet called by the pipeline, output unchanged): every partial pixel between two flat inks in exactly one column or row window whose unmixed sum is the left face's exact area there (`window_sum_eq_area`, proved), so any candidate curve (lines, Béziers, arcs drawn as usvg converts them) is scored by `χ²` over windows, calibrated at `χ²/M` 0.97 on exact 8-bit renders; per-pixel terms at junctions (with arms in cyclic order and possible continuations) and at corners; corner proposals from the fourth difference. Runs and corner proposals are accepted only by checkers generated from `Gen/Evidence.lean`. `bench/theory/renderer_floor.py` measures what the corpus intake adds beyond quantisation, per family and tier (`docs/theory/chain-boundary.md`, "Phase 2, milestone 1"). +- **`bench/theory`**: an exact-area rasteriser (font-rs's accumulation in float64) and the scripts that score boundary readings, and inkvec's stage 07, against exactly known geometry. - **Half-turn symmetry.** A drawing that is its own 180° rotation about the image centre, and no mirror image, now comes back exactly so (`bench/cases` `mirror_r`, Quality and Fast), through the same pairing, confirmation and averaging as the mirrors. ## [0.2.7] - 2026-10-08 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 85380171..822771ef 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -59,14 +59,23 @@ the installer refuses to replace a pre-push hook it did not write (unless `--for ## The regression gate `bench/ci_gate.py` scores the committed 246-icon screen set (`bench/data`, kept in the -repository so the gate runs from a bare checkout) under six conditions: Quality and Fast mode, -each at 128 px, 512 px with transparency and 512 px flattened onto white (an opaque logo). +repository so the gate runs from a bare checkout) under eight conditions: Quality and Fast +mode, each at 128 px, 512 px with transparency, 512 px flattened onto white (an opaque logo) +and `web` (the same logo resized to 400 px and saved as a quality-80 JPEG: the noise real +inputs carry; `bench/build_web_tier.py`). Each condition is compared icon by icon with the per-platform baseline -`bench/gate/baselines/-.json`, on three axes: +`bench/gate/baselines/-.json`, on four axes: - **dE00** (colour error against the artist's file), margin 1% -- **turning** (control-polygon turning per unit length, read command by command), margin 2% -- **ratio** (parameter count versus the artist's), margin 3% +- **turning_gap** (distance from the artist's control-polygon turning, per canvas side), + margin 2% +- **ratio_gap** (distance from the artist's parameter count, `|ln(ratio)|`), margin 3% + +Turning and parameters are judged as distances from the artist's file, not as raw values: +a trace that turns more, or writes more numbers, toward what the artist drew is not a +regression. The raw values are still reported. +- **geom** (geometric match to the artist's file: the mean distance between the trace's + edges and the artist's, in input pixels, read as the area between them), margin 2% The verdict is statistical: a paired bootstrap interval for the change of each axis, and a non-inferiority test that passes when the one-sided 95% upper bound stays below the margin. @@ -75,7 +84,7 @@ the margin is floored at the smallest effect the set can detect, and such a pass reported as "within-noise"; there is no "inconclusive" verdict. Details and the literature are in `bench/README.md`. -Run it against a release build (about 30 min for all six conditions on a desktop; pass +Run it against a release build (about 40 min for all eight conditions on a desktop; pass `--conditions` for a subset while iterating): ``` @@ -83,7 +92,17 @@ cargo build --release -p inkvec-cli python bench/ci_gate.py --exe target/release/inkvec --workers 4 ``` -(needs `numpy`, `pillow`, `scikit-image`, `resvg_py`). `python tools/prepush.py --gate` +(needs `numpy`, `scipy`, `pillow`, `scikit-image`, `resvg_py`). Icons whose SVG is +byte-identical to the baseline's are traced but not scored again, so a change that moves few +icons costs little more than the traces. The gate also reports, without gating them, how far +each trace is from the artist's file in how it is *drawn* (segment kinds, smooth joins, nodes +at the extrema, the design grid, ...); to tune a build or a flag against those statistics: + +``` +python bench/human_stats.py --exe target/release/inkvec --extra-args "--editability" --base-args "" +``` + +`python tools/prepush.py --gate` runs it with the hard cases. Only a demonstrable gain moves a baseline. If a change regresses an axis, the gate fails; it can only be bypassed with `--exe ... --bypass-gate ""`, and only with a strong, explicit diff --git a/Cargo.lock b/Cargo.lock index 82380eaa..0a4e91c5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3823,6 +3823,7 @@ dependencies = [ "inkvec-sr", "inkvec-svgmin", "inkvec-trace", + "inkvec-verified", "rayon", ] @@ -3933,10 +3934,15 @@ dependencies = [ "image", "inkvec-core", "inkvec-fit", + "inkvec-verified", "moxcms", "rayon", ] +[[package]] +name = "inkvec-verified" +version = "0.2.7" + [[package]] name = "inkvec-wasm" version = "0.2.7" diff --git a/Cargo.toml b/Cargo.toml index 88348e83..65bee971 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,7 @@ resolver = "2" members = [ "crates/inkvec-core", + "crates/inkvec-verified", "crates/inkvec-fit", "crates/inkvec-trace", "crates/inkvec-cli", @@ -43,6 +44,7 @@ too_many_lines = "warn" # Internal crates carry a version as well as a path: crates.io refuses a published crate # whose dependency is a bare path. inkvec-core = { path = "crates/inkvec-core", version = "0.2.7" } +inkvec-verified = { path = "crates/inkvec-verified", version = "0.2.7" } inkvec-fit = { path = "crates/inkvec-fit", version = "0.2.7" } inkvec-trace = { path = "crates/inkvec-trace", version = "0.2.7" } inkvec-sr = { path = "crates/inkvec-sr", version = "0.2.7" } diff --git a/PIPELINE_EXPLANATION.md b/PIPELINE_EXPLANATION.md index bc19730d..0420daeb 100644 --- a/PIPELINE_EXPLANATION.md +++ b/PIPELINE_EXPLANATION.md @@ -59,7 +59,7 @@ Inkvec implements a dual-tier neural pre-processing architecture. These two neur | **Extreme Clamping / Snapping** | **`SNAP_LEVELS = 6`** (`crates/inkvec-restore/src/lib.rs:101`) | Channel-wise affine **`clean::match_flats`** (`crates/inkvec-sr/src/clean.rs:206`) | | **Stochastic Routing Fix** | N/A (deterministic feed-forward CNN) | **Pinned Seed `ROUTING_SEED = 0x5641_4331`** ("VAC1", `tools/inkvec_sr/model.py:40`) | | **Damage Gating** | `inkvec_restore::decide` (`crates/inkvec-restore/src/lib.rs:568`) | `inkvec_sr::decide` (`crates/inkvec-sr/src/lib.rs:171`) | -| **CLI Flag** | `inkvec --restore ` (default: `off`) | `inkvec --sr ` (default: `off`) | +| **CLI Flag** | `inkvec --restore ` (default: `auto` in Quality mode when the build can restore, else `off`) | `inkvec --sr ` (default: `off`) | | **Tracer Intake Interaction** | Forces tracer **`--lossy on`** (soft intake) when restoration triggers | Runs before intake normalization; downsampled to target scale | > **Critical Architectural Clarification (The Arrhenius Attribution):** @@ -885,7 +885,7 @@ Crucially, Inkvec derives the **honest posterior covariance** of every measureme $$\sigma_{\text{pos}} = \frac{\sigma_\alpha}{\|\nabla \alpha\|} = \frac{\sigma_{\text{pixel}}}{\|F - B\| \cdot \|\nabla \alpha\|}$$ #### 3. Quantization Noise Floor (`sigma_floor`) -On inputs with discretized alpha channels (e.g. 16-level alpha), uniform quantization noise creates artificial gradient steps. The floor that uniform quantization over a unit interval would suggest is shown below; Inkvec does not apply it: `SIGMA_FLOOR` is zero, because coverage-derived positions can be more precise than whole pixel coordinates and a universal $1/\sqrt{12}$ px floor oversmooths clean small artwork (`crates/inkvec-trace/src/contour.rs:318-327`, applied on the planar path at `crates/inkvec-trace/src/planar.rs:1253-1255`): +On inputs with discretized alpha channels (e.g. 16-level alpha), uniform quantization noise creates artificial gradient steps. The floor that uniform quantization over a unit interval would suggest is shown below; Inkvec does not apply it: `SIGMA_FLOOR` is zero, because coverage-derived positions can be more precise than whole pixel coordinates and a universal $1/\sqrt{12}$ px floor oversmooths clean small artwork (`crates/inkvec-trace/src/contour.rs:318-327`, applied on the planar path at `crates/inkvec-trace/src/planar.rs:1214-1216`): $$\sigma_{\text{floor}} \ge \frac{1}{\sqrt{12}} \approx 0.2887\text{ px}$$ diff --git a/README.md b/README.md index eee7f3ca..b16dbab0 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ Per-case coordinate count over the same 21 cases, from the same script and data ### Damaged input: JPEG, WebP, AI-decoder output -Inkvec ships an optional trained restorer that removes compression and decode damage before tracing. It is **off by default** (`--restore off`; `--restore auto` enables it only when the input looks damaged). The weights that ship — `restorer.onnx` from [`Logolabs/inkvec-denoiser-001`](https://huggingface.co/Logolabs/inkvec-denoiser-001), pulled on first use or via `tools/pull_model.py` — have **no published benchmark in this repository**, and no LPIPS or ablation figure for them is reported anywhere here. The figures that previously appeared in this section were measured during development on a different checkpoint and are not reproduced for the shipped weights; the VectorArk and StarVector numbers were those projects' own published results, measured under their protocols, not here. +Inkvec ships an optional trained restorer that removes compression and decode damage before tracing. In Quality mode it is **`auto` by default** in a build that carries it (`--restore auto`: it restores only when the input shows compression and its trace disagrees with it; a clean PNG pays the ringing score alone); Fast and balanced keep it off unless `--restore auto` or `on` is given, and a build without it traces as `--restore off`. The weights that ship — `restorer.onnx` from [`Logolabs/inkvec-denoiser-001`](https://huggingface.co/Logolabs/inkvec-denoiser-001), pulled on first use or via `tools/pull_model.py` — have **no published benchmark in this repository**, and no LPIPS or ablation figure for them is reported anywhere here. The figures that previously appeared in this section were measured during development on a different checkpoint and are not reproduced for the shipped weights; the VectorArk and StarVector numbers were those projects' own published results, measured under their protocols, not here. The same pre-pass runs **in the browser**, on the same `restorer.onnx`: see [In the browser](#in-the-browser). @@ -194,7 +194,7 @@ inkvec [-o ] [OPTIONS] | Flag | Default | What it does | |---|---|---| | `--mode ` | quality | `quality` is the full engine: best fidelity, fewest parameters. `fast` is a Potrace-class fit on the same planar map, with flat fills: several times faster, a little less faithful (see [Speed](#speed-quality-and-fast)). `balanced` is `fast` plus eight iterations of Quality's boundary solve and a fit a quarter finer, on inputs up to 1024 px on the longer side (larger ones trace as `fast`). Options that only steer Quality stages are ignored in Fast and Balanced, and the report names them. | -| `--restore ` | off | Trained-network cleanup for JPEG/WebP/AI-decoder damage. `auto` only restores if it looks damaged, and traces directly when no restorer is available (`on` is an error then). | +| `--restore ` | auto in Quality mode when the build can restore, else off | Trained-network cleanup for JPEG/WebP/AI-decoder damage. `auto` only restores if it looks damaged, and traces directly when no restorer is available (`on` is an error then). | | `--sr ` | off | Super-resolution pre-pass (2-4× upscale), complementary to `--restore`. | | `--lossy ` | auto | Whether to trust the file as clean or trace with noise-aware intake. | | `--max-dim ` | 2048 | Cap on the longer side; SVG is written at the original size. | @@ -381,7 +381,7 @@ Full stage reference: [`docs/algorithm/`](docs/algorithm/) (start at `docs/algor ## Benchmark and CI gate -`bench/` scores against a source SVG with CIEDE2000, DISTS, LPIPS, DINOv2/v3, parameter ratio, bytes and time. CI runs `cargo test` on Linux, Windows and macOS, then `bench/ci_gate.py` against the 246-icon screen set in Quality and Fast mode at 128 and 512 px, failing unless a paired bootstrap shows colour error stays within 1%, anchor turning within 2% and the parameter ratio within 3% of the per-platform baseline. +`bench/` scores against a source SVG with CIEDE2000, DISTS, LPIPS, DINOv2/v3, parameter ratio, bytes and time. CI runs `cargo test` on Linux, Windows and macOS, then `bench/ci_gate.py` against the 246-icon screen set in Quality and Fast mode at 128 and 512 px and as a resized, quality-80 JPEG (the noise real inputs carry), failing unless a paired bootstrap shows colour error stays within 1%, the distance from the artist's control-polygon turning within 2%, the distance from the artist's parameter count within 3% and the geometric match to the artist's file (mean edge displacement, by area) within 2% of the per-platform baseline. --- diff --git a/bench/README.md b/bench/README.md index 769a33e6..a250d978 100644 --- a/bench/README.md +++ b/bench/README.md @@ -26,16 +26,30 @@ python tools/prepush.py --gate # build, ha ``` Scores the committed 246-icon screen set (under `bench/data`, so this runs from a bare -checkout) under six conditions: Quality and Fast, each at 128 px (`128ss`), 512 px -(`512ss`) and 512 px flattened onto white (`512ssop`, an opaque logo). Each condition's -three axes are compared icon by icon with the per-platform baseline +checkout) under eight conditions: Quality and Fast, each at 128 px (`128ss`), 512 px +(`512ss`), 512 px flattened onto white (`512ssop`, an opaque logo) and `web`, the logo as it +usually reaches a tracer: on white, resized to 400 px (bicubic) and saved as a JPEG at +quality 80 with 4:2:0 chroma (`bench/build_web_tier.py`; the JPEG files are committed, so +every machine reads the same bytes). The first three are exact renders; `web` carries the +blur, ringing, block artefacts and half-resolution colour of real inputs. Each condition's +four gated axes are compared icon by icon with the per-platform baseline `bench/gate/baselines/-.json`: | axis | aggregate | margin at the one-sided 95 % upper bound | |---|---|---| | dE00 (colour error vs. the artist's file) | family-macro mean | 1 % | -| turning (control-polygon turning per unit length; `inkvec_bench/turning.py`) | mean | 2 % | -| parameter ratio vs. the artist's file | family-macro mean | 3 % | +| turning gap (distance from the artist's control-polygon turning, per canvas side; `ci_gate.with_gaps`, `inkvec_bench/turning.py`) | family-macro mean | 2 % | +| parameter gap (absolute log of parameters over the artist's: twice and half the artist's count are equally far) | family-macro mean | 3 % | +| geom (mean edge displacement from the artist's file, input px; `inkvec_bench/geomatch.py`) | family-macro mean | 2 % | + +`geom` compares the trace with the artist's file as geometry: both drawn flat (no +anti-aliasing) at four times the input's size, every pixel given the nearest of the +artist's colours, and the area where they disagree divided by the length of the artist's +edges. That is the mean distance between the two files' edges: an edge moved by `δ` reads +`δ` in any colour, where dE00 reads the colour contrast as much as the displacement +(`bench/theory/geom_calibration.py`: a disc grown by 0.1 px reads geom 0.097 in dark red +and in pale grey, dE00 0.021 and 0.0018). `geom_far`, the part of it more than an input +pixel from any artist edge (missing or extra features), and `self_res` are reported. The change of each aggregate gets a paired, family-stratified bootstrap interval (`bench/gate_stats.py`). The gate passes an axis when the interval's one-sided upper bound @@ -43,13 +57,94 @@ is below the margin, or, where the 246 icons cannot resolve the margin (a broad 512 px), below the minimum detectable effect; that pass is reported as `within-noise`. There is no "inconclusive" verdict: the margin is floored at what the set can detect, so a change fails only when it is worse by more than the margin and the set can see it. Icons whose SVG is -byte-identical to the baseline's keep its numbers. A baseline moves only by +byte-identical to the baseline's keep its numbers, and are not scored again at all: the gate +hashes each SVG as soon as it is traced and skips the renders when the hash is the baseline's +(`--rescore` scores them anyway, to check the scorer). A baseline moves only by `--write-baseline` or, locally, on a demonstrable gain. Until a platform's baseline file is committed, the gate falls back to the old scalar rule against `bench/gate/baseline.json` on quality-128ss. CI uploads every run as the `gate-baseline` artifact, in the format to commit. The scorer is a pure function of the SVGs: the reference renders are the same 8-bit images whether the cache is warm or cold. +### What a run costs + +Each condition's console line says where the CPU went, per icon: the tracer, the gate's +signals and the design battery (below), and how many icons were byte-identical to the +baseline. What the artist's file contributes is computed once and kept in +`bench/data/_cache`, keyed by the file's hash and the renderer's and libraries' versions: +the 1024 px reference render (`gt1024/`), the artist's side of `geom` (`geomatch/`: the +flat render's palette, labels, edge length and near-edge mask, at each size and page) and +its design profile (`design/`). dE00 converts and compares only the sampled pixels where +the two renders differ (a pixel equal in both has a CIEDE2000 of exactly 0), and the flat +renders are labelled run by run; both give bit-identical numbers. One process pool serves +every condition. On the full set (246 icons, `--workers 2`, CPU per icon): + +| condition | before | every icon scored, cold cache | every icon scored, warm cache | a normal run against the baseline | +|---|---|---|---|---| +| quality-512ssop | 3.99 s | 2.84 s | 2.15 s | 1.43 s (246 identical) | +| fast-web | 1.75 s | 1.03 s | 0.64 s | 0.35 s (133 identical) | +| quality-web | 3.0 s (30-icon sample) | | | 1.53 s (246 identical) | + +The tracer itself is 1.41 s of quality-512ssop's and 0.05 s of fast-web's; the gate's own +scoring of a changed 512 px icon fell from 2.58 to 0.72 s (the artist's flat render and +labels, about 1.1 s, now come off the cache; labelling the trace's flat render 0.47 to +0.04 s; dE00 0.14 to about 0.04 s), and the design battery adds about 10 ms. Every gate +number is unchanged, bit for bit: run old and new on the same binary (2026-10-10, both +conditions above, cold and warm), all 246 per-icon rows, every summary and every verdict +were identical. What is left is the tracer, and the resvg renders of the trace (its flat +render at four times the input's size is about 0.4 s at 512 px, most of it the PNG +encoding `resvg_py` does on the way out, which it offers no way around). + +## Human statistics: how a trace is drawn + +```bash +python bench/human_stats.py --exe target/release/inkvec # quality-512ssop and quality-web +python bench/human_stats.py --exe target/release/inkvec --extra-args "--editability" --base-args "" +python bench/human_stats.py --exe new/inkvec --base-exe old/inkvec --conditions fast-web +python bench/human_stats.py --from-report gate/report.json --correlate # a gate run's numbers +``` + +The gate's axes ask whether a trace looks like the artist's drawing and is about as long; +none asks whether it is *built* like it. `inkvec_bench/design.py` reads a file once (paths, +primitives, transforms and inherited paint, mapped to the canvas the gate renders) and +takes a battery of statistics of its construction: the segment-kind mix, lines and handles +on the axes, smooth joins and nodes at the extrema, kinked joins, corner angles, curve +sweeps, handle lengths, segment lengths, coordinates on the artist's design grid, decimals, +repeated values, mirror symmetry, primitives, strokes, colours, nested subpaths and stacked +shapes. Each is read on the trace and on the artist's own file, and the **divergence**, the +per-icon distance between the two (a share's difference, a count's log ratio, a +distribution's Wasserstein-1, a mix's total variation), is zero for a trace drawn as the +artist drew it, whatever the family's style. The module's documentation defines each one. +`halfpx`, the share of numbers on the raster's half-pixel grid, is an artefact signal (pixel +snapping), reported but left out of the composite. + +The statistics are reported, not gated. The gate takes them on every icon it traces (about +10 ms each; the artist's side is cached), prints each one's family-macro mean divergence +per condition, and writes every icon's values to `--report-json` (`human`) and to +`--artifact-dir` (`human-.json`). `bench/human_stats.py` traces without +rendering (the tracer's time plus the battery) and prints, per family, the artist's mean, +the trace's mean and the divergence of each statistic, then the oddities: the icons +farthest from their artist on each statistic and overall. With `--base-exe` or +`--base-args` it traces a second arm and compares the two icon by icon: each statistic's +family-macro divergence before and after, a paired, family-stratified bootstrap interval of +the change (`gate_stats.compare`, as the gate does), how many icons moved closer and +further, and one composite, the geometric mean of the after/before ratios, to tune against +(below 1 is closer to the artist). Traces are kept under `bench/data/_cache/traces`, keyed +by the executable's bytes and the flags, so an arm already traced costs nothing. + +The battery is non-redundant by construction: `--correlate` computes the Spearman +correlation of the per-icon divergences (pooled over the conditions, with the gate's own +axes when known) and drops a statistic correlated beyond |rho| 0.7 with one kept before it; +`design.KEPT` is what survived on quality-512ssop, quality-web and fast-web. + +On the 246 icons of quality-512ssop and quality-web pooled, seven of the 36 candidates went: +`grid_int` (rho 0.98 with `grid_half`), `grid_level` (0.72) and `decimals` (0.74) with it, +`wide_curves` with `sweep` (0.72), `length_gini` with `segment_lengths` (0.79), `palette` +with `colours` (0.84), and `evenodd`, nonzero on 6 of 616 icon-conditions. The 29 kept +statistics stay below |rho| 0.7 with each other (largest: `segment_lengths` with +`nodes_per_subpath`, 0.68) and below 0.57 with every gate axis (largest: `colours` with +dE00, `smooth` with geom), so none repeats what the gate already reads. + ## Hard cases ```bash diff --git a/bench/build_web_tier.py b/bench/build_web_tier.py new file mode 100644 index 00000000..6963b540 --- /dev/null +++ b/bench/build_web_tier.py @@ -0,0 +1,72 @@ +"""Build the `web` raster tier: the screen set as logos usually reach a tracer. + +Each icon's committed 512 px raster (`512ss`) goes through the pipeline a logo meets on its +way to a user: flattened onto a white page, resized by a non-integer factor with bicubic +interpolation (Pillow's, `a = -0.5`: blur and a slight overshoot at every edge), and saved +as a JPEG at quality 80 with 4:2:0 chroma subsampling (8x8 block quantisation, colour at half +resolution). The JPEG files themselves are committed under +`bench/data/corpus_raster//web/.jpg` and the tracer decodes them, so the gate +reads the same bytes on every machine whatever Pillow or libjpeg a later run has. + + python bench/build_web_tier.py # (re)build every icon of the screen set + python bench/build_web_tier.py --check # report icons whose file is missing + +The degradation follows the practical models of Zhang, Liang, Van Gool, Timofte (2021), +Designing a practical degradation model for deep blind image super-resolution, ICCV, +arXiv 2103.14006 (blur, resampling, JPEG), fixed to one realistic setting rather than drawn +at random, so a gate can compare builds on it. +""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "bench")) + +#: The tier's name, its source tier and its parameters (recorded in the files' names' +#: directory and in the gate's documentation). +TIER = "web" +SOURCE = "512ss" +SIZE = 400 # px; 512 -> 400 is a factor of 0.78125 +QUALITY = 80 +SUBSAMPLING = "4:2:0" + + +def build_one(src: Path, dst: Path) -> None: + from PIL import Image + im = Image.open(src).convert("RGBA") + page = Image.new("RGBA", im.size, (255, 255, 255, 255)) + page.alpha_composite(im) + out = page.convert("RGB").resize((SIZE, SIZE), Image.BICUBIC) + dst.parent.mkdir(parents=True, exist_ok=True) + out.save(dst, format="JPEG", quality=QUALITY, subsampling=SUBSAMPLING, optimize=False) + + +def main() -> int: + import svgeval + ap = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--check", action="store_true") + a = ap.parse_args() + items = svgeval.load_sets()["screen"] + base = ROOT / "bench" / "data" / "corpus_raster" + missing = 0 + for it in items: + src = base / it["corpus"] / SOURCE / f"{it['stem']}.png" + dst = base / it["corpus"] / TIER / f"{it['stem']}.jpg" + if a.check: + missing += not dst.exists() + continue + build_one(src, dst) + if a.check: + print(f"{missing} of {len(items)} missing") + return 1 if missing else 0 + print(f"wrote {len(items)} files under {base}//{TIER}/") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/bench/ci_gate.py b/bench/ci_gate.py index ad68c07d..9d3b13d4 100644 --- a/bench/ci_gate.py +++ b/bench/ci_gate.py @@ -1,4 +1,4 @@ -"""The regression gate: score the 246-icon screen set under six conditions, and fail when a +"""The regression gate: score the 246-icon screen set under eight conditions, and fail when a change cannot show it is not worse than the recorded baseline. python bench/ci_gate.py --exe target/release/inkvec [--workers N] @@ -11,29 +11,53 @@ ---------- Each condition is a tracer mode and an intake tier of the same 246 icons (`CONDITIONS`): - quality-128ss quality-512ss quality-512ssop - fast-128ss fast-512ss fast-512ssop + quality-128ss quality-512ss quality-512ssop quality-web + fast-128ss fast-512ss fast-512ssop fast-web `128ss` / `512ss` are the committed 8x-supersampled rasters at 128 and 512 px; `512ssop` is the 512 px raster flattened onto white, an opaque logo on a white page (`svgeval.item_paths` -derives it). Every condition is judged at 1024 px against the artist's file. +derives it). `web` is a logo as it usually reaches a tracer: the 512 px raster on white, +resized to 400 px (bicubic) and saved as a JPEG at quality 80 with 4:2:0 chroma, so blur, +ringing, block artefacts and half-resolution colour (`build_web_tier.py`; the JPEG files are +committed). Every condition is judged at 1024 px against the artist's file. -Why six and not one. The gate used to score Quality at 128 px only, 98 % transparent; users +Why eight and not one. The gate used to score Quality at 128 px only, 98 % transparent; users send 512-2048 px, mostly opaque. On the 0.2.4 boundary-solve rewrite the 128 px gate read -8.5 % dE00 where 512 px read -0.9 % (indistinguishable from zero), per-icon deltas at 128 and 512 px were uncorrelated (Spearman +0.14), and material-icons went from -47 % at 128 px to +14 % at 512 px: a regression the old gate could not see (r2-eval, 2026-10-02). 128 px -stays as the continuity row; Fast mode had no fidelity gate at all. +stays as the continuity row; Fast mode had no fidelity gate at all. The rasters above are +exact renders, noiseless but for 8-bit rounding; the files users send have been resampled +and compressed on the way, and a tracer tuned on exact renders alone can fit that noise +(a ringing edge read as a thin band of its own colour, a JPEG block read as a corner). The +`web` rows gate that case. Axes and the decision --------------------- -Per condition, three axes are gated against the per-icon baseline of the same condition: +Per condition, four axes are gated against the per-icon baseline of the same condition: * **dE00** colour error against the artist's render, family-macro mean, margin `MARGINS` -* **turning** control-polygon turning per unit length, plain mean (`inkvec_bench/turning.py`) -* **ratio** parameters against the artist's file, family-macro mean - -and `self_res` is reported. For each axis, `bench/gate_stats.py` computes the relative +* **turning_gap** distance from the artist's control-polygon turning: |the trace's turning + per unit length × the raster's side − the artist's turning per unit length + × the longer side of its canvas|, family-macro mean (`with_gaps`, + `inkvec_bench/turning.py`). Scale-free, and zero where the trace turns exactly + as much as the artist's file +* **ratio_gap** distance from the artist's parameter count, |ln(parameters / the + artist's)|, family-macro mean: twice and half the artist's count are equally far +* **geom** geometric match to the artist's file, family-macro mean: the mean distance, + in input pixels, between the trace's edges and the artist's, read as the area + where the two files, drawn flat in the artist's colours, disagree, over the + length of the artist's edges (`inkvec_bench/geomatch.py`). An edge moved by + `δ` reads `δ`; the artist's own file reads 0 + +and the raw `turning` (plain mean) and `ratio` (family-macro mean), `self_res` and +`geom_far` (the part of `geom` more than an input pixel from any artist edge: missing or +extra features) are reported. Turning and parameters were gated raw until 2026-10-10, lower +counting as better; but the artists' files turn more than the traces of lucide, material-icons +and simple-icons (per canvas side 3.35, 6.71 and 8.73 against 2.65, 4.70 and 6.89 at +512ssop), and noto-emoji on `web` writes fewer numbers than its artists, so a trace moving +toward the artist read as a regression. The gaps are computed from the stored rows, so the +baselines needed no re-trace. For each axis, `bench/gate_stats.py` computes the relative change of the aggregate with a paired, family-stratified bootstrap interval (Koehn 2004) and takes a non-inferiority verdict (Lakens 2017) against the effective margin max(`MARGINS`, minimum detectable effect): the change passes when the one-sided 95 % upper @@ -43,7 +67,21 @@ smallest rise the set would detect (Card et al. 2020), and the report marks those passes. Icons whose SVG bytes match the baseline's (SHA-256) take the baseline's numbers exactly, -so a byte-identical build is "identical" on every axis whatever platform scores it. +so a byte-identical build is "identical" on every axis whatever platform scores it. They are +not even scored: each SVG is hashed as soon as it is traced, and a match skips the renders +(`svgeval.score_one`; `--rescore` scores every icon, to check the scorer). What the artist's +file contributes (its reference render, its side of `geom`, its design profile) is cached in +`bench/data/_cache` by the file's hash; each condition's line says where the CPU went. + +Human statistics +---------------- +Every traced icon also gets the design battery (`inkvec_bench/design.py`): statistics of how +the file is drawn (segment kinds, lines and handles on the axes, smooth joins at the extrema, +corner angles, the design grid, repeated values, primitives, layers, ...), each as a +divergence from the artist's file. They are reported, not gated: a table of family-macro +means per condition on the console, every icon's values in `--report-json` (`human`) and in +`--artifact-dir` (`human-.json`); `bench/human_stats.py` reads them per family, +lists the oddities and compares two builds or flag sets. Baselines --------- @@ -77,10 +115,14 @@ from __future__ import annotations import argparse +import contextlib +import functools import hashlib import json +import math import os import platform +import re import subprocess import sys import time @@ -91,6 +133,7 @@ sys.path.insert(0, str(ROOT / "bench")) import gate_stats # noqa: E402 +import human_stats import svgeval # noqa: E402 BASELINE = ROOT / "bench" / "gate" / "baseline.json" # legacy scalar baseline (09-19) @@ -98,7 +141,7 @@ LEGACY_LIMITS = {"de00": 0.01, "turning": 0.01, "ratio": 0.05} LEGACY_CONDITION = "quality-128ss" #: Layout of the per-platform baseline files; bumped on an incompatible change. -BASELINE_FORMAT = 1 +BASELINE_FORMAT = 2 @dataclass(frozen=True) @@ -114,14 +157,17 @@ class Condition: Condition("quality-128ss", "128ss"), Condition("quality-512ss", "512ss"), Condition("quality-512ssop", "512ssop"), + Condition("quality-web", "web"), Condition("fast-128ss", "128ss", ("--mode", "fast")), Condition("fast-512ss", "512ss", ("--mode", "fast")), Condition("fast-512ssop", "512ssop", ("--mode", "fast")), + Condition("fast-web", "web", ("--mode", "fast")), ) BY_NAME = {c.name: c for c in CONDITIONS} #: How each axis is aggregated over the set (see gate_stats.compare). -AGGREGATE = {"de00": "macro", "turning": "micro", "ratio": "macro", "self_res": "micro"} +AGGREGATE = {"de00": "macro", "turning": "micro", "ratio": "macro", "self_res": "micro", + "geom": "macro", "geom_far": "macro", "turning_gap": "macro", "ratio_gap": "macro"} #: The relative rise each gated axis may show at its one-sided 95 % upper bound. Chosen on #: the replay of the 0.2.4 decisions through this rule (REPORT of agent w2-gate, #: 2026-10-02): at 2 % every recorded 0.2.4 change passes at every condition, while at 1 % @@ -135,14 +181,72 @@ class Condition: #: stays at 2 %), and asked that the gate never answer "inconclusive": gate_stats.decide #: floors each margin at the comparison's minimum detectable effect (about 4 % for a broad #: edit at 512 px), so the strict margin holds wherever the set can test it. -MARGINS = {"de00": 0.01, "turning": 0.02, "ratio": 0.03} +#: +#: Turning and parameters are gated as distances from the artist's file (`turning_gap`, +#: `ratio_gap`, see `with_gaps`), not as raw values, since 2026-10-10: lower is not better +#: where the artist's own file turns more or holds more numbers than the trace (lucide, +#: material-icons and simple-icons traces turn less than their artists do; noto-emoji on +#: `web` writes fewer numbers), and a trace moving toward the artist must not read as a +#: regression. The raw values stay reported. Same margins as the raw axes had. +MARGINS = {"de00": 0.01, "turning_gap": 0.02, "ratio_gap": 0.03, "geom": 0.02} GATED_AXES = tuple(MARGINS) #: The Ladder's step (gate_stats.decide): a "better" verdict, the only one that moves a #: baseline, needs its one-sided upper bound below -0.1 %. Comparing the Linux and Windows #: builds of v0.2.4 read "better" on fast-512ss dE00 at -0.00 % (two icons, both a hair #: lower) without it. LADDER_STEP = 0.001 -REPORTED_AXES = GATED_AXES + ("self_res",) +REPORTED_AXES = GATED_AXES + ("turning", "ratio", "self_res", "geom_far") + +#: Side of each committed raster tier, in px (every screen raster is square: +#: `tests/test_ci_gate.py` checks it). An opaque tier `op` has its base tier's side. +TIER_PX = {"128ss": 128, "512ss": 512, "web": 400} + + +def canvas_side(svg: str) -> float | None: + """The longer side of an SVG's canvas, in its own user units: the viewBox's, else the + root's width and height. The harness fits the longer side to the raster + (`inkvec_bench.render.fit_viewbox`), so a turning per user unit times this side is a + turning per raster side, the same in the artist's units and in the trace's px.""" + head = svg[:svg.find(">", svg.find(" 0 else None + + +@functools.cache +def artist_turning(key: str) -> float | None: + """The artist's file's turning per canvas side (`inkvec_bench/turning.py` times + `canvas_side`) for icon `family/stem`, or None when its file is missing or has no canvas + size. Read as written: a scale in a `transform` is not applied (none of the screen set's + files scales a group).""" + from inkvec_bench.turning import turning + corpus, stem = key.split("/", 1) + path = ROOT / "bench" / "data" / "corpus_svg" / corpus / f"{stem}.svg" + if not path.exists(): + return None + svg = path.read_text(encoding="utf-8") + side = canvas_side(svg) + return turning(svg) * side if side else None + + +def with_gaps(rows: dict, cond: Condition) -> dict: + """Add the two distances from the artist's file to each row, in place, and return rows: + + * `turning_gap` = |turning × raster side − the artist's turning per canvas side|, in + radians of control-polygon turning per canvas side (scale-free; an icon without an + artist reading measures from 0); + * `ratio_gap` = |ln(parameters / the artist's)|, so twice and half the artist's count + are equally far. + """ + px = TIER_PX[svgeval.base_tier(cond.tier)] + for k, r in rows.items(): + a = artist_turning(k) + r["turning_gap"] = abs(r["turning"] * px - (a if a is not None else 0.0)) + r["ratio_gap"] = abs(math.log(max(r["ratio"], 1e-9))) + return rows # --------------------------------------------------------------------------- provenance @@ -186,26 +290,46 @@ def in_ci() -> bool: # --------------------------------------------------------------------------- scoring -def score_condition(exe: Path, cond: Condition, items: list[dict], workers: int) -> tuple[dict, list[str]]: +def score_condition(exe: Path, cond: Condition, items: list[dict], workers: int, + base_rows: dict | None = None, pool=None) -> tuple[dict, list[str]]: """Trace and score every icon under one condition. - Returns ({"family/stem": {"corpus", "de00", "turning", "ratio", "self_res", "sha256"}}, + Returns ({"family/stem": {"corpus", *ROW_AXES, "sha256", "reused", "human", "cpu"}}, failures). The score cache is off: the gate must measure this build, not remember one. + An icon whose SVG is byte-identical to `base_rows`' is traced but not scored again: it + takes the baseline's numbers, which `compare_condition` would substitute anyway. """ svgeval.set_tier(cond.tier) work = ROOT / "bench" / "data" / "_gate" / cond.name + known = {k: (r["sha256"][:SHA_CHARS], {ax: r[ax] for ax in ROW_AXES}) + for k, r in (base_rows or {}).items() if r.get("sha256")} t0 = time.time() ss = svgeval.score_set(exe, cond.name, items, work, extra_args=cond.args, - workers=workers, use_cache=False) + workers=workers, use_cache=False, known=known, human=True, pool=pool) rows = {f"{i.corpus}/{i.stem}": {"corpus": i.corpus, "de00": i.de00, "turning": i.turning, "ratio": i.ratio, "self_res": i.self_res, - "sha256": i.sha256[:SHA_CHARS]} + "geom": i.geom, "geom_far": i.geom_far, + "sha256": i.sha256[:SHA_CHARS], "reused": i.reused, + "human": i.human, "cpu": i.cpu} for i in ss.images} print(f" {cond.name}: {len(rows)} icons in {time.time() - t0:.0f} s" - + (f", {len(ss.failures)} failed" if ss.failures else ""), flush=True) + + (f", {len(ss.failures)} failed" if ss.failures else "") + "; " + cpu_line(rows), + flush=True) return rows, ss.failures +def cpu_line(rows: dict) -> str: + """Where one condition's CPU time went, per icon: the tracer, the gate's signals, the + design battery; and how many icons were byte-identical to the baseline (not re-scored).""" + n = max(1, len(rows)) + tot = {k: sum(r.get("cpu", {}).get(k, 0.0) for r in rows.values()) / n + for k in ("trace", "score", "human")} + reused = sum(bool(r.get("reused")) for r in rows.values()) + return (f"CPU {sum(tot.values()):.2f} s/icon (trace {tot['trace']:.2f}, scoring " + f"{tot['score']:.2f}, design battery {tot['human']:.3f}); {reused} byte-identical " + "to the baseline, not re-scored") + + def summarise(rows: dict) -> dict: """The set-level numbers of one condition: each axis's aggregate, plus n.""" fam = {k: r["corpus"] for k, r in rows.items()} @@ -227,17 +351,21 @@ def summarise(rows: dict) -> dict: DIGITS = 9 +#: The scores of a per-icon row in the baseline file, in order; the row ends with the SVG's +#: hash. +ROW_AXES = ("de00", "turning", "ratio", "self_res", "geom", "geom_far") + + def pack_rows(rows: dict) -> dict: - """Per-icon rows as compact lists, [de00, turning, ratio, self_res, sha256], for the file.""" + """Per-icon rows as compact lists, [*ROW_AXES, sha256], for the file.""" rnd = lambda x: float(f"{x:.{DIGITS}g}") # noqa: E731 - return {k: [rnd(r["de00"]), rnd(r["turning"]), rnd(r["ratio"]), rnd(r["self_res"]), - r["sha256"][:SHA_CHARS]] + return {k: [rnd(r[ax]) for ax in ROW_AXES] + [r["sha256"][:SHA_CHARS]] for k, r in sorted(rows.items())} def unpack_rows(packed: dict) -> dict: - return {k: {"corpus": k.split("/", 1)[0], "de00": v[0], "turning": v[1], "ratio": v[2], - "self_res": v[3], "sha256": v[4]} for k, v in packed.items()} + return {k: {"corpus": k.split("/", 1)[0], **dict(zip(ROW_AXES, v[:-1])), "sha256": v[-1]} + for k, v in packed.items()} def baseline_document(exe: Path, results: dict) -> dict: @@ -338,7 +466,7 @@ def fmt_row(cond: str, ax: str, c: gate_stats.Comparison, v: gate_stats.Verdict) margin = f"{v.margin * 100:.0f}%" if gated else "-" if gated and v.effective == v.effective and v.effective > v.margin: margin = f"{v.effective * 100:.1f}%*" # floored at the MDE: the set cannot resolve the margin - return (f" {cond:16s} {ax:9s} {c.base:9.5f} -> {c.cur:9.5f} {c.rel * 100:+7.2f}% " + return (f" {cond:16s} {ax:11s} {c.base:9.5f} -> {c.cur:9.5f} {c.rel * 100:+7.2f}% " f"95% CI [{c.p025 * 100:+6.2f}, {c.p975 * 100:+6.2f}] upper {c.p95 * 100:+6.2f}% " f"vs {margin:>3s} MDE {c.mde * 100:5.2f}% " f"changed {c.changed:3d} (better {c.better}, worse {c.worse}) " @@ -422,6 +550,9 @@ def main() -> int: "never a verdict to merge on; cannot write a baseline)") ap.add_argument("--bypass-gate", type=str, default=None, metavar="JUSTIFICATION", help="Bypass a failing gate if the user agreed and gives a strong justification") + ap.add_argument("--rescore", action="store_true", + help="score every icon, also those byte-identical to the baseline's (their " + "verdict is the same either way; this checks the scorer itself)") a = ap.parse_args() if a.sample is not None and a.write_baseline: ap.error("--sample cannot write a baseline: a baseline holds the whole set") @@ -463,17 +594,25 @@ def main() -> int: f"baseline {shown(bfile)}" if base_doc else f"legacy mode ({shown(BASELINE)})"), flush=True) results, failures = {}, [] - for name in names: - rows, fails = score_condition(exe, BY_NAME[name], items, a.workers) - results[name] = rows - if len(rows) < len(items) - 2: - failures.append(f"{name}: only {len(rows)} of {len(items)} icons scored " - f"({'; '.join(fails[:3])})") + with contextlib.ExitStack() as stack: + pool = stack.enter_context(svgeval.scoring_pool(a.workers)) if a.workers > 1 else None + for name in names: + cond_base = (base_doc or {}).get("conditions", {}).get(name) + base_rows = unpack_rows(cond_base["icons"]) if cond_base and not a.rescore else None + rows, fails = score_condition(exe, BY_NAME[name], items, a.workers, base_rows, pool) + results[name] = with_gaps(rows, BY_NAME[name]) + if len(rows) < len(items) - 2: + failures.append(f"{name}: only {len(rows)} of {len(items)} icons scored " + f"({'; '.join(fails[:3])})") doc = baseline_document(exe, results) + human = human_stats.document(results) if a.artifact_dir: write_json(a.artifact_dir / f"{tag}.json", doc) print(f"wrote this run as {a.artifact_dir / (tag + '.json')}") + (a.artifact_dir / f"human-{tag}.json").write_text(json.dumps(human), encoding="utf-8", + newline="\n") + human_stats.print_summary(human) if failures: print("\nregression gate FAILED: icons failed to trace or score\n") for f in failures: @@ -515,7 +654,7 @@ def main() -> int: if cond_base is None: print(f" {name}: not in the baseline, informational only") continue - base_rows = unpack_rows(cond_base["icons"]) + base_rows = with_gaps(unpack_rows(cond_base["icons"]), BY_NAME[name]) missing = sorted(set(base_rows) - set(rows)) if len(missing) > 2 and a.sample is None: gate_fail.append(f"{name}: {len(missing)} baseline icons were not scored") @@ -531,7 +670,11 @@ def main() -> int: if a.report_json: write_json(a.report_json, {"platform": tag, "legacy": legacy, "failures": gate_fail, "summaries": {n: d["summary"] for n, d in doc["conditions"].items()}, - "verdicts": verdict_json(verdicts)}) + "verdicts": verdict_json(verdicts), + "per_icon": {n: {k: {ax: r[ax] for ax in REPORTED_AXES} + for k, r in sorted(rows.items())} + for n, rows in results.items()}, + "human": human}) if os.environ.get("GITHUB_STEP_SUMMARY"): with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as fh: fh.write(markdown_summary(verdicts, legacy) if verdicts else levels_markdown(doc, gate_fail)) diff --git a/bench/data/corpus_raster/lucide/web/app-window-mac.jpg b/bench/data/corpus_raster/lucide/web/app-window-mac.jpg new file mode 100644 index 00000000..7b8f80ff Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/app-window-mac.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/audio-lines-x.jpg b/bench/data/corpus_raster/lucide/web/audio-lines-x.jpg new file mode 100644 index 00000000..93e9144b Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/audio-lines-x.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/badge-russian-ruble.jpg b/bench/data/corpus_raster/lucide/web/badge-russian-ruble.jpg new file mode 100644 index 00000000..d6359308 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/badge-russian-ruble.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/bath.jpg b/bench/data/corpus_raster/lucide/web/bath.jpg new file mode 100644 index 00000000..27715c83 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/bath.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/bell.jpg b/bench/data/corpus_raster/lucide/web/bell.jpg new file mode 100644 index 00000000..e71346fd Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/bell.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/birdhouse.jpg b/bench/data/corpus_raster/lucide/web/birdhouse.jpg new file mode 100644 index 00000000..a90845dd Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/birdhouse.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/book-heart.jpg b/bench/data/corpus_raster/lucide/web/book-heart.jpg new file mode 100644 index 00000000..7fdfca51 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/book-heart.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/bug.jpg b/bench/data/corpus_raster/lucide/web/bug.jpg new file mode 100644 index 00000000..8b896ae6 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/bug.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/cat.jpg b/bench/data/corpus_raster/lucide/web/cat.jpg new file mode 100644 index 00000000..0c05efc4 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/cat.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/chess-king.jpg b/bench/data/corpus_raster/lucide/web/chess-king.jpg new file mode 100644 index 00000000..befdbf9d Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/chess-king.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/circle-arrow-right.jpg b/bench/data/corpus_raster/lucide/web/circle-arrow-right.jpg new file mode 100644 index 00000000..6eb06162 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/circle-arrow-right.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/closed-caption.jpg b/bench/data/corpus_raster/lucide/web/closed-caption.jpg new file mode 100644 index 00000000..97e65718 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/closed-caption.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/cooking-pot.jpg b/bench/data/corpus_raster/lucide/web/cooking-pot.jpg new file mode 100644 index 00000000..9aba2662 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/cooking-pot.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/diff.jpg b/bench/data/corpus_raster/lucide/web/diff.jpg new file mode 100644 index 00000000..639dc6b4 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/diff.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/equal.jpg b/bench/data/corpus_raster/lucide/web/equal.jpg new file mode 100644 index 00000000..909d6b3c Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/equal.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/file-digit.jpg b/bench/data/corpus_raster/lucide/web/file-digit.jpg new file mode 100644 index 00000000..186906d0 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/file-digit.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/focus.jpg b/bench/data/corpus_raster/lucide/web/focus.jpg new file mode 100644 index 00000000..78c1812f Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/focus.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/folder-open.jpg b/bench/data/corpus_raster/lucide/web/folder-open.jpg new file mode 100644 index 00000000..cca32cde Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/folder-open.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/git-compare.jpg b/bench/data/corpus_raster/lucide/web/git-compare.jpg new file mode 100644 index 00000000..e4b8e615 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/git-compare.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/hard-drive-download.jpg b/bench/data/corpus_raster/lucide/web/hard-drive-download.jpg new file mode 100644 index 00000000..b0efe741 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/hard-drive-download.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/ice-cream-cone.jpg b/bench/data/corpus_raster/lucide/web/ice-cream-cone.jpg new file mode 100644 index 00000000..88a8e65f Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/ice-cream-cone.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/iteration-ccw.jpg b/bench/data/corpus_raster/lucide/web/iteration-ccw.jpg new file mode 100644 index 00000000..2a63085c Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/iteration-ccw.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/list-checks.jpg b/bench/data/corpus_raster/lucide/web/list-checks.jpg new file mode 100644 index 00000000..63e5c51e Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/list-checks.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/message-circle-dashed-check.jpg b/bench/data/corpus_raster/lucide/web/message-circle-dashed-check.jpg new file mode 100644 index 00000000..c0a51237 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/message-circle-dashed-check.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/messages-square.jpg b/bench/data/corpus_raster/lucide/web/messages-square.jpg new file mode 100644 index 00000000..543d297f Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/messages-square.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/navigation-2-off.jpg b/bench/data/corpus_raster/lucide/web/navigation-2-off.jpg new file mode 100644 index 00000000..5047c089 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/navigation-2-off.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/omega.jpg b/bench/data/corpus_raster/lucide/web/omega.jpg new file mode 100644 index 00000000..440eeb02 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/omega.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/panel-right.jpg b/bench/data/corpus_raster/lucide/web/panel-right.jpg new file mode 100644 index 00000000..26ccf745 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/panel-right.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/pen-line.jpg b/bench/data/corpus_raster/lucide/web/pen-line.jpg new file mode 100644 index 00000000..4df07c98 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/pen-line.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/phone-forwarded.jpg b/bench/data/corpus_raster/lucide/web/phone-forwarded.jpg new file mode 100644 index 00000000..009a76f9 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/phone-forwarded.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/rectangle-goggles.jpg b/bench/data/corpus_raster/lucide/web/rectangle-goggles.jpg new file mode 100644 index 00000000..f135e9d3 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/rectangle-goggles.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/save-pen.jpg b/bench/data/corpus_raster/lucide/web/save-pen.jpg new file mode 100644 index 00000000..34b2fdbc Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/save-pen.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/shapes.jpg b/bench/data/corpus_raster/lucide/web/shapes.jpg new file mode 100644 index 00000000..41a67489 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/shapes.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/shopping-cart-plus.jpg b/bench/data/corpus_raster/lucide/web/shopping-cart-plus.jpg new file mode 100644 index 00000000..2e3d83cf Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/shopping-cart-plus.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/sparkle.jpg b/bench/data/corpus_raster/lucide/web/sparkle.jpg new file mode 100644 index 00000000..78bbf37b Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/sparkle.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/square-minus.jpg b/bench/data/corpus_raster/lucide/web/square-minus.jpg new file mode 100644 index 00000000..8a5a94d8 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/square-minus.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/swiss-franc.jpg b/bench/data/corpus_raster/lucide/web/swiss-franc.jpg new file mode 100644 index 00000000..4c55caef Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/swiss-franc.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/ticket-minus.jpg b/bench/data/corpus_raster/lucide/web/ticket-minus.jpg new file mode 100644 index 00000000..4450ae04 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/ticket-minus.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/undo.jpg b/bench/data/corpus_raster/lucide/web/undo.jpg new file mode 100644 index 00000000..9b6b9cc3 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/undo.jpg differ diff --git a/bench/data/corpus_raster/lucide/web/vegan.jpg b/bench/data/corpus_raster/lucide/web/vegan.jpg new file mode 100644 index 00000000..a95a4661 Binary files /dev/null and b/bench/data/corpus_raster/lucide/web/vegan.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/12mp.jpg b/bench/data/corpus_raster/material-icons/web/12mp.jpg new file mode 100644 index 00000000..c2076157 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/12mp.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/admin_panel_settings.jpg b/bench/data/corpus_raster/material-icons/web/admin_panel_settings.jpg new file mode 100644 index 00000000..0a6e5663 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/admin_panel_settings.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/arrow_drop_down.jpg b/bench/data/corpus_raster/material-icons/web/arrow_drop_down.jpg new file mode 100644 index 00000000..31f05e71 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/arrow_drop_down.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/bento.jpg b/bench/data/corpus_raster/material-icons/web/bento.jpg new file mode 100644 index 00000000..a1a40324 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/bento.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/border_left.jpg b/bench/data/corpus_raster/material-icons/web/border_left.jpg new file mode 100644 index 00000000..de521815 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/border_left.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/call.jpg b/bench/data/corpus_raster/material-icons/web/call.jpg new file mode 100644 index 00000000..c5c864a0 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/call.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/chair.jpg b/bench/data/corpus_raster/material-icons/web/chair.jpg new file mode 100644 index 00000000..6ef03f6e Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/chair.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/closed_caption.jpg b/bench/data/corpus_raster/material-icons/web/closed_caption.jpg new file mode 100644 index 00000000..a09d3859 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/closed_caption.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/crop_landscape.jpg b/bench/data/corpus_raster/material-icons/web/crop_landscape.jpg new file mode 100644 index 00000000..cfa3fbcf Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/crop_landscape.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/dining.jpg b/bench/data/corpus_raster/material-icons/web/dining.jpg new file mode 100644 index 00000000..57c5addf Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/dining.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/double_arrow.jpg b/bench/data/corpus_raster/material-icons/web/double_arrow.jpg new file mode 100644 index 00000000..bb83019c Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/double_arrow.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/dynamic_feed.jpg b/bench/data/corpus_raster/material-icons/web/dynamic_feed.jpg new file mode 100644 index 00000000..d58e480b Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/dynamic_feed.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/expand_circle_down.jpg b/bench/data/corpus_raster/material-icons/web/expand_circle_down.jpg new file mode 100644 index 00000000..8d4b1f1c Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/expand_circle_down.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/flight.jpg b/bench/data/corpus_raster/material-icons/web/flight.jpg new file mode 100644 index 00000000..3e88176a Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/flight.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/free_breakfast.jpg b/bench/data/corpus_raster/material-icons/web/free_breakfast.jpg new file mode 100644 index 00000000..36528f7f Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/free_breakfast.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/group_remove.jpg b/bench/data/corpus_raster/material-icons/web/group_remove.jpg new file mode 100644 index 00000000..3c22097f Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/group_remove.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/headset.jpg b/bench/data/corpus_raster/material-icons/web/headset.jpg new file mode 100644 index 00000000..6b0d3804 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/headset.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/houseboat.jpg b/bench/data/corpus_raster/material-icons/web/houseboat.jpg new file mode 100644 index 00000000..f8efcecd Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/houseboat.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/javascript.jpg b/bench/data/corpus_raster/material-icons/web/javascript.jpg new file mode 100644 index 00000000..0dd1e509 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/javascript.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/laptop.jpg b/bench/data/corpus_raster/material-icons/web/laptop.jpg new file mode 100644 index 00000000..49fbbc44 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/laptop.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/lyrics.jpg b/bench/data/corpus_raster/material-icons/web/lyrics.jpg new file mode 100644 index 00000000..0f95736d Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/lyrics.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/miscellaneous_services.jpg b/bench/data/corpus_raster/material-icons/web/miscellaneous_services.jpg new file mode 100644 index 00000000..5359d63b Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/miscellaneous_services.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/music_note.jpg b/bench/data/corpus_raster/material-icons/web/music_note.jpg new file mode 100644 index 00000000..1789be24 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/music_note.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/no_food.jpg b/bench/data/corpus_raster/material-icons/web/no_food.jpg new file mode 100644 index 00000000..2a70520c Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/no_food.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/notifications_paused.jpg b/bench/data/corpus_raster/material-icons/web/notifications_paused.jpg new file mode 100644 index 00000000..780e15f8 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/notifications_paused.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/perm_media.jpg b/bench/data/corpus_raster/material-icons/web/perm_media.jpg new file mode 100644 index 00000000..215616be Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/perm_media.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/phone_iphone.jpg b/bench/data/corpus_raster/material-icons/web/phone_iphone.jpg new file mode 100644 index 00000000..7a5d5e08 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/phone_iphone.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/polyline.jpg b/bench/data/corpus_raster/material-icons/web/polyline.jpg new file mode 100644 index 00000000..0a6a692d Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/polyline.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/qr_code.jpg b/bench/data/corpus_raster/material-icons/web/qr_code.jpg new file mode 100644 index 00000000..99b6d254 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/qr_code.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/report.jpg b/bench/data/corpus_raster/material-icons/web/report.jpg new file mode 100644 index 00000000..0c2ca297 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/report.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/rule_folder.jpg b/bench/data/corpus_raster/material-icons/web/rule_folder.jpg new file mode 100644 index 00000000..c9f40b19 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/rule_folder.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/sd_card_alert.jpg b/bench/data/corpus_raster/material-icons/web/sd_card_alert.jpg new file mode 100644 index 00000000..6d68b928 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/sd_card_alert.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/settings_overscan.jpg b/bench/data/corpus_raster/material-icons/web/settings_overscan.jpg new file mode 100644 index 00000000..214bb358 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/settings_overscan.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/sms_failed.jpg b/bench/data/corpus_raster/material-icons/web/sms_failed.jpg new file mode 100644 index 00000000..091a3fd9 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/sms_failed.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/storage.jpg b/bench/data/corpus_raster/material-icons/web/storage.jpg new file mode 100644 index 00000000..f12f2059 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/storage.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/table_rows.jpg b/bench/data/corpus_raster/material-icons/web/table_rows.jpg new file mode 100644 index 00000000..3cb6a484 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/table_rows.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/transfer_within_a_station.jpg b/bench/data/corpus_raster/material-icons/web/transfer_within_a_station.jpg new file mode 100644 index 00000000..6454a8a4 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/transfer_within_a_station.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/two_wheeler.jpg b/bench/data/corpus_raster/material-icons/web/two_wheeler.jpg new file mode 100644 index 00000000..9cbfe58f Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/two_wheeler.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/video_camera_back.jpg b/bench/data/corpus_raster/material-icons/web/video_camera_back.jpg new file mode 100644 index 00000000..b11e05b1 Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/video_camera_back.jpg differ diff --git a/bench/data/corpus_raster/material-icons/web/view_week.jpg b/bench/data/corpus_raster/material-icons/web/view_week.jpg new file mode 100644 index 00000000..0919ac6d Binary files /dev/null and b/bench/data/corpus_raster/material-icons/web/view_week.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u0030.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u0030.jpg new file mode 100644 index 00000000..51596630 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u0030.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f36a.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f36a.jpg new file mode 100644 index 00000000..88e053a7 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f36a.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f39e.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f39e.jpg new file mode 100644 index 00000000..f4adabe9 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f39e.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f3c2_1f3fd.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f3c2_1f3fd.jpg new file mode 100644 index 00000000..a78e5be6 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f3c2_1f3fd.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f3c4_1f3fe.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f3c4_1f3fe.jpg new file mode 100644 index 00000000..59658654 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f3c4_1f3fe.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f3cb_200d_2642.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f3cb_200d_2642.jpg new file mode 100644 index 00000000..c6970799 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f3cb_200d_2642.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f41b.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f41b.jpg new file mode 100644 index 00000000..fc19b00d Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f41b.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f44d_1f3fc.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f44d_1f3fc.jpg new file mode 100644 index 00000000..9d8438ca Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f44d_1f3fc.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f468_1f3fb_200d_2764_200d_1f468_1f3fd.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f468_1f3fb_200d_2764_200d_1f468_1f3fd.jpg new file mode 100644 index 00000000..40ca6b30 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f468_1f3fb_200d_2764_200d_1f468_1f3fd.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f468_1f3ff_200d_1f393.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f468_1f3ff_200d_1f393.jpg new file mode 100644 index 00000000..8634cc00 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f468_1f3ff_200d_1f393.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f469_1f3fb_200d_1f52c.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f469_1f3fb_200d_1f52c.jpg new file mode 100644 index 00000000..4e77426f Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f469_1f3fb_200d_1f52c.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f469_1f3fc_200d_1f91d_200d_1f468_1f3fb.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f469_1f3fc_200d_1f91d_200d_1f468_1f3fb.jpg new file mode 100644 index 00000000..1eb5fc75 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f469_1f3fc_200d_1f91d_200d_1f468_1f3fb.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f469_1f3fe_200d_1faef_200d_1f469_1f3fd.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f469_1f3fe_200d_1faef_200d_1f469_1f3fd.jpg new file mode 100644 index 00000000..acc5e275 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f469_1f3fe_200d_1faef_200d_1f469_1f3fd.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f469_200d_1f469_200d_1f466_200d_1f466.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f469_200d_1f469_200d_1f466_200d_1f466.jpg new file mode 100644 index 00000000..1d284e36 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f469_200d_1f469_200d_1f466_200d_1f466.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f46c_1f3fd.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f46c_1f3fd.jpg new file mode 100644 index 00000000..346865c2 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f46c_1f3fd.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f470_1f3fb_200d_2640.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f470_1f3fb_200d_2640.jpg new file mode 100644 index 00000000..6ae55461 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f470_1f3fb_200d_2640.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f482_1f3ff_200d_2640.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f482_1f3ff_200d_2640.jpg new file mode 100644 index 00000000..0de6ec98 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f482_1f3ff_200d_2640.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f4d8.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f4d8.jpg new file mode 100644 index 00000000..905c9120 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f4d8.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f520.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f520.jpg new file mode 100644 index 00000000..f58bf5b6 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f520.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f56f.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f56f.jpg new file mode 100644 index 00000000..3dc0f7d7 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f56f.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f5a8.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f5a8.jpg new file mode 100644 index 00000000..9c31927b Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f5a8.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f62d.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f62d.jpg new file mode 100644 index 00000000..2a716259 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f62d.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f64b_1f3fe_200d_2640.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f64b_1f3fe_200d_2640.jpg new file mode 100644 index 00000000..6721f036 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f64b_1f3fe_200d_2640.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f6c0_1f3ff.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f6c0_1f3ff.jpg new file mode 100644 index 00000000..dcc71978 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f6c0_1f3ff.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f90d.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f90d.jpg new file mode 100644 index 00000000..fff8e39f Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f90d.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f91c_1f3fe.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f91c_1f3fe.jpg new file mode 100644 index 00000000..946c1bd6 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f91c_1f3fe.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f926_1f3ff.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f926_1f3ff.jpg new file mode 100644 index 00000000..d392dee0 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f926_1f3ff.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f932.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f932.jpg new file mode 100644 index 00000000..8c4f3be5 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f932.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f93c_1f3fe_200d_2640.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f93c_1f3fe_200d_2640.jpg new file mode 100644 index 00000000..2d4b62bc Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f93c_1f3fe_200d_2640.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f987.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f987.jpg new file mode 100644 index 00000000..caca7924 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f987.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9be.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9be.jpg new file mode 100644 index 00000000..26fb412a Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9be.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9ce_1f3fd_200d_2642.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9ce_1f3fd_200d_2642.jpg new file mode 100644 index 00000000..53665713 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9ce_1f3fd_200d_2642.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9cf_1f3fc.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9cf_1f3fc.jpg new file mode 100644 index 00000000..3ea7243e Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9cf_1f3fc.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9d1_1f3fc_200d_1f37c.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9d1_1f3fc_200d_1f37c.jpg new file mode 100644 index 00000000..2ef0a2d9 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9d1_1f3fc_200d_1f37c.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9d1_1f3fd_200d_1f91d_200d_1f9d1_1f3ff.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9d1_1f3fd_200d_1f91d_200d_1f9d1_1f3ff.jpg new file mode 100644 index 00000000..6d238df3 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9d1_1f3fd_200d_1f91d_200d_1f9d1_1f3ff.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9d1_1f3fe_200d_1f9bc_200d_27a1.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9d1_1f3fe_200d_1f9bc_200d_27a1.jpg new file mode 100644 index 00000000..7ba33e17 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9d1_1f3fe_200d_1f9bc_200d_27a1.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9d6_1f3fe_200d_2642.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9d6_1f3fe_200d_2642.jpg new file mode 100644 index 00000000..42a05f11 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9d6_1f3fe_200d_2642.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9dd_1f3fd_200d_2640.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9dd_1f3fd_200d_2640.jpg new file mode 100644 index 00000000..2add9068 Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9dd_1f3fd_200d_2640.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9ed.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9ed.jpg new file mode 100644 index 00000000..05a4921d Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1f9ed.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1faa5.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1faa5.jpg new file mode 100644 index 00000000..8a86d0fa Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1faa5.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u1faf1_1f3fc_200d_1faf2_1f3ff.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u1faf1_1f3fc_200d_1faf2_1f3ff.jpg new file mode 100644 index 00000000..4564127b Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u1faf1_1f3fc_200d_1faf2_1f3ff.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u26bd.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u26bd.jpg new file mode 100644 index 00000000..463bab3c Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u26bd.jpg differ diff --git a/bench/data/corpus_raster/noto-emoji/web/emoji_u2b05.jpg b/bench/data/corpus_raster/noto-emoji/web/emoji_u2b05.jpg new file mode 100644 index 00000000..7e8ac85f Binary files /dev/null and b/bench/data/corpus_raster/noto-emoji/web/emoji_u2b05.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F195.jpg b/bench/data/corpus_raster/openmoji/web/1F195.jpg new file mode 100644 index 00000000..64906df7 Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F195.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F1FF-1F1F2.jpg b/bench/data/corpus_raster/openmoji/web/1F1FF-1F1F2.jpg new file mode 100644 index 00000000..9267f912 Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F1FF-1F1F2.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F361.jpg b/bench/data/corpus_raster/openmoji/web/1F361.jpg new file mode 100644 index 00000000..770b1f80 Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F361.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F38A.jpg b/bench/data/corpus_raster/openmoji/web/1F38A.jpg new file mode 100644 index 00000000..5d9fdb10 Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F38A.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F3A9.jpg b/bench/data/corpus_raster/openmoji/web/1F3A9.jpg new file mode 100644 index 00000000..fc3a5a23 Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F3A9.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F3C3-1F3FF-200D-2642-FE0F.jpg b/bench/data/corpus_raster/openmoji/web/1F3C3-1F3FF-200D-2642-FE0F.jpg new file mode 100644 index 00000000..e83e582a Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F3C3-1F3FF-200D-2642-FE0F.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F3CC-FE0F-200D-2640-FE0F.jpg b/bench/data/corpus_raster/openmoji/web/1F3CC-FE0F-200D-2640-FE0F.jpg new file mode 100644 index 00000000..e1c19e11 Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F3CC-FE0F-200D-2640-FE0F.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F3F4-E0069-E0074-E0062-E0061-E007F.jpg b/bench/data/corpus_raster/openmoji/web/1F3F4-E0069-E0074-E0062-E0061-E007F.jpg new file mode 100644 index 00000000..7fe91f62 Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F3F4-E0069-E0074-E0062-E0061-E007F.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F442-1F3FF.jpg b/bench/data/corpus_raster/openmoji/web/1F442-1F3FF.jpg new file mode 100644 index 00000000..776e05bd Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F442-1F3FF.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F468-1F3FC-200D-1F3ED.jpg b/bench/data/corpus_raster/openmoji/web/1F468-1F3FC-200D-1F3ED.jpg new file mode 100644 index 00000000..494919f7 Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F468-1F3FC-200D-1F3ED.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F468-1F3FF-200D-1F9B0.jpg b/bench/data/corpus_raster/openmoji/web/1F468-1F3FF-200D-1F9B0.jpg new file mode 100644 index 00000000..a6040220 Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F468-1F3FF-200D-1F9B0.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F468-200D-1F9B1.jpg b/bench/data/corpus_raster/openmoji/web/1F468-200D-1F9B1.jpg new file mode 100644 index 00000000..929c019a Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F468-200D-1F9B1.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F469-1F3FC-200D-2764-FE0F-200D-1F48B-200D-1F469-1F3FC.jpg b/bench/data/corpus_raster/openmoji/web/1F469-1F3FC-200D-2764-FE0F-200D-1F48B-200D-1F469-1F3FC.jpg new file mode 100644 index 00000000..e83a332f Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F469-1F3FC-200D-2764-FE0F-200D-1F48B-200D-1F469-1F3FC.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F469-1F3FF-200D-1F9B2.jpg b/bench/data/corpus_raster/openmoji/web/1F469-1F3FF-200D-1F9B2.jpg new file mode 100644 index 00000000..c3b162ba Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F469-1F3FF-200D-1F9B2.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F481-1F3FB-200D-2642-FE0F.jpg b/bench/data/corpus_raster/openmoji/web/1F481-1F3FB-200D-2642-FE0F.jpg new file mode 100644 index 00000000..7ba53278 Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F481-1F3FB-200D-2642-FE0F.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F49B.jpg b/bench/data/corpus_raster/openmoji/web/1F49B.jpg new file mode 100644 index 00000000..6c0d5c1e Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F49B.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F517.jpg b/bench/data/corpus_raster/openmoji/web/1F517.jpg new file mode 100644 index 00000000..4b27554b Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F517.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F646-1F3FC.jpg b/bench/data/corpus_raster/openmoji/web/1F646-1F3FC.jpg new file mode 100644 index 00000000..1eca8f4e Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F646-1F3FC.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F6B4-1F3FD-200D-2640-FE0F.jpg b/bench/data/corpus_raster/openmoji/web/1F6B4-1F3FD-200D-2640-FE0F.jpg new file mode 100644 index 00000000..731ff961 Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F6B4-1F3FD-200D-2640-FE0F.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F6E0.jpg b/bench/data/corpus_raster/openmoji/web/1F6E0.jpg new file mode 100644 index 00000000..6c218ba2 Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F6E0.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F938-1F3FB.jpg b/bench/data/corpus_raster/openmoji/web/1F938-1F3FB.jpg new file mode 100644 index 00000000..bc08b6d2 Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F938-1F3FB.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F93E-1F3FE.jpg b/bench/data/corpus_raster/openmoji/web/1F93E-1F3FE.jpg new file mode 100644 index 00000000..11f10fc7 Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F93E-1F3FE.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F9B3.jpg b/bench/data/corpus_raster/openmoji/web/1F9B3.jpg new file mode 100644 index 00000000..242049ee Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F9B3.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F9D1-1F3FC-200D-1FA70.jpg b/bench/data/corpus_raster/openmoji/web/1F9D1-1F3FC-200D-1FA70.jpg new file mode 100644 index 00000000..a8412a6e Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F9D1-1F3FC-200D-1FA70.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F9D1-1F3FD-200D-1F527.jpg b/bench/data/corpus_raster/openmoji/web/1F9D1-1F3FD-200D-1F527.jpg new file mode 100644 index 00000000..1ec1ba4c Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F9D1-1F3FD-200D-1F527.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F9D1-200D-1F393.jpg b/bench/data/corpus_raster/openmoji/web/1F9D1-200D-1F393.jpg new file mode 100644 index 00000000..d23ccf52 Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F9D1-200D-1F393.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F9D1.jpg b/bench/data/corpus_raster/openmoji/web/1F9D1.jpg new file mode 100644 index 00000000..68dc9bef Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F9D1.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1F9D6-1F3FD-200D-2642-FE0F.jpg b/bench/data/corpus_raster/openmoji/web/1F9D6-1F3FD-200D-2642-FE0F.jpg new file mode 100644 index 00000000..c709118e Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1F9D6-1F3FD-200D-2642-FE0F.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1FA8B.jpg b/bench/data/corpus_raster/openmoji/web/1FA8B.jpg new file mode 100644 index 00000000..fd925d0f Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1FA8B.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/1FAC4-1F3FD.jpg b/bench/data/corpus_raster/openmoji/web/1FAC4-1F3FD.jpg new file mode 100644 index 00000000..58399be0 Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/1FAC4-1F3FD.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/25FC.jpg b/bench/data/corpus_raster/openmoji/web/25FC.jpg new file mode 100644 index 00000000..88db857f Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/25FC.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/2705.jpg b/bench/data/corpus_raster/openmoji/web/2705.jpg new file mode 100644 index 00000000..ba1f32dd Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/2705.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/E056.jpg b/bench/data/corpus_raster/openmoji/web/E056.jpg new file mode 100644 index 00000000..3c280deb Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/E056.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/E1D1.jpg b/bench/data/corpus_raster/openmoji/web/E1D1.jpg new file mode 100644 index 00000000..e39843ee Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/E1D1.jpg differ diff --git a/bench/data/corpus_raster/openmoji/web/E30B.jpg b/bench/data/corpus_raster/openmoji/web/E30B.jpg new file mode 100644 index 00000000..9153f5ae Binary files /dev/null and b/bench/data/corpus_raster/openmoji/web/E30B.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/alchemy.jpg b/bench/data/corpus_raster/simple-icons/web/alchemy.jpg new file mode 100644 index 00000000..9417f80a Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/alchemy.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/appletv.jpg b/bench/data/corpus_raster/simple-icons/web/appletv.jpg new file mode 100644 index 00000000..b7e7d588 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/appletv.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/atlassian.jpg b/bench/data/corpus_raster/simple-icons/web/atlassian.jpg new file mode 100644 index 00000000..5107ec5e Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/atlassian.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/autocad.jpg b/bench/data/corpus_raster/simple-icons/web/autocad.jpg new file mode 100644 index 00000000..c87d85aa Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/autocad.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/bandrautomation.jpg b/bench/data/corpus_raster/simple-icons/web/bandrautomation.jpg new file mode 100644 index 00000000..ebc20eac Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/bandrautomation.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/bim.jpg b/bench/data/corpus_raster/simple-icons/web/bim.jpg new file mode 100644 index 00000000..d48bc9ab Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/bim.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/boosty.jpg b/bench/data/corpus_raster/simple-icons/web/boosty.jpg new file mode 100644 index 00000000..68f5b0f2 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/boosty.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/changedetection.jpg b/bench/data/corpus_raster/simple-icons/web/changedetection.jpg new file mode 100644 index 00000000..4d5aaca2 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/changedetection.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/cocos.jpg b/bench/data/corpus_raster/simple-icons/web/cocos.jpg new file mode 100644 index 00000000..b1eb141a Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/cocos.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/contentstack.jpg b/bench/data/corpus_raster/simple-icons/web/contentstack.jpg new file mode 100644 index 00000000..1722a154 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/contentstack.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/debridlink.jpg b/bench/data/corpus_raster/simple-icons/web/debridlink.jpg new file mode 100644 index 00000000..c84117e8 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/debridlink.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/elixir.jpg b/bench/data/corpus_raster/simple-icons/web/elixir.jpg new file mode 100644 index 00000000..247028c9 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/elixir.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/fampay.jpg b/bench/data/corpus_raster/simple-icons/web/fampay.jpg new file mode 100644 index 00000000..8075d1e2 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/fampay.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/fluxer.jpg b/bench/data/corpus_raster/simple-icons/web/fluxer.jpg new file mode 100644 index 00000000..bafa582b Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/fluxer.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/googlechrome.jpg b/bench/data/corpus_raster/simple-icons/web/googlechrome.jpg new file mode 100644 index 00000000..8057fdd8 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/googlechrome.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/h2database.jpg b/bench/data/corpus_raster/simple-icons/web/h2database.jpg new file mode 100644 index 00000000..29a0c4de Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/h2database.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/hitachi.jpg b/bench/data/corpus_raster/simple-icons/web/hitachi.jpg new file mode 100644 index 00000000..3f809cca Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/hitachi.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/infinityfree.jpg b/bench/data/corpus_raster/simple-icons/web/infinityfree.jpg new file mode 100644 index 00000000..8d05b067 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/infinityfree.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/jdoodle.jpg b/bench/data/corpus_raster/simple-icons/web/jdoodle.jpg new file mode 100644 index 00000000..3b4e5050 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/jdoodle.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/kleinanzeigen.jpg b/bench/data/corpus_raster/simple-icons/web/kleinanzeigen.jpg new file mode 100644 index 00000000..14787ca6 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/kleinanzeigen.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/leetcode.jpg b/bench/data/corpus_raster/simple-icons/web/leetcode.jpg new file mode 100644 index 00000000..75ba8f85 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/leetcode.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/looker.jpg b/bench/data/corpus_raster/simple-icons/web/looker.jpg new file mode 100644 index 00000000..e53ce455 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/looker.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/mamp.jpg b/bench/data/corpus_raster/simple-icons/web/mamp.jpg new file mode 100644 index 00000000..1b41752e Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/mamp.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/microeditor.jpg b/bench/data/corpus_raster/simple-icons/web/microeditor.jpg new file mode 100644 index 00000000..dd4ffcd1 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/microeditor.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/mysql.jpg b/bench/data/corpus_raster/simple-icons/web/mysql.jpg new file mode 100644 index 00000000..f2d8686d Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/mysql.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/notion.jpg b/bench/data/corpus_raster/simple-icons/web/notion.jpg new file mode 100644 index 00000000..98e1038b Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/notion.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/osano.jpg b/bench/data/corpus_raster/simple-icons/web/osano.jpg new file mode 100644 index 00000000..5767a13b Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/osano.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/phpstorm.jpg b/bench/data/corpus_raster/simple-icons/web/phpstorm.jpg new file mode 100644 index 00000000..27acd281 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/phpstorm.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/playerfm.jpg b/bench/data/corpus_raster/simple-icons/web/playerfm.jpg new file mode 100644 index 00000000..2a76dcf8 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/playerfm.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/premierleague.jpg b/bench/data/corpus_raster/simple-icons/web/premierleague.jpg new file mode 100644 index 00000000..a5efa354 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/premierleague.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/pronounsdotpage.jpg b/bench/data/corpus_raster/simple-icons/web/pronounsdotpage.jpg new file mode 100644 index 00000000..993b1d88 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/pronounsdotpage.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/purescript.jpg b/bench/data/corpus_raster/simple-icons/web/purescript.jpg new file mode 100644 index 00000000..cf878b64 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/purescript.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/redsys.jpg b/bench/data/corpus_raster/simple-icons/web/redsys.jpg new file mode 100644 index 00000000..b62ca472 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/redsys.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/sagemath.jpg b/bench/data/corpus_raster/simple-icons/web/sagemath.jpg new file mode 100644 index 00000000..3e3cf506 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/sagemath.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/slackware.jpg b/bench/data/corpus_raster/simple-icons/web/slackware.jpg new file mode 100644 index 00000000..7ea866c8 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/slackware.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/sparkar.jpg b/bench/data/corpus_raster/simple-icons/web/sparkar.jpg new file mode 100644 index 00000000..5f1d32f9 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/sparkar.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/stmicroelectronics.jpg b/bench/data/corpus_raster/simple-icons/web/stmicroelectronics.jpg new file mode 100644 index 00000000..453700a8 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/stmicroelectronics.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/ubiquiti.jpg b/bench/data/corpus_raster/simple-icons/web/ubiquiti.jpg new file mode 100644 index 00000000..43099d0c Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/ubiquiti.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/visa.jpg b/bench/data/corpus_raster/simple-icons/web/visa.jpg new file mode 100644 index 00000000..72878f64 Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/visa.jpg differ diff --git a/bench/data/corpus_raster/simple-icons/web/wxt.jpg b/bench/data/corpus_raster/simple-icons/web/wxt.jpg new file mode 100644 index 00000000..8f3ae0fe Binary files /dev/null and b/bench/data/corpus_raster/simple-icons/web/wxt.jpg differ diff --git a/bench/data/corpus_raster/synthetic/web/gradient_linear.jpg b/bench/data/corpus_raster/synthetic/web/gradient_linear.jpg new file mode 100644 index 00000000..6f6b098f Binary files /dev/null and b/bench/data/corpus_raster/synthetic/web/gradient_linear.jpg differ diff --git a/bench/data/corpus_raster/synthetic/web/mosaic_grid6.jpg b/bench/data/corpus_raster/synthetic/web/mosaic_grid6.jpg new file mode 100644 index 00000000..0ef402b0 Binary files /dev/null and b/bench/data/corpus_raster/synthetic/web/mosaic_grid6.jpg differ diff --git a/bench/data/corpus_raster/synthetic/web/prim_ellipse.jpg b/bench/data/corpus_raster/synthetic/web/prim_ellipse.jpg new file mode 100644 index 00000000..e703e062 Binary files /dev/null and b/bench/data/corpus_raster/synthetic/web/prim_ellipse.jpg differ diff --git a/bench/data/corpus_raster/synthetic/web/prim_star5.jpg b/bench/data/corpus_raster/synthetic/web/prim_star5.jpg new file mode 100644 index 00000000..c1990667 Binary files /dev/null and b/bench/data/corpus_raster/synthetic/web/prim_star5.jpg differ diff --git a/bench/data/corpus_raster/synthetic/web/symmetry_rot3.jpg b/bench/data/corpus_raster/synthetic/web/symmetry_rot3.jpg new file mode 100644 index 00000000..a3c94069 Binary files /dev/null and b/bench/data/corpus_raster/synthetic/web/symmetry_rot3.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f17e.jpg b/bench/data/corpus_raster/twemoji/web/1f17e.jpg new file mode 100644 index 00000000..572066b0 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f17e.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f1f8.jpg b/bench/data/corpus_raster/twemoji/web/1f1f8.jpg new file mode 100644 index 00000000..733bad9c Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f1f8.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f1fa.jpg b/bench/data/corpus_raster/twemoji/web/1f1fa.jpg new file mode 100644 index 00000000..66996fba Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f1fa.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f325.jpg b/bench/data/corpus_raster/twemoji/web/1f325.jpg new file mode 100644 index 00000000..1b47beed Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f325.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f369.jpg b/bench/data/corpus_raster/twemoji/web/1f369.jpg new file mode 100644 index 00000000..ccd50f44 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f369.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f3ca-1f3fe-200d-2640-fe0f.jpg b/bench/data/corpus_raster/twemoji/web/1f3ca-1f3fe-200d-2640-fe0f.jpg new file mode 100644 index 00000000..b9364e9f Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f3ca-1f3fe-200d-2640-fe0f.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f3cc-1f3fb-200d-2640-fe0f.jpg b/bench/data/corpus_raster/twemoji/web/1f3cc-1f3fb-200d-2640-fe0f.jpg new file mode 100644 index 00000000..82a0491e Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f3cc-1f3fb-200d-2640-fe0f.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f42b.jpg b/bench/data/corpus_raster/twemoji/web/1f42b.jpg new file mode 100644 index 00000000..007cd81a Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f42b.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f468-1f3fb-200d-1f91d-200d-1f468-1f3fd.jpg b/bench/data/corpus_raster/twemoji/web/1f468-1f3fb-200d-1f91d-200d-1f468-1f3fd.jpg new file mode 100644 index 00000000..e056f50e Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f468-1f3fb-200d-1f91d-200d-1f468-1f3fd.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f468-1f3fc-200d-1f9b0.jpg b/bench/data/corpus_raster/twemoji/web/1f468-1f3fc-200d-1f9b0.jpg new file mode 100644 index 00000000..99ee3d82 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f468-1f3fc-200d-1f9b0.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f468-1f3fe-200d-2764-fe0f-200d-1f48b-200d-1f468-1f3ff.jpg b/bench/data/corpus_raster/twemoji/web/1f468-1f3fe-200d-2764-fe0f-200d-1f48b-200d-1f468-1f3ff.jpg new file mode 100644 index 00000000..d75a4108 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f468-1f3fe-200d-2764-fe0f-200d-1f48b-200d-1f468-1f3ff.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f469-1f3fb-200d-1f37c.jpg b/bench/data/corpus_raster/twemoji/web/1f469-1f3fb-200d-1f37c.jpg new file mode 100644 index 00000000..a16d38a3 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f469-1f3fb-200d-1f37c.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f469-1f3fc-200d-2764-fe0f-200d-1f468-1f3fc.jpg b/bench/data/corpus_raster/twemoji/web/1f469-1f3fc-200d-2764-fe0f-200d-1f468-1f3fc.jpg new file mode 100644 index 00000000..bdc22a71 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f469-1f3fc-200d-2764-fe0f-200d-1f468-1f3fc.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f469-1f3fe.jpg b/bench/data/corpus_raster/twemoji/web/1f469-1f3fe.jpg new file mode 100644 index 00000000..a948bd97 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f469-1f3fe.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f469-1f3ff-200d-1f91d-200d-1f468-1f3fc.jpg b/bench/data/corpus_raster/twemoji/web/1f469-1f3ff-200d-1f91d-200d-1f468-1f3fc.jpg new file mode 100644 index 00000000..388ac4c1 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f469-1f3ff-200d-1f91d-200d-1f468-1f3fc.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f469-200d-1f467-200d-1f467.jpg b/bench/data/corpus_raster/twemoji/web/1f469-200d-1f467-200d-1f467.jpg new file mode 100644 index 00000000..13536939 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f469-200d-1f467-200d-1f467.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f470-1f3fc-200d-2640-fe0f.jpg b/bench/data/corpus_raster/twemoji/web/1f470-1f3fc-200d-2640-fe0f.jpg new file mode 100644 index 00000000..bf893c7f Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f470-1f3fc-200d-2640-fe0f.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f481-1f3fc-200d-2640-fe0f.jpg b/bench/data/corpus_raster/twemoji/web/1f481-1f3fc-200d-2640-fe0f.jpg new file mode 100644 index 00000000..0b5a45e6 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f481-1f3fc-200d-2640-fe0f.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f486-1f3ff.jpg b/bench/data/corpus_raster/twemoji/web/1f486-1f3ff.jpg new file mode 100644 index 00000000..aad87f43 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f486-1f3ff.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f4e6.jpg b/bench/data/corpus_raster/twemoji/web/1f4e6.jpg new file mode 100644 index 00000000..c5a15b57 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f4e6.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f53a.jpg b/bench/data/corpus_raster/twemoji/web/1f53a.jpg new file mode 100644 index 00000000..5e1207e9 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f53a.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f57a-1f3fb.jpg b/bench/data/corpus_raster/twemoji/web/1f57a-1f3fb.jpg new file mode 100644 index 00000000..15167f8d Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f57a-1f3fb.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f635.jpg b/bench/data/corpus_raster/twemoji/web/1f635.jpg new file mode 100644 index 00000000..a9bd7ae1 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f635.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f646-1f3fb-200d-2640-fe0f.jpg b/bench/data/corpus_raster/twemoji/web/1f646-1f3fb-200d-2640-fe0f.jpg new file mode 100644 index 00000000..3df7214a Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f646-1f3fb-200d-2640-fe0f.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f648.jpg b/bench/data/corpus_raster/twemoji/web/1f648.jpg new file mode 100644 index 00000000..bf6ce6d9 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f648.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f64d-1f3fd.jpg b/bench/data/corpus_raster/twemoji/web/1f64d-1f3fd.jpg new file mode 100644 index 00000000..bad53ae8 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f64d-1f3fd.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f6a3-1f3ff-200d-2642-fe0f.jpg b/bench/data/corpus_raster/twemoji/web/1f6a3-1f3ff-200d-2642-fe0f.jpg new file mode 100644 index 00000000..5ac3a556 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f6a3-1f3ff-200d-2642-fe0f.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f6d6.jpg b/bench/data/corpus_raster/twemoji/web/1f6d6.jpg new file mode 100644 index 00000000..e8916faf Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f6d6.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f7eb.jpg b/bench/data/corpus_raster/twemoji/web/1f7eb.jpg new file mode 100644 index 00000000..a5dca4f5 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f7eb.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f91c-1f3fe.jpg b/bench/data/corpus_raster/twemoji/web/1f91c-1f3fe.jpg new file mode 100644 index 00000000..91e36fea Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f91c-1f3fe.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f938-1f3fe.jpg b/bench/data/corpus_raster/twemoji/web/1f938-1f3fe.jpg new file mode 100644 index 00000000..56ad206c Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f938-1f3fe.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f977-1f3fb.jpg b/bench/data/corpus_raster/twemoji/web/1f977-1f3fb.jpg new file mode 100644 index 00000000..a76feb5b Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f977-1f3fb.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f9a8.jpg b/bench/data/corpus_raster/twemoji/web/1f9a8.jpg new file mode 100644 index 00000000..0c43160f Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f9a8.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f9c9.jpg b/bench/data/corpus_raster/twemoji/web/1f9c9.jpg new file mode 100644 index 00000000..56fe7d3e Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f9c9.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f9d1-1f3fd-200d-1f9af-200d-27a1-fe0f.jpg b/bench/data/corpus_raster/twemoji/web/1f9d1-1f3fd-200d-1f9af-200d-27a1-fe0f.jpg new file mode 100644 index 00000000..155f8fa6 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f9d1-1f3fd-200d-1f9af-200d-27a1-fe0f.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f9d1-1f3ff-200d-2764-fe0f-200d-1f9d1-1f3fb.jpg b/bench/data/corpus_raster/twemoji/web/1f9d1-1f3ff-200d-2764-fe0f-200d-1f9d1-1f3fb.jpg new file mode 100644 index 00000000..8f311c7a Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f9d1-1f3ff-200d-2764-fe0f-200d-1f9d1-1f3fb.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f9d4-1f3fd.jpg b/bench/data/corpus_raster/twemoji/web/1f9d4-1f3fd.jpg new file mode 100644 index 00000000..053cbc4b Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f9d4-1f3fd.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f9d8-1f3fe.jpg b/bench/data/corpus_raster/twemoji/web/1f9d8-1f3fe.jpg new file mode 100644 index 00000000..3e5963aa Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f9d8-1f3fe.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1f9e9.jpg b/bench/data/corpus_raster/twemoji/web/1f9e9.jpg new file mode 100644 index 00000000..69abfd6c Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1f9e9.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1faa3.jpg b/bench/data/corpus_raster/twemoji/web/1faa3.jpg new file mode 100644 index 00000000..1c07dd1b Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1faa3.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/1fae5.jpg b/bench/data/corpus_raster/twemoji/web/1fae5.jpg new file mode 100644 index 00000000..98ad54a8 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/1fae5.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/2196.jpg b/bench/data/corpus_raster/twemoji/web/2196.jpg new file mode 100644 index 00000000..bf26ee00 Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/2196.jpg differ diff --git a/bench/data/corpus_raster/twemoji/web/271d.jpg b/bench/data/corpus_raster/twemoji/web/271d.jpg new file mode 100644 index 00000000..19b09a0b Binary files /dev/null and b/bench/data/corpus_raster/twemoji/web/271d.jpg differ diff --git a/bench/gate/baselines/linux-x86_64.json b/bench/gate/baselines/linux-x86_64.json index 95647f77..5a04f4d2 100644 --- a/bench/gate/baselines/linux-x86_64.json +++ b/bench/gate/baselines/linux-x86_64.json @@ -1,790 +1,1065 @@ { "_note": "Per-icon regression-gate baseline written by bench/ci_gate.py. Recording a new one is a decision: say why in the commit that does it.", - "format": 1, - "scorer_version": 3, + "format": 2, + "scorer_version": 4, "platform": "linux-x86_64", "_provenance": { - "executable_sha256": "a41045a4dcd40c1a45399ddc0ddf23fafe5bcb4c006034b64ba95ccc09712bf2", - "platform": "Linux x86_64 tracer (WSL2 Debian 12, glibc 2.36), scored on Windows by the same bench code", - "rustc": "rustc 1.98.0 (WSL toolchain 1.98.0-x86_64-unknown-linux-gnu)", - "source_revision": "a07b394 (engine, v0.2.4) / scorer version 3 (2026-10-04)" + "executable_sha256": "c2ad1ea48a908ef10c19a5aa7bb9db288ee00a7e77e4fdb8158078c82c94f964", + "platform": "Linux-6.18.44-fc-v114-x86_64-with-glibc2.39", + "rustc": "rustc 1.98.0 (88d9e12ae 2026-08-18)", + "source_revision": "6d8f0c82d2ec727981551b936e84627ea36843e0" }, "conditions": { "quality-128ss": { "tier": "128ss", "args": [], "summary": { - "de00": 0.12909185231054715, - "turning": 0.08325589546949906, - "ratio": 1.516011933603636, - "self_res": 0.0029819390475768898, + "de00": 0.09185489535094685, + "turning_gap": 1.7869223814438, + "ratio_gap": 0.3837073863004163, + "geom": 0.05640738068638488, + "turning": 0.07559643259974495, + "ratio": 0.9059377301932775, + "self_res": 0.0027178910116291053, + "geom_far": 0.0018913535377533379, "n": 246 }, "icons": { - "lucide/app-window-mac": [0.0104526253, 0.0519146883, 1.25, 0.00234183506, "0f4c6fc0cb6e8007"], - "lucide/audio-lines-x": [0.0440754816, 0.0608834356, 6.4375, 0.00331720058, "ae6fef35384dd1e8"], - "lucide/badge-russian-ruble": [0.0723472387, 0.0853107833, 4.26760563, 0.00254408899, "075cf90c9eeba610"], - "lucide/bath": [0.0870155394, 0.0674870226, 4.2972973, 0.00249693613, "79b9bda0bedd4394"], - "lucide/bell": [0.068626076, 0.0427417191, 2.97619048, 0.00192344515, "65160d7a7b911ed6"], - "lucide/birdhouse": [0.0357833058, 0.0554766802, 5.04545455, 0.0022109088, "60de4ab772ef5ef8"], - "lucide/book-heart": [0.0765323415, 0.0350086866, 2.50819672, 0.00321906595, "0ccd741d2b5005e2"], - "lucide/bug": [0.135424271, 0.0901779065, 4.33783784, 0.00362572749, "d21006c9242bd9dc"], - "lucide/cat": [0.0749639869, 0.058441091, 2.33802817, 0.00232579838, "57a6b7d9f1905700"], - "lucide/chess-king": [0.103964858, 0.0595619355, 2.2, 0.00313888234, "e188ec94e2db6f3c"], - "lucide/circle-arrow-right": [0.0698551014, 0.0376984541, 6.55555556, 0.00399744371, "b5c36b0ee500787c"], - "lucide/closed-caption": [0.0224286169, 0.0518133391, 5.85, 0.00275711343, "bd9e097fc9590fc0"], - "lucide/cooking-pot": [0.112067021, 0.044096967, 3.45454545, 0.00262810173, "bdbc63dfdaeb90f7"], - "lucide/diff": [0.0452156663, 0.0502779705, 12.1666667, 0.00227218308, "643b6f687b14b3f5"], - "lucide/equal": [0.0663237572, 0.0337743906, 1.5, 0.00201439927, "33fc32e59ba9169f"], - "lucide/file-digit": [0.0732740164, 0.0611671871, 3.69491525, 0.00284375926, "aff19216563b0b82"], - "lucide/focus": [0.0434878096, 0.0812043394, 4.31914894, 0.00224657264, "ea7ffec128b99550"], - "lucide/folder-open": [0.0643098056, 0.0340825916, 1.98648649, 0.00295745232, "18b0eea4f2ba94f5"], - "lucide/git-compare": [0.0786617398, 0.0608286684, 4.96428571, 0.00290958188, "4128713ba5ba435e"], - "lucide/hard-drive-download": [0.0558277927, 0.0601914986, 4.25, 0.00281551573, "6b7c19736b9d1add"], - "lucide/ice-cream-cone": [0.0778992996, 0.0516341759, 3.32352941, 0.00176236022, "c9bc55fac9934d38"], - "lucide/iteration-ccw": [0.0311525203, 0.0411321405, 7.23076923, 0.00209386484, "5c73cc7c5c96eb26"], - "lucide/list-checks": [0.0577818789, 0.062259651, 6.71428571, 0.00196844363, "01d8b5deecaf417d"], - "lucide/message-circle-dashed-check": [0.159539402, 0.0979771003, 4.453125, 0.00286434405, "ddeee4624d562ef3"], - "lucide/messages-square": [0.122845039, 0.0418732906, 1.82278481, 0.00366163068, "ac7c58520349ef13"], - "lucide/navigation-2-off": [0.290253937, 0.0515470523, 6.75, 0.00376838259, "2ab3ded514c969aa"], - "lucide/omega": [0.0325918458, 0.0445400839, 2.48837209, 0.00183368765, "08e606668590cbe5"], - "lucide/panel-right": [0.07815364, 0.0211132023, 10.0, 0.00523729483, "943e6cfd39e6177f"], - "lucide/pen-line": [0.023203671, 0.0254974714, 1.75, 0.00262092054, "403d730848f41891"], - "lucide/phone-forwarded": [0.0919665396, 0.042630276, 2.25, 0.0032260071, "63e990ec71d2962b"], - "lucide/rectangle-goggles": [0.0801937804, 0.0298664676, 1.78688525, 0.00295697362, "b7612d154e2bb642"], - "lucide/save-pen": [0.0671738461, 0.046741959, 2.32978723, 0.00355080981, "84935d3fa06f3ba3"], - "lucide/shapes": [0.0291597042, 0.0460927924, 1.23529412, 0.00257041771, "ebf8996b402eba75"], - "lucide/shopping-cart-plus": [0.115655184, 0.0773717317, 5.0, 0.00275136903, "1b746871d008dbb8"], - "lucide/sparkle": [0.17419374, 0.0454288225, 1.91428571, 0.0027697992, "0250b9d73f5ff9c5"], - "lucide/square-minus": [0.00829916727, 0.0253832394, 1.5, 0.00433876133, "84c75c8c35fcb8ac"], - "lucide/swiss-franc": [0.0727339908, 0.0617449037, 11.625, 0.00176618982, "dd5603d105883795"], - "lucide/ticket-minus": [0.0585091002, 0.0494749307, 3.03703704, 0.00287679024, "186f23a94819b6d6"], - "lucide/undo": [0.0504795052, 0.04939309, 3.55, 0.00134564564, "923705746b09e899"], - "lucide/vegan": [0.0917249992, 0.0410507618, 5.67857143, 0.00330906291, "4547167011104f25"], - "material-icons/12mp": [0.0315960459, 0.0727396969, 0.83125, 0.00427365722, "9afd3a5113cfd79f"], - "material-icons/admin_panel_settings": [0.0371877551, 0.0480132646, 0.819672131, 0.00165824161, "fabccc5800954093"], - "material-icons/arrow_drop_down": [2.07082394e-05, 0.0488391708, 1.0, 0.000646493922, "2d382a3246d48c43"], - "material-icons/bento": [0.00321407081, 0.0386777212, 0.7125, 0.00388877676, "c6c112bf242d83af"], - "material-icons/border_left": [0.00369462138, 0.119143076, 0.75, 0.00309196883, "7ff2780c18249e6d"], - "material-icons/call": [0.0587593354, 0.0599566918, 1.00917431, 0.0012690525, "646a55eccca9e16d"], - "material-icons/chair": [0.0526561067, 0.051826289, 1.07926829, 0.00339905987, "ad565ab1e2931f48"], - "material-icons/closed_caption": [0.0387631692, 0.070041932, 0.789855072, 0.00257376861, "d5102452b70adc40"], - "material-icons/crop_landscape": [0.00215818407, 0.0214443208, 0.15, 0.00250315922, "1a85ddd8236805af"], - "material-icons/dining": [0.0713238493, 0.0517913614, 0.659722222, 0.00601854501, "dedd8f7b04b9af6e"], - "material-icons/double_arrow": [0.0035800084, 0.0378446499, 1.2, 0.00104573555, "1fdbb9daf48b2260"], - "material-icons/dynamic_feed": [0.00535773672, 0.040751116, 1.05263158, 0.00292705442, "172f7827ae3a1acb"], - "material-icons/expand_circle_down": [0.013664525, 0.0334979818, 0.25, 0.00313098379, "487648a4f352624f"], - "material-icons/flight": [0.0026619127, 0.0522458148, 1.04545455, 0.00122213922, "03cbdf852fb687f4"], - "material-icons/free_breakfast": [0.00827558525, 0.0368489242, 1.04225352, 0.00242417236, "1020fcbc86efc280"], - "material-icons/group_remove": [0.0919351354, 0.0543869466, 0.753731343, 0.00264940434, "a6b37007df1eee98"], - "material-icons/headset": [0.0259157177, 0.044598805, 1.06976744, 0.001838714, "9d2dc31efdf2bf08"], - "material-icons/houseboat": [0.0511492305, 0.0902408108, 1.01315789, 0.00199333648, "e25e2161ee3fb06d"], - "material-icons/javascript": [0.0248463787, 0.123304441, 1.08333333, 0.000747022394, "6c59f8883e999fde"], - "material-icons/laptop": [0.0161851067, 0.0324939047, 1.125, 0.0032394107, "682740b2ce29189a"], - "material-icons/lyrics": [0.0260389335, 0.056120224, 1.02803738, 0.0037308035, "ee0537c95b33635e"], - "material-icons/miscellaneous_services": [0.0791715086, 0.115897672, 0.376436782, 0.00186600024, "0deb6cd2e4ac1319"], - "material-icons/music_note": [0.00796211977, 0.0523246718, 0.886792453, 0.000953105919, "4dad313ff9d360c3"], - "material-icons/no_food": [0.109938636, 0.0431185857, 1.01219512, 0.00460970961, "7bdcba2e6e6ee139"], - "material-icons/notifications_paused": [0.0417543948, 0.0591454902, 1.15217391, 0.00256060413, "9ab55b25e3088083"], - "material-icons/perm_media": [0.0352836214, 0.0290176509, 1.1375, 0.00414775731, "424bfbbbe700df9a"], - "material-icons/phone_iphone": [0.00336143794, 0.0286828852, 0.823529412, 0.00249597873, "6d379d6f165782d4"], - "material-icons/polyline": [0.000794225838, 0.0707731879, 0.896551724, 0.00199764455, "8071a1f899080bb3"], - "material-icons/qr_code": [0.00294015603, 0.0952942681, 0.8125, 0.00348929572, "ef0b155be6c8da43"], - "material-icons/report": [0.00145599002, 0.0359720361, 1.0, 0.00187437795, "38d440abd3a8b872"], - "material-icons/rule_folder": [0.0163123198, 0.0483287617, 1.04761905, 0.00327148405, "d613970bbe5e10ed"], - "material-icons/sd_card_alert": [0.00351021672, 0.0333858448, 1.06, 0.00309723499, "05a76bad1f6e93ee"], - "material-icons/settings_overscan": [0.00546546467, 0.0523396987, 0.46875, 0.00294979289, "b181fc13dbf67d20"], - "material-icons/sms_failed": [0.044901263, 0.0347322086, 1.14, 0.00426097214, "399ae94b57d2a7ff"], - "material-icons/storage": [0.0, 0.0420617573, 0.75, 0.00498621305, "ea5a2eb8e54e26ee"], - "material-icons/table_rows": [0.000998579431, 0.0270960272, 0.964285714, 0.00339235761, "77a5999afe3d80db"], - "material-icons/transfer_within_a_station": [0.0124427844, 0.0757382183, 0.777777778, 0.00256826356, "bdee4356946f895a"], - "material-icons/two_wheeler": [0.0463781953, 0.0748232816, 0.913043478, 0.00199836283, "938379eb3a381e98"], - "material-icons/video_camera_back": [0.00419805292, 0.0387199499, 1.03448276, 0.00296463328, "68b25c739a2d6b95"], - "material-icons/view_week": [0.00171319942, 0.0284106674, 0.964285714, 0.00413818331, "cf6800ab20902a4d"], - "noto-emoji/emoji_u0030": [0.0375472009, 0.0325960004, 0.453703704, 0.000733857334, "11980b46108fad3a"], - "noto-emoji/emoji_u1f36a": [0.314500332, 0.124644645, 0.857512953, 0.00461726822, "04036a12d072777c"], - "noto-emoji/emoji_u1f39e": [0.435896188, 0.100593665, 1.18313953, 0.00453878567, "aa786c20ac44e802"], - "noto-emoji/emoji_u1f3c2_1f3fd": [0.299403846, 0.13448412, 0.657228018, 0.00331489276, "5fa3dbffbbc03937"], - "noto-emoji/emoji_u1f3c4_1f3fe": [0.445831478, 0.197196467, 0.578125, 0.00741189206, "dbd13ebc87b515f1"], - "noto-emoji/emoji_u1f3cb_200d_2642": [0.847437203, 0.230420845, 0.352073733, 0.0088492455, "e6cce3980eae6adf"], - "noto-emoji/emoji_u1f41b": [0.182896793, 0.169950162, 1.37172775, 0.00251000095, "934de31f4a105053"], - "noto-emoji/emoji_u1f44d_1f3fc": [0.143563807, 0.141906465, 1.12465374, 0.00269686454, "1312c890836acf9d"], - "noto-emoji/emoji_u1f468_1f3fb_200d_2764_200d_1f468_1f3fd": [0.338596433, 0.13799015, 0.622282609, 0.00445715291, "253e77bbfae5b0de"], - "noto-emoji/emoji_u1f468_1f3ff_200d_1f393": [0.569419801, 0.123581774, 0.615479115, 0.00714683719, "eb4aa7b219b7cf3e"], - "noto-emoji/emoji_u1f469_1f3fb_200d_1f52c": [0.62062484, 0.128138041, 0.883548983, 0.00652011158, "4277665634ddba46"], - "noto-emoji/emoji_u1f469_1f3fc_200d_1f91d_200d_1f468_1f3fb": [0.411134392, 0.197585951, 0.403458213, 0.00455957837, "9efb497fac66bf57"], - "noto-emoji/emoji_u1f469_1f3fe_200d_1faef_200d_1f469_1f3fd": [0.459942669, 0.238725135, 0.443026436, 0.00602431176, "b3c68504375cf5b8"], - "noto-emoji/emoji_u1f469_200d_1f469_200d_1f466_200d_1f466": [0.179143816, 0.0665361364, 0.65397351, 0.00350721949, "175c0b7c1e84b4f0"], - "noto-emoji/emoji_u1f46c_1f3fd": [0.346961409, 0.193298095, 0.280694981, 0.00386361219, "be5203a6f89d67ed"], - "noto-emoji/emoji_u1f470_1f3fb_200d_2640": [0.240853965, 0.117717913, 1.01027397, 0.00404880336, "e3bc78a80601e50e"], - "noto-emoji/emoji_u1f482_1f3ff_200d_2640": [0.197240219, 0.126952689, 0.658266129, 0.00451316824, "8a9ebfffd25b85c5"], - "noto-emoji/emoji_u1f4d8": [0.167055011, 0.0389706068, 1.25238095, 0.003401316, "877454dbff96498e"], - "noto-emoji/emoji_u1f520": [0.0384304188, 0.0595452139, 0.668949772, 0.00131360756, "81f7077616cf54e9"], - "noto-emoji/emoji_u1f56f": [0.201217592, 0.14309068, 0.726804124, 0.00159998715, "a8997fbc93126e18"], - "noto-emoji/emoji_u1f5a8": [0.471150577, 0.0847219489, 1.30930233, 0.00516618835, "9f279547082a3774"], - "noto-emoji/emoji_u1f62d": [0.297079831, 0.0959966624, 1.18318318, 0.00389457215, "cbb53ff1709fee53"], - "noto-emoji/emoji_u1f64b_1f3fe_200d_2640": [0.292398065, 0.108740051, 0.768170426, 0.00408091722, "a2b0920f7cf9ab0e"], - "noto-emoji/emoji_u1f6c0_1f3ff": [0.608160436, 0.305171821, 1.02012651, 0.00535689155, "cc62c0f725093015"], - "noto-emoji/emoji_u1f90d": [0.0316668898, 0.0461559425, 0.903409091, 0.000704971317, "cfee5f0545ed30ac"], - "noto-emoji/emoji_u1f91c_1f3fe": [0.0936565325, 0.0938947883, 1.06888889, 0.00257705827, "484cc26213905f37"], - "noto-emoji/emoji_u1f926_1f3ff": [0.422215015, 0.18252817, 0.769877676, 0.00615284033, "8460ecc178daca56"], - "noto-emoji/emoji_u1f932": [0.302757442, 0.153792122, 0.91087344, 0.00464354875, "199b1d9f5be096c0"], - "noto-emoji/emoji_u1f93c_1f3fe_200d_2640": [0.446999907, 0.233852907, 0.488542621, 0.00637882343, "cb162e1c8aff0d96"], - "noto-emoji/emoji_u1f987": [0.235754609, 0.179901407, 0.805172414, 0.00293975626, "898c2200eca317d2"], - "noto-emoji/emoji_u1f9be": [0.357724011, 0.173429831, 1.12335329, 0.00378938415, "efb2fc8839361b07"], - "noto-emoji/emoji_u1f9ce_1f3fd_200d_2642": [0.160831541, 0.161850891, 0.512254902, 0.00221410091, "ddb782671c7c3746"], - "noto-emoji/emoji_u1f9cf_1f3fc": [0.231661543, 0.163037898, 1.03464203, 0.00288756657, "098eca82efc2c8ab"], - "noto-emoji/emoji_u1f9d1_1f3fc_200d_1f37c": [0.309779048, 0.219728931, 0.778781038, 0.00450914027, "dc99d721ab5ee4f0"], - "noto-emoji/emoji_u1f9d1_1f3fd_200d_1f91d_200d_1f9d1_1f3ff": [0.593365967, 0.217598727, 0.391727494, 0.00647412054, "100db221906da000"], - "noto-emoji/emoji_u1f9d1_1f3fe_200d_1f9bc_200d_27a1": [0.585067809, 0.26373263, 0.686090226, 0.00745083718, "fb0813baf10a872d"], - "noto-emoji/emoji_u1f9d6_1f3fe_200d_2642": [0.396693677, 0.146320342, 1.3004386, 0.00397676043, "35b21da180f9e45a"], - "noto-emoji/emoji_u1f9dd_1f3fd_200d_2640": [0.439255863, 0.142506708, 0.718248175, 0.00512611587, "444dbde70dfb9eb7"], - "noto-emoji/emoji_u1f9ed": [0.242099807, 0.116236445, 1.37552743, 0.00356895593, "fe248e4a53d75d56"], - "noto-emoji/emoji_u1faa5": [0.0952382162, 0.188364017, 0.815972222, 0.0014709048, "4dd46363018c2dfd"], - "noto-emoji/emoji_u1faf1_1f3fc_200d_1faf2_1f3ff": [0.216968879, 0.165950193, 0.78452579, 0.00354032312, "6b0a5abb4e5ad842"], - "noto-emoji/emoji_u26bd": [0.270689815, 0.103325661, 1.66666667, 0.00441248668, "ebcc5bb53f05db71"], - "noto-emoji/emoji_u2b05": [0.0314154029, 0.0354197926, 1.05769231, 0.0006312654, "06c3e54d0c33b950"], - "openmoji/1F195": [0.085822165, 0.0658747998, 4.79411765, 0.00332154497, "9a29d46bb2465a0c"], - "openmoji/1F1FF-1F1F2": [0.0257917643, 0.0470938552, 1.4375, 0.00241858792, "ea004b209c18042c"], - "openmoji/1F361": [0.0900802761, 0.0881164475, 2.16428571, 0.00208708341, "cb2d5ca9605b02b0"], - "openmoji/1F38A": [0.175099894, 0.103732203, 1.33333333, 0.0027909514, "dbbfc0f2254b09d4"], - "openmoji/1F3A9": [0.0834658444, 0.0314813181, 0.858208955, 0.00284877722, "dd7f65b291981e7f"], - "openmoji/1F3C3-1F3FF-200D-2642-FE0F": [0.0730383173, 0.101164568, 1.54404145, 0.00163510826, "5e51c61afe523ecb"], - "openmoji/1F3CC-FE0F-200D-2640-FE0F": [0.17896688, 0.117726997, 1.06640625, 0.00283946074, "dc2db48e9ff99fb6"], - "openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F": [0.0248130839, 0.0277407986, 2.8, 0.00290000741, "cc24a82668ec6ead"], - "openmoji/1F442-1F3FF": [0.130123615, 0.0868347754, 3.42982456, 0.00255780388, "3dfef548062b5491"], - "openmoji/1F468-1F3FC-200D-1F3ED": [0.319662392, 0.166000856, 0.412403101, 0.00471564149, "092311e2a1e0db7b"], - "openmoji/1F468-1F3FF-200D-1F9B0": [0.109848686, 0.0755164314, 0.911538462, 0.00214157905, "8871cce744c58863"], - "openmoji/1F468-200D-1F9B1": [0.192096248, 0.137014302, 0.990825688, 0.00260320143, "9b8b85871654954b"], - "openmoji/1F469-1F3FC-200D-2764-FE0F-200D-1F48B-200D-1F469-1F3FC": [0.199926317, 0.114362183, 1.5452381, 0.00345942262, "011f5da30e71ad72"], - "openmoji/1F469-1F3FF-200D-1F9B2": [0.066363357, 0.0783537924, 1.21052632, 0.00142265356, "f469db939744706d"], - "openmoji/1F481-1F3FB-200D-2642-FE0F": [0.167492837, 0.0854975588, 1.24074074, 0.00309312507, "65e6588bae6a422d"], - "openmoji/1F49B": [0.0275685638, 0.0394095027, 0.806818182, 0.000971216999, "4a0034d8a95f8f7e"], - "openmoji/1F517": [0.0839050487, 0.0997352466, 2.4020979, 0.00261142082, "81cc454aa9527f75"], - "openmoji/1F646-1F3FC": [0.207004339, 0.0857721054, 0.705240175, 0.0032029096, "20a4d3ced30605f2"], - "openmoji/1F6B4-1F3FD-200D-2640-FE0F": [0.117892571, 0.1143524, 1.875, 0.00319410209, "f7e3b057809ec1bf"], - "openmoji/1F6E0": [0.166105941, 0.108348984, 1.63839286, 0.00390614034, "b2c13833da6a9a00"], - "openmoji/1F938-1F3FB": [0.1659116, 0.0898280222, 1.34210526, 0.00235471758, "960c06077a71555f"], - "openmoji/1F93E-1F3FE": [0.14654994, 0.100060621, 1.41777778, 0.00213324348, "fc9067b7b0dfc3a5"], - "openmoji/1F9B3": [0.157704741, 0.0434881627, 2.33333333, 0.00225216057, "fcb2f29cf8b7ebba"], - "openmoji/1F9D1": [0.135158285, 0.0764759064, 1.13302752, 0.00246782578, "f288bdf9bccdec6d"], - "openmoji/1F9D1-1F3FC-200D-1FA70": [0.217131048, 0.133351199, 1.4, 0.0031247884, "ee1df2c5ede47230"], - "openmoji/1F9D1-1F3FD-200D-1F527": [0.302511752, 0.146198318, 1.05263158, 0.00487548066, "343e69df2daeb6aa"], - "openmoji/1F9D1-200D-1F393": [0.210211575, 0.133115007, 0.383264463, 0.00348211452, "6d90eea162cabd88"], - "openmoji/1F9D6-1F3FD-200D-2642-FE0F": [0.181548774, 0.133501423, 1.0536193, 0.00334822549, "b7d5986f51ac39ca"], - "openmoji/1FA8B": [0.274482608, 0.151389415, 0.408653846, 0.00358862523, "c87885eacc360f75"], - "openmoji/1FAC4-1F3FD": [0.161260441, 0.118016015, 0.816720257, 0.00284726149, "0399efdff74bcf09"], - "openmoji/25FC": [0.0526055284, 0.0222503259, 0.5, 0.00159768481, "e58721f2a67ba3e6"], - "openmoji/2705": [0.187077016, 0.0582949715, 1.50657895, 0.00338411494, "3dc2adcbd26fc296"], - "openmoji/E056": [0.235954747, 0.0676996431, 0.96996997, 0.00473275175, "a76afd907c5ff91f"], - "openmoji/E1D1": [0.0650592819, 0.0663739302, 0.5, 0.00461545447, "d88c26dbd816dc3b"], - "openmoji/E30B": [0.250626802, 0.0882935331, 0.987179487, 0.00455154711, "4c5facc892966267"], - "simple-icons/alchemy": [0.081905961, 0.0345891012, 0.290566038, 0.00195767288, "c7e20cd699db6f2f"], - "simple-icons/appletv": [0.0939587876, 0.0959765063, 0.801169591, 0.00212522014, "5e81d63ef5c27544"], - "simple-icons/atlassian": [0.11485289, 0.0236813796, 0.892307692, 0.00182842184, "c1c65dc1e8becaa4"], - "simple-icons/autocad": [0.0403100997, 0.0315408242, 1.0, 0.00356780435, "2e7ae656b7bc2a72"], - "simple-icons/bandrautomation": [0.0556491427, 0.0777543211, 0.85, 0.00369442184, "cde3901a2d9ef12f"], - "simple-icons/bim": [0.0344518796, 0.0684070694, 0.964539007, 0.00273174257, "f782bffd97e4b0cf"], - "simple-icons/boosty": [0.0897984803, 0.041452143, 1.29545455, 0.00184182578, "9edf25ca4705fb4b"], - "simple-icons/changedetection": [0.271048456, 0.0431554747, 0.434042553, 0.00495031057, "d86b1fc425b00d9d"], - "simple-icons/cocos": [0.331742555, 0.106926871, 0.337827715, 0.00693000341, "fc7ac0a1b8b1fc11"], - "simple-icons/contentstack": [0.14124541, 0.0646182228, 0.321078431, 0.00668394798, "a941f2f83721070b"], - "simple-icons/debridlink": [0.0879360735, 0.0463987412, 0.563636364, 0.00219726562, "c5dba13ed84dbf47"], - "simple-icons/elixir": [0.0411087014, 0.0254633848, 0.716981132, 0.000928213121, "bf8876da3239d4d8"], - "simple-icons/fampay": [0.0865786299, 0.0476254943, 0.673796791, 0.00175158924, "3822ca9b94dbd4e6"], - "simple-icons/fluxer": [0.198766485, 0.0490681168, 0.728070175, 0.00338039012, "ce26ea0ef226606a"], - "simple-icons/googlechrome": [0.246952832, 0.0358834173, 1.07692308, 0.00400103396, "84072bbf3bb3deac"], - "simple-icons/h2database": [0.130777463, 0.0418035721, 0.764397906, 0.0045546582, "d2c5b0a7304b378c"], - "simple-icons/hitachi": [0.0242266357, 0.152873562, 0.5, 0.00213623047, "ff224904ec25c6c5"], - "simple-icons/infinityfree": [0.448724955, 0.162194713, 0.668280872, 0.00556856021, "3748e9ad190be89b"], - "simple-icons/jdoodle": [0.167262256, 0.0860456245, 0.507537688, 0.00383635866, "91de4ac5a357e94a"], - "simple-icons/kleinanzeigen": [0.144572183, 0.0407689441, 1.0, 0.00365732308, "a8e2e2b48749eb58"], - "simple-icons/leetcode": [0.0730404556, 0.0388442361, 0.689655172, 0.00230066641, "94e5fc01c5faaa47"], - "simple-icons/looker": [0.209405825, 0.0744842713, 0.994475138, 0.00337536377, "78a331fa44064efc"], - "simple-icons/mamp": [0.123516724, 0.0514654449, 1.54166667, 0.00211636396, "5c72a2f3c5870343"], - "simple-icons/microeditor": [0.137581035, 0.0484884285, 0.330612245, 0.00265347376, "be5aaafd41c4ff4d"], - "simple-icons/mysql": [0.171377957, 0.133038831, 0.402676399, 0.0037102194, "91e87a24f785eeba"], - "simple-icons/notion": [0.503961921, 0.0377866505, 1.05617978, 0.00748314941, "0f72817460f05f62"], - "simple-icons/osano": [0.110011898, 0.0210585803, 2.35714286, 0.00204647286, "daa1b3da468d1476"], - "simple-icons/phpstorm": [0.0409244038, 0.0425186949, 0.756944444, 0.00183847453, "f948514ac02ce75b"], - "simple-icons/playerfm": [0.231594056, 0.04424301, 0.561111111, 0.00377269089, "e6a13925a67d1155"], - "simple-icons/premierleague": [0.256663561, 0.1570299, 0.924170616, 0.00420089392, "580a9ab880b1c339"], - "simple-icons/pronounsdotpage": [0.089050442, 0.0399308721, 0.709302326, 0.0024710861, "d2c8b844715455e5"], - "simple-icons/purescript": [0.204595596, 0.0575101979, 0.962962963, 0.00325616612, "0d4f98f3145d3598"], - "simple-icons/redsys": [0.143877044, 0.0418359832, 0.577464789, 0.00206705742, "4488891170d17f4b"], - "simple-icons/sagemath": [0.595495462, 0.12252705, 0.639321075, 0.00853917748, "964cad6f409f63f6"], - "simple-icons/slackware": [0.0699069202, 0.0405708755, 0.559241706, 0.00324731017, "81c5d6364bf8f194"], - "simple-icons/sparkar": [0.00812732708, 0.0339552273, 1.16666667, 0.00121807039, "a0f32be93cb6bd39"], - "simple-icons/stmicroelectronics": [0.179460928, 0.0414905783, 0.603896104, 0.0030709065, "57e5af57e2de06df"], - "simple-icons/ubiquiti": [0.341800064, 0.0505226371, 0.389380531, 0.00455633411, "9e460a7f93c58501"], - "simple-icons/visa": [0.0894006491, 0.0876267071, 0.816176471, 0.00190501474, "0e81b4df45c479f8"], - "simple-icons/wxt": [0.0370002463, 0.0622080208, 1.12371134, 0.00243614078, "e410239abeef5fdb"], - "synthetic/gradient_linear": [0.0460794717, 0.0136816972, 1.0, 0.000183265031, "21303189b91f8410"], - "synthetic/mosaic_grid6": [0.122991219, 0.0843937901, 2.81081081, 0.00274558947, "96407c90961aae91"], - "synthetic/prim_ellipse": [0.00237076031, 0.0159301953, 1.0, 0.000335414108, "3396036e374fd169"], - "synthetic/prim_star5": [0.00153058907, 0.0271562614, 1.08333333, 0.000262570829, "7df6219ac8ec86b3"], - "synthetic/symmetry_rot3": [0.0367910638, 0.0252206582, 1.52777778, 0.000598383893, "d61b4b303967664b"], - "twemoji/1f17e": [0.0112404013, 0.0198854706, 1.05, 0.000687019725, "9b98f461d0a2c390"], - "twemoji/1f1f8": [0.0175019614, 0.0330647422, 1.07692308, 0.00049668987, "0a9e76cb008da4d4"], - "twemoji/1f1fa": [0.0200282168, 0.0222249493, 1.21590909, 0.000574492675, "72fa6bcf2f0d2b45"], - "twemoji/1f325": [0.0506202467, 0.0741731901, 1.03825137, 0.000682941638, "10226015075d0290"], - "twemoji/1f369": [0.108697362, 0.0865107184, 0.584269663, 0.00217212341, "5fca16a726de981e"], - "twemoji/1f3ca-1f3fe-200d-2640-fe0f": [0.0609732643, 0.0999571117, 0.886792453, 0.0013080287, "47ebcb451bc13ccb"], - "twemoji/1f3cc-1f3fb-200d-2640-fe0f": [0.133421466, 0.131357831, 0.906122449, 0.0018596272, "fd78fbe68882c006"], - "twemoji/1f42b": [0.0713614747, 0.0960057258, 0.871212121, 0.00116101268, "af305d25eb5b81c4"], - "twemoji/1f468-1f3fb-200d-1f91d-200d-1f468-1f3fd": [0.350890815, 0.165207428, 0.734042553, 0.00452607358, "32b4e281f370a7c6"], - "twemoji/1f468-1f3fc-200d-1f9b0": [0.0324516781, 0.0859359781, 0.789256198, 0.000855116406, "cf9fd53440b9479d"], - "twemoji/1f468-1f3fe-200d-2764-fe0f-200d-1f48b-200d-1f468-1f3ff": [0.134964436, 0.108492309, 0.706521739, 0.00236369972, "46473a66ff3b7591"], - "twemoji/1f469-1f3fb-200d-1f37c": [0.335346878, 0.135499267, 0.742666667, 0.00322389673, "9eb9bef2e658ed9f"], - "twemoji/1f469-1f3fc-200d-2764-fe0f-200d-1f468-1f3fc": [0.131746188, 0.0828062033, 1.0326087, 0.00211004005, "6634921542998223"], - "twemoji/1f469-1f3fe": [0.0512683243, 0.0507345897, 0.696969697, 0.00280176755, "afceaec3cc412e5e"], - "twemoji/1f469-1f3ff-200d-1f91d-200d-1f468-1f3fc": [0.336962283, 0.172293552, 0.910560345, 0.00511537539, "fa6fd06782932f07"], - "twemoji/1f469-200d-1f467-200d-1f467": [0.0535478517, 0.0575709106, 0.489583333, 0.00110033806, "86a4caf637056f22"], - "twemoji/1f470-1f3fc-200d-2640-fe0f": [0.0721447989, 0.0547535667, 1.12702703, 0.00161117816, "5e23b3c231ed777c"], - "twemoji/1f481-1f3fc-200d-2640-fe0f": [0.0516256653, 0.0825594815, 1.11148649, 0.00161943922, "bc771ec7a5cd9b3a"], - "twemoji/1f486-1f3ff": [0.355748683, 0.207611932, 1.32786885, 0.00406989548, "1c8628a4eec72f8e"], - "twemoji/1f4e6": [0.102349006, 0.051092621, 0.770491803, 0.00149209239, "da8711013bedce86"], - "twemoji/1f53a": [0.0599502251, 0.025162809, 1.125, 0.000747662678, "4b5e057c105d43cf"], - "twemoji/1f57a-1f3fb": [0.231022209, 0.176512173, 0.372047244, 0.00335645978, "91522f6c9f61c0fd"], - "twemoji/1f635": [0.0713626072, 0.0691938805, 0.871212121, 0.00122430944, "a405fd23cc0d7f8a"], - "twemoji/1f646-1f3fb-200d-2640-fe0f": [0.113347031, 0.0643976655, 1.17391304, 0.00200141338, "31c0e247cbbbc911"], - "twemoji/1f648": [0.105328269, 0.100217536, 0.549634274, 0.00170249399, "9dd0625c9c0addab"], - "twemoji/1f64d-1f3fd": [0.045885358, 0.095146369, 1.14453125, 0.00117485982, "1999c7107a017fc3"], - "twemoji/1f6a3-1f3ff-200d-2642-fe0f": [0.201525792, 0.0837194749, 0.839108911, 0.00287274644, "6b0b66f85046fd65"], - "twemoji/1f6d6": [0.17765139, 0.197925986, 1.00982801, 0.00269245612, "392d72362075f8ad"], - "twemoji/1f7eb": [0.134881929, 0.0194792811, 1.125, 0.00155798625, "c1ca689eafb837d5"], - "twemoji/1f91c-1f3fe": [0.0740081593, 0.0771320546, 0.981132075, 0.00104037754, "f412498ad715714e"], - "twemoji/1f938-1f3fe": [0.211613387, 0.221766636, 0.360320285, 0.00266859005, "65ece5a93b458d35"], - "twemoji/1f977-1f3fb": [0.157980517, 0.134512515, 0.951271186, 0.00358343124, "8a84b2d5b33c91ad"], - "twemoji/1f9a8": [0.364753008, 0.0839811352, 1.9579288, 0.00537179643, "e8c7364a14d633f1"], - "twemoji/1f9c9": [0.0883199051, 0.0796496532, 0.972318339, 0.00190292986, "f55563f83c5ca17e"], - "twemoji/1f9d1-1f3fd-200d-1f9af-200d-27a1-fe0f": [0.267484188, 0.163172278, 0.4325, 0.00327142607, "e809a472c6231559"], - "twemoji/1f9d1-1f3ff-200d-2764-fe0f-200d-1f9d1-1f3fb": [0.217197254, 0.0958076233, 1.04009434, 0.00361544988, "17fbd4c61eff184c"], - "twemoji/1f9d4-1f3fd": [0.0738733113, 0.0789395984, 0.77037037, 0.00145867246, "36aa857715ee53af"], - "twemoji/1f9d8-1f3fe": [0.181821436, 0.154890292, 0.686351706, 0.00256129866, "df107ae5258f1eea"], - "twemoji/1f9e9": [0.0378503688, 0.0737708869, 0.65, 0.000763546966, "45f4d5c921e489bb"], - "twemoji/1faa3": [0.299527705, 0.0620763119, 3.35185185, 0.00381479599, "7e78591c043f5b45"], - "twemoji/1fae5": [0.0652595833, 0.145458202, 1.53968254, 0.00122939411, "7b2965e90d3a2486"], - "twemoji/2196": [0.00252896943, 0.0241328317, 1.19047619, 0.000182944976, "0be500c424340b02"], - "twemoji/271d": [0.0259645376, 0.0322104688, 1.11538462, 0.00081284839, "1d1c37b9f6ff6c98"] + "lucide/app-window-mac": [0.0104526235, 0.0519146883, 1.25, 0.00234183506, 0.00374345469, 0.0, "b162ca2268191d74"], + "lucide/audio-lines-x": [0.00394113781, 0.0, 1.0, 0.00340097421, 0.00093360459, 0.0, "14fad89d493171f3"], + "lucide/badge-russian-ruble": [0.0166145042, 0.0781913298, 1.28169014, 0.00404483592, 0.00552405781, 0.0, "422ccefdedee7990"], + "lucide/bath": [0.00431337673, 0.0148128626, 1.0, 0.00261493749, 0.000916973477, 0.0, "f8f19bb6393b4465"], + "lucide/bell": [0.0202930346, 0.0355762336, 1.21428571, 0.00242225803, 0.00993279482, 0.0, "62b34bcda81c6e19"], + "lucide/birdhouse": [0.0101787727, 0.0180115073, 1.0, 0.00233968091, 0.00356017768, 0.0, "dc822bd8b10629fd"], + "lucide/book-heart": [0.0181820728, 0.0409500954, 1.39344262, 0.00353525206, 0.00540897153, 0.0, "46ba7bd8be4b13a1"], + "lucide/bug": [0.0289855264, 0.0410018704, 1.43243243, 0.00413411437, 0.0141443464, 0.0, "90fbfea803237106"], + "lucide/cat": [0.0615253858, 0.0721285582, 1.33802817, 0.00325257541, 0.02618531, 0.0, "9a907739734ee6e4"], + "lucide/chess-king": [0.0324479192, 0.0312050281, 0.9, 0.00362429139, 0.013972704, 0.0, "ad5299cdd9deb264"], + "lucide/circle-arrow-right": [0.0229129773, 0.0132760064, 1.0, 0.00372888916, 0.00513950586, 0.0, "5ddd13d1ee8aec49"], + "lucide/closed-caption": [0.010336333, 0.028885464, 1.0, 0.00292944815, 0.00218749269, 0.0, "734497bde829e932"], + "lucide/cooking-pot": [0.00479034102, 0.014255614, 1.0, 0.00264820736, 0.00170499496, 0.0, "ecfd310bac01cb46"], + "lucide/diff": [0.00167624711, 0.0, 1.0, 0.00232508034, 0.000257898917, 0.0, "529c37289d0e22a5"], + "lucide/equal": [0.00158054975, 0.0, 0.5, 0.0019646138, 0.000356968637, 0.0, "0bc352c2d91f2c48"], + "lucide/file-digit": [0.0201652143, 0.0298298268, 0.830508475, 0.00285764202, 0.00409374834, 0.0, "ee113547dca90972"], + "lucide/focus": [0.0188368708, 0.0465067904, 1.0, 0.00233824481, 0.00624087057, 0.0, "92576fb979ccfbed"], + "lucide/folder-open": [0.0115194684, 0.0265194776, 1.02702703, 0.0027341356, 0.00270796609, 0.0, "192c7b78470c12cc"], + "lucide/git-compare": [0.00768720498, 0.0434382054, 1.0, 0.00243231095, 0.00422388076, 0.0, "f9fb022cb0ef46b3"], + "lucide/hard-drive-download": [0.00857202895, 0.040560778, 1.125, 0.00259363512, 0.00215857034, 0.0, "dab5e86422ba2d48"], + "lucide/ice-cream-cone": [0.0202739127, 0.0420465654, 1.08823529, 0.00172214897, 0.0096279439, 0.0, "e438e864e7c3a1fd"], + "lucide/iteration-ccw": [0.0198606681, 0.0149898496, 1.0, 0.00236146222, 0.0129675143, 0.0, "b8d02fc0ac2dd96e"], + "lucide/list-checks": [0.00496161217, 0.0143763207, 1.0, 0.00198663468, 0.00129767855, 0.0, "241fe224df2e4d5f"], + "lucide/message-circle-dashed-check": [0.0231177807, 0.0260558973, 0.890625, 0.00307593285, 0.0158536133, 0.0, "81080581193da224"], + "lucide/messages-square": [0.00945198815, 0.0328801999, 1.0, 0.00278846896, 0.00198250691, 0.0, "85f7e8bb565c365c"], + "lucide/navigation-2-off": [0.0203255191, 0.0164174916, 0.75, 0.00183009729, 0.00492456446, 0.00116398796, "02816f234217ebf3"], + "lucide/omega": [0.0214897264, 0.0340841105, 0.534883721, 0.00219199993, 0.00641314851, 0.0, "06cc04e12df45c77"], + "lucide/panel-right": [0.00527296169, 0.0134051918, 1.0, 0.00462191692, 0.00170669155, 0.0, "acac2e3ef8ce68b9"], + "lucide/pen-line": [0.0190130938, 0.0181765299, 0.888888889, 0.0029040759, 0.00452773877, 0.0, "eac1c59292a86a01"], + "lucide/phone-forwarded": [0.0330498219, 0.0284903037, 0.954545455, 0.0036326691, 0.00896710611, 0.0, "f33dd4ffbfd8415f"], + "lucide/rectangle-goggles": [0.00619428232, 0.0296782549, 1.03278689, 0.00263671856, 0.00238774221, 0.0, "166fdc719d6d8e89"], + "lucide/save-pen": [0.0148424804, 0.0375569441, 0.904255319, 0.00364296068, 0.00368416515, 0.0, "35ce4c0c592ce963"], + "lucide/shapes": [0.017148653, 0.0461855522, 1.23529412, 0.00242752372, 0.00899278049, 0.0, "634af6f442a94086"], + "lucide/shopping-cart-plus": [0.0215976462, 0.033287739, 0.88372093, 0.00273341755, 0.0054325036, 0.0, "1138f5e5a7b3a78d"], + "lucide/sparkle": [0.0458873473, 0.0989646053, 1.17142857, 0.00182507094, 0.0149669032, 0.0, "54b1703aeb4ad540"], + "lucide/square-minus": [0.00396274263, 0.0151280731, 1.0, 0.00439836038, 0.000843815834, 0.0, "57325b44eec08440"], + "lucide/swiss-franc": [0.00132730103, 0.00701091866, 1.0, 0.00156130316, 0.00126468062, 0.0, "1347c14c9e134bdc"], + "lucide/ticket-minus": [0.0159960818, 0.0439617996, 1.11111111, 0.00273676845, 0.00430138599, 0.0, "ac481a983b1bed6f"], + "lucide/undo": [0.0125415763, 0.0114085179, 0.65, 0.0015354529, 0.0165576969, 0.0, "c62d55fad0b57227"], + "lucide/vegan": [0.056016814, 0.0268111328, 2.35714286, 0.00485002063, 0.0206472188, 0.0, "2d496a71b5527a19"], + "material-icons/12mp": [0.0229678862, 0.0733228232, 0.83125, 0.00426216843, 0.00602099021, 0.0, "5e696577911c282f"], + "material-icons/admin_panel_settings": [0.0356442779, 0.0488998472, 0.336065574, 0.00238515832, 0.0136906365, 0.0, "bef6e24309987c5f"], + "material-icons/arrow_drop_down": [0.000764867815, 0.0488429687, 1.0, 0.000651759736, 0.0272314269, 0.0, "99633cbda397d8fb"], + "material-icons/bento": [0.00967581011, 0.02637016, 0.1625, 0.00385335274, 0.00139021864, 0.0, "6e73e6b55d1bee0f"], + "material-icons/border_left": [8.20357915e-09, 0.119180298, 0.75, 0.00309196883, 0.0, 0.0, "9f5371e60b1cf6a6"], + "material-icons/call": [0.0160124619, 0.0663622464, 0.385321101, 0.00176762603, 0.0161720463, 0.0, "3c71d3d1ddf2012c"], + "material-icons/chair": [0.0418389514, 0.0530114523, 1.12195122, 0.00339810248, 0.0236528663, 0.0, "737e7caf7328ab05"], + "material-icons/closed_caption": [0.0311738215, 0.0708613521, 0.811594203, 0.00246677757, 0.00798695466, 0.0, "be9b1576d40dea29"], + "material-icons/crop_landscape": [0.00215820316, 0.0214443208, 0.15, 0.00250315922, 0.00271686229, 0.0, "1a85ddd8236805af"], + "material-icons/dining": [0.0607894845, 0.0517314054, 0.659722222, 0.0059831203, 0.013156863, 0.0, "cd6d54a5cdbad248"], + "material-icons/double_arrow": [0.00141202379, 0.0378462071, 1.2, 0.00104573555, 0.0, 0.0, "37625ffcb4a83509"], + "material-icons/dynamic_feed": [0.00203717174, 0.0407472496, 1.05263158, 0.00287248194, 0.00146209887, 0.0, "0d974487522aa864"], + "material-icons/expand_circle_down": [0.0136645231, 0.0334979818, 0.25, 0.00313098379, 0.0201647716, 0.0, "997de62be638a57e"], + "material-icons/flight": [0.00340467831, 0.0522530994, 1.04545455, 0.00123338879, 0.00465426361, 0.0, "9ca725554d19059f"], + "material-icons/free_breakfast": [0.0158191957, 0.0282996569, 0.676056338, 0.00258118869, 0.00513473173, 0.0, "7452057539f742c6"], + "material-icons/group_remove": [0.0353167281, 0.0608095113, 0.544776119, 0.00241579558, 0.014250552, 0.0, "9494a9f910d2e85d"], + "material-icons/headset": [0.0132456115, 0.0419748662, 0.558139535, 0.00219774432, 0.0141187301, 0.0, "2df3840b0c876dc1"], + "material-icons/houseboat": [0.0363495387, 0.0959713481, 1.02631579, 0.0018870635, 0.0122685484, 0.0, "142f9686e51206f8"], + "material-icons/javascript": [0.0164804645, 0.123387462, 1.08333333, 0.000653674535, 0.0201014324, 0.0, "db32e8118727fd88"], + "material-icons/laptop": [0.0576876402, 0.0398567613, 1.125, 0.00356732518, 0.0133762184, 0.0, "c7b29239cf84ffcb"], + "material-icons/lyrics": [0.0368371233, 0.0559684294, 1.00934579, 0.00381266256, 0.00726483987, 0.0, "1e54487311699b69"], + "material-icons/miscellaneous_services": [0.0788850188, 0.121006951, 0.379310345, 0.001843501, 0.0337849631, 0.0, "4bfdfd13b35761f4"], + "material-icons/music_note": [0.00797780138, 0.0532664037, 0.849056604, 0.000957892917, 0.00688662994, 0.0, "2d94cb956794577a"], + "material-icons/no_food": [0.117261305, 0.0426653278, 0.93902439, 0.00431841658, 0.00682569258, 0.0, "cb19d27847753c42"], + "material-icons/notifications_paused": [0.0406202041, 0.0590865003, 1.13043478, 0.00255055143, 0.0118919103, 0.0, "c8a29c4b431d071b"], + "material-icons/perm_media": [0.0192751084, 0.0302293421, 0.825, 0.00416834187, 0.00382004046, 0.0, "4d769fe82922c996"], + "material-icons/phone_iphone": [0.00336143747, 0.0286828852, 0.823529412, 0.00249597873, 0.000908224789, 0.0, "350fb077623f5aae"], + "material-icons/polyline": [0.000735684414, 0.0707728567, 0.896551724, 0.00199764478, 0.000226525829, 0.0, "58bf5b355d985719"], + "material-icons/qr_code": [3.52171114e-09, 0.0952969083, 0.8125, 0.0034914501, 0.0, 0.0, "4d8d6a90aed32fe3"], + "material-icons/report": [0.0014559991, 0.045323084, 0.609756098, 0.00187437795, 9.46759717e-05, 0.0, "624b47988698d0ba"], + "material-icons/rule_folder": [0.0154517908, 0.0640024878, 0.904761905, 0.00332868961, 0.00746252062, 0.0, "8f88161343249fc1"], + "material-icons/sd_card_alert": [0.0499214754, 0.0431396924, 0.8, 0.00329709495, 0.00927200317, 0.0, "753bbaf8e008a524"], + "material-icons/settings_overscan": [0.00602387683, 0.052339782, 0.46875, 0.00295362249, 0.0527562762, 0.0, "4189c33ea5f3a1ca"], + "material-icons/sms_failed": [0.00150789379, 0.034555765, 1.06, 0.00389069202, 0.000485139631, 0.0, "5645ca3ab06efd85"], + "material-icons/storage": [0.0, 0.0420617573, 0.75, 0.00498621305, 0.0, 0.0, "696bcaca32f7657a"], + "material-icons/table_rows": [0.00141275069, 0.0124080165, 0.178571429, 0.00333946035, 0.00171568761, 0.0, "64cf4d0b63f53cd6"], + "material-icons/transfer_within_a_station": [0.0103757242, 0.0757275087, 0.777777778, 0.00253786566, 0.00370496557, 0.0, "84a4f99e71142ac3"], + "material-icons/two_wheeler": [0.0227553453, 0.0744213106, 0.775362319, 0.00192775333, 0.0110165199, 0.0, "1b6d7587d2f9f52e"], + "material-icons/video_camera_back": [0.00277493871, 0.0385056251, 1.03448276, 0.00300292973, 0.00111335045, 0.0, "52053c7aca3d33e8"], + "material-icons/view_week": [0.00171320001, 0.0284106674, 0.964285714, 0.00413818331, 0.000374065765, 0.0, "a7cc59527fc6010f"], + "noto-emoji/emoji_u0030": [0.0323986188, 0.0325937166, 0.453703704, 0.000702385034, 0.12956787, 0.0, "8bf832729902acd1"], + "noto-emoji/emoji_u1f36a": [0.322381645, 0.120350523, 0.573402418, 0.00356094539, 0.326217415, 0.0245933741, "b0e709cf4bd59656"], + "noto-emoji/emoji_u1f39e": [0.404308051, 0.103231783, 1.15261628, 0.00427592918, 0.409738211, 0.0274208342, "d9c0b3c6dcad1b9d"], + "noto-emoji/emoji_u1f3c2_1f3fd": [0.238018274, 0.123350542, 0.611028316, 0.0029677283, 0.236307536, 0.034104742, "c4c74d3645c16e64"], + "noto-emoji/emoji_u1f3c4_1f3fe": [0.389090538, 0.187855252, 0.53828125, 0.00656781858, 0.111083483, 0.000596665133, "706538fffc07fb96"], + "noto-emoji/emoji_u1f3cb_200d_2642": [0.412114143, 0.227420079, 0.325345622, 0.00427134894, 0.27133208, 0.00174408414, "0f03e6410b88de6e"], + "noto-emoji/emoji_u1f41b": [0.155251876, 0.173891296, 1.44502618, 0.00234537362, 0.0507902862, 0.0, "cd17d8276caaab87"], + "noto-emoji/emoji_u1f44d_1f3fc": [0.131440476, 0.123446099, 1.02493075, 0.0023979852, 0.0721011849, 0.0, "ac75bd9e29ff9c8c"], + "noto-emoji/emoji_u1f468_1f3fb_200d_2764_200d_1f468_1f3fd": [0.345534682, 0.144680904, 0.615036232, 0.00438308483, 0.283879898, 0.00734725856, "bc8e84b976b5b67e"], + "noto-emoji/emoji_u1f468_1f3ff_200d_1f393": [0.261722744, 0.115786624, 0.626535627, 0.00407936377, 0.248970374, 0.00503279402, "b96531c0d0626d27"], + "noto-emoji/emoji_u1f469_1f3fb_200d_1f52c": [0.571566641, 0.146836278, 0.824399261, 0.00608422607, 0.380180165, 0.0408285803, "4341c730406746da"], + "noto-emoji/emoji_u1f469_1f3fc_200d_1f91d_200d_1f468_1f3fb": [0.338269442, 0.166002645, 0.336215178, 0.00373246963, 0.364862984, 0.00484806068, "89f939318ef6b58b"], + "noto-emoji/emoji_u1f469_1f3fe_200d_1faef_200d_1f469_1f3fd": [0.392222524, 0.203061991, 0.366909754, 0.00455028703, 0.259162473, 0.00226581601, "fd7607a7c678bdeb"], + "noto-emoji/emoji_u1f469_200d_1f469_200d_1f466_200d_1f466": [0.159159601, 0.0691388024, 0.668874172, 0.00324637839, 0.0223887882, 0.0, "eff31e87f590b090"], + "noto-emoji/emoji_u1f46c_1f3fd": [0.28630662, 0.173224089, 0.254826255, 0.00323878671, 0.349757743, 0.0179683902, "a428abae31d95f98"], + "noto-emoji/emoji_u1f470_1f3fb_200d_2640": [0.22442691, 0.102957563, 0.824200913, 0.00368448719, 0.257588602, 0.00802291158, "68418e3f61315e1a"], + "noto-emoji/emoji_u1f482_1f3ff_200d_2640": [0.168598488, 0.118171806, 0.615927419, 0.00316301454, 0.14932887, 0.00613384425, "1062f5a0f3ed2031"], + "noto-emoji/emoji_u1f4d8": [0.152931005, 0.0402215565, 1.0, 0.00343765807, 0.0517107768, 0.0, "6e2d2a78edb6f048"], + "noto-emoji/emoji_u1f520": [0.0232377741, 0.0584114739, 0.716894977, 0.00108163559, 0.0141503, 0.0, "91827c051cf32a96"], + "noto-emoji/emoji_u1f56f": [0.197097257, 0.148715776, 0.632302405, 0.00147044146, 0.233628029, 0.000724919707, "d125caaf70de4917"], + "noto-emoji/emoji_u1f5a8": [0.415106326, 0.0792440848, 1.12325581, 0.00514424639, 0.260196772, 0.00312618215, "4979184373e8bde9"], + "noto-emoji/emoji_u1f62d": [0.155168906, 0.0880206939, 0.936936937, 0.00276070531, 0.20577089, 0.0, "9d066a6ed285384e"], + "noto-emoji/emoji_u1f64b_1f3fe_200d_2640": [0.207708821, 0.103632406, 0.682957393, 0.00278912392, 0.257113979, 0.00258113127, "45bb0a7e3ca8fc45"], + "noto-emoji/emoji_u1f6c0_1f3ff": [0.575903475, 0.280312545, 0.886141461, 0.00498194713, 0.218540033, 0.00038214008, "0d2fcf4941993977"], + "noto-emoji/emoji_u1f90d": [0.0260964334, 0.0517440543, 0.960227273, 0.000621567306, 0.0647540729, 0.0, "9040f1f4bcd82b6c"], + "noto-emoji/emoji_u1f91c_1f3fe": [0.0718779936, 0.0973380573, 1.12222222, 0.00203416916, 0.0544550836, 0.0, "3a2e1c14e001a55e"], + "noto-emoji/emoji_u1f926_1f3ff": [0.371547431, 0.199804417, 0.814984709, 0.00617177272, 0.311405459, 0.0126236031, "007e8e96d9425f29"], + "noto-emoji/emoji_u1f932": [0.184655994, 0.130525324, 0.926024955, 0.00335153821, 0.0720875928, 0.0, "a222d2f604dfbcb3"], + "noto-emoji/emoji_u1f93c_1f3fe_200d_2640": [0.347605824, 0.201966554, 0.353345555, 0.0041126865, 0.270374886, 0.00565547842, "b39da947269bddfe"], + "noto-emoji/emoji_u1f987": [0.16985178, 0.150137499, 0.637931034, 0.00208002119, 0.202880514, 0.0, "391a0f45d7d5cdbd"], + "noto-emoji/emoji_u1f9be": [0.325118303, 0.182678505, 1.11736527, 0.00338490005, 0.23104884, 0.0226392539, "1a1ed8272a93336b"], + "noto-emoji/emoji_u1f9ce_1f3fd_200d_2642": [0.164056361, 0.146248059, 0.383578431, 0.00217683776, 0.197821799, 0.00026869849, "12960116587e499e"], + "noto-emoji/emoji_u1f9cf_1f3fc": [0.224025995, 0.149925395, 0.878752887, 0.00275388989, 0.225390849, 0.0232117086, "85b51c3e81b3438c"], + "noto-emoji/emoji_u1f9d1_1f3fc_200d_1f37c": [0.269740939, 0.194331483, 0.678893905, 0.00403242512, 0.122056088, 0.00273148205, "5752f506723d06d4"], + "noto-emoji/emoji_u1f9d1_1f3fd_200d_1f91d_200d_1f9d1_1f3ff": [0.504417956, 0.208980665, 0.389699919, 0.00565722398, 0.240571712, 0.00325880404, "58930f1aa4d7440f"], + "noto-emoji/emoji_u1f9d1_1f3fe_200d_1f9bc_200d_27a1": [0.495530337, 0.234202366, 0.573308271, 0.00617335923, 0.291199755, 0.0113325892, "664dcdfd40c7a55c"], + "noto-emoji/emoji_u1f9d6_1f3fe_200d_2642": [0.36447826, 0.126416478, 1.01864035, 0.00350521505, 0.2181132, 0.00786209603, "1ea9fb3e8f6ab8af"], + "noto-emoji/emoji_u1f9dd_1f3fd_200d_2640": [0.432541937, 0.147538892, 0.748175182, 0.00486834208, 0.353379604, 0.00462575443, "f85d1d81a445f48f"], + "noto-emoji/emoji_u1f9ed": [0.238005653, 0.130789725, 1.32489451, 0.00332819601, 0.0992100062, 0.000785137751, "6bbefde5f8927456"], + "noto-emoji/emoji_u1faa5": [0.0979301259, 0.174156962, 0.840277778, 0.0015753546, 0.182026444, 0.0, "f99047d59128b42f"], + "noto-emoji/emoji_u1faf1_1f3fc_200d_1faf2_1f3ff": [0.190676033, 0.158329501, 0.760399334, 0.00327761658, 0.0773763552, 0.0, "2991859ed58979ab"], + "noto-emoji/emoji_u26bd": [0.199013561, 0.0951095143, 1.18181818, 0.00353572262, 0.0629763707, 0.0, "713c42a7d9c166b9"], + "noto-emoji/emoji_u2b05": [0.0200123861, 0.0326292703, 1.13461538, 0.00046372725, 0.00768559177, 0.0, "6582e2b1bae8f6f7"], + "openmoji/1F195": [0.0299874805, 0.0458062945, 2.5, 0.0029034738, 0.0119161122, 0.0, "3ef306f9f22644d1"], + "openmoji/1F1FF-1F1F2": [0.0482269675, 0.0461903285, 1.27083333, 0.00261134724, 0.0411535523, 0.00418257519, "49161c1c26848176"], + "openmoji/1F361": [0.0626018271, 0.0819671933, 1.60714286, 0.00186975021, 0.0553679881, 0.0, "ac6c490a704ee4bd"], + "openmoji/1F38A": [0.040983431, 0.0869130412, 0.848958333, 0.00247296854, 0.0194934177, 0.0, "fa3bd4211ee41f0a"], + "openmoji/1F3A9": [0.0222057737, 0.0248822129, 0.78358209, 0.00212756381, 0.0161138127, 0.0, "6d708924b3165d18"], + "openmoji/1F3C3-1F3FF-200D-2642-FE0F": [0.119600125, 0.0969048836, 0.89119171, 0.00317900907, 0.0549316322, 0.00802266106, "6f2b85d0ba44acd8"], + "openmoji/1F3CC-FE0F-200D-2640-FE0F": [0.130726635, 0.109445331, 0.75, 0.00277644279, 0.0319236966, 0.0, "8f5609a767c73059"], + "openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F": [0.025735449, 0.0232250786, 1.0, 0.00287427311, 0.00535511307, 0.0, "6d94023f7c7e5592"], + "openmoji/1F442-1F3FF": [0.109144688, 0.0939242383, 1.97368421, 0.00252789143, 0.0544089262, 0.0, "c9231a1ab7ac48a2"], + "openmoji/1F468-1F3FC-200D-1F3ED": [0.227891684, 0.158481116, 0.412403101, 0.00410524709, 0.0579797342, 9.8941526e-05, "7b02b5fbfc64f9d4"], + "openmoji/1F468-1F3FF-200D-1F9B0": [0.066868566, 0.0664362512, 0.7, 0.00168406765, 0.0430431454, 0.0, "447cff88f0a9947a"], + "openmoji/1F468-200D-1F9B1": [0.124516733, 0.147259027, 0.873853211, 0.00220742426, 0.0339452313, 0.0, "65f8e12c8cd756d0"], + "openmoji/1F469-1F3FC-200D-2764-FE0F-200D-1F48B-200D-1F469-1F3FC": [0.12054839, 0.0952670313, 0.976190476, 0.00374136376, 0.0309793853, 0.0, "408e656142570404"], + "openmoji/1F469-1F3FF-200D-1F9B2": [0.042694997, 0.0653969719, 0.802631579, 0.00126893562, 0.0259877652, 0.0, "ad9eb9d8a182ea0b"], + "openmoji/1F481-1F3FB-200D-2642-FE0F": [0.130440339, 0.08009583, 0.907407407, 0.00282557611, 0.0364221553, 0.0, "658ddd98cde42543"], + "openmoji/1F49B": [0.0173555855, 0.0400441273, 0.909090909, 0.000916165707, 0.023918237, 0.0, "73a2d5161bc151b0"], + "openmoji/1F517": [0.0490041338, 0.0964560006, 1.40559441, 0.00243902742, 0.0351350213, 0.0, "40d580cdaa46a8a3"], + "openmoji/1F646-1F3FC": [0.210805476, 0.0770360104, 0.580786026, 0.00320544373, 0.0464166845, 0.0, "2193afbf022cfdc4"], + "openmoji/1F6B4-1F3FD-200D-2640-FE0F": [0.0724759176, 0.10280366, 0.914772727, 0.00301422295, 0.0239208415, 0.00139591118, "5a97bc5edaa3f3d3"], + "openmoji/1F6E0": [0.106451094, 0.0972370092, 1.14732143, 0.00364402239, 0.0265922072, 0.0, "ca79995e7b560951"], + "openmoji/1F938-1F3FB": [0.180998966, 0.0832376786, 1.34649123, 0.00250065955, 0.0605430628, 0.0, "f6aac3cc5f8d496e"], + "openmoji/1F93E-1F3FE": [0.125732824, 0.0928216962, 1.56888889, 0.00195683609, 0.0492110797, 0.0, "8c731365794c7e31"], + "openmoji/1F9B3": [0.0816244185, 0.0460460759, 1.89393939, 0.00183458265, 0.0642545242, 0.0, "ccebd6ceb120f94c"], + "openmoji/1F9D1": [0.0716957375, 0.0691411474, 0.917431193, 0.00186441711, 0.0346305363, 0.0, "6185c3eecf501022"], + "openmoji/1F9D1-1F3FC-200D-1FA70": [0.191417739, 0.131911372, 1.33461538, 0.00318662077, 0.0636848923, 0.000220362949, "97c0abed6332acf5"], + "openmoji/1F9D1-1F3FD-200D-1F527": [0.170165554, 0.132982699, 0.821862348, 0.00420185039, 0.049316119, 0.0, "f0b8cbddaa17515a"], + "openmoji/1F9D1-200D-1F393": [0.185708284, 0.136300913, 0.341942149, 0.00281362073, 0.0985522487, 0.00519046279, "78aa6054444f6370"], + "openmoji/1F9D6-1F3FD-200D-2642-FE0F": [0.168979689, 0.123576362, 0.809651475, 0.00305370917, 0.0623738355, 0.0, "486413d63b9e9416"], + "openmoji/1FA8B": [0.261271238, 0.148936926, 0.330128205, 0.0031897109, 0.133742026, 0.00384353605, "d6b568b65b316a3c"], + "openmoji/1FAC4-1F3FD": [0.0734125599, 0.123730411, 0.673633441, 0.00223856047, 0.0372348714, 0.0, "89e19597871bc26b"], + "openmoji/25FC": [0.0654804558, 0.0227519746, 0.5, 0.00402131118, 0.134753461, 0.0, "063386391ee1e946"], + "openmoji/2705": [0.0596938208, 0.0662469205, 0.986842105, 0.00287796627, 0.0319875183, 0.0, "2cceb8607cec4513"], + "openmoji/E056": [0.150272027, 0.0651687358, 0.403903904, 0.00557504082, 0.0472542768, 0.0, "bb47241e11f4958c"], + "openmoji/E1D1": [0.0706313774, 0.0634804237, 0.384393064, 0.00481602224, 0.020045688, 0.0, "98f7332e83d9354c"], + "openmoji/E30B": [0.103652857, 0.0651803796, 0.811965812, 0.00381529541, 0.0222941874, 4.7944489e-05, "03c3ea58cdb0ac3d"], + "simple-icons/alchemy": [0.14880985, 0.0379591887, 0.362264151, 0.00261110789, 0.0560069331, 0.0, "7b7dac878044af82"], + "simple-icons/appletv": [0.049968522, 0.0883713893, 0.766081871, 0.00177361013, 0.0275939112, 0.0, "f689e9d70e09849f"], + "simple-icons/atlassian": [0.0674725845, 0.0249460028, 1.04615385, 0.00167571416, 0.0464901562, 0.0, "12113e90cc849b74"], + "simple-icons/autocad": [0.00347757852, 0.0315633863, 1.0, 0.00354482676, 0.00937597806, 0.0, "6c04117340e676fb"], + "simple-icons/bandrautomation": [0.0594469532, 0.077741897, 0.840909091, 0.00371859665, 0.0207400492, 0.0, "8f17b9c7330b0f89"], + "simple-icons/bim": [0.0341497064, 0.0708766982, 0.95035461, 0.00274371053, 0.0147152639, 0.0, "d8a9b2d5bd16751a"], + "simple-icons/boosty": [0.0742314979, 0.0330765108, 1.18181818, 0.00168792123, 0.0288486166, 0.0, "eab84ed5061cddd3"], + "simple-icons/changedetection": [0.101548366, 0.0531193369, 0.325531915, 0.00530790398, 0.0445721072, 0.0, "409d6533b513491a"], + "simple-icons/cocos": [0.371858746, 0.109652318, 0.351310861, 0.0066475668, 0.0314734261, 0.0, "c6ae287462c7891c"], + "simple-icons/contentstack": [0.027839059, 0.0567752984, 0.176470588, 0.00616407255, 0.0218141805, 0.0, "c6119337d931b5f6"], + "simple-icons/debridlink": [0.104719788, 0.040707548, 0.466666667, 0.00242489087, 0.0304524365, 0.00023790966, "c188233284549e40"], + "simple-icons/elixir": [0.0312425625, 0.024148166, 0.622641509, 0.000787951984, 0.0247274743, 0.0, "cee473595a9e7a9b"], + "simple-icons/fampay": [0.0822946504, 0.0470596468, 0.663101604, 0.00173818565, 0.0310688399, 0.000188295999, "9bf14f28aa551c84"], + "simple-icons/fluxer": [0.0779320225, 0.0468567093, 0.561403509, 0.00210176338, 0.0222016365, 0.0, "4787d64378bd14d5"], + "simple-icons/googlechrome": [0.073788628, 0.0338035239, 0.736263736, 0.00270397705, 0.026309225, 0.000134919103, "c8c33aaf293e5aaf"], + "simple-icons/h2database": [0.091899842, 0.0408570262, 0.565445026, 0.00473560998, 0.0389696506, 0.0, "6bddd456496e90e1"], + "simple-icons/hitachi": [0.0232787076, 0.152869701, 0.493197279, 0.00214963406, 0.0315888619, 0.0, "1f62fcd42d30923a"], + "simple-icons/infinityfree": [0.454780757, 0.162573754, 0.636803874, 0.00546085089, 0.104635039, 0.00022862718, "95f5d5494804afb0"], + "simple-icons/jdoodle": [0.0836884826, 0.0548270754, 0.351758794, 0.00297995168, 0.0369119965, 0.0, "60553ef7ae98fa0e"], + "simple-icons/kleinanzeigen": [0.0817222968, 0.0232597404, 0.466666667, 0.00384665118, 0.0279191866, 0.0, "cf76b3ff3d54763e"], + "simple-icons/leetcode": [0.0262413938, 0.0486133954, 0.247126437, 0.00245074113, 0.0152276985, 0.0, "fc992f9a8799a1d8"], + "simple-icons/looker": [0.0786795989, 0.0779093992, 0.806629834, 0.00222814246, 0.0422153233, 0.0, "1b72e8c1288460e2"], + "simple-icons/mamp": [0.0832081065, 0.0506657812, 1.19166667, 0.00184565538, 0.0340259852, 0.0, "5b89096457b396cc"], + "simple-icons/microeditor": [0.0728667825, 0.0455904628, 0.253061224, 0.00197777874, 0.0216286856, 0.0, "ccdaec4bdf13cdb1"], + "simple-icons/mysql": [0.151292592, 0.140374677, 0.409975669, 0.00347254123, 0.0351951331, 0.0, "daff3449a5540734"], + "simple-icons/notion": [0.239718959, 0.0365143802, 1.02808989, 0.00534715876, 0.0530725714, 4.6636706e-05, "e9e4e826d788b8d0"], + "simple-icons/osano": [0.0161840599, 0.018950222, 0.107142857, 0.00280402671, 0.0318288776, 0.0, "5d4880d7cf9e41fc"], + "simple-icons/phpstorm": [0.0411866195, 0.0424617593, 0.756944444, 0.00179108267, 0.0227325327, 0.0, "9186485fcd5c5979"], + "simple-icons/playerfm": [0.0895138234, 0.0435633941, 0.477777778, 0.00264988304, 0.0314322338, 0.000698494084, "4ce838a2f2f343d2"], + "simple-icons/premierleague": [0.219105899, 0.156814047, 0.902843602, 0.00362237659, 0.048846635, 0.0, "a692ded1e69a1641"], + "simple-icons/pronounsdotpage": [0.0746413395, 0.0399718997, 0.639534884, 0.0022427428, 0.0362443851, 0.0, "78a1872a6019fb0e"], + "simple-icons/purescript": [0.0178686678, 0.0582588862, 1.14814815, 0.00181789009, 0.00647372087, 0.0, "cdc617c78bde4d54"], + "simple-icons/redsys": [0.0470610186, 0.0306647132, 0.436619718, 0.00155244721, 0.0318196467, 0.0, "a538f5b699933cd2"], + "simple-icons/sagemath": [0.496083409, 0.117601875, 0.609618105, 0.00777468225, 0.0494228666, 0.000731954883, "a7b8d4bda6a9aaa1"], + "simple-icons/slackware": [0.0619428121, 0.0389486909, 0.582938389, 0.00311446865, 0.0188479203, 0.0, "174588e73d125bc1"], + "simple-icons/sparkar": [0.00400136318, 0.0273215872, 1.0, 0.00121232576, 0.00214808496, 0.0, "68fb87712e65d786"], + "simple-icons/stmicroelectronics": [0.0856985077, 0.0411936328, 0.564935065, 0.00256730616, 0.0292547181, 0.0, "85144d95c25e9833"], + "simple-icons/ubiquiti": [0.0423403606, 0.049988552, 0.287610619, 0.00171089952, 0.0253229505, 0.0, "c78c84daf50565f8"], + "simple-icons/visa": [0.0521511547, 0.0875795206, 0.801470588, 0.00162138103, 0.0212438758, 0.0, "b3f02fbd4b45e408"], + "simple-icons/wxt": [0.0454552472, 0.06419857, 0.56185567, 0.00246725674, 0.031684367, 0.0, "9e3e77c3ebda4c7e"], + "synthetic/gradient_linear": [0.0460796878, 0.0136816972, 1.0, 0.000183265031, 0.0235764057, 0.0, "21303189b91f8410"], + "synthetic/mosaic_grid6": [0.143993407, 0.0795373812, 2.06306306, 0.00185833999, 0.160186221, 0.0185504408, "7f322780f3483def"], + "synthetic/prim_ellipse": [0.00237076078, 0.0159301953, 1.0, 0.000335414108, 0.00471771619, 0.0, "3396036e374fd169"], + "synthetic/prim_star5": [0.00146514783, 0.0271564152, 1.08333333, 0.00026209213, 0.000517161792, 0.0, "ef02cdef55c71a8f"], + "synthetic/symmetry_rot3": [0.0210523754, 0.0250928601, 1.55555556, 0.000449825107, 0.0219940125, 0.0, "e8d035017a414be2"], + "twemoji/1f17e": [0.0100257555, 0.0198305815, 0.675, 0.000721969816, 0.0111457112, 0.0, "8a42dd227e29e3b7"], + "twemoji/1f1f8": [0.014337508, 0.0332170363, 0.798076923, 0.000560323533, 0.0245513978, 0.0, "cd4fc45807dd83ee"], + "twemoji/1f1fa": [0.0116035445, 0.0221346541, 0.875, 0.000584258873, 0.013900544, 0.0, "dbb83100e8b63903"], + "twemoji/1f325": [0.0292543601, 0.0656165243, 0.68852459, 0.000488794001, 0.028618013, 0.0, "54a5e597b57a64d5"], + "twemoji/1f369": [0.0610879324, 0.0599613783, 0.378277154, 0.00188546663, 0.0331014723, 0.0, "022e9428784b53b7"], + "twemoji/1f3ca-1f3fe-200d-2640-fe0f": [0.0760260522, 0.0807392578, 0.849056604, 0.00134745415, 0.0518208692, 0.0, "c4b59152d8ce8fba"], + "twemoji/1f3cc-1f3fb-200d-2640-fe0f": [0.119999908, 0.121650723, 0.808163265, 0.00165834336, 0.0748256136, 0.00291898207, "59e7f0d80491262a"], + "twemoji/1f42b": [0.0642892271, 0.100732203, 0.863636364, 0.00114293071, 0.0400118382, 0.0, "adaf451f5b8c39d4"], + "twemoji/1f468-1f3fb-200d-1f91d-200d-1f468-1f3fd": [0.152145982, 0.142230195, 0.65, 0.00269047893, 0.0630831724, 0.0, "f1445a3d78d227e4"], + "twemoji/1f468-1f3fc-200d-1f9b0": [0.0290364642, 0.0713567772, 0.669421488, 0.000928408292, 0.0300249556, 0.0, "06971836e11228b5"], + "twemoji/1f468-1f3fe-200d-2764-fe0f-200d-1f48b-200d-1f468-1f3ff": [0.0513432771, 0.091630809, 0.605072464, 0.00179225951, 0.0419087423, 0.000433538713, "c6b1eaceb17b4d65"], + "twemoji/1f469-1f3fb-200d-1f37c": [0.279165059, 0.13395734, 0.605333333, 0.00271196011, 0.115057682, 0.00797865324, "0bba56fe55ece6c7"], + "twemoji/1f469-1f3fc-200d-2764-fe0f-200d-1f468-1f3fc": [0.0464258604, 0.0754154926, 0.883152174, 0.00136276323, 0.0347598809, 0.00415329459, "d322fcebf2cb0026"], + "twemoji/1f469-1f3fe": [0.0344073251, 0.0233711067, 0.416666667, 0.00128494808, 0.0280224048, 0.0, "19bb902c271b8f32"], + "twemoji/1f469-1f3ff-200d-1f91d-200d-1f468-1f3fc": [0.238393903, 0.161471797, 0.877155172, 0.00397050614, 0.0998463657, 0.00483819826, "c50488fc3a28a38e"], + "twemoji/1f469-200d-1f467-200d-1f467": [0.0400480218, 0.0651274792, 0.4140625, 0.0010054413, 0.0448599217, 0.0, "0f7efac87d270bd3"], + "twemoji/1f470-1f3fc-200d-2640-fe0f": [0.0654810593, 0.0459811375, 0.862162162, 0.00128968945, 0.0582827201, 0.00519497929, "47c99319ae748ff2"], + "twemoji/1f481-1f3fc-200d-2640-fe0f": [0.029748017, 0.0684679993, 0.972972973, 0.00113838271, 0.0367032296, 0.0, "87ae9fa2b4de1a08"], + "twemoji/1f486-1f3ff": [0.354569554, 0.192213677, 1.21516393, 0.00390358665, 0.325229294, 0.0509830734, "0e6ddf5be7dc93ce"], + "twemoji/1f4e6": [0.0986496732, 0.0423581672, 0.709016393, 0.00132508262, 0.0609100787, 0.0, "b603d74cd8ec4287"], + "twemoji/1f53a": [0.0708608106, 0.0258956818, 1.125, 0.000846377399, 0.13504478, 0.0, "270c8a378251cc63"], + "twemoji/1f57a-1f3fb": [0.190729469, 0.150258318, 0.375, 0.00277713384, 0.10011685, 0.0, "e395e4452dc33edb"], + "twemoji/1f635": [0.0181445684, 0.0192072591, 0.117424242, 0.000937922101, 0.0149044389, 0.0, "b3e8e051b444e20d"], + "twemoji/1f646-1f3fb-200d-2640-fe0f": [0.066237919, 0.0614447491, 0.99378882, 0.00154078787, 0.0206145073, 0.0, "bafc886754aec9de"], + "twemoji/1f648": [0.0866172537, 0.0930098414, 0.505747126, 0.00171900226, 0.0385704898, 0.0, "5b3499ed17360fe7"], + "twemoji/1f64d-1f3fd": [0.0365180708, 0.0813660406, 1.03125, 0.000943853054, 0.025446452, 0.0, "58de38b256d81274"], + "twemoji/1f6a3-1f3ff-200d-2642-fe0f": [0.106842764, 0.0858811473, 0.826732673, 0.00195955927, 0.0521900738, 0.0, "9701acb8888e212c"], + "twemoji/1f6d6": [0.207799271, 0.179718182, 0.781326781, 0.00249069533, 0.22820167, 0.00017265116, "e2b54f9068438fea"], + "twemoji/1f7eb": [0.00048911979, 0.0126432664, 0.1875, 0.000128009429, 0.00234393721, 0.0, "bdb957327cb81794"], + "twemoji/1f91c-1f3fe": [0.0391807966, 0.0599451751, 0.735849057, 0.000624154287, 0.0484673564, 0.0, "465ec486e225c546"], + "twemoji/1f938-1f3fe": [0.191763029, 0.200965524, 0.363879004, 0.00238678209, 0.120495758, 0.000146946047, "a567dbde93488a6d"], + "twemoji/1f977-1f3fb": [0.10234154, 0.121258467, 0.769067797, 0.00261856639, 0.0440024556, 0.0, "9fb0410901b6140e"], + "twemoji/1f9a8": [0.259694189, 0.0838586547, 1.58576052, 0.00473938975, 0.0642192561, 0.0, "3007133be6d73aca"], + "twemoji/1f9c9": [0.0883905068, 0.0726399859, 0.958477509, 0.00182120583, 0.122361115, 0.0152652076, "ec98416c2d191292"], + "twemoji/1f9d1-1f3fd-200d-1f9af-200d-27a1-fe0f": [0.109123483, 0.141800043, 0.40625, 0.00153161737, 0.0730665287, 0.0027541707, "ba5d8fb5c5e11694"], + "twemoji/1f9d1-1f3ff-200d-2764-fe0f-200d-1f9d1-1f3fb": [0.106844611, 0.0854249554, 0.919811321, 0.00240334519, 0.0456288123, 0.0, "f2b593f2fd88681f"], + "twemoji/1f9d4-1f3fd": [0.0593276806, 0.0550342591, 0.707407407, 0.00133637025, 0.0338809746, 0.0, "41eb0105ab81c684"], + "twemoji/1f9d8-1f3fe": [0.125961438, 0.152262411, 0.661417323, 0.00219213963, 0.0784027328, 0.0, "951ed6c5000ce81e"], + "twemoji/1f9e9": [0.0390122421, 0.0694763912, 0.65, 0.000805809919, 0.0343726633, 0.0, "d19da91128eafc2f"], + "twemoji/1faa3": [0.288728863, 0.0719116248, 3.15740741, 0.00385207706, 0.136221732, 0.000259371157, "71b8eec49992e44d"], + "twemoji/1fae5": [0.0388696007, 0.138173597, 1.52777778, 0.00103777193, 0.0371557842, 0.0, "e5435e13e5735fa8"], + "twemoji/2196": [0.000453581481, 0.0240603355, 0.476190476, 0.000216691624, 0.000534438186, 0.0, "4f81de47fd70b04a"], + "twemoji/271d": [0.00858718157, 0.0321740079, 0.826923077, 0.000784438278, 0.0491603493, 0.0, "543a95451b6bad2f"] } }, "quality-512ss": { "tier": "512ss", "args": [], "summary": { - "de00": 0.049235778745723456, - "turning": 0.021061797475258007, - "ratio": 1.7822581210112125, - "self_res": 0.0007316163941348024, + "de00": 0.03765296101178145, + "turning_gap": 1.7473491075290273, + "ratio_gap": 0.31517349387897525, + "geom": 0.09260348241478497, + "turning": 0.01920314634830507, + "ratio": 1.1151802214927227, + "self_res": 0.000647365255975072, + "geom_far": 0.015558911972308161, "n": 246 }, "icons": { - "lucide/app-window-mac": [0.054622706, 0.0129755666, 1.25, 0.000531245198, "95532afc18afa51b"], - "lucide/audio-lines-x": [0.0538766459, 0.0152541413, 6.75, 0.000565667171, "6ffed74f5e6d05c3"], - "lucide/badge-russian-ruble": [0.0367821343, 0.020706458, 4.29577465, 0.000675949326, "425f483e384f525e"], - "lucide/bath": [0.0791039914, 0.0170998689, 5.56756757, 0.000696204661, "13f4bc2f792b72c0"], - "lucide/bell": [0.0357734635, 0.0106007574, 3.14285714, 0.000475042063, "b387cfcba3899a9c"], - "lucide/birdhouse": [0.0623714626, 0.0141578471, 6.04545455, 0.000921555853, "38825032307cf837"], - "lucide/book-heart": [0.0363109745, 0.00844343508, 2.59016393, 0.000601405802, "b67bd07cfb16301e"], - "lucide/bug": [0.0509759262, 0.0219461116, 5.0, 0.000872309029, "e8ef702bfbc4143f"], - "lucide/cat": [0.0304863397, 0.0127987885, 2.83098592, 0.000602393062, "f3c5b0e43bf00250"], - "lucide/chess-king": [0.0370730981, 0.0144824308, 2.6375, 0.000652552408, "80b8f9a555b14d12"], - "lucide/circle-arrow-right": [0.0394645967, 0.0095748059, 7.55555556, 0.000583514164, "4955a38dbf237f35"], - "lucide/closed-caption": [0.0189057216, 0.0127559478, 5.9, 0.000657429453, "21c53ade28ce1e0d"], - "lucide/cooking-pot": [0.0369559601, 0.0108590239, 3.45454545, 0.000636515964, "76cf65b6bf1a2185"], - "lucide/diff": [0.0429748446, 0.0123367366, 13.6666667, 0.00041230151, "455c3d8bff4a8ba7"], - "lucide/equal": [0.0573098846, 0.00842867244, 1.5, 0.000336456258, "5689e2ffa6e4824c"], - "lucide/file-digit": [0.0487476774, 0.0144712918, 2.88135593, 0.000627570029, "01794be6aaf9d33d"], - "lucide/focus": [0.0155470856, 0.0200952329, 4.31914894, 0.000599042163, "0f6664f1d4df8c7f"], - "lucide/folder-open": [0.0379070826, 0.00778747551, 2.27027027, 0.00056497904, "11bc1eb14570bffe"], - "lucide/git-compare": [0.0331758447, 0.0149447188, 5.14285714, 0.000632820826, "72b589e97180340f"], - "lucide/hard-drive-download": [0.0134257106, 0.0150956682, 4.5625, 0.000611054653, "a852bf20c7c33890"], - "lucide/ice-cream-cone": [0.0224197619, 0.0131089255, 3.61764706, 0.000405569648, "3c2e3374b00a2f79"], - "lucide/iteration-ccw": [0.0187846255, 0.0101784777, 8.30769231, 0.000515447871, "877bd314b70f4328"], - "lucide/list-checks": [0.0340822116, 0.015419868, 7.42857143, 0.000393841183, "2126f3ecf6a5f1f3"], - "lucide/message-circle-dashed-check": [0.0275217406, 0.021821852, 5.9375, 0.000585952366, "e6cab77701997dd9"], - "lucide/messages-square": [0.0430254526, 0.00981644519, 2.35443038, 0.000714948925, "d9c008f8193c54f2"], - "lucide/navigation-2-off": [0.019691743, 0.0121678412, 7.625, 0.000420155324, "ea774bd37b310c34"], - "lucide/omega": [0.0181918703, 0.0107414651, 2.62790698, 0.000412436115, "a2b53555d6b1b1a8"], - "lucide/panel-right": [0.0613055341, 0.00530499222, 10.0, 0.000824183924, "a653fae0a2a001e0"], - "lucide/pen-line": [0.0304376334, 0.00629424044, 2.36111111, 0.000482835923, "a267a2491634bd73"], - "lucide/phone-forwarded": [0.0418392085, 0.0109995343, 2.61363636, 0.000779709022, "ab986e30480a9376"], - "lucide/rectangle-goggles": [0.0206463113, 0.00749134023, 2.01639344, 0.000540325651, "e6d339d3d5358aca"], - "lucide/save-pen": [0.0795521811, 0.0113594429, 2.5, 0.000808042474, "5c134ff58014e734"], - "lucide/shapes": [0.0110911336, 0.0115160098, 1.23529412, 0.00064416026, "4a6e4817bf774013"], - "lucide/shopping-cart-plus": [0.0516239554, 0.0196231836, 5.90697674, 0.000647047476, "0b3ee071c5d16d68"], - "lucide/sparkle": [0.0430880785, 0.01146996, 2.24285714, 0.000550094352, "57c8bb8a3593db40"], - "lucide/square-minus": [0.00383821921, 0.00634539572, 1.5, 0.00081845466, "a23cdb5fe73b0d14"], - "lucide/swiss-franc": [0.0282608774, 0.0152616736, 13.875, 0.000324354041, "6edb3e54173d36b7"], - "lucide/ticket-minus": [0.0222339388, 0.0119448718, 3.2037037, 0.000586909824, "a06089108b129130"], - "lucide/undo": [0.0169160794, 0.0122996255, 4.65, 0.000291771983, "4ac9b64e29b93ff7"], - "lucide/vegan": [0.033524625, 0.0107734857, 6.25, 0.000807309814, "1f5f4ad51d83037f"], - "material-icons/12mp": [0.0901785642, 0.0146416113, 1.29375, 0.000731000619, "3e25092a470b4a9b"], - "material-icons/admin_panel_settings": [0.0245084297, 0.0124396287, 0.950819672, 0.000557723863, "871c80fdb67587ae"], - "material-icons/arrow_drop_down": [0.00759741943, 0.0121998273, 1.0, 0.000128577754, "ed745e1bd118b5d1"], - "material-icons/bento": [0.10253454, 0.00966876928, 0.7125, 0.000682247512, "e251cbd368f56ebe"], - "material-icons/border_left": [0.0578408092, 0.0297987318, 0.75, 0.00051134883, "977b22b60bccf358"], - "material-icons/call": [0.0227143522, 0.015010018, 1.11926606, 0.000427021732, "ad18930e4fb4aaa4"], - "material-icons/chair": [0.0522137843, 0.0129308164, 1.18292683, 0.000659269339, "ec565f8f38cb9847"], - "material-icons/closed_caption": [0.0209223591, 0.017491006, 0.797101449, 0.00047236422, "978a04bdfd22c3c6"], - "material-icons/crop_landscape": [0.019466985, 0.00536136608, 0.15, 0.000490824343, "9e99fda435691e4b"], - "material-icons/dining": [0.0336420164, 0.013091847, 0.784722222, 0.00106823479, "3e06b7acf55e865e"], - "material-icons/double_arrow": [0.00922255777, 0.00946469373, 1.2, 0.000218140878, "84468b063dcb62d1"], - "material-icons/dynamic_feed": [0.0430920906, 0.0102719684, 1.26315789, 0.000558381842, "2a89c033c0154edb"], - "material-icons/expand_circle_down": [0.0129531454, 0.00837443785, 0.25, 0.000676368305, "c948b2aec1538940"], - "material-icons/flight": [0.0310411584, 0.013004669, 1.22727273, 0.000333733624, "6e1cb615960ee1f3"], - "material-icons/free_breakfast": [0.0454232283, 0.00917523795, 1.12676056, 0.00051824539, "b429921abd815714"], - "material-icons/group_remove": [0.0402739905, 0.0135501067, 0.73880597, 0.000591442687, "4f144edfa6465119"], - "material-icons/headset": [0.0295585785, 0.0109041865, 1.23255814, 0.000363443367, "0a455af289e55122"], - "material-icons/houseboat": [0.0254897028, 0.0246591653, 1.17105263, 0.000437283918, "2ea03e4343ec83fc"], - "material-icons/javascript": [0.0093210889, 0.0307818705, 1.08333333, 0.000111269474, "55d5ec46ce606b08"], - "material-icons/laptop": [0.0635120869, 0.00836596204, 1.16666667, 0.000554956088, "253acff5757bc287"], - "material-icons/lyrics": [0.0689121783, 0.0142419914, 1.14018692, 0.000700348814, "5a5930ff1baeb538"], - "material-icons/miscellaneous_services": [0.0282170642, 0.0339619517, 0.977011494, 0.000418270327, "3d281b5222a3117c"], - "material-icons/music_note": [0.00635917531, 0.0130351242, 0.867924528, 0.000243093469, "79ef7636489f0575"], - "material-icons/no_food": [0.110762671, 0.0108629817, 1.30487805, 0.00154149637, "a924a0ac32841405"], - "material-icons/notifications_paused": [0.0497195907, 0.0147955602, 1.14130435, 0.000490719744, "7637c55ba293d19a"], - "material-icons/perm_media": [0.0963568538, 0.00715877017, 1.1625, 0.000848209194, "d0425c080846339a"], - "material-icons/phone_iphone": [0.0415013395, 0.00713851978, 0.823529412, 0.000437717739, "396f62527d43feae"], - "material-icons/polyline": [0.0558457896, 0.0177383805, 1.06896552, 0.000410880311, "6e7b04ec7a285cee"], - "material-icons/qr_code": [0.0660534501, 0.0238184793, 0.8125, 0.00057145668, "6a99bf32a0a84743"], - "material-icons/report": [0.0410009548, 0.00902401294, 1.19512195, 0.000442534831, "39471b2804b7265b"], - "material-icons/rule_folder": [0.0464775078, 0.0121626834, 1.19047619, 0.000747800339, "6a454538bad7cb60"], - "material-icons/sd_card_alert": [0.0351005942, 0.00829754547, 1.06, 0.000535478757, "f2a55546c1db6762"], - "material-icons/settings_overscan": [0.0447883382, 0.00962765935, 1.03125, 0.000454248308, "f20ef395a7f419ef"], - "material-icons/sms_failed": [0.104811929, 0.00876157475, 1.14, 0.000706093211, "beb7a942e4f96cf1"], - "material-icons/storage": [0.133961737, 0.0105191363, 0.75, 0.00082482741, "987ac360e57e5ac2"], - "material-icons/table_rows": [0.0930667743, 0.00677845774, 1.5, 0.000579878804, "8bda95a3e4e5b7fc"], - "material-icons/transfer_within_a_station": [0.0450575985, 0.0189453706, 0.759259259, 0.000522613525, "c044373393acd507"], - "material-icons/two_wheeler": [0.0380995609, 0.018577597, 0.949275362, 0.000572249352, "082171c0fec6a7b1"], - "material-icons/video_camera_back": [0.0633729324, 0.00982757702, 1.24137931, 0.00068727386, "864ffa024df993ed"], - "material-icons/view_week": [0.0954990685, 0.00710153101, 0.964285714, 0.000693003356, "fe60acd77b97baf2"], - "noto-emoji/emoji_u0030": [0.0155350519, 0.0148714443, 0.833333333, 0.000198163034, "b222cf0b3b866980"], - "noto-emoji/emoji_u1f36a": [0.0861865506, 0.0356111733, 1.30829016, 0.000951305497, "022d34d2f7fae5b3"], - "noto-emoji/emoji_u1f39e": [0.38901332, 0.0273549863, 1.35755814, 0.00276338239, "b41e831884f936ee"], - "noto-emoji/emoji_u1f3c2_1f3fd": [0.180280149, 0.0334355692, 0.990312966, 0.00158073765, "0a6f522cd58868d3"], - "noto-emoji/emoji_u1f3c4_1f3fe": [0.0670349374, 0.0521631882, 0.907421875, 0.00118718029, "b400dcc07934591c"], - "noto-emoji/emoji_u1f3cb_200d_2642": [0.11698544, 0.0760419121, 0.69124424, 0.00134580245, "23cd696679c05521"], - "noto-emoji/emoji_u1f41b": [0.030876467, 0.0383396864, 1.39267016, 0.000536641397, "957aaa7e201e9449"], - "noto-emoji/emoji_u1f44d_1f3fc": [0.0409481563, 0.0332676586, 1.43490305, 0.000684379076, "f79bb1f565d36d26"], - "noto-emoji/emoji_u1f468_1f3fb_200d_2764_200d_1f468_1f3fd": [0.110048108, 0.0295138277, 0.904891304, 0.0011894214, "f33dbfc70ab4efe4"], - "noto-emoji/emoji_u1f468_1f3ff_200d_1f393": [0.221925125, 0.0309027652, 1.24570025, 0.00243591075, "f57ffa843fe0b9b1"], - "noto-emoji/emoji_u1f469_1f3fb_200d_1f52c": [0.220859349, 0.0355544328, 1.62476895, 0.00207640417, "ab91e5732b26c522"], - "noto-emoji/emoji_u1f469_1f3fc_200d_1f91d_200d_1f468_1f3fb": [0.103687651, 0.0465667708, 0.620557157, 0.00125270337, "3099129a93a26f50"], - "noto-emoji/emoji_u1f469_1f3fe_200d_1faef_200d_1f469_1f3fd": [0.175106212, 0.0640001006, 0.742935278, 0.00195849501, "0513a27e066b77d6"], - "noto-emoji/emoji_u1f469_200d_1f469_200d_1f466_200d_1f466": [0.032515984, 0.0179058354, 0.862582781, 0.000780966075, "97148c941a0f479a"], - "noto-emoji/emoji_u1f46c_1f3fd": [0.0835800394, 0.0503659029, 0.518532819, 0.00105454726, "2f69ff0664875d7a"], - "noto-emoji/emoji_u1f470_1f3fb_200d_2640": [0.119289175, 0.0280067962, 1.33105023, 0.00143983343, "1ae772574f3ce378"], - "noto-emoji/emoji_u1f482_1f3ff_200d_2640": [0.0589494854, 0.0315151793, 0.973790323, 0.00109389145, "c58e0b804b0e00a3"], - "noto-emoji/emoji_u1f4d8": [0.0734499693, 0.0103701293, 1.52380952, 0.00108896522, "aebe77d0d6c17f36"], - "noto-emoji/emoji_u1f520": [0.00955760758, 0.0147670925, 0.742009132, 0.00027713555, "b0916e14ddf0bfa8"], - "noto-emoji/emoji_u1f56f": [0.105624221, 0.0418951751, 1.24914089, 0.000671657966, "5f6687e2ce8e4a78"], - "noto-emoji/emoji_u1f5a8": [0.0819088593, 0.0215603244, 1.74418605, 0.00158333813, "1a42ffc55e5618f0"], - "noto-emoji/emoji_u1f62d": [0.125460118, 0.0252618659, 1.75375375, 0.0014065518, "b2ce8e55adebdd26"], - "noto-emoji/emoji_u1f64b_1f3fe_200d_2640": [0.108209155, 0.024616689, 0.927318296, 0.00119613961, "c6a82e25196eac23"], - "noto-emoji/emoji_u1f6c0_1f3ff": [0.206792831, 0.0877823578, 1.68257619, 0.00201192591, "5833e4f43e8ad88d"], - "noto-emoji/emoji_u1f90d": [0.0100033702, 0.0131876348, 1.09090909, 0.000174650864, "7d7053fcc0cd6960"], - "noto-emoji/emoji_u1f91c_1f3fe": [0.034008339, 0.0265130558, 1.39555556, 0.000579502492, "193fc7731c222f8a"], - "noto-emoji/emoji_u1f926_1f3ff": [0.184067041, 0.0423931731, 1.32415902, 0.0021719744, "7cfe70b61250a391"], - "noto-emoji/emoji_u1f932": [0.06605874, 0.0325801726, 1.28877005, 0.0008534058, "1a9e65707e0070be"], - "noto-emoji/emoji_u1f93c_1f3fe_200d_2640": [0.401361525, 0.0629270655, 0.769935839, 0.00477113714, "4e9dfb71f7cfa0d5"], - "noto-emoji/emoji_u1f987": [0.0972490609, 0.0338516703, 1.15689655, 0.00103279902, "7b80f39b3b0e9687"], - "noto-emoji/emoji_u1f9be": [0.178701416, 0.0442288426, 1.91377246, 0.00177504017, "938cd49e32af2146"], - "noto-emoji/emoji_u1f9ce_1f3fd_200d_2642": [0.0562837236, 0.039629505, 0.639705882, 0.000728321087, "e8d5671fe4935f15"], - "noto-emoji/emoji_u1f9cf_1f3fc": [0.152090371, 0.0341182836, 1.30600462, 0.00162099313, "fa7e4c032d0da95c"], - "noto-emoji/emoji_u1f9d1_1f3fc_200d_1f37c": [0.0593508072, 0.0541646672, 1.15462754, 0.000916667806, "2eaaeff610fc883a"], - "noto-emoji/emoji_u1f9d1_1f3fd_200d_1f91d_200d_1f9d1_1f3ff": [0.15502581, 0.0708146492, 0.862124899, 0.00194852706, "d20cd9d4d9c7b5c9"], - "noto-emoji/emoji_u1f9d1_1f3fe_200d_1f9bc_200d_27a1": [0.0746214539, 0.0614079743, 0.993107769, 0.00115999498, "819c66a1628d1b07"], - "noto-emoji/emoji_u1f9d6_1f3fe_200d_2642": [0.214861453, 0.0331582746, 1.56578947, 0.00164871989, "265247cf816bd8da"], - "noto-emoji/emoji_u1f9dd_1f3fd_200d_2640": [0.117203653, 0.0364437012, 1.34233577, 0.00190251658, "45355639bbcc6a08"], - "noto-emoji/emoji_u1f9ed": [0.0548078828, 0.0306747897, 2.32911392, 0.000806344906, "61bf9a39de17421a"], - "noto-emoji/emoji_u1faa5": [0.0826448873, 0.0492414169, 1.01388889, 0.00110871752, "5f458a78744c4ad9"], - "noto-emoji/emoji_u1faf1_1f3fc_200d_1faf2_1f3ff": [0.0685956106, 0.0424792647, 1.10732113, 0.00104025926, "d2cf0d6bdb6a1646"], - "noto-emoji/emoji_u26bd": [0.0385898203, 0.024523144, 1.88744589, 0.000782619638, "d80cd60d4cce299e"], - "noto-emoji/emoji_u2b05": [0.0058954102, 0.00848514436, 1.26923077, 0.000136423987, "0315b2ed38ec24cc"], - "openmoji/1F195": [0.0565653443, 0.0165160098, 6.08823529, 0.000661928148, "0c413f870a58770c"], - "openmoji/1F1FF-1F1F2": [0.0240948051, 0.0133258272, 2.25, 0.000228039047, "b269268e39d4335c"], - "openmoji/1F361": [0.0340546668, 0.0220720018, 2.12857143, 0.000548638287, "f414a7154953f58a"], - "openmoji/1F38A": [0.0393864997, 0.0264258073, 1.70833333, 0.000542492548, "414c2f2c166fa095"], - "openmoji/1F3A9": [0.0405667722, 0.00825687643, 1.23880597, 0.000629168237, "1443eb0b8dd91965"], - "openmoji/1F3C3-1F3FF-200D-2642-FE0F": [0.0219419822, 0.0252611, 2.05699482, 0.000551494944, "62eebfc5ca1dc9a2"], - "openmoji/1F3CC-FE0F-200D-2640-FE0F": [0.0412185676, 0.0295689131, 1.6953125, 0.000640998653, "e14c478924554058"], - "openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F": [0.0200627148, 0.00700965986, 3.4, 0.00032755037, "267ce44a283a99e2"], - "openmoji/1F442-1F3FF": [0.0221683215, 0.0221167057, 3.88596491, 0.000349151465, "abee9947ec3b736a"], - "openmoji/1F468-1F3FC-200D-1F3ED": [0.081866689, 0.0457367949, 0.653488372, 0.00121609599, "39ad0cf95f270cd6"], - "openmoji/1F468-1F3FF-200D-1F9B0": [0.0426689349, 0.0221223452, 1.14230769, 0.000660532794, "c265cf4086693fb1"], - "openmoji/1F468-200D-1F9B1": [0.0517550744, 0.0385552795, 1.32568807, 0.000655065698, "9905a1ce60a798b6"], - "openmoji/1F469-1F3FC-200D-2764-FE0F-200D-1F48B-200D-1F469-1F3FC": [0.0817278549, 0.0291484256, 2.13333333, 0.00100615656, "f566ad50f29765cb"], - "openmoji/1F469-1F3FF-200D-1F9B2": [0.0337119326, 0.0216627315, 1.5, 0.000458258233, "a4c852e1386b3ddb"], - "openmoji/1F481-1F3FB-200D-2642-FE0F": [0.0496214405, 0.0244626654, 1.88518519, 0.00073139224, "9b0cf1d86b3b7f28"], - "openmoji/1F49B": [0.0230851416, 0.00946711049, 0.931818182, 0.000337658013, "eb9be4d201e0fc84"], - "openmoji/1F517": [0.0371243656, 0.0240372727, 2.87062937, 0.000586400216, "d8cce8bfe6b864a0"], - "openmoji/1F646-1F3FC": [0.0538961627, 0.0213289913, 1.11353712, 0.000764834054, "729a0aab1ba7d3ce"], - "openmoji/1F6B4-1F3FD-200D-2640-FE0F": [0.0371214114, 0.0281238363, 2.32386364, 0.000919913931, "37d5f7c4bc2db3aa"], - "openmoji/1F6E0": [0.0767769143, 0.0262238812, 2.43303571, 0.00121826853, "74da9df0d8e9d4ea"], - "openmoji/1F938-1F3FB": [0.03534941, 0.0266179516, 2.17982456, 0.000514095242, "0f81030a1ab21253"], - "openmoji/1F93E-1F3FE": [0.0381224006, 0.0302047268, 2.65333333, 0.000517775363, "75482c269fcd2cc2"], - "openmoji/1F9B3": [0.0480296724, 0.0137533929, 3.03030303, 0.000549418386, "852a05206fe6e8d6"], - "openmoji/1F9D1": [0.0450255871, 0.0208229936, 1.55963303, 0.000685827632, "7e6ee68a11a87c42"], - "openmoji/1F9D1-1F3FC-200D-1FA70": [0.0409042314, 0.0388732466, 2.53461538, 0.000639850041, "603623cfdb226994"], - "openmoji/1F9D1-1F3FD-200D-1F527": [0.0534363575, 0.0360866453, 1.39068826, 0.000964043662, "d2c721846febf05a"], - "openmoji/1F9D1-200D-1F393": [0.0395054556, 0.0316740763, 0.455578512, 0.000764854078, "0fb3c6f1feb79079"], - "openmoji/1F9D6-1F3FD-200D-2642-FE0F": [0.0397877842, 0.036826886, 1.72386059, 0.000612992444, "c8f759a2e84c7301"], - "openmoji/1FA8B": [0.0495624319, 0.0514857935, 0.729967949, 0.00057279435, "e058bf1d575ccb69"], - "openmoji/1FAC4-1F3FD": [0.0391650312, 0.0311460333, 1.14469453, 0.000759919698, "d9ae863a03480de2"], - "openmoji/25FC": [0.00289744162, 0.00556379447, 0.5, 0.000162326513, "7e3fc99beea4b82b"], - "openmoji/2705": [0.0565713421, 0.0139662656, 2.11842105, 0.000813619699, "f046bc00cf11d4a8"], - "openmoji/E056": [0.101896197, 0.015964281, 0.813813814, 0.00117719045, "ceaee0177568fa2f"], - "openmoji/E1D1": [0.0395382345, 0.01748732, 0.962427746, 0.000612904958, "1c151931564423b6"], - "openmoji/E30B": [0.0307989046, 0.0223747489, 1.2991453, 0.00130319048, "a6236b0697748f31"], - "simple-icons/alchemy": [0.0406392887, 0.00806695532, 0.422641509, 0.000795596221, "4400426b19da2bdc"], - "simple-icons/appletv": [0.0155143626, 0.021901395, 0.918128655, 0.000395935698, "fdbc4f77f8dcd2ff"], - "simple-icons/atlassian": [0.0495271832, 0.00606484304, 1.27692308, 0.000725181366, "39d4177723b34230"], - "simple-icons/autocad": [0.0144418376, 0.00786204454, 1.03225806, 0.000872024859, "9f6813b57c59e288"], - "simple-icons/bandrautomation": [0.0481557734, 0.0191423649, 0.95, 0.00110475125, "4ad381ffa72169d9"], - "simple-icons/bim": [0.0205446444, 0.0171240229, 1.17730496, 0.000585982343, "36f7beed662a65b9"], - "simple-icons/boosty": [0.0266848616, 0.00805494596, 1.15909091, 0.000466919009, "8f4da59a79b85d6d"], - "simple-icons/changedetection": [0.0528936647, 0.0124459715, 0.676595745, 0.00105231802, "30495d146538692e"], - "simple-icons/cocos": [0.127186671, 0.0269274238, 0.593258427, 0.00216439879, "3392b875761bc80a"], - "simple-icons/contentstack": [0.0534893945, 0.0148555701, 0.612745098, 0.00123035221, "c53c18e1287aefcc"], - "simple-icons/debridlink": [0.0268738717, 0.0101401344, 0.751515152, 0.000574089412, "fb83ffdeeac4e2b0"], - "simple-icons/elixir": [0.012804592, 0.00565636324, 1.03773585, 0.000270888413, "b5234ae6dc824b23"], - "simple-icons/fampay": [0.0252484772, 0.0150703738, 0.919786096, 0.000476552988, "a3a2dfcc68024eb7"], - "simple-icons/fluxer": [0.0341533832, 0.010221016, 0.828947368, 0.000680841214, "5789e9348f18ef63"], - "simple-icons/googlechrome": [0.0403670222, 0.00862002346, 1.23076923, 0.000880701467, "90235b1648d8a618"], - "simple-icons/h2database": [0.0441474319, 0.0101807087, 0.743455497, 0.00111703307, "71f69cad490b9f9f"], - "simple-icons/hitachi": [0.00943891704, 0.0388104589, 0.571428571, 0.000617173209, "f65121ee72528ab6"], - "simple-icons/infinityfree": [0.0500021353, 0.0378417923, 0.653753027, 0.000895675912, "65cb58acf3ba77da"], - "simple-icons/jdoodle": [0.0298774708, 0.0193830976, 0.592964824, 0.000761847419, "6c87784192c63a3f"], - "simple-icons/kleinanzeigen": [0.0427348651, 0.00927729563, 1.14, 0.00088067149, "e6ade635faa08bc3"], - "simple-icons/leetcode": [0.0234428942, 0.00950759052, 0.752873563, 0.000689233479, "d8219a1bd94431da"], - "simple-icons/looker": [0.026807813, 0.0196994281, 0.955801105, 0.00060089695, "805a3baf71a3e0ab"], - "simple-icons/mamp": [0.02802765, 0.0140962004, 1.3, 0.000591487566, "27e61a9ede400162"], - "simple-icons/microeditor": [0.038010601, 0.0129889559, 0.463265306, 0.000734875386, "57181b75e50dfb9d"], - "simple-icons/mysql": [0.0483537242, 0.0366011327, 0.587591241, 0.000955544412, "b653548dad58e36d"], - "simple-icons/notion": [0.122780785, 0.00898305313, 1.24719101, 0.00168925279, "59562a791586c3e9"], - "simple-icons/osano": [0.0209526364, 0.0048719188, 2.21428571, 0.000457105314, "3f4386ce23c8f1a4"], - "simple-icons/phpstorm": [0.0106424978, 0.0107070369, 0.909722222, 0.000429475011, "079ae04b665597e7"], - "simple-icons/playerfm": [0.034718506, 0.0108950513, 0.7, 0.000777794223, "8f56c5f775bc0b9c"], - "simple-icons/premierleague": [0.0693073347, 0.0375124393, 1.11137441, 0.00117703597, "1555585c18e4c9c1"], - "simple-icons/pronounsdotpage": [0.0402589701, 0.0106700001, 1.06395349, 0.000735413807, "7f6d134e1bee1cda"], - "simple-icons/purescript": [0.012060917, 0.014395762, 1.42592593, 0.00059518253, "0b50b34306efef70"], - "simple-icons/redsys": [0.0247638691, 0.00867706539, 0.901408451, 0.000458361901, "06444d8dba071076"], - "simple-icons/sagemath": [0.108323902, 0.0316100573, 0.75106082, 0.00197112164, "787ddf98c75dcb38"], - "simple-icons/slackware": [0.026922768, 0.0102354983, 0.857819905, 0.000812994258, "d51c5274ffc3afde"], - "simple-icons/sparkar": [0.00900505297, 0.00684970045, 1.33333333, 0.000310471543, "e034f864da051b7c"], - "simple-icons/stmicroelectronics": [0.0420091115, 0.0110922439, 0.896103896, 0.000638146361, "2c3981308449b43a"], - "simple-icons/ubiquiti": [0.0252003949, 0.0148529381, 0.477876106, 0.000426931889, "7d90dc04775d6ac9"], - "simple-icons/visa": [0.0195335448, 0.0214839368, 0.963235294, 0.000365732209, "57f2b1782d4a1c2d"], - "simple-icons/wxt": [0.0346309952, 0.015741392, 1.15463918, 0.000711987319, "73016e3cc8a22b45"], - "synthetic/gradient_linear": [0.0854768604, 0.0034204243, 1.0, 0.000332257623, "df1fa421bd6a2bf9"], - "synthetic/mosaic_grid6": [0.0756873861, 0.0218216859, 3.21621622, 0.000539188564, "f9ef5b639ed0f555"], - "synthetic/prim_ellipse": [0.00235147611, 0.00398260463, 1.0, 7.4045005e-05, "3c562886b2293c07"], - "synthetic/prim_star5": [0.00022116366, 0.00678917133, 1.08333333, 7.05993298e-05, "8dd23c16d139d573"], - "synthetic/symmetry_rot3": [0.00855858624, 0.00636233672, 1.66666667, 0.000161638425, "af9f00d1272c3b5b"], - "twemoji/1f17e": [0.00788325723, 0.00500800305, 1.1, 0.000180502539, "bca18acf68f43b16"], - "twemoji/1f1f8": [0.00741406297, 0.00780894242, 1.07692308, 0.000161007512, "5edea965bfdae52a"], - "twemoji/1f1fa": [0.0146323396, 0.00538831653, 1.14772727, 0.000282345311, "1bd5c9368d60fa50"], - "twemoji/1f325": [0.0100324992, 0.0185155875, 1.24043716, 0.000158725234, "f29b99c6a403a426"], - "twemoji/1f369": [0.0158273224, 0.0231699561, 1.02247191, 0.00038447688, "ee433ed04c7f4c44"], - "twemoji/1f3ca-1f3fe-200d-2640-fe0f": [0.0304633435, 0.0216720572, 1.15408805, 0.000358791789, "6f42555b19d933b3"], - "twemoji/1f3cc-1f3fb-200d-2640-fe0f": [0.0252226591, 0.0365606213, 1.20612245, 0.000379618607, "4436168d7d64f3b9"], - "twemoji/1f42b": [0.0161515549, 0.0239988258, 1.11363636, 0.000281720713, "5e4784f6e9ca2950"], - "twemoji/1f468-1f3fb-200d-1f91d-200d-1f468-1f3fd": [0.0427037477, 0.037919959, 0.94893617, 0.000716140261, "114127ce476eec25"], - "twemoji/1f468-1f3fc-200d-1f9b0": [0.0129649099, 0.0218940922, 0.79338843, 0.000244147755, "56ade51faf079fba"], - "twemoji/1f468-1f3fe-200d-2764-fe0f-200d-1f48b-200d-1f468-1f3ff": [0.0222693514, 0.0264553042, 0.967391304, 0.000431588298, "b3c0d9ae9b78a8aa"], - "twemoji/1f469-1f3fb-200d-1f37c": [0.07478939, 0.0386044326, 1.23333333, 0.000922996725, "85eff55fd4628ee6"], - "twemoji/1f469-1f3fc-200d-2764-fe0f-200d-1f468-1f3fc": [0.0279561616, 0.0200966986, 1.06521739, 0.000482854404, "c425d822c383eca8"], - "twemoji/1f469-1f3fe": [0.0267075375, 0.0128001761, 0.742424242, 0.000555519422, "d53ec44df913b571"], - "twemoji/1f469-1f3ff-200d-1f91d-200d-1f468-1f3fc": [0.0478884652, 0.0376134432, 1.1012931, 0.000861991663, "2e68485f35d12825"], - "twemoji/1f469-200d-1f467-200d-1f467": [0.00805017352, 0.0162208567, 0.690104167, 0.000223314142, "abaf9e21d301f336"], - "twemoji/1f470-1f3fc-200d-2640-fe0f": [0.0269462317, 0.014114244, 1.24054054, 0.000419405667, "f73696473d418131"], - "twemoji/1f481-1f3fc-200d-2640-fe0f": [0.0296378806, 0.019686823, 1.27027027, 0.000389885041, "5a6e0d7c2ae51410"], - "twemoji/1f486-1f3ff": [0.0372631922, 0.0283437811, 1.42008197, 0.000810230791, "4bcff91715cedd1e"], - "twemoji/1f4e6": [0.0283407755, 0.0127819153, 1.00819672, 0.000438151648, "ee55973c2f6d2933"], - "twemoji/1f53a": [0.0152773988, 0.00604635518, 1.0, 0.00010742306, "013dad9168b24a6e"], - "twemoji/1f57a-1f3fb": [0.0447848141, 0.0491899314, 0.669291339, 0.000712748151, "a5c8c486a92c75e9"], - "twemoji/1f635": [0.0112261064, 0.0172198251, 1.06439394, 0.000258696848, "b698dd75bccc8918"], - "twemoji/1f646-1f3fb-200d-2640-fe0f": [0.0419048481, 0.0160825463, 1.2826087, 0.000692958245, "1099af5f3435f0dc"], - "twemoji/1f648": [0.0409286059, 0.0248890144, 0.895506792, 0.000810034864, "09a611c51a8b91a0"], - "twemoji/1f64d-1f3fd": [0.0192456916, 0.0244730694, 1.30859375, 0.000397855503, "22d995317006bbc9"], - "twemoji/1f6a3-1f3ff-200d-2642-fe0f": [0.0332039781, 0.0238353648, 1.23019802, 0.000363668893, "39c56b25f7197d97"], - "twemoji/1f6d6": [0.0534012392, 0.053595154, 1.41891892, 0.000745350029, "4abe918641a9732e"], - "twemoji/1f7eb": [0.117052697, 0.00440116687, 1.125, 0.00136209105, "d56e3711f8748909"], - "twemoji/1f91c-1f3fe": [0.0186204314, 0.0157799139, 1.23584906, 0.000314205972, "f564be4f7ed8f269"], - "twemoji/1f938-1f3fe": [0.0423668958, 0.0632449688, 0.725978648, 0.000554755738, "284264235d1d9f76"], - "twemoji/1f977-1f3fb": [0.0263542794, 0.0332360037, 1.28601695, 0.000657434866, "9ecca76b7da4d027"], - "twemoji/1f9a8": [0.0853318051, 0.0192407472, 1.94498382, 0.00185642147, "cde664c6624be1b7"], - "twemoji/1f9c9": [0.0238825679, 0.0194205008, 1.38754325, 0.000460049225, "b6c05c2462594042"], - "twemoji/1f9d1-1f3fd-200d-1f9af-200d-27a1-fe0f": [0.03388156, 0.0427649293, 0.65125, 0.000483642361, "a8df02f2a7a786ad"], - "twemoji/1f9d1-1f3ff-200d-2764-fe0f-200d-1f9d1-1f3fb": [0.0304219946, 0.0237551124, 1.26886792, 0.000602198357, "08db01d2d816869a"], - "twemoji/1f9d4-1f3fd": [0.0229490083, 0.0181178652, 0.892592593, 0.000373885414, "06882e85ccc2b021"], - "twemoji/1f9d8-1f3fe": [0.0355747268, 0.036680744, 0.921259843, 0.000540043693, "a72ee14e5a1926aa"], - "twemoji/1f9e9": [0.0120448992, 0.0202404325, 0.808333333, 0.000220638001, "22820138a5d46f26"], - "twemoji/1faa3": [0.0215318166, 0.0114052937, 3.19444444, 0.000446085382, "9511f6fa8f34c6e3"], - "twemoji/1fae5": [0.0170283038, 0.0344645224, 1.85714286, 0.00023411178, "a46d8922bcfdf757"], - "twemoji/2196": [0.003059173, 0.00605197866, 1.28571429, 0.000113818249, "1fc5062cc2a0aef6"], - "twemoji/271d": [0.0192150492, 0.0078401594, 1.11538462, 0.000191825515, "7e12ebd2a3d55bb8"] + "lucide/app-window-mac": [0.00851302035, 0.0129747265, 1.33333333, 0.000516225758, 0.00553831046, 0.0, "cccce224bd9193e9"], + "lucide/audio-lines-x": [0.00636626361, 0.0, 1.0, 0.000692479778, 0.00735739909, 0.0, "acb70008082bd747"], + "lucide/badge-russian-ruble": [0.011342789, 0.022836019, 1.57746479, 0.0011449029, 0.00715878148, 0.000180611459, "a039c958100f6063"], + "lucide/bath": [0.00591258518, 0.00381669594, 1.0, 0.00055815751, 0.00723663053, 0.0, "b868c1d13e448170"], + "lucide/bell": [0.0154257128, 0.00881762863, 1.23809524, 0.000614046527, 0.0166339139, 0.0, "78b28f887b8c9c11"], + "lucide/birdhouse": [0.00557573372, 0.0045434045, 1.18181818, 0.000584740716, 0.00664017177, 0.0, "e08015aa4039f07e"], + "lucide/book-heart": [0.0361856297, 0.0101981244, 1.44262295, 0.000715158472, 0.00598349675, 0.0, "81d7abed5afd96c8"], + "lucide/bug": [0.0264893938, 0.00661851035, 1.32432432, 0.000932656054, 0.0148790122, 0.0, "ff077b933a18794b"], + "lucide/cat": [0.0280396324, 0.0159944904, 1.63380282, 0.000930546783, 0.0229275914, 0.0, "c4debf550cf5626e"], + "lucide/chess-king": [0.0154266441, 0.00669552387, 1.0875, 0.000862151443, 0.0149520667, 0.0, "86f0e5e4c91d4a68"], + "lucide/circle-arrow-right": [0.0304984413, 0.00331822764, 1.0, 0.000581404718, 0.0312503481, 0.0, "8d7aa239c535d274"], + "lucide/closed-caption": [0.0137017351, 0.00722088988, 1.0, 0.000714380585, 0.0052279284, 0.0, "70c40d65d9745fdd"], + "lucide/cooking-pot": [0.00696204416, 0.00358635062, 1.0, 0.000587179151, 0.00489163619, 0.0, "91589162ed5063ef"], + "lucide/diff": [0.00339997653, 0.0, 1.0, 0.000443776458, 0.00593100154, 0.0, "0a206ce284bb1cec"], + "lucide/equal": [0.00220696186, 0.0, 0.5, 0.000372867944, 0.0066944891, 0.0, "40a09af214281d13"], + "lucide/file-digit": [0.0121236872, 0.00772575192, 1.11864407, 0.000723760284, 0.00692705232, 0.0, "5fc2603be5f003b3"], + "lucide/focus": [0.0108078169, 0.0118499016, 1.0, 0.000656501914, 0.0124583466, 0.0, "4fa013003f0d1294"], + "lucide/folder-open": [0.00689471932, 0.00675093379, 1.02702703, 0.000622423948, 0.00422503551, 0.0, "c7677bfe94700a90"], + "lucide/git-compare": [0.00648096576, 0.0108178063, 1.0, 0.000689353154, 0.0072505525, 0.0, "4cd17cd46870a015"], + "lucide/hard-drive-download": [0.0207075048, 0.0101388932, 1.125, 0.000631145376, 0.00767024915, 0.0, "a25ca8603a463d84"], + "lucide/ice-cream-cone": [0.0172318239, 0.0129955811, 1.47058824, 0.000478318165, 0.0121502587, 0.0, "1932c90031681551"], + "lucide/iteration-ccw": [0.0197591577, 0.00374916392, 1.0, 0.000603530032, 0.0182190367, 0.0, "a60673bd3ef7f621"], + "lucide/list-checks": [0.0062424168, 0.00359370999, 1.0, 0.000462101918, 0.0114579614, 0.0, "8dd6415c9374e5df"], + "lucide/message-circle-dashed-check": [0.0200431086, 0.0064356622, 0.9375, 0.000884516106, 0.0232462342, 0.0, "a237f243c6eb3c06"], + "lucide/messages-square": [0.00464600138, 0.00816698663, 1.0, 0.000655379903, 0.00440507561, 0.0, "5718f839b657a6ec"], + "lucide/navigation-2-off": [0.00556965824, 0.0124862766, 1.875, 0.000326403446, 0.00460167412, 0.0, "2d50383806b3feb7"], + "lucide/omega": [0.0134969763, 0.0195700385, 1.04651163, 0.000777465233, 0.0171391709, 0.0, "87b47940a0c108ca"], + "lucide/panel-right": [0.00228985259, 0.00335101644, 1.0, 0.000857783249, 0.00224537891, 0.0, "6afca98302cb240b"], + "lucide/pen-line": [0.00521603972, 0.00434093773, 1.02777778, 0.00055957865, 0.00339600814, 0.0, "3372e99086552043"], + "lucide/phone-forwarded": [0.0114903413, 0.00669228829, 0.977272727, 0.000844903057, 0.00961868391, 0.0, "a1640fec376b50f2"], + "lucide/rectangle-goggles": [0.00497534964, 0.00815951405, 1.09836066, 0.000570199976, 0.00372657497, 0.0, "51bf58cc5c577b78"], + "lucide/save-pen": [0.0107643791, 0.00681370451, 1.07446809, 0.000875270984, 0.00576889391, 0.0, "3bfb6b7525fde1ab"], + "lucide/shapes": [0.00986515824, 0.0115157395, 1.23529412, 0.000641527353, 0.0120500902, 0.0, "918dec6eb3676d88"], + "lucide/shopping-cart-plus": [0.019939106, 0.00903160572, 1.25581395, 0.000654302828, 0.00912312989, 3.57069663e-05, "999fd086fcb6d206"], + "lucide/sparkle": [0.00680996478, 0.0108958895, 1.05714286, 0.000407170301, 0.00710953113, 0.0, "6cda7903d22196e6"], + "lucide/square-minus": [0.00327491458, 0.0037812501, 1.0, 0.000838156324, 0.00375897613, 0.0, "25acce31c4d330f8"], + "lucide/swiss-franc": [0.00376446382, 0.00175294482, 1.0, 0.000309379422, 0.00511783965, 0.0, "a5a7b71889b7cfa8"], + "lucide/ticket-minus": [0.00447057141, 0.010950092, 1.03703704, 0.000689697219, 0.00520650454, 0.0, "44d16633e9bb3f8d"], + "lucide/undo": [0.0153030688, 0.00284963427, 0.65, 0.000399780314, 0.0194346316, 0.0, "91bbba1c82a6539d"], + "lucide/vegan": [0.0445848666, 0.00676883708, 3.25, 0.00111725752, 0.0235729511, 0.0, "8fe134eb5fd696a9"], + "material-icons/12mp": [0.0846990123, 0.0181204232, 0.86875, 0.000768085476, 0.00136095752, 0.0, "66e523ae252e2e64"], + "material-icons/admin_panel_settings": [0.0220124722, 0.0123135584, 0.991803279, 0.000488789927, 0.0202907708, 0.0, "35847f0ad48dcbfa"], + "material-icons/arrow_drop_down": [0.00759742409, 0.0121998273, 1.0, 0.00012857774, 0.0146047967, 0.0, "04f29c07a04f103d"], + "material-icons/bento": [0.0941997543, 0.00966870977, 0.7125, 0.000681918289, 0.00130809903, 0.0, "2f5a492a15f2fa28"], + "material-icons/border_left": [0.068697378, 0.0297997294, 0.75, 0.000511348946, 0.0, 0.0, "3c295fd774c21f6b"], + "material-icons/call": [0.0164934676, 0.0142435117, 0.394495413, 0.000427291001, 0.0289349997, 0.0, "e485d8b858a88286"], + "material-icons/chair": [0.0422010422, 0.0128348155, 1.18292683, 0.000613807235, 0.0108748547, 0.0, "3f89bdc626b04920"], + "material-icons/closed_caption": [0.0257787146, 0.0173940956, 0.797101449, 0.000471242267, 0.00206642288, 0.0, "def643caaddeb89a"], + "material-icons/crop_landscape": [0.00242847414, 0.00536110745, 0.15, 0.000484646065, 0.000933520662, 0.0, "911d687d90d61278"], + "material-icons/dining": [0.030356219, 0.0131244869, 0.791666667, 0.00105729944, 0.00467517827, 0.0, "02a4b7da4edab64c"], + "material-icons/double_arrow": [0.0174490493, 0.00946501184, 1.2, 0.000219726542, 0.00273214777, 0.0, "9a44495eac23f1a1"], + "material-icons/dynamic_feed": [0.0437568128, 0.0102612528, 1.15789474, 0.000529091049, 0.00638057235, 0.0, "e59fa714b232494d"], + "material-icons/expand_circle_down": [0.0129531445, 0.00837437492, 0.25, 0.000676667492, 0.0387571867, 0.0, "58f1678693c773c6"], + "material-icons/flight": [0.0294497814, 0.0130008375, 1.13636364, 0.000320389692, 0.0173026163, 0.0, "243b59c829720690"], + "material-icons/free_breakfast": [0.04428057, 0.00923873617, 1.04225352, 0.000452482927, 0.0061594072, 0.0, "27ae468d72e346a5"], + "material-icons/group_remove": [0.0402793922, 0.013508156, 0.71641791, 0.00059940113, 0.013522762, 0.0, "a8cc8722b793b96c"], + "material-icons/headset": [0.0253069177, 0.01096091, 1.06976744, 0.000348409027, 0.0123202105, 0.0, "56cff42932504f74"], + "material-icons/houseboat": [0.0230071098, 0.0245561558, 1.18421053, 0.000417671952, 0.0110654241, 0.0, "edb4bc8d2c21c985"], + "material-icons/javascript": [0.00909070019, 0.0307419958, 1.08333333, 0.000108157888, 0.00288336602, 0.0, "6f81ed896f57b205"], + "material-icons/laptop": [0.0850295871, 0.00832110901, 1.20833333, 0.000540280773, 0.00491027183, 0.0, "3e22a1f8b6e983d1"], + "material-icons/lyrics": [0.0594478585, 0.0142321906, 1.10280374, 0.000683683495, 0.0136722897, 0.0, "19b8840240b5aa00"], + "material-icons/miscellaneous_services": [0.0215284266, 0.0340917099, 0.988505747, 0.000353585026, 0.0190350135, 0.0, "023eb1b0e6a1b5df"], + "material-icons/music_note": [0.0397549458, 0.0131176795, 0.830188679, 0.000553714577, 0.0798366884, 0.0, "40d34979a03d8f5a"], + "material-icons/no_food": [0.0736042038, 0.0114089185, 1.32926829, 0.00116207649, 0.033058919, 0.00276362405, "718c87869e8d4336"], + "material-icons/notifications_paused": [0.0488961525, 0.0148347834, 1.15217391, 0.000494669017, 0.00811628502, 0.0, "59d5677dc567d210"], + "material-icons/perm_media": [0.0798472017, 0.00717415627, 1.0875, 0.00077848247, 0.00822531484, 0.0, "d4454a07e1fa5e04"], + "material-icons/phone_iphone": [0.0415013395, 0.00713851978, 0.823529412, 0.000437717797, 0.00148821499, 0.0, "8f01310aca0898c7"], + "material-icons/polyline": [0.0577931404, 0.017730583, 1.0, 0.000402742298, 0.00897772311, 0.0, "13de24048748e6b3"], + "material-icons/qr_code": [0.0744707361, 0.0238197942, 0.8125, 0.000571591256, 0.0, 0.0, "c9f6da30f2f9aa68"], + "material-icons/report": [0.0304191522, 0.011332701, 0.609756098, 0.000407499407, 0.0002365398, 0.0, "8f2a8f3798fcf5c8"], + "material-icons/rule_folder": [0.0481159166, 0.0120804496, 1.07142857, 0.000617128273, 0.00694663461, 0.0, "e3198828f66ddd95"], + "material-icons/sd_card_alert": [0.0364013799, 0.00829792492, 1.06, 0.000533608778, 0.00189962699, 0.0, "20865a0d31144667"], + "material-icons/settings_overscan": [0.0310184062, 0.00962779014, 1.03125, 0.000452393317, 0.000857231082, 0.0, "b2a1adf4195f49da"], + "material-icons/sms_failed": [0.0853167623, 0.00867712265, 1.06, 0.000676622556, 0.00837318333, 0.0, "a93fa2e560dac9d2"], + "material-icons/storage": [0.123084165, 0.0105189602, 0.75, 0.000824827293, 0.0, 0.0, "459098062604592c"], + "material-icons/table_rows": [0.0928154811, 0.00677572981, 0.964285714, 0.000574702804, 0.000517506951, 0.0, "ed6ab43aee3f4f97"], + "material-icons/transfer_within_a_station": [0.0450271852, 0.0189574734, 0.759259259, 0.000518200395, 0.00843953171, 0.0, "7a6fa64e08bf188f"], + "material-icons/two_wheeler": [0.0300841369, 0.0187908362, 0.971014493, 0.000523989787, 0.0294023671, 0.0, "7f2a08bd05f1e57f"], + "material-icons/video_camera_back": [0.0545612238, 0.00976713554, 1.03448276, 0.000524767675, 0.00198239498, 0.0, "ab2488a8965edb2a"], + "material-icons/view_week": [0.0955588892, 0.00710150979, 0.964285714, 0.000691417605, 0.00106593177, 0.0, "7204aefbf5edacc5"], + "noto-emoji/emoji_u0030": [0.0161471125, 0.0148862098, 0.833333333, 0.000207174628, 0.450860543, 0.0262964273, "8ff9b4873a1929ec"], + "noto-emoji/emoji_u1f36a": [0.0690441281, 0.0310129944, 1.22366149, 0.000923319079, 0.367101321, 0.112841263, "100f35ba14d85745"], + "noto-emoji/emoji_u1f39e": [0.227146879, 0.0292024493, 1.36046512, 0.00147647678, 0.9588745, 0.252636724, "336dd91d7d800174"], + "noto-emoji/emoji_u1f3c2_1f3fd": [0.128006846, 0.0323881081, 0.868107303, 0.00107156567, 0.91682117, 0.421947917, "dcb46f9f1f4a6633"], + "noto-emoji/emoji_u1f3c4_1f3fe": [0.0622901097, 0.0513368823, 0.90390625, 0.00110117381, 0.0543556327, 6.41743007e-06, "760a5f9b4ad872ac"], + "noto-emoji/emoji_u1f3cb_200d_2642": [0.100610018, 0.0716978955, 0.643778802, 0.00125287275, 0.511789241, 0.125249073, "bbf3e904dee93935"], + "noto-emoji/emoji_u1f41b": [0.0281666014, 0.0387096296, 1.37696335, 0.000497772417, 0.0419447056, 0.0, "db656981776fe52d"], + "noto-emoji/emoji_u1f44d_1f3fc": [0.0388240628, 0.0355694915, 1.48476454, 0.000678613782, 0.0589299004, 0.0, "369996fa38ea4909"], + "noto-emoji/emoji_u1f468_1f3fb_200d_2764_200d_1f468_1f3fd": [0.094084844, 0.0302560941, 0.795289855, 0.000896159152, 0.415927526, 0.0551895516, "c4123a3fbf04a117"], + "noto-emoji/emoji_u1f468_1f3ff_200d_1f393": [0.127004147, 0.0299496744, 1.05528256, 0.00127827132, 0.605995888, 0.0990338256, "651e222be725f147"], + "noto-emoji/emoji_u1f469_1f3fb_200d_1f52c": [0.181413531, 0.0326688746, 1.24584104, 0.00163071917, 0.302539878, 0.0102548172, "f05644c29d7c5826"], + "noto-emoji/emoji_u1f469_1f3fc_200d_1f91d_200d_1f468_1f3fb": [0.0786603019, 0.0439421253, 0.527377522, 0.000981973135, 0.662472167, 0.114346812, "09b413601a71983d"], + "noto-emoji/emoji_u1f469_1f3fe_200d_1faef_200d_1f469_1f3fd": [0.108604603, 0.059912793, 0.681403829, 0.00115458586, 0.531605407, 0.0956513241, "d7367a3591ff85d4"], + "noto-emoji/emoji_u1f469_200d_1f469_200d_1f466_200d_1f466": [0.0312052574, 0.0181797561, 0.839403974, 0.000761022151, 0.0347136458, 0.0, "94a2d46d2ce7cd39"], + "noto-emoji/emoji_u1f46c_1f3fd": [0.0706545934, 0.0467761725, 0.404247104, 0.000907070469, 0.454757716, 0.04298015, "2c8143c8e8ceb53a"], + "noto-emoji/emoji_u1f470_1f3fb_200d_2640": [0.11783535, 0.0240802954, 1.07648402, 0.00138851441, 0.710463963, 0.379049231, "4a6291232fb79f02"], + "noto-emoji/emoji_u1f482_1f3ff_200d_2640": [0.0407843851, 0.0305910017, 0.939516129, 0.000787067751, 0.34338566, 0.20824644, "72433c3cb68901e8"], + "noto-emoji/emoji_u1f4d8": [0.0379341468, 0.0105745826, 1.22380952, 0.000931320072, 0.0591035103, 0.0, "0c47f2e2496f8a40"], + "noto-emoji/emoji_u1f520": [0.0104706185, 0.0149354183, 0.723744292, 0.000280326145, 0.039194144, 0.000112400757, "b6f2f92d53d7f452"], + "noto-emoji/emoji_u1f56f": [0.101245858, 0.0324336927, 0.828178694, 0.000585475413, 1.56468933, 0.615720626, "921e442051ec19d0"], + "noto-emoji/emoji_u1f5a8": [0.0699100867, 0.0213165329, 1.71627907, 0.00136385148, 0.274076066, 0.0349740373, "169244cf12c77661"], + "noto-emoji/emoji_u1f62d": [0.0963980928, 0.0248975047, 1.46546547, 0.00105959852, 0.809634625, 0.125007571, "2d528303cffe8c59"], + "noto-emoji/emoji_u1f64b_1f3fe_200d_2640": [0.103692859, 0.0229029705, 0.784461153, 0.00101035775, 0.559802742, 0.100293898, "3ac7d2af949e752c"], + "noto-emoji/emoji_u1f6c0_1f3ff": [0.207877189, 0.0761362566, 1.40655549, 0.00199959357, 0.489002157, 0.0463276017, "49115c46612a8da5"], + "noto-emoji/emoji_u1f90d": [0.00984599534, 0.0138092995, 1.0625, 0.000171890846, 0.104010381, 0.0, "cc97e751cdb9f66f"], + "noto-emoji/emoji_u1f91c_1f3fe": [0.0322965197, 0.0259982907, 1.43777778, 0.000550658617, 0.0514569163, 0.000112844115, "fa554a887e98502e"], + "noto-emoji/emoji_u1f926_1f3ff": [0.130951986, 0.0470406081, 1.2469419, 0.00163500197, 0.451963361, 0.0714488058, "712440953919902a"], + "noto-emoji/emoji_u1f932": [0.0695191696, 0.0317413151, 1.32352941, 0.00087167602, 0.07720221, 0.0014801371, "74fc2450c1690194"], + "noto-emoji/emoji_u1f93c_1f3fe_200d_2640": [0.108345099, 0.0553991856, 0.676901925, 0.00114022696, 0.465337566, 0.040257442, "3b3827521bc4ebe5"], + "noto-emoji/emoji_u1f987": [0.0410528034, 0.0393832317, 0.975862069, 0.000510847953, 0.202582282, 0.000942223652, "b4d4a60a5765fae6"], + "noto-emoji/emoji_u1f9be": [0.122511186, 0.0409520649, 1.71856287, 0.0011515232, 0.435206014, 0.157211641, "62381388c37eaa44"], + "noto-emoji/emoji_u1f9ce_1f3fd_200d_2642": [0.0299587026, 0.0371403891, 0.526960784, 0.000350077986, 0.198856832, 0.00162173616, "e3b8977e46a8b603"], + "noto-emoji/emoji_u1f9cf_1f3fc": [0.0940777138, 0.0316411394, 1.21593533, 0.00104748807, 0.607786371, 0.243432823, "ab2e99c823009ed0"], + "noto-emoji/emoji_u1f9d1_1f3fc_200d_1f37c": [0.0451983996, 0.0514185293, 1.04006772, 0.000733925321, 0.0661079163, 0.0018450877, "89e4aa90bea705e4"], + "noto-emoji/emoji_u1f9d1_1f3fd_200d_1f91d_200d_1f9d1_1f3ff": [0.108220711, 0.07030972, 0.808191403, 0.00152295874, 0.260185278, 0.0406012457, "af32775dfa7f97fa"], + "noto-emoji/emoji_u1f9d1_1f3fe_200d_1f9bc_200d_27a1": [0.0783479661, 0.0585047743, 0.971804511, 0.00123842119, 0.299552417, 0.0408073143, "f5e2420656fcd9cd"], + "noto-emoji/emoji_u1f9d6_1f3fe_200d_2642": [0.18447797, 0.0329040743, 1.56578947, 0.00128168648, 0.279598844, 0.020612002, "19d4f5588717c4f9"], + "noto-emoji/emoji_u1f9dd_1f3fd_200d_2640": [0.0821176842, 0.0348591575, 1.23722628, 0.00132134149, 0.591781226, 0.175864111, "4385a2e1476e8fe2"], + "noto-emoji/emoji_u1f9ed": [0.0352071635, 0.0231728474, 1.58860759, 0.000636411132, 0.0429090716, 0.0, "2a886bf9f864e1b0"], + "noto-emoji/emoji_u1faa5": [0.0528698042, 0.0405691415, 0.795138889, 0.000642911531, 0.530620283, 0.211417892, "a1e8a014465db303"], + "noto-emoji/emoji_u1faf1_1f3fc_200d_1faf2_1f3ff": [0.0576681793, 0.0405518312, 1.10482529, 0.00089463935, 0.0688226404, 0.000185007098, "d7e7fdbef95848e6"], + "noto-emoji/emoji_u26bd": [0.0409124494, 0.0250054653, 1.72727273, 0.00078663585, 0.0450561834, 0.000706354971, "0b5463a8fe06ee96"], + "noto-emoji/emoji_u2b05": [0.00707064895, 0.00860353142, 1.21794872, 0.0001383372, 0.0360963264, 0.0, "a7d00fd438a921c4"], + "openmoji/1F195": [0.0234352965, 0.0114813853, 2.85294118, 0.000514933665, 0.0100072581, 0.0, "5f886a8aef481c4b"], + "openmoji/1F1FF-1F1F2": [0.0197540149, 0.0135347462, 2.22916667, 0.000212850122, 0.00134211752, 0.0, "2dc824ec87badf98"], + "openmoji/1F361": [0.0278053787, 0.0208329143, 1.52857143, 0.000544359791, 0.0470789014, 0.000285573925, "aa3a12afd946872a"], + "openmoji/1F38A": [0.028921539, 0.0223924638, 0.921875, 0.000768158294, 0.0147734121, 0.0, "747d7494b9af4cc2"], + "openmoji/1F3A9": [0.0114419609, 0.00649960657, 0.955223881, 0.000477255933, 0.015511083, 0.0, "357e4e003222cd7c"], + "openmoji/1F3C3-1F3FF-200D-2642-FE0F": [0.0156073971, 0.0244540589, 1.89119171, 0.000403781043, 0.0310602588, 0.0, "42e5764769a9b140"], + "openmoji/1F3CC-FE0F-200D-2640-FE0F": [0.0134701394, 0.0204952478, 1.2109375, 0.0006243026, 0.0139694444, 0.0, "b1fbebe62e5d4c9d"], + "openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F": [0.0315538682, 0.00584048974, 1.0, 0.000432211353, 0.0201617433, 0.00487129367, "eb92d238e8b4e968"], + "openmoji/1F442-1F3FF": [0.0231955741, 0.0213658812, 3.19298246, 0.00042740241, 0.0517692804, 0.000806603519, "6866811855bfe598"], + "openmoji/1F468-1F3FC-200D-1F3ED": [0.0563353822, 0.039944892, 0.551162791, 0.000916188816, 0.0455832161, 0.0, "22064ee975fb04aa"], + "openmoji/1F468-1F3FF-200D-1F9B0": [0.033439301, 0.0201769897, 0.811538462, 0.000527064083, 0.040383138, 0.0, "673654f0e061351c"], + "openmoji/1F468-200D-1F9B1": [0.0542013124, 0.039821289, 1.15137615, 0.000794580963, 0.0878558142, 0.0, "b503a927a3f7c42f"], + "openmoji/1F469-1F3FC-200D-2764-FE0F-200D-1F48B-200D-1F469-1F3FC": [0.0486990139, 0.0229446531, 1.35, 0.000946519722, 0.0278365526, 0.0, "5c6700b00e0178c9"], + "openmoji/1F469-1F3FF-200D-1F9B2": [0.0336120613, 0.0218562777, 0.980263158, 0.000559444423, 0.106494852, 0.0, "ddc2f86978cbcdea"], + "openmoji/1F481-1F3FB-200D-2642-FE0F": [0.0445647389, 0.0228663715, 1.27407407, 0.000803607749, 0.0504795518, 0.0, "85770598f5cfaecb"], + "openmoji/1F49B": [0.0198989697, 0.00946615809, 0.931818182, 0.00030191461, 0.0325134159, 0.0, "e95466203eda243d"], + "openmoji/1F517": [0.020463191, 0.0244386583, 1.68531469, 0.000714912254, 0.0216471436, 0.0, "6da9c13bccde5f9f"], + "openmoji/1F646-1F3FC": [0.0479619987, 0.0193545542, 0.943231441, 0.000700683508, 0.0511728241, 0.0, "a03c2369828afc5e"], + "openmoji/1F6B4-1F3FD-200D-2640-FE0F": [0.0134495273, 0.0266047112, 1.26704545, 0.000940044934, 0.00863088327, 0.0, "2ba2b1578ae080d1"], + "openmoji/1F6E0": [0.0553173684, 0.0280186859, 2.11160714, 0.000970870722, 0.0475990881, 0.000679404626, "a67064cb0bbd5905"], + "openmoji/1F938-1F3FB": [0.0303275809, 0.0255652497, 1.90350877, 0.000531174999, 0.0444163847, 0.0, "cfeb8ece0118f21b"], + "openmoji/1F93E-1F3FE": [0.0238679778, 0.0345684409, 2.03555556, 0.000487237936, 0.0286322206, 0.0, "05ad92bc29574549"], + "openmoji/1F9B3": [0.0399976596, 0.0167537657, 2.66666667, 0.000622258463, 0.10856776, 0.000382370602, "ad642b13e9e73b58"], + "openmoji/1F9D1": [0.0298969466, 0.0202067854, 1.19724771, 0.000576925231, 0.0292642352, 0.0, "091eecd44abf1f7e"], + "openmoji/1F9D1-1F3FC-200D-1FA70": [0.0284666009, 0.0361339697, 2.1, 0.000562905974, 0.0323603096, 0.0, "49ff8f10ce1f8b0c"], + "openmoji/1F9D1-1F3FD-200D-1F527": [0.0553818606, 0.0344657803, 1.36032389, 0.000992046553, 0.0553056796, 0.0, "6a35fb465b9e087b"], + "openmoji/1F9D1-200D-1F393": [0.0441286303, 0.0287081929, 0.377066116, 0.000757204369, 0.0355718017, 0.00102483815, "a106d142bdc5df63"], + "openmoji/1F9D6-1F3FD-200D-2642-FE0F": [0.0385646783, 0.0313023156, 1.29758713, 0.000681530393, 0.0371580061, 0.0, "06041601219ff75a"], + "openmoji/1FA8B": [0.0383650884, 0.0527143356, 0.594551282, 0.000564386428, 0.0648927939, 0.0, "74195ef19cae29d0"], + "openmoji/1FAC4-1F3FD": [0.0259975437, 0.0279614252, 0.958199357, 0.000538033026, 0.0342716371, 0.0, "9866bc9f6b69ba6f"], + "openmoji/25FC": [0.00289498759, 0.00556382052, 0.5, 0.00016265575, 0.000379874979, 0.0, "e82a56cbcc354bd6"], + "openmoji/2705": [0.0339026339, 0.0143476396, 1.90131579, 0.000697536569, 0.0214848827, 0.0, "514b01e504bda62f"], + "openmoji/E056": [0.0984522998, 0.0156572535, 0.681681682, 0.00156610517, 0.0521660706, 0.0, "7cbd090639633455"], + "openmoji/E1D1": [0.0339983366, 0.0167160102, 0.632947977, 0.000616764475, 0.0374657224, 0.0, "8802d34aa2a6077f"], + "openmoji/E30B": [0.0339531042, 0.0186644249, 1.20512821, 0.00132447295, 0.0460975952, 0.0, "7b647f824d05bbd5"], + "simple-icons/alchemy": [0.0263872575, 0.00801530511, 0.40754717, 0.000441457727, 0.0248305604, 0.0, "c7d44b49490ce75b"], + "simple-icons/appletv": [0.0171568003, 0.0215110159, 0.85380117, 0.000430866348, 0.0277674372, 0.000128315329, "108a387db10b3fb1"], + "simple-icons/atlassian": [0.0234036874, 0.00602320575, 1.04615385, 0.000402592676, 0.0245495505, 0.0, "f5fd95415a34f6dd"], + "simple-icons/autocad": [0.00599152269, 0.00788270269, 1.0, 0.0008682849, 0.0266892183, 0.0, "61836d45d58b2b9e"], + "simple-icons/bandrautomation": [0.0216168351, 0.0193260877, 0.940909091, 0.00111181231, 0.0627502776, 0.0, "9b0e560ceaef65b5"], + "simple-icons/bim": [0.0184470657, 0.017043028, 1.12056738, 0.000570379547, 0.00945491056, 0.0, "35a9fb1ca86aca46"], + "simple-icons/boosty": [0.0298823435, 0.00808693179, 1.38636364, 0.000525485782, 0.0464675465, 7.90712646e-05, "92fd7532b1d28f79"], + "simple-icons/changedetection": [0.0464720316, 0.0107768804, 0.612765957, 0.000890559808, 0.0269534877, 0.0, "ed4002df707d196f"], + "simple-icons/cocos": [0.0984564051, 0.02848451, 0.634456929, 0.00197306625, 0.0509589274, 6.76296316e-05, "6be6b22e4f4560ef"], + "simple-icons/contentstack": [0.0401308015, 0.0142939046, 0.323529412, 0.00112177536, 0.030919497, 0.0, "863a37dbbc95aa65"], + "simple-icons/debridlink": [0.023353247, 0.010158249, 0.763636364, 0.000513518171, 0.0305971996, 0.0, "7fab576b5cd0ef4d"], + "simple-icons/elixir": [0.0100599332, 0.00568612639, 1.05660377, 0.000204632335, 0.0226571266, 0.0, "225ebef7573aca86"], + "simple-icons/fampay": [0.0140308375, 0.0145220032, 0.946524064, 0.000357938261, 0.0186438048, 0.0, "5ab3037a016b3e89"], + "simple-icons/fluxer": [0.0346936099, 0.00998612512, 0.671052632, 0.000571695913, 0.0318978585, 0.0, "9174919b9f3fb72a"], + "simple-icons/googlechrome": [0.0271517225, 0.00849033628, 0.78021978, 0.000748234161, 0.0493761111, 0.0, "20e0c1682ad913cc"], + "simple-icons/h2database": [0.0484654494, 0.0101998617, 0.722513089, 0.00126797566, 0.045598424, 2.65725082e-05, "c4bc694ec7e668bc"], + "simple-icons/hitachi": [0.00783984736, 0.0388113644, 0.56462585, 0.000614929246, 0.0252501077, 0.0, "636f4693344be31c"], + "simple-icons/infinityfree": [0.0348987132, 0.038923597, 0.665859564, 0.000775206368, 0.0413967359, 0.0, "ee70c2b81f1805d7"], + "simple-icons/jdoodle": [0.0408449546, 0.0173845001, 0.590452261, 0.000692823844, 0.0321993867, 0.0, "8b52d1d375922360"], + "simple-icons/kleinanzeigen": [0.0396368727, 0.0091450881, 1.05333333, 0.000858157349, 0.0279423143, 5.08042078e-05, "9024d91c66310bc6"], + "simple-icons/leetcode": [0.0111904992, 0.00860061015, 0.235632184, 0.000753410161, 0.0371244205, 0.0, "05f8cc9291ff6994"], + "simple-icons/looker": [0.0195110012, 0.0195671809, 0.883977901, 0.000555330189, 0.0326906694, 8.80556752e-05, "905bcb81ae79b283"], + "simple-icons/mamp": [0.02956561, 0.0128891216, 1.4, 0.000632372103, 0.0428170534, 2.34357161e-05, "bb02200b695b5da6"], + "simple-icons/microeditor": [0.0420054458, 0.0149768826, 0.430612245, 0.000593776291, 0.0362182671, 0.000577421521, "2db1974e6baa08e8"], + "simple-icons/mysql": [0.0438853726, 0.0340179853, 0.591240876, 0.000929978269, 0.0382584036, 0.0, "90e61c8d33160a15"], + "simple-icons/notion": [0.0892286226, 0.00975704313, 1.20786517, 0.00143760222, 0.0466175995, 5.80109501e-05, "150efaa191eb18b9"], + "simple-icons/osano": [0.0181957576, 0.00473730752, 0.107142857, 0.000447860424, 0.0662201452, 0.0, "4268f5496413c17b"], + "simple-icons/phpstorm": [0.00897552818, 0.0106210256, 0.958333333, 0.000444748875, 0.037806602, 0.0, "d0d6f4a803033f11"], + "simple-icons/playerfm": [0.0461157523, 0.0109020575, 0.633333333, 0.000889901537, 0.0459590473, 0.00134758884, "59bf5d5cb2851dcd"], + "simple-icons/premierleague": [0.0512419231, 0.0375641903, 1.07345972, 0.000952357892, 0.04457909, 0.0, "579cecaee74efd01"], + "simple-icons/pronounsdotpage": [0.0335021019, 0.0104322994, 0.976744186, 0.000657324679, 0.0443452045, 0.0, "f7efccc8304e0485"], + "simple-icons/purescript": [0.00090032554, 0.0143472623, 1.14814815, 0.000467128353, 0.0370493552, 0.0, "4cc339a1174bfec8"], + "simple-icons/redsys": [0.015786171, 0.00777935709, 0.732394366, 0.000416176015, 0.0364879258, 9.12198145e-05, "e7587ff55e80d6e0"], + "simple-icons/sagemath": [0.106300771, 0.031161775, 0.762376238, 0.0019399157, 0.0476781548, 8.69318254e-05, "0e89f0de2a9d54d0"], + "simple-icons/slackware": [0.019868793, 0.0102036113, 0.90521327, 0.000742893841, 0.0160361501, 0.0, "4bca0d372d6e6533"], + "simple-icons/sparkar": [0.00111858011, 0.00683046199, 1.0, 0.00024002674, 0.00296751765, 0.0, "1cbcb44065082b2c"], + "simple-icons/stmicroelectronics": [0.0310504548, 0.0105321196, 0.87012987, 0.00063337438, 0.0515054115, 0.0, "38be363815a8757f"], + "simple-icons/ubiquiti": [0.0166623648, 0.0124232191, 0.371681416, 0.000369726447, 0.0243423076, 0.000143895415, "b79e0e73fd9ed0c8"], + "simple-icons/visa": [0.0157903023, 0.0215288375, 0.941176471, 0.000325790141, 0.0139761262, 0.0, "668c885ed4b93bee"], + "simple-icons/wxt": [0.0316828638, 0.0156873713, 1.1443299, 0.000751345826, 0.0325741054, 0.00369982327, "8bd42b78374a38ca"], + "synthetic/gradient_linear": [0.0854770467, 0.0034204243, 1.0, 0.000332257623, 0.337472378, 0.0381622787, "df1fa421bd6a2bf9"], + "synthetic/mosaic_grid6": [0.0773499906, 0.021074623, 2.45045045, 0.00051629846, 0.264316278, 0.0506000785, "559e6abb8e24c0eb"], + "synthetic/prim_ellipse": [0.00235147518, 0.00398260463, 1.0, 7.40450123e-05, 0.0131581307, 0.0, "3c562886b2293c07"], + "synthetic/prim_star5": [0.00882482808, 0.00685395697, 1.58333333, 0.000159045449, 0.0455970835, 8.57894327e-05, "c0c9e16cfec1e2e5"], + "synthetic/symmetry_rot3": [0.00693180272, 0.00633217241, 1.38888889, 0.000140176402, 0.0217202098, 0.0, "d57142694d2f0e9b"], + "twemoji/1f17e": [0.00667179609, 0.00495633322, 0.675, 0.000175946974, 0.0146529367, 0.0, "292852525b04e6c3"], + "twemoji/1f1f8": [0.00542800967, 0.00774735198, 0.740384615, 0.000147937724, 0.024598359, 0.0, "508bace10bab984c"], + "twemoji/1f1fa": [0.0113299666, 0.00533550519, 0.75, 0.000300361047, 0.0702160309, 0.0, "9e79693387d13741"], + "twemoji/1f325": [0.00991795491, 0.0175258017, 1.10928962, 0.000154874593, 0.0354054414, 0.0, "f054e3e625e9a417"], + "twemoji/1f369": [0.0185833555, 0.0167362014, 0.550561798, 0.000398213509, 0.031810753, 0.0, "68f667845610c330"], + "twemoji/1f3ca-1f3fe-200d-2640-fe0f": [0.0258559231, 0.0202999043, 1.02515723, 0.000341520645, 0.0395421862, 0.0, "96640611262a621a"], + "twemoji/1f3cc-1f3fb-200d-2640-fe0f": [0.0270374622, 0.035380024, 1.1755102, 0.000397246564, 0.0710068322, 0.00858168792, "eb476b887f03a02a"], + "twemoji/1f42b": [0.0230723787, 0.025864517, 1.15909091, 0.000357293291, 0.0547012968, 0.0, "559ff83545e85402"], + "twemoji/1f468-1f3fb-200d-1f91d-200d-1f468-1f3fd": [0.0338850431, 0.0358990192, 0.885106383, 0.000593415054, 0.0424357688, 0.00203342495, "985a421292d03c45"], + "twemoji/1f468-1f3fc-200d-1f9b0": [0.0125304731, 0.0185829737, 0.727272727, 0.000241443864, 0.0331885151, 0.0, "e74d2681bf374784"], + "twemoji/1f468-1f3fe-200d-2764-fe0f-200d-1f48b-200d-1f468-1f3ff": [0.0174926203, 0.0170912045, 0.576086957, 0.00040652373, 0.0327004528, 5.39611432e-05, "7ee0bfce9f0f7805"], + "twemoji/1f469-1f3fb-200d-1f37c": [0.0452548452, 0.0284202801, 0.882666667, 0.000571167096, 0.0766646802, 0.0028338819, "7117f95a47d23b02"], + "twemoji/1f469-1f3fc-200d-2764-fe0f-200d-1f468-1f3fc": [0.0238770097, 0.0174623396, 1.0, 0.000413861912, 0.0409903584, 0.00105710316, "c19259a1a13163c9"], + "twemoji/1f469-1f3fe": [0.0172255281, 0.00593246835, 0.424242424, 0.000321445026, 0.037857574, 0.0, "75d7bff81de72bc9"], + "twemoji/1f469-1f3ff-200d-1f91d-200d-1f468-1f3fc": [0.0425975658, 0.0345727815, 0.961206897, 0.000680827128, 0.0397322511, 0.00202814116, "73fbb81dbfc8b0da"], + "twemoji/1f469-200d-1f467-200d-1f467": [0.00721426681, 0.0159180341, 0.59375, 0.000213535546, 0.0252423021, 0.0, "fd21838bb4709cc5"], + "twemoji/1f470-1f3fc-200d-2640-fe0f": [0.0202149134, 0.0105740656, 1.02702703, 0.000326292822, 0.0273949303, 0.0, "67b313cc4fa3ef55"], + "twemoji/1f481-1f3fc-200d-2640-fe0f": [0.0253652204, 0.0160274596, 1.02364865, 0.000284895155, 0.0431807091, 9.90383235e-05, "42a698ca16ac3741"], + "twemoji/1f486-1f3ff": [0.0255003478, 0.0269853262, 1.42418033, 0.000613172306, 0.0426017019, 0.000340486748, "b5489027e9dc0bd6"], + "twemoji/1f4e6": [0.0220501553, 0.0130147805, 0.87295082, 0.000388921238, 0.0629460924, 0.0, "d39d83c3b2b490b2"], + "twemoji/1f53a": [0.0181886554, 0.00605014724, 1.0, 0.000138314048, 0.0799227998, 0.0, "a774b82e53ea62e0"], + "twemoji/1f57a-1f3fb": [0.0438044332, 0.0471706415, 0.617125984, 0.000688116997, 0.0784701518, 3.29429688e-05, "b3eabc9e4a1d0041"], + "twemoji/1f635": [0.0141348811, 0.00482513002, 0.102272727, 0.000265893934, 0.0226705442, 0.0, "6164ea87f54d061c"], + "twemoji/1f646-1f3fb-200d-2640-fe0f": [0.0320173316, 0.0130715701, 1.0310559, 0.000463536941, 0.0309843209, 0.00345716745, "e167d448241cdf6a"], + "twemoji/1f648": [0.0315456204, 0.0249944847, 0.882967607, 0.000672898081, 0.0413787292, 0.000457003972, "461ec38ec9586be3"], + "twemoji/1f64d-1f3fd": [0.015915826, 0.0201990746, 1.1953125, 0.000332994066, 0.0394932376, 0.0, "69be71012a5c335e"], + "twemoji/1f6a3-1f3ff-200d-2642-fe0f": [0.0293871053, 0.0213458943, 1.13366337, 0.000352966221, 0.0372995221, 0.0, "6ed529f9526a8450"], + "twemoji/1f6d6": [0.0311259814, 0.0475748393, 1.22235872, 0.000481190975, 0.154636742, 0.00280078667, "7f4b40762eea4081"], + "twemoji/1f7eb": [0.000198463502, 0.00316085024, 0.1875, 3.13711353e-05, 0.00534324551, 0.0, "e28886996c3ed6c8"], + "twemoji/1f91c-1f3fe": [0.0134985847, 0.0150126921, 0.83490566, 0.000192065359, 0.0816330119, 0.0, "d565f24ee32d36ee"], + "twemoji/1f938-1f3fe": [0.0287777036, 0.0537259631, 0.632562278, 0.000450475141, 0.0673791259, 7.26851413e-05, "aa51dd3b8f1f9400"], + "twemoji/1f977-1f3fb": [0.0246421117, 0.0305649804, 0.959745763, 0.000598451647, 0.0319055898, 0.0, "fce2abf86afbe48a"], + "twemoji/1f9a8": [0.0504824072, 0.0205893598, 2.08737864, 0.00116244657, 0.0443767729, 0.0, "7dc8e1f5e88862fb"], + "twemoji/1f9c9": [0.0192788634, 0.0197629649, 1.4083045, 0.000401951635, 0.0489668367, 0.0, "ea2663526666a5bc"], + "twemoji/1f9d1-1f3fd-200d-1f9af-200d-27a1-fe0f": [0.0268162154, 0.039089146, 0.57625, 0.000397859694, 0.0523468391, 0.0, "4ec082584a0bcb0f"], + "twemoji/1f9d1-1f3ff-200d-2764-fe0f-200d-1f9d1-1f3fb": [0.0236878674, 0.020271342, 1.18396226, 0.000541645335, 0.0388174826, 0.000529879833, "f15039037792543b"], + "twemoji/1f9d4-1f3fd": [0.0327290595, 0.0159206742, 0.814814815, 0.000478296512, 0.0545579707, 0.0, "a00bdcfe0628b3b3"], + "twemoji/1f9d8-1f3fe": [0.0287571047, 0.0338263874, 0.872703412, 0.000467159058, 0.0553664198, 0.0, "f71c12c3877f9b97"], + "twemoji/1f9e9": [0.0105758309, 0.0234195017, 0.825, 0.000200640716, 0.0331913116, 0.0, "cec1516e9fdf0713"], + "twemoji/1faa3": [0.0214504115, 0.0109297374, 3.0, 0.000515995373, 0.0287594596, 0.0, "7f8b86f9a91e23d1"], + "twemoji/1fae5": [0.0160186738, 0.021668455, 1.54761905, 0.000223433526, 0.0356767296, 0.0, "8ea1e462cafd3cce"], + "twemoji/2196": [0.000190561492, 0.00601528323, 0.476190476, 0.000107576721, 0.0012720454, 0.0, "7565c49fbabfe51f"], + "twemoji/271d": [0.00166170206, 0.0076332158, 0.826923077, 0.000144275895, 0.00262357375, 0.0, "b8c72cae893b585d"] } }, "quality-512ssop": { "tier": "512ssop", "args": [], "summary": { - "de00": 0.04942525255418097, - "turning": 0.01696918948137987, - "ratio": 1.9849073377124993, - "self_res": 0.0007285429217562323, + "de00": 0.038696575947080515, + "turning_gap": 1.8960152963048889, + "ratio_gap": 0.36462151656330255, + "geom": 0.09687272651059749, + "turning": 0.015396709759868479, + "ratio": 1.3189905299094815, + "self_res": 0.0006654488196125331, + "geom_far": 0.018731146988030696, "n": 246 }, "icons": { - "lucide/app-window-mac": [0.05706653, 0.00688475717, 2.25, 0.00046439073, "36edb13496f9732a"], - "lucide/audio-lines-x": [0.0538766459, 0.0109242307, 7.125, 0.000565667229, "219ef9fb14a530dc"], - "lucide/badge-russian-ruble": [0.0367803872, 0.0147062839, 4.38028169, 0.00067270291, "ef8949dea916139b"], - "lucide/bath": [0.0814310014, 0.011266815, 5.67567568, 0.0006779838, "5752f85be0b15fae"], - "lucide/bell": [0.0357460827, 0.00739137799, 3.28571429, 0.00047513179, "b4f18850aa552bda"], - "lucide/birdhouse": [0.0662799552, 0.0102845003, 6.45454545, 0.000872248958, "86634fb01a5ef583"], - "lucide/book-heart": [0.0362233259, 0.00676842495, 2.68852459, 0.000591936172, "7cf09c4843bd661b"], - "lucide/bug": [0.0513294302, 0.0156229667, 5.08108108, 0.00087625836, "93052e06c9a92144"], - "lucide/cat": [0.0304728579, 0.00923027703, 2.91549296, 0.000599221734, "88e3263e574f3674"], - "lucide/chess-king": [0.0371826813, 0.0102837193, 2.7125, 0.000648722809, "8c302553a1841636"], - "lucide/circle-arrow-right": [0.0540765375, 0.00596155788, 8.55555556, 0.000603111053, "6e0cd896cac47abe"], - "lucide/closed-caption": [0.0651504174, 0.00764084913, 6.5, 0.000576438149, "5884a5039cf0ea7f"], - "lucide/cooking-pot": [0.0373301096, 0.00799243522, 3.59090909, 0.00063147425, "f919a3f593f335f2"], - "lucide/diff": [0.0429748446, 0.0077062645, 14.6666667, 0.00041230151, "478e4ab1faf35234"], - "lucide/equal": [0.0573098846, 0.00532637718, 2.25, 0.000336456316, "828c36a0e0457c67"], - "lucide/file-digit": [0.0531664938, 0.0105391572, 3.08474576, 0.00057025993, "9d55586d61b3ece7"], - "lucide/focus": [0.0259896349, 0.0121798526, 4.5106383, 0.000494594278, "f3e9c97ed7323ec6"], - "lucide/folder-open": [0.0379540548, 0.00606977642, 2.35135135, 0.000563423324, "1981731187075227"], - "lucide/git-compare": [0.0354416966, 0.00995267779, 4.57142857, 0.000636067067, "83a14ee9e83252ab"], - "lucide/hard-drive-download": [0.0505063422, 0.0086159505, 5.3125, 0.000532950682, "e590aa88239e178e"], - "lucide/ice-cream-cone": [0.0226679351, 0.00863926352, 3.79411765, 0.000404148479, "5042bbf83f770453"], - "lucide/iteration-ccw": [0.018784605, 0.00701811179, 8.76923077, 0.00051544793, "8888106496f2c744"], - "lucide/list-checks": [0.0340821967, 0.00980930515, 7.85714286, 0.00039384127, "9f1df981d7002fe3"], - "lucide/message-circle-dashed-check": [0.0275217164, 0.0145779977, 6.03125, 0.000585952424, "f38ef292df3a7a9c"], - "lucide/messages-square": [0.0430507511, 0.00736652554, 2.43037975, 0.000714530062, "0ba852e3311ec57f"], - "lucide/navigation-2-off": [0.0198978614, 0.00835724436, 8.0, 0.000423192076, "125301b55278e476"], - "lucide/omega": [0.0181918573, 0.00727157011, 2.76744186, 0.000412436115, "e4f025b476fbbb3e"], - "lucide/panel-right": [0.0622567385, 0.00449030644, 7.0, 0.000842763984, "e01aebe70beb02f2"], - "lucide/pen-line": [0.0304405913, 0.00498638455, 2.52777778, 0.000487922196, "9b6e5cbe66b5af13"], - "lucide/phone-forwarded": [0.0441732258, 0.00829622879, 2.75, 0.000773740059, "e5ba8c81250b4af9"], - "lucide/rectangle-goggles": [0.0207072813, 0.00559980872, 2.1147541, 0.000540475186, "a92ced9d05c10196"], - "lucide/save-pen": [0.0795860887, 0.00868046087, 2.56382979, 0.0008078182, "a44de57f3547ae54"], - "lucide/shapes": [0.0207942501, 0.00826168766, 1.67647059, 0.000467801496, "ad9e0021be41fd99"], - "lucide/shopping-cart-plus": [0.0515187234, 0.0136862681, 5.53488372, 0.000648438756, "5a423258a65db0e6"], - "lucide/sparkle": [0.0432356447, 0.0079666515, 2.32857143, 0.000551949313, "dbbc4889c5f69eac"], - "lucide/square-minus": [0.110339627, 0.00455360966, 3.0, 0.000793083105, "7d4b2af35e5df8a7"], - "lucide/swiss-franc": [0.0282608774, 0.00890458252, 14.625, 0.000324354012, "b27c53db33a91598"], - "lucide/ticket-minus": [0.0213899743, 0.00868073355, 3.35185185, 0.000576602586, "0702f2d084d50d0d"], - "lucide/undo": [0.0169160757, 0.00721622499, 4.95, 0.000291771983, "4d1c2cdaf26c6bb1"], - "lucide/vegan": [0.0338083543, 0.00830725721, 6.46428571, 0.000799755333, "6fe40127438d4af8"], - "material-icons/12mp": [0.0897622705, 0.0113515445, 0.95625, 0.000722069759, "b2cc600562e431db"], - "material-icons/admin_panel_settings": [0.0247309208, 0.00885456264, 0.909836066, 0.000555569655, "8fd323132b4d40ac"], - "material-icons/arrow_drop_down": [0.00759741804, 0.00490294982, 2.0, 0.000128577754, "bb6b59c8af442a93"], - "material-icons/bento": [0.103418291, 0.00711677736, 0.4125, 0.000687707681, "0b38e9ac67faa8a0"], - "material-icons/border_left": [0.0578408092, 0.0200793491, 0.794117647, 0.00051134883, "a41a33e55e7afb02"], - "material-icons/call": [0.0222727675, 0.0087435118, 1.17431193, 0.00042664769, "6780ced7179e2165"], - "material-icons/chair": [0.0524535738, 0.00940202409, 1.2195122, 0.000662500795, "7005f7e645aacf3d"], - "material-icons/closed_caption": [0.0501163118, 0.00973145703, 0.884057971, 0.000411104789, "f3ec50cb3a9fc1da"], - "material-icons/crop_landscape": [0.0709302947, 0.00429184553, 0.45, 0.000439827214, "ce35ac5c15364150"], - "material-icons/dining": [0.137457475, 0.00802959163, 0.868055556, 0.00103080587, "9dbeb4b1b40d4318"], - "material-icons/double_arrow": [0.00922254287, 0.00610556569, 1.5, 0.000218140878, "fbae421d027ceee6"], - "material-icons/dynamic_feed": [0.043149475, 0.00739362923, 0.947368421, 0.000559653447, "e7cd4cb42cdabfd5"], - "material-icons/expand_circle_down": [0.00941376202, 0.00537873531, 0.4, 0.000406332634, "71765ac0bde6ec29"], - "material-icons/flight": [0.0310411435, 0.00764023883, 1.36363636, 0.000333733624, "ba2d5d05903eeda6"], - "material-icons/free_breakfast": [0.0454413816, 0.00674342146, 1.21126761, 0.000518200512, "55c5d5cccd403f4d"], - "material-icons/group_remove": [0.0342342295, 0.0105328425, 1.08955224, 0.000477889349, "4f05e603eb87e24d"], - "material-icons/headset": [0.0293542575, 0.00766022063, 1.30232558, 0.000358656369, "ad0332e5a9664117"], - "material-icons/houseboat": [0.0255814772, 0.0161125069, 1.21052632, 0.000438196439, "dcacd76ca680d78b"], - "material-icons/javascript": [0.00932108797, 0.013487456, 1.14583333, 0.000111269481, "ce987e27e16e8800"], - "material-icons/laptop": [0.0634341612, 0.00741054038, 2.5, 0.00069272652, "a42eec1069184bdd"], - "material-icons/lyrics": [0.0690830722, 0.0113960257, 1.54205607, 0.000702381658, "d46524ce38a37d8c"], - "material-icons/miscellaneous_services": [0.0284102932, 0.0197007425, 0.931034483, 0.000418374984, "85f61cc35d8012e2"], - "material-icons/music_note": [0.00639770785, 0.00730781109, 0.773584906, 0.000242510068, "1ac02f0fe40f1a66"], - "material-icons/no_food": [0.11079485, 0.0083810645, 1.37804878, 0.00154059881, "ffba562680600f2d"], - "material-icons/notifications_paused": [0.0495464876, 0.00992710532, 1.20652174, 0.000485274591, "a3bc41f47dab6698"], - "material-icons/perm_media": [0.0960895121, 0.00748146453, 2.125, 0.00107876316, "70180c5989966e59"], - "material-icons/phone_iphone": [0.0415261872, 0.00536046073, 0.308823529, 0.000437104376, "6f5275780f8bed6a"], - "material-icons/polyline": [0.0557654053, 0.0108375245, 1.17241379, 0.000409010419, "b38a23268e0d842e"], - "material-icons/qr_code": [0.0925044194, 0.0156453556, 1.5625, 0.000592160795, "0d046e714f09da92"], - "material-icons/report": [0.0409572385, 0.00650484476, 1.34146341, 0.000438181654, "2759aff1075dbf2f"], - "material-icons/rule_folder": [0.0468254723, 0.0088884334, 1.26190476, 0.000754143286, "e5aeb72c808a486e"], - "material-icons/sd_card_alert": [0.0351432376, 0.00618796874, 1.18, 0.000533938, "a378a3e81c6714ac"], - "material-icons/settings_overscan": [0.0454381444, 0.00737499056, 0.65625, 0.000455041067, "9e0eae0080f33bca"], - "material-icons/sms_failed": [0.105236247, 0.00656569493, 1.26, 0.000713767775, "1f9d55460bddfb50"], - "material-icons/storage": [0.134061113, 0.00780955087, 0.875, 0.000826667529, "6b4ee19180c217e1"], - "material-icons/table_rows": [0.0927718729, 0.00545819317, 0.535714286, 0.000573505939, "fadd7f94e5f41d8f"], - "material-icons/transfer_within_a_station": [0.0450575799, 0.012638056, 0.814814815, 0.000522613525, "74458cdb7c979af4"], - "material-icons/two_wheeler": [0.0294719618, 0.0159248217, 1.65217391, 0.000541693124, "87b2c5ae8005001e"], - "material-icons/video_camera_back": [0.0633537844, 0.00723689981, 1.34482759, 0.00068727386, "2d51666e09b6a6ca"], - "material-icons/view_week": [0.0967240185, 0.00562298042, 0.535714286, 0.000715981296, "667cb8f6f0462511"], - "noto-emoji/emoji_u0030": [0.0159586854, 0.00871249854, 1.2037037, 0.000339463208, "4ee4305c4e6dda68"], - "noto-emoji/emoji_u1f36a": [0.23039262, 0.0310458382, 1.21243523, 0.00240489026, "f2b19efb9aab5ade"], - "noto-emoji/emoji_u1f39e": [0.235331878, 0.0242246429, 0.909883721, 0.00179096265, "3846661da4844b63"], - "noto-emoji/emoji_u1f3c2_1f3fd": [0.176805869, 0.0309138323, 1.01043219, 0.00144821883, "f6eb79bcec811990"], - "noto-emoji/emoji_u1f3c4_1f3fe": [0.0729712993, 0.0463079565, 0.919140625, 0.00126161252, "ffac24e5150e08dc"], - "noto-emoji/emoji_u1f3cb_200d_2642": [0.112091899, 0.0660335992, 0.78156682, 0.00133971672, "b2c10bff12798236"], - "noto-emoji/emoji_u1f41b": [0.0303899143, 0.0296721694, 1.40488656, 0.000524628151, "305891b08cad7cc8"], - "noto-emoji/emoji_u1f44d_1f3fc": [0.0420282483, 0.0278496865, 1.45152355, 0.000691238092, "f541119d7810befc"], - "noto-emoji/emoji_u1f468_1f3fb_200d_2764_200d_1f468_1f3fd": [0.107441932, 0.0248784958, 0.901268116, 0.00113574264, "147aff5f98f5daef"], - "noto-emoji/emoji_u1f468_1f3ff_200d_1f393": [0.2174422, 0.0255740923, 1.16707617, 0.00229998305, "3f05b05667f0453e"], - "noto-emoji/emoji_u1f469_1f3fb_200d_1f52c": [0.205250725, 0.0318156862, 1.42698706, 0.00201194105, "8d01571fdb1454c0"], - "noto-emoji/emoji_u1f469_1f3fc_200d_1f91d_200d_1f468_1f3fb": [0.0987329185, 0.040368201, 0.620557157, 0.00120285142, "b5a3d70559a32f48"], - "noto-emoji/emoji_u1f469_1f3fe_200d_1faef_200d_1f469_1f3fd": [0.154319271, 0.0558751696, 0.788058341, 0.00174221955, "504ecbb5ec6ed995"], - "noto-emoji/emoji_u1f469_200d_1f469_200d_1f466_200d_1f466": [0.0325430408, 0.0149994258, 0.872516556, 0.000783224532, "a4190348ebb9a222"], - "noto-emoji/emoji_u1f46c_1f3fd": [0.0813485682, 0.0455030774, 0.571814672, 0.00100526493, "c447997131267f38"], - "noto-emoji/emoji_u1f470_1f3fb_200d_2640": [0.131760672, 0.0248603921, 1.34931507, 0.00169098785, "19a749fe70f63360"], - "noto-emoji/emoji_u1f482_1f3ff_200d_2640": [0.0537141562, 0.0255579143, 0.84375, 0.00100782304, "1489344997889b41"], - "noto-emoji/emoji_u1f4d8": [0.0800114498, 0.00925532005, 1.55714286, 0.00133346824, "bc7adde1c9e5b290"], - "noto-emoji/emoji_u1f520": [0.00955715496, 0.0120169266, 0.755707763, 0.000307125476, "318644d6d71bebde"], - "noto-emoji/emoji_u1f56f": [0.131086826, 0.0339616671, 1.26116838, 0.000702627294, "fd1bb9cc66bd98a5"], - "noto-emoji/emoji_u1f5a8": [0.0922896415, 0.0187736532, 1.75348837, 0.00170142006, "4e2ca9ac2dee4203"], - "noto-emoji/emoji_u1f62d": [0.141564399, 0.0222576502, 1.65165165, 0.00150137022, "add47178e10c5c82"], - "noto-emoji/emoji_u1f64b_1f3fe_200d_2640": [0.18221049, 0.0206561194, 0.974937343, 0.00204091729, "1c8101a799f5a094"], - "noto-emoji/emoji_u1f6c0_1f3ff": [0.119257152, 0.0684566427, 1.5520414, 0.0012253006, "f1d8e66c6bb4854d"], - "noto-emoji/emoji_u1f90d": [0.0113944877, 0.00892327876, 1.14204545, 0.00018573842, "8e9a871bc8930369"], - "noto-emoji/emoji_u1f91c_1f3fe": [0.0338897854, 0.0214080159, 1.42666667, 0.000570514123, "75c05b9de67872bd"], - "noto-emoji/emoji_u1f926_1f3ff": [0.201962873, 0.0398035504, 1.25382263, 0.00246507768, "09efe0f27bc2ce3b"], - "noto-emoji/emoji_u1f932": [0.0642032027, 0.0275838112, 1.30392157, 0.000830132922, "b926b9fa80d41481"], - "noto-emoji/emoji_u1f93c_1f3fe_200d_2640": [0.146165714, 0.0547781598, 0.832722273, 0.00166445458, "4776a596dad2ce95"], - "noto-emoji/emoji_u1f987": [0.0963350236, 0.0267038845, 1.10862069, 0.000991128152, "1b4cc993dd5cd862"], - "noto-emoji/emoji_u1f9be": [0.163846731, 0.0400072694, 1.91856287, 0.00162670144, "7959daf29067c199"], - "noto-emoji/emoji_u1f9ce_1f3fd_200d_2642": [0.0495177172, 0.0292920984, 0.694852941, 0.000633588759, "61b5562d8564c644"], - "noto-emoji/emoji_u1f9cf_1f3fc": [0.152793601, 0.0295195677, 1.36720554, 0.00165351934, "bdf5f9e0bb468699"], - "noto-emoji/emoji_u1f9d1_1f3fc_200d_1f37c": [0.0563320667, 0.0455771535, 1.10665914, 0.00087555038, "8efb117a7d34ac46"], - "noto-emoji/emoji_u1f9d1_1f3fd_200d_1f91d_200d_1f9d1_1f3ff": [0.153709143, 0.0612254656, 0.826034063, 0.00190536922, "1df9faaaf6439b56"], - "noto-emoji/emoji_u1f9d1_1f3fe_200d_1f9bc_200d_27a1": [0.0781841949, 0.0550363767, 1.15789474, 0.00121630519, "ab67d529d2a8824d"], - "noto-emoji/emoji_u1f9d6_1f3fe_200d_2642": [0.11995022, 0.0302166516, 1.56030702, 0.00127174531, "14cd03f86518375d"], - "noto-emoji/emoji_u1f9dd_1f3fd_200d_2640": [0.143738568, 0.0337095592, 1.40583942, 0.0023800265, "0f691dbc3896edd5"], - "noto-emoji/emoji_u1f9ed": [0.0551147088, 0.0258746001, 2.33755274, 0.000797082379, "5dff15c5b8d0ad5a"], - "noto-emoji/emoji_u1faa5": [0.0791545436, 0.0344210135, 1.02777778, 0.00105964288, "91443eef4e1afc2e"], - "noto-emoji/emoji_u1faf1_1f3fc_200d_1faf2_1f3ff": [0.066927433, 0.0350136045, 1.10482529, 0.00101299887, "351eacd4cf704299"], - "noto-emoji/emoji_u26bd": [0.0390941761, 0.0205100413, 1.91341991, 0.000778432703, "a950f56180533991"], - "noto-emoji/emoji_u2b05": [0.00843637437, 0.00691282881, 1.30769231, 0.000145157916, "dd929be640142359"], - "openmoji/1F195": [0.05671487, 0.0121274477, 6.26470588, 0.000655614014, "59813dfb84c0f93e"], - "openmoji/1F1FF-1F1F2": [0.0240947362, 0.00968765297, 2.375, 0.000228039047, "de977e73be18285f"], - "openmoji/1F361": [0.0340546593, 0.0153091751, 2.17142857, 0.000548638287, "ee785c21ea285e86"], - "openmoji/1F38A": [0.0394166261, 0.0185166518, 1.73958333, 0.000541801681, "0127a1f9a0a446a1"], - "openmoji/1F3A9": [0.0366864055, 0.00672511202, 1.28358209, 0.00060935918, "50d1c305d58d2cce"], - "openmoji/1F3C3-1F3FF-200D-2642-FE0F": [0.0218094215, 0.0171772891, 2.0880829, 0.000546513998, "e6019c062d916884"], - "openmoji/1F3CC-FE0F-200D-2640-FE0F": [0.0391917489, 0.0200231921, 1.71875, 0.000579559593, "416a1207c21995b5"], - "openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F": [0.0200626422, 0.00583474874, 3.7, 0.00032755037, "16dde8378c56b85d"], - "openmoji/1F442-1F3FF": [0.0222182106, 0.0166580512, 3.96491228, 0.000342878891, "743e83ba9b227583"], - "openmoji/1F468-1F3FC-200D-1F3ED": [0.0864452496, 0.0357040403, 0.665891473, 0.00130231783, "4051ecf929b7f579"], - "openmoji/1F468-1F3FF-200D-1F9B0": [0.0423579253, 0.015694451, 1.16538462, 0.000654327741, "694a15b8725af706"], - "openmoji/1F468-200D-1F9B1": [0.0515568182, 0.0272144157, 1.33944954, 0.000654382631, "6ae7b4462a609bb6"], - "openmoji/1F469-1F3FC-200D-2764-FE0F-200D-1F48B-200D-1F469-1F3FC": [0.0817826986, 0.0232696569, 2.14761905, 0.00100478134, "6705e784efd9ab20"], - "openmoji/1F469-1F3FF-200D-1F9B2": [0.033562392, 0.014217793, 1.53947368, 0.000457195216, "69c65cfd1d3c5fe7"], - "openmoji/1F481-1F3FB-200D-2642-FE0F": [0.0496275052, 0.0185482831, 1.90740741, 0.000728208281, "601d467a703a4e4c"], - "openmoji/1F49B": [0.023085136, 0.00636362474, 1.0, 0.000337658013, "c538e211a0363a83"], - "openmoji/1F517": [0.0377716087, 0.0197976113, 2.9020979, 0.000735593319, "378bd536c8cde871"], - "openmoji/1F646-1F3FC": [0.0539841726, 0.016456183, 1.12663755, 0.000768923259, "2e6aa4fb92b3a71b"], - "openmoji/1F6B4-1F3FD-200D-2640-FE0F": [0.0456628539, 0.0194321061, 2.375, 0.000794454478, "3824601a07643353"], - "openmoji/1F6E0": [0.0742805302, 0.0196744114, 2.48214286, 0.00116856897, "67cb0d3194c94607"], - "openmoji/1F938-1F3FB": [0.0371163972, 0.0190377402, 2.20614035, 0.000509469013, "09b72846c55b633b"], - "openmoji/1F93E-1F3FE": [0.0474289879, 0.0240728017, 2.64, 0.000599755265, "0cd723827a9caf9f"], - "openmoji/1F9B3": [0.022018088, 0.0107526331, 3.34848485, 0.000363662752, "b1fa40f679b1b1f3"], - "openmoji/1F9D1": [0.0448725149, 0.0149478147, 1.58715596, 0.000683508872, "b5180c8b872f3fbb"], - "openmoji/1F9D1-1F3FC-200D-1FA70": [0.0372530669, 0.0272377508, 2.57307692, 0.000598388899, "a66f73564bc57d38"], - "openmoji/1F9D1-1F3FD-200D-1F527": [0.0514760464, 0.0283400041, 1.41093117, 0.000940704311, "7d0225e20cdc78a1"], - "openmoji/1F9D1-200D-1F393": [0.0473107211, 0.0233336354, 0.443181818, 0.000936745142, "05c2be95f610dff0"], - "openmoji/1F9D6-1F3FD-200D-2642-FE0F": [0.0382147357, 0.0273562015, 1.73458445, 0.000598244311, "43425af5f0e7375a"], - "openmoji/1FA8B": [0.0493453667, 0.0381041578, 0.734775641, 0.000570738572, "8c83700aa92270d5"], - "openmoji/1FAC4-1F3FD": [0.0442319959, 0.0232794624, 1.11736334, 0.00081523339, "0de638e333edcf90"], - "openmoji/25FC": [0.00289744092, 0.00437690247, 0.75, 0.000162326483, "53ad9acdedb63c98"], - "openmoji/2705": [0.0564123467, 0.010845568, 2.15789474, 0.000811682723, "39097cca00b2d98c"], - "openmoji/E056": [0.0644278303, 0.0126544192, 0.747747748, 0.000919387036, "cfa12d2b49d3eda9"], - "openmoji/E1D1": [0.0404799841, 0.0135856935, 0.979768786, 0.000621970335, "999e25c07e638e7e"], - "openmoji/E30B": [0.0302610192, 0.0171519914, 1.32478632, 0.00129721174, "a727117c60d68604"], - "simple-icons/alchemy": [0.0406365916, 0.0079898848, 0.754716981, 0.000797070505, "4b2399ff683b1f69"], - "simple-icons/appletv": [0.0155167682, 0.0157447869, 1.57894737, 0.000395976618, "935bd08b7ac5b5c4"], - "simple-icons/atlassian": [0.0542536341, 0.0101872296, 2.70769231, 0.00102063059, "1adedb96d744911e"], - "simple-icons/autocad": [0.0152119556, 0.0069360816, 1.90322581, 0.000968520239, "ff02e15f9727e49c"], - "simple-icons/bandrautomation": [0.0482604019, 0.0143811569, 1.41363636, 0.00110661052, "0d67fc9c76f87161"], - "simple-icons/bim": [0.0228506941, 0.0134148745, 1.58865248, 0.000699246593, "4f3b391a5f3991ba"], - "simple-icons/boosty": [0.0268647727, 0.00770422378, 2.63636364, 0.000466881815, "a174239d35800d2c"], - "simple-icons/changedetection": [0.0520704873, 0.0116424789, 0.780851064, 0.00120201986, "759235d691faf4a1"], - "simple-icons/cocos": [0.128175408, 0.0216325146, 0.606741573, 0.00229546335, "987597de1e4d335d"], - "simple-icons/contentstack": [0.0534845926, 0.014484464, 0.980392157, 0.00122794358, "be7a0ebb22d01a7a"], - "simple-icons/debridlink": [0.0269609448, 0.010063393, 1.55151515, 0.000574841921, "418bf6459b73d924"], - "simple-icons/elixir": [0.01577501, 0.00685968084, 2.22641509, 0.000491595769, "ddcf1eca37cf8895"], - "simple-icons/fampay": [0.0256746933, 0.0117431881, 1.60427807, 0.000484335556, "cf5ed692f7a77ba6"], - "simple-icons/fluxer": [0.0330691002, 0.0101970805, 1.0745614, 0.000807475823, "454d767ad4601b93"], - "simple-icons/googlechrome": [0.0405607, 0.00964175823, 2.56043956, 0.000881662301, "948e22a65f065011"], - "simple-icons/h2database": [0.0438339338, 0.00962070794, 1.17277487, 0.00110934721, "d0d0811446d335c9"], - "simple-icons/hitachi": [0.00947872549, 0.0264267208, 0.734693878, 0.000618282997, "d57d2b208013ba6e"], - "simple-icons/infinityfree": [0.0502244011, 0.0269803118, 0.944309927, 0.000897803518, "dbbc310dae0f781d"], - "simple-icons/jdoodle": [0.0300885662, 0.015164851, 0.836683417, 0.000758843264, "37c5deb55b3c6ff9"], - "simple-icons/kleinanzeigen": [0.0471188389, 0.010028205, 1.74666667, 0.00104680762, "128f064b2f214c51"], - "simple-icons/leetcode": [0.0235504564, 0.00920253982, 1.51724138, 0.000691570167, "6b2b06887ac80d27"], - "simple-icons/looker": [0.0271279197, 0.0156264813, 1.65745856, 0.000606112648, "e8b96b09365498ef"], - "simple-icons/mamp": [0.0546686612, 0.0125948989, 2.66666667, 0.00137401244, "3f81223d01dbef6d"], - "simple-icons/microeditor": [0.037036512, 0.0115555813, 0.57755102, 0.000894445984, "9dfadf6eca2cc49b"], - "simple-icons/mysql": [0.0484251566, 0.0261599909, 0.669099757, 0.000957669457, "787bf2753cfdc89f"], - "simple-icons/notion": [0.130690649, 0.00797113922, 1.65730337, 0.00192548183, "1792d324ee1cb4f9"], - "simple-icons/osano": [0.0205661114, 0.0079287397, 3.82142857, 0.000595148595, "ad8e9645b6daf528"], - "simple-icons/phpstorm": [0.0100256074, 0.0106942066, 0.9375, 0.000442819088, "e1d660cc74301d4f"], - "simple-icons/playerfm": [0.0336085632, 0.010671846, 0.891666667, 0.000976175535, "b1a53a4781e96db1"], - "simple-icons/premierleague": [0.0619876422, 0.0306604114, 1.90521327, 0.00110376149, "7116868ac623d9b8"], - "simple-icons/pronounsdotpage": [0.0402365699, 0.0101772351, 2.1744186, 0.000739602314, "03e405931576a9e5"], - "simple-icons/purescript": [0.0121095683, 0.0123188877, 2.51851852, 0.000595176884, "26ba8927261d0b90"], - "simple-icons/redsys": [0.0417406, 0.0108003011, 1.85915493, 0.00105364819, "31b2ceefbab7ed9b"], - "simple-icons/sagemath": [0.108096279, 0.027077317, 0.994342291, 0.00199417863, "f89584ed05bb5a98"], - "simple-icons/slackware": [0.0269259587, 0.00792839954, 0.990521327, 0.00081298867, "d070f35aa1d71bea"], - "simple-icons/sparkar": [0.00903660804, 0.00691527762, 3.0, 0.000306326139, "a7d092bac888ecfc"], - "simple-icons/stmicroelectronics": [0.0420391224, 0.00895895113, 1.35714286, 0.000637651829, "27fb9ffd9358742a"], - "simple-icons/ubiquiti": [0.0258050282, 0.0126381096, 1.00884956, 0.000428225234, "4c1a416b3512cbf2"], - "simple-icons/visa": [0.0195864383, 0.0156225642, 1.49264706, 0.000365267741, "edf6bafc6fb309b7"], - "simple-icons/wxt": [0.0429142974, 0.016197762, 1.80412371, 0.00102793553, "a82894df32ad3538"], - "synthetic/gradient_linear": [0.0854768604, 0.0034204243, 1.0, 0.000332257623, "df1fa421bd6a2bf9"], - "synthetic/mosaic_grid6": [0.0756873861, 0.0218216859, 3.21621622, 0.000539188564, "f9ef5b639ed0f555"], - "synthetic/prim_ellipse": [0.00235147611, 0.00398260463, 1.0, 7.4045005e-05, "3c562886b2293c07"], - "synthetic/prim_star5": [0.00022116366, 0.00678917133, 1.08333333, 7.05993298e-05, "8dd23c16d139d573"], - "synthetic/symmetry_rot3": [0.00855858624, 0.00636233672, 1.66666667, 0.000161638425, "af9f00d1272c3b5b"], - "twemoji/1f17e": [0.00827313121, 0.0121310835, 1.7, 0.000212247061, "d1cb5d25de7aa5a1"], - "twemoji/1f1f8": [0.00761469314, 0.01474535, 1.53846154, 0.000188724662, "75c966f66152a119"], - "twemoji/1f1fa": [0.0146157816, 0.012891267, 1.69318182, 0.000309319788, "a07d97d46481a413"], - "twemoji/1f325": [0.0114183268, 0.0142790656, 1.9726776, 0.000163470511, "82f8a373d5ae3e5a"], - "twemoji/1f369": [0.017176358, 0.0176169688, 1.01123596, 0.000336745608, "9e023d920c3c364d"], - "twemoji/1f3ca-1f3fe-200d-2640-fe0f": [0.029113315, 0.0182340901, 1.62578616, 0.000338348706, "75dabaaabba07559"], - "twemoji/1f3cc-1f3fb-200d-2640-fe0f": [0.0295271967, 0.0320525665, 1.87755102, 0.000421252131, "b16e63edc92f12a9"], - "twemoji/1f42b": [0.0177745037, 0.0187013381, 2.28409091, 0.000283891044, "0b15e7970d440a8e"], - "twemoji/1f468-1f3fb-200d-1f91d-200d-1f468-1f3fd": [0.0429194905, 0.0327027477, 1.52340426, 0.000716175244, "c4fe03e05149d326"], - "twemoji/1f468-1f3fc-200d-1f9b0": [0.0132512646, 0.0153594854, 0.842975207, 0.000245372212, "5f7f3c94f982e428"], - "twemoji/1f468-1f3fe-200d-2764-fe0f-200d-1f48b-200d-1f468-1f3ff": [0.0257277563, 0.0226717278, 1.17753623, 0.000502485549, "a0302d187c5b4f22"], - "twemoji/1f469-1f3fb-200d-1f37c": [0.0622441173, 0.0288612773, 1.18533333, 0.000747366401, "d54931bd2d92a0ad"], - "twemoji/1f469-1f3fc-200d-2764-fe0f-200d-1f468-1f3fc": [0.0291662272, 0.0220259316, 1.44565217, 0.000512838771, "73b2cb99ca070332"], - "twemoji/1f469-1f3fe": [0.0278073289, 0.00966592398, 0.761363636, 0.000556856103, "47e3abd4178fecfb"], - "twemoji/1f469-1f3ff-200d-1f91d-200d-1f468-1f3fc": [0.0493857861, 0.0330966193, 1.69935345, 0.000861779088, "60218fde05066da3"], - "twemoji/1f469-200d-1f467-200d-1f467": [0.00842447765, 0.0210575386, 0.815104167, 0.000252004713, "4b01be90ce87d987"], - "twemoji/1f470-1f3fc-200d-2640-fe0f": [0.0269791819, 0.0119199523, 1.38648649, 0.000424901256, "685aa6bcd79f11d5"], - "twemoji/1f481-1f3fc-200d-2640-fe0f": [0.0337227732, 0.0175452597, 1.60135135, 0.000393918221, "7e51a048a52a34bb"], - "twemoji/1f486-1f3ff": [0.0377131775, 0.0241633627, 1.77459016, 0.000842632202, "8755b27efd70a13c"], - "twemoji/1f4e6": [0.0283306632, 0.0100393265, 1.03278689, 0.000434287009, "73675b002e9dfbcc"], - "twemoji/1f53a": [0.00974447187, 0.00406969545, 1.25, 9.31534087e-05, "bc8d40185a1e8dc4"], - "twemoji/1f57a-1f3fb": [0.0453223661, 0.0366172073, 0.67519685, 0.000698857475, "d156992094966a45"], - "twemoji/1f635": [0.0107621895, 0.0138719988, 1.27272727, 0.000285508722, "ce0be4c6f5a8c00f"], - "twemoji/1f646-1f3fb-200d-2640-fe0f": [0.0440347344, 0.0146626397, 1.63354037, 0.000675423129, "044731ed5e2c5ad1"], - "twemoji/1f648": [0.0420019515, 0.0214959538, 1.04597701, 0.000892547716, "61301dacdc02b199"], - "twemoji/1f64d-1f3fd": [0.0195637885, 0.0178976568, 1.75390625, 0.000400459976, "dda344e895abfaaa"], - "twemoji/1f6a3-1f3ff-200d-2642-fe0f": [0.031645529, 0.0255037995, 1.85148515, 0.000347278576, "775ab646f3c2691b"], - "twemoji/1f6d6": [0.0538979582, 0.0460250318, 1.63022113, 0.000747240381, "8fc0778d1114e0be"], - "twemoji/1f7eb": [0.00333041744, 0.0157628199, 2.5, 3.35236145e-05, "574225fe2bda033e"], - "twemoji/1f91c-1f3fe": [0.0216227937, 0.0128795799, 1.70754717, 0.000363593776, "bc53379c321d19a7"], - "twemoji/1f938-1f3fe": [0.0419247001, 0.0442129293, 0.722419929, 0.000559478998, "f2f7e30c1aa6c6e3"], - "twemoji/1f977-1f3fb": [0.0266160201, 0.0285966086, 2.02966102, 0.000652785937, "93a5c894168b9378"], - "twemoji/1f9a8": [0.0800600797, 0.0160205163, 1.98705502, 0.00174126728, "8e74b69916b36629"], - "twemoji/1f9c9": [0.0233015809, 0.0153044462, 1.38408304, 0.000439478172, "eed43af52e80cb03"], - "twemoji/1f9d1-1f3fd-200d-1f9af-200d-27a1-fe0f": [0.0331506617, 0.0326609478, 1.0925, 0.000462337164, "6bfa339fd92bc78f"], - "twemoji/1f9d1-1f3ff-200d-2764-fe0f-200d-1f9d1-1f3fb": [0.0445569642, 0.0243989994, 1.65566038, 0.000706655672, "08808ce412651d25"], - "twemoji/1f9d4-1f3fd": [0.0282809623, 0.0129706414, 1.28148148, 0.000608628383, "90019f9a14952f9a"], - "twemoji/1f9d8-1f3fe": [0.0330775343, 0.0298081431, 1.37270341, 0.000507857534, "91c551202b57eb95"], - "twemoji/1f9e9": [0.0115005672, 0.0123919957, 0.825, 0.000217891487, "df45a4047fbce12d"], - "twemoji/1faa3": [0.0218542032, 0.0104741532, 3.58333333, 0.000437742885, "365c1c2715fa763f"], - "twemoji/1fae5": [0.0223263726, 0.0297665017, 2.83333333, 0.000269060518, "cab8cd2445dc1c58"], - "twemoji/2196": [0.00346230762, 0.0141977591, 2.42857143, 0.000141034281, "9ecd3b4427b55293"], - "twemoji/271d": [0.0144883385, 0.0153157544, 1.53846154, 0.000148980165, "4da53aba4aa3822d"] + "lucide/app-window-mac": [0.00851386506, 0.00788343881, 1.83333333, 0.000516225817, 0.00553831046, 0.0, "c17e8acbe76b6d24"], + "lucide/audio-lines-x": [0.00631094724, 0.00184524965, 1.375, 0.000691761728, 0.00728561959, 0.0, "202ce9bd122de766"], + "lucide/badge-russian-ruble": [0.0118187033, 0.0131044628, 1.66197183, 0.00115290622, 0.0080125811, 0.000180611459, "a72e0ac4a86429e3"], + "lucide/bath": [0.00585521292, 0.00338273712, 1.16216216, 0.000557993015, 0.0072137298, 0.0, "701b36afb82fe994"], + "lucide/bell": [0.0154257035, 0.00532847335, 1.38095238, 0.000614046527, 0.0166339139, 0.0, "f040da00f28f32a0"], + "lucide/birdhouse": [0.005769148, 0.00372776869, 1.45454545, 0.000584965106, 0.00675874627, 0.0, "686739bc53bf0a15"], + "lucide/book-heart": [0.0385947563, 0.00689962286, 1.47540984, 0.000736715272, 0.0060851581, 0.0, "c8d2cd45f2b70e50"], + "lucide/bug": [0.0264997501, 0.00489744345, 1.40540541, 0.000932880503, 0.0149114283, 0.0, "177f023cf41fd481"], + "lucide/cat": [0.0309704766, 0.0104181299, 1.90140845, 0.000945162319, 0.0239944263, 0.0, "69da7571f5de1d1c"], + "lucide/chess-king": [0.0162332449, 0.00482836173, 1.125, 0.000905728724, 0.0160401719, 0.0, "b02eb6c1d9f4f669"], + "lucide/circle-arrow-right": [0.045110371, 0.00347593261, 2.0, 0.000601001841, 0.0187395006, 0.0, "fc6d1088acf38eee"], + "lucide/closed-caption": [0.0137017146, 0.00508175921, 1.3, 0.000714380585, 0.0052279284, 0.0, "9a6c865a0271a970"], + "lucide/cooking-pot": [0.00625561364, 0.00332969837, 1.13636364, 0.000598368933, 0.00450252876, 0.0, "92bca41fc6acaa13"], + "lucide/diff": [0.00339996372, 0.00213406742, 2.0, 0.000443776458, 0.00593100154, 0.0, "ec83e7b54148cf66"], + "lucide/equal": [0.00220693392, 0.00237502847, 1.25, 0.000372867915, 0.0066944891, 0.0, "ad2ee9324cd99577"], + "lucide/file-digit": [0.0180983432, 0.00500263258, 1.20338983, 0.000683414284, 0.0107853846, 0.0, "a6df1d764e7a36ff"], + "lucide/focus": [0.0108077955, 0.00609431079, 1.12765957, 0.000656501856, 0.0124583466, 0.0, "041c9f12f5e86984"], + "lucide/folder-open": [0.00689469418, 0.00478751259, 1.10810811, 0.000622424006, 0.00422503551, 0.0, "d72f04f29448df87"], + "lucide/git-compare": [0.00648094248, 0.00628969933, 1.21428571, 0.000689353154, 0.0072505525, 0.0, "ab9823ad3e6daa92"], + "lucide/hard-drive-download": [0.0110802008, 0.00643249196, 1.5, 0.000628976268, 0.00801714484, 0.0, "2569a6697faff988"], + "lucide/ice-cream-cone": [0.0172576085, 0.00707845132, 1.64705882, 0.000479724404, 0.0122755191, 0.0, "e09887032ac566d0"], + "lucide/iteration-ccw": [0.0197591316, 0.00332793793, 1.46153846, 0.000603530032, 0.0182190367, 0.0, "5869bffd150cc10d"], + "lucide/list-checks": [0.00624239352, 0.00322525278, 1.42857143, 0.000462101918, 0.0114579614, 0.0, "8c9b11d17a403d0d"], + "lucide/message-circle-dashed-check": [0.0200655907, 0.00416792286, 1.03125, 0.000882406777, 0.0227876892, 0.0, "a24babefa46ea4d8"], + "lucide/messages-square": [0.00471083308, 0.00542625891, 1.07594937, 0.000657773518, 0.00447849354, 0.0, "65e70f00de65b20b"], + "lucide/navigation-2-off": [0.0056634862, 0.00713946615, 2.25, 0.000326164067, 0.00460167412, 0.0, "950704e97b9918c2"], + "lucide/omega": [0.0152677195, 0.00698463941, 1.04651163, 0.000645147578, 0.0228255314, 0.0, "f12ae7ff6de6ce60"], + "lucide/panel-right": [0.00228982558, 0.00320324813, 1.75, 0.000857783249, 0.00224537891, 0.0, "2f1aa7cdca066156"], + "lucide/pen-line": [0.00908099022, 0.00360629215, 1.38888889, 0.000539817032, 0.00502870437, 0.0, "fa68fc37d2766be8"], + "lucide/phone-forwarded": [0.012470549, 0.00488918406, 1.05681818, 0.000848029566, 0.0102001242, 0.0, "d95abdef33e72c74"], + "lucide/rectangle-goggles": [0.00486811437, 0.00509450753, 1.19672131, 0.000568569405, 0.00396545798, 0.0, "2f7d37bb433fdc18"], + "lucide/save-pen": [0.011578165, 0.00501123884, 1.14893617, 0.00087808352, 0.00652069125, 0.0, "d8663bcb18af56ac"], + "lucide/shapes": [0.00986514054, 0.00742611013, 1.41176471, 0.000641527295, 0.0120500902, 0.0, "9ec8794dc8f1bda4"], + "lucide/shopping-cart-plus": [0.0232629813, 0.00590713009, 1.48837209, 0.000659778074, 0.00874820675, 0.0, "0e7f3c8e7fae5022"], + "lucide/sparkle": [0.00481138844, 0.00635649213, 1.11428571, 0.000406571926, 0.00595783138, 0.0, "fecf57e7a216c468"], + "lucide/square-minus": [0.00327487895, 0.0033874643, 1.75, 0.000838156324, 0.00375897613, 0.0, "113af6e8b72940a2"], + "lucide/swiss-franc": [0.00376445265, 0.00266771112, 1.75, 0.000309379422, 0.00511783965, 0.0, "cf25b45533d93899"], + "lucide/ticket-minus": [0.00458021089, 0.00667897369, 1.14814815, 0.00068986183, 0.00533855356, 0.0, "56743433ee1e459f"], + "lucide/undo": [0.0153130274, 0.00300613371, 0.95, 0.000400438526, 0.0194346316, 0.0, "1cbc3726e62f5f9e"], + "lucide/vegan": [0.0454021394, 0.00515614143, 3.46428571, 0.00112198468, 0.0234693012, 0.0, "bbdc5681b5e9f706"], + "material-icons/12mp": [0.0835538805, 0.0128633896, 0.90625, 0.00077000045, 0.00146367129, 0.0, "405089775566df52"], + "material-icons/admin_panel_settings": [0.0226420406, 0.00873754215, 0.885245902, 0.00047819849, 0.0198535554, 0.0, "c6e5a2a5eb8dcb05"], + "material-icons/arrow_drop_down": [0.00733127631, 0.00490298247, 2.0, 0.000127620311, 0.0129393374, 0.0, "f921184ae009c80e"], + "material-icons/bento": [0.0950654224, 0.00711675049, 0.4125, 0.000685613311, 0.00141029427, 0.0, "74ebbdbccca7c226"], + "material-icons/border_left": [0.0686973706, 0.0200797769, 0.794117647, 0.000511349004, 0.0, 0.0, "0888b201761dc7b8"], + "material-icons/call": [0.0166107044, 0.00678605447, 0.449541284, 0.00041797114, 0.028970115, 0.0, "3fc02edb5a2d92c4"], + "material-icons/chair": [0.0453467891, 0.00874095239, 0.926829268, 0.000631369825, 0.0100328149, 0.0, "83262be8266dd2de"], + "material-icons/closed_caption": [0.0549726561, 0.0096997954, 0.884057971, 0.00040998272, 0.00187379024, 0.0, "5d52eeddb8b7635e"], + "material-icons/crop_landscape": [0.0431680232, 0.00429172245, 0.45, 0.000431300141, 0.00110325169, 0.0, "a8cbb1228e2c9321"], + "material-icons/dining": [0.0303561874, 0.00916756364, 0.833333333, 0.00105729944, 0.00467517827, 0.0, "60623b18f36797d1"], + "material-icons/double_arrow": [0.0174490362, 0.0061056885, 1.5, 0.000219726542, 0.00273214777, 0.0, "df8dcf03d78d891a"], + "material-icons/dynamic_feed": [0.0503160544, 0.00738753553, 0.842105263, 0.000530362653, 0.00638057235, 0.0, "71461482365a6b85"], + "material-icons/expand_circle_down": [0.0137451654, 0.00537864986, 0.4, 0.000397296972, 0.0159299511, 0.0, "e5ad480cd545931c"], + "material-icons/flight": [0.0295101125, 0.00763921314, 1.27272727, 0.000321526633, 0.0174477116, 0.0, "a97cfa91f1bf0b8b"], + "material-icons/free_breakfast": [0.0442805588, 0.00677327003, 1.12676056, 0.000452482927, 0.0061594072, 0.0, "f0fba09c56f38b2f"], + "material-icons/group_remove": [0.0316309072, 0.0104949581, 1.07462687, 0.000503170188, 0.0147079466, 0.0, "bed2af0ccb4b2653"], + "material-icons/headset": [0.0253069121, 0.00767976307, 1.13953488, 0.000348409027, 0.0123202105, 0.0, "2168e69615f52a7d"], + "material-icons/houseboat": [0.0230028406, 0.0160413115, 1.22368421, 0.000417537318, 0.0111084802, 0.0, "295b71666b930864"], + "material-icons/javascript": [0.00909069739, 0.0134731511, 1.14583333, 0.000108157888, 0.00288336602, 0.0, "806070077b2929d3"], + "material-icons/laptop": [0.0743751377, 0.00528515129, 1.375, 0.000566011295, 0.0059574862, 0.0, "104145b642fa6c36"], + "material-icons/lyrics": [0.0668423697, 0.0114069985, 1.54205607, 0.000681459904, 0.0113436759, 0.0, "cd904afcf0595c22"], + "material-icons/miscellaneous_services": [0.0214354116, 0.0197552448, 0.942528736, 0.000351086812, 0.0184688162, 0.0, "cd9cf2f2acbcff2b"], + "material-icons/music_note": [0.0397934765, 0.00734825621, 0.735849057, 0.000553131104, 0.0798366884, 0.0, "91696fa22c1a1e37"], + "material-icons/no_food": [0.0848144665, 0.00875802531, 1.40243902, 0.00120357436, 0.0356582195, 0.0024947309, "affd72c6a8cc8609"], + "material-icons/notifications_paused": [0.0515921861, 0.0099460682, 1.2173913, 0.000499411195, 0.00866810043, 0.0, "9e33abac360bab5f"], + "material-icons/perm_media": [0.0764962211, 0.00725917624, 1.65, 0.000999826472, 0.00998160982, 0.0, "fdb134b167cda35f"], + "material-icons/phone_iphone": [0.0415261798, 0.00536046073, 0.308823529, 0.000437104463, 0.00148821499, 0.0, "6f5275780f8bed6a"], + "material-icons/polyline": [0.0578731373, 0.0108366906, 1.10344828, 0.000405494851, 0.00962705528, 0.0, "0ce30ee3a71509e4"], + "material-icons/qr_code": [0.0742918104, 0.0166124319, 1.125, 0.000594210171, 0.0, 0.0, "4e50e34c3911e991"], + "material-icons/report": [0.0304191131, 0.0067719711, 0.756097561, 0.000407499465, 0.0002365398, 0.0, "dd5a00b46e16a937"], + "material-icons/rule_folder": [0.0481158867, 0.00884174876, 1.14285714, 0.000617128273, 0.00694663461, 0.0, "5cb37653c01046eb"], + "material-icons/sd_card_alert": [0.0364013761, 0.00618813757, 1.18, 0.000533608778, 0.00189962699, 0.0, "058c58913b3b10fd"], + "material-icons/settings_overscan": [0.031018395, 0.00737505634, 0.65625, 0.0004523932, 0.000857231082, 0.0, "052ab4a3b0829777"], + "material-icons/sms_failed": [0.0815230757, 0.006518347, 1.18, 0.00067677215, 0.00833283064, 0.0, "b49c7568509aaf34"], + "material-icons/storage": [0.123084128, 0.00780946767, 0.875, 0.000824827293, 0.0, 0.0, "2fb183c1646c5306"], + "material-icons/table_rows": [0.0925285593, 0.00545677796, 0.535714286, 0.000568329997, 0.000517506951, 0.0, "fa31283a71529966"], + "material-icons/transfer_within_a_station": [0.0450271592, 0.0126430155, 0.814814815, 0.000518200395, 0.00843953171, 0.0, "350c93e371721a5a"], + "material-icons/two_wheeler": [0.0295072198, 0.0155591878, 1.60144928, 0.000562677218, 0.0337608356, 0.0, "0c4d17489159d76b"], + "material-icons/video_camera_back": [0.061212156, 0.00722002095, 1.27586207, 0.000648004876, 0.0173459561, 0.000337007146, "a29d363339485d96"], + "material-icons/view_week": [0.0967838392, 0.00562296978, 0.535714286, 0.000714395486, 0.00106593177, 0.0, "3c52a16a42975ea2"], + "noto-emoji/emoji_u0030": [0.0135044595, 0.00855128889, 0.703703704, 0.000185070166, 0.297114433, 0.0, "1cfdc0497a5f8b00"], + "noto-emoji/emoji_u1f36a": [0.086374186, 0.0255924883, 1.06822107, 0.00107016962, 0.493381166, 0.112704678, "df12a25fccf3a791"], + "noto-emoji/emoji_u1f39e": [0.244634107, 0.0235594468, 0.840116279, 0.00177654682, 1.1304499, 0.259170405, "7e4e1eb7fab79746"], + "noto-emoji/emoji_u1f3c2_1f3fd": [0.121353365, 0.0289984447, 0.903129657, 0.0010414921, 0.875306829, 0.461193027, "252803b3eb6732ad"], + "noto-emoji/emoji_u1f3c4_1f3fe": [0.0629738942, 0.0452932839, 0.916015625, 0.00110536453, 0.0533930182, 6.41743007e-06, "c18570a7fa3314e6"], + "noto-emoji/emoji_u1f3cb_200d_2642": [0.0999817327, 0.0579157938, 0.703225806, 0.00122260302, 0.406134798, 0.0305294617, "ca32f6780cb382c9"], + "noto-emoji/emoji_u1f41b": [0.0301130544, 0.0300221885, 1.39790576, 0.000502093928, 0.0428042833, 0.0, "259ed37f9d1ce45a"], + "noto-emoji/emoji_u1f44d_1f3fc": [0.0379092768, 0.029576524, 1.49030471, 0.00064316293, 0.0582809208, 0.0, "f897bce05d8899b1"], + "noto-emoji/emoji_u1f468_1f3fb_200d_2764_200d_1f468_1f3fd": [0.0978079587, 0.0251809527, 0.809782609, 0.000884486188, 0.420985188, 0.0585449683, "9d21efb705012a23"], + "noto-emoji/emoji_u1f468_1f3ff_200d_1f393": [0.126048729, 0.0263193899, 0.964373464, 0.00128846511, 0.537386162, 0.099228204, "57b24d91169f94bd"], + "noto-emoji/emoji_u1f469_1f3fb_200d_1f52c": [0.220285743, 0.0310225619, 1.23197782, 0.00207556947, 0.373368269, 0.0253969192, "005f7657b3f96c7f"], + "noto-emoji/emoji_u1f469_1f3fc_200d_1f91d_200d_1f468_1f3fb": [0.0884050578, 0.0392339512, 0.536023055, 0.00113366323, 0.679429882, 0.118340476, "fc3a1aa242f1e4f5"], + "noto-emoji/emoji_u1f469_1f3fe_200d_1faef_200d_1f469_1f3fd": [0.105507001, 0.0478929138, 0.65952598, 0.00107379991, 0.535091126, 0.11177648, "3f4bf1cf6de7859a"], + "noto-emoji/emoji_u1f469_200d_1f469_200d_1f466_200d_1f466": [0.0316440128, 0.0146794174, 0.874172185, 0.000763522869, 0.034668645, 0.0, "6db8fd117e87400a"], + "noto-emoji/emoji_u1f46c_1f3fd": [0.0792325512, 0.0427245011, 0.446332046, 0.000937662553, 0.435683576, 0.0439889007, "cf5ca608df5544f5"], + "noto-emoji/emoji_u1f470_1f3fb_200d_2640": [0.105245188, 0.0208636238, 1.10958904, 0.00125698512, 0.779082497, 0.340231647, "a0d1e0e5a4a424f6"], + "noto-emoji/emoji_u1f482_1f3ff_200d_2640": [0.0382039249, 0.0253920902, 0.869959677, 0.000724802434, 0.416462329, 0.296732635, "544307e88e7d30fe"], + "noto-emoji/emoji_u1f4d8": [0.0832966566, 0.00928637292, 1.48095238, 0.00138644048, 0.203011508, 0.0676788243, "88e46884a0794be0"], + "noto-emoji/emoji_u1f520": [0.010290633, 0.0121923657, 0.737442922, 0.000281265355, 0.0391716639, 0.000112400757, "5713c88c9a02778f"], + "noto-emoji/emoji_u1f56f": [0.125071228, 0.0240935766, 0.800687285, 0.000624942128, 1.50148228, 0.515778642, "7a0a63c1ab363141"], + "noto-emoji/emoji_u1f5a8": [0.0777379498, 0.0184489853, 1.73023256, 0.00142840203, 0.190073531, 0.0421422347, "19597f0227367fa7"], + "noto-emoji/emoji_u1f62d": [0.0954876766, 0.0214944895, 1.44894895, 0.00104349677, 0.780733009, 0.120030984, "f72045e942fdfc3b"], + "noto-emoji/emoji_u1f64b_1f3fe_200d_2640": [0.113821685, 0.0191838151, 0.85839599, 0.00111773622, 0.492781215, 0.07533917, "49e2076f49d8225e"], + "noto-emoji/emoji_u1f6c0_1f3ff": [0.0950199217, 0.0647892988, 1.4519839, 0.000982197234, 0.208336887, 0.00301011501, "c468350282fcad9f"], + "noto-emoji/emoji_u1f90d": [0.0101342099, 0.00988028191, 1.15340909, 0.000168968632, 0.106507094, 0.0, "b745354f988c249b"], + "noto-emoji/emoji_u1f91c_1f3fe": [0.0363812819, 0.0212228394, 1.42888889, 0.000643058214, 0.0529561309, 0.000128964702, "4856d7c3b77f7c01"], + "noto-emoji/emoji_u1f926_1f3ff": [0.138234809, 0.0452887226, 1.24847095, 0.00171530235, 0.538934713, 0.105981864, "155577dbb7508ca3"], + "noto-emoji/emoji_u1f932": [0.0670124665, 0.0275715793, 1.33600713, 0.000840539869, 0.0760006869, 0.00136695015, "5b0db8d18b894471"], + "noto-emoji/emoji_u1f93c_1f3fe_200d_2640": [0.0994194672, 0.0504924008, 0.702108158, 0.00105177937, 0.467429581, 0.0472786739, "61adddd5731ee2ff"], + "noto-emoji/emoji_u1f987": [0.0434398353, 0.0286882388, 1.00517241, 0.000575759972, 0.221084701, 0.00299874744, "787097a6e60fbe02"], + "noto-emoji/emoji_u1f9be": [0.138682961, 0.0351763778, 1.77125749, 0.00137559476, 0.434102418, 0.161612185, "022db19fd976f5e9"], + "noto-emoji/emoji_u1f9ce_1f3fd_200d_2642": [0.0311977994, 0.0278907502, 0.594362745, 0.000374787807, 0.173129853, 7.61378481e-06, "89e5c59f613f0d66"], + "noto-emoji/emoji_u1f9cf_1f3fc": [0.106492467, 0.0274069517, 1.31755196, 0.00121077488, 0.769538201, 0.362290839, "29c7bceac29fe5b3"], + "noto-emoji/emoji_u1f9d1_1f3fc_200d_1f37c": [0.0468073711, 0.0445250113, 1.04232506, 0.000731589098, 0.064698603, 0.000788102789, "eb6c91f8676174e3"], + "noto-emoji/emoji_u1f9d1_1f3fd_200d_1f91d_200d_1f9d1_1f3ff": [0.127146319, 0.063229953, 0.773317113, 0.00170576305, 0.419334643, 0.0542328551, "98c9d5fffef3fd27"], + "noto-emoji/emoji_u1f9d1_1f3fe_200d_1f9bc_200d_27a1": [0.0691624135, 0.0507130008, 1.06390977, 0.00115487596, 0.282150787, 0.0389399589, "d61c064d25871124"], + "noto-emoji/emoji_u1f9d6_1f3fe_200d_2642": [0.146118149, 0.0288865031, 1.36184211, 0.00132569449, 0.938965958, 0.663870613, "cd839996a46b390e"], + "noto-emoji/emoji_u1f9dd_1f3fd_200d_2640": [0.0921297371, 0.0341157118, 1.29124088, 0.00145019835, 0.861419712, 0.389813623, "093c291b8687c1d0"], + "noto-emoji/emoji_u1f9ed": [0.034787491, 0.019769929, 1.56540084, 0.00062416424, 0.0429404035, 0.0, "30e41345fd7b9dcd"], + "noto-emoji/emoji_u1faa5": [0.0517110936, 0.028704056, 0.817708333, 0.00063371344, 0.527959729, 0.211417892, "f493b2bd057c3dc4"], + "noto-emoji/emoji_u1faf1_1f3fc_200d_1faf2_1f3ff": [0.0553316958, 0.0343352009, 1.12312812, 0.000866674352, 0.0654801788, 0.000123338065, "7c2caa6b16a52b08"], + "noto-emoji/emoji_u26bd": [0.0379688963, 0.0212500901, 1.76623377, 0.000728043728, 0.039764311, 0.0, "621249dc79f970f2"], + "noto-emoji/emoji_u2b05": [0.00704205781, 0.00703016196, 1.25641026, 0.000138097021, 0.0358267141, 0.0, "0ba6e2a6530204b2"], + "openmoji/1F195": [0.0141981384, 0.00959239644, 2.85294118, 0.000549480959, 0.0100693186, 0.0, "c84056ab41e2d74d"], + "openmoji/1F1FF-1F1F2": [0.019754, 0.0098058729, 2.35416667, 0.000212850122, 0.00134211752, 0.0, "c4727f0309c471bc"], + "openmoji/1F361": [0.0279969182, 0.0144373921, 1.57142857, 0.000543731439, 0.0469361145, 0.000285573925, "9b919b409d0bd6c8"], + "openmoji/1F38A": [0.0273664892, 0.0150663539, 0.953125, 0.000785129552, 0.0163818782, 0.0, "d9077d93d144c31b"], + "openmoji/1F3A9": [0.0114858253, 0.00545435285, 1.0, 0.000478218426, 0.0155883294, 0.0, "f68b4dc3540c9254"], + "openmoji/1F3C3-1F3FF-200D-2642-FE0F": [0.0157262944, 0.0165732218, 2.00518135, 0.000405699277, 0.0312250971, 0.0, "1c2065aed4f43247"], + "openmoji/1F3CC-FE0F-200D-2640-FE0F": [0.0146789765, 0.0149327157, 1.3359375, 0.000610600866, 0.0140981103, 0.0, "ac59ba82191824cb"], + "openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F": [0.0315539129, 0.00494646247, 1.3, 0.000432207715, 0.0201617433, 0.00487129367, "e6f5ee159b8bc6f8"], + "openmoji/1F442-1F3FF": [0.0228842702, 0.0160492501, 3.21052632, 0.000424732832, 0.0515859614, 0.000769939722, "1bff181a4c87de0a"], + "openmoji/1F468-1F3FC-200D-1F3ED": [0.0546250157, 0.0321768333, 0.575193798, 0.000880491978, 0.043394121, 0.0, "38ec5701c3916234"], + "openmoji/1F468-1F3FF-200D-1F9B0": [0.0296296701, 0.0138134395, 0.834615385, 0.000481594325, 0.0349328776, 0.0, "3202cc2299787148"], + "openmoji/1F468-200D-1F9B1": [0.0558624603, 0.0248065219, 1.20412844, 0.000693302543, 0.0908591434, 0.0, "303655509d3e573a"], + "openmoji/1F469-1F3FC-200D-2764-FE0F-200D-1F48B-200D-1F469-1F3FC": [0.0516499132, 0.0174843869, 1.36904762, 0.00096631021, 0.0286570234, 0.0, "304fd7f54d5e9a90"], + "openmoji/1F469-1F3FF-200D-1F9B2": [0.0238168277, 0.0123291337, 1.00657895, 0.000409469125, 0.0530245298, 0.0, "805cb51bb3b56e66"], + "openmoji/1F481-1F3FB-200D-2642-FE0F": [0.0425773524, 0.0170021964, 1.32592593, 0.000811249018, 0.0462936568, 0.0, "894b6de1c39c5dee"], + "openmoji/1F49B": [0.0198989622, 0.00636319591, 1.0, 0.000301914581, 0.0325134159, 0.0, "4cf4be47a8846eab"], + "openmoji/1F517": [0.0210679732, 0.0207039487, 2.03146853, 0.00079150236, 0.0329510007, 0.0, "5ec2fecdc68c7321"], + "openmoji/1F646-1F3FC": [0.0469866134, 0.0147469102, 0.962882096, 0.000678866461, 0.0476823203, 0.0, "dfaeca7b18f479c1"], + "openmoji/1F6B4-1F3FD-200D-2640-FE0F": [0.0132176559, 0.0172219587, 1.27272727, 0.000931713672, 0.00867839272, 0.0, "1fa2153592957752"], + "openmoji/1F6E0": [0.0593961887, 0.019815681, 2.13839286, 0.00107930007, 0.0469468597, 0.000679404626, "17204ba67d237860"], + "openmoji/1F938-1F3FB": [0.0302421134, 0.0178968103, 1.94736842, 0.000527639932, 0.0446259949, 0.0, "99ed765ede15b89b"], + "openmoji/1F93E-1F3FE": [0.0265678484, 0.0225944939, 2.06666667, 0.000512111874, 0.0340066757, 5.67724135e-05, "d2793ed549f227cf"], + "openmoji/1F9B3": [0.0178980511, 0.00957031699, 2.86363636, 0.000506641634, 0.0622244427, 0.000382370602, "67375f9e30f159a9"], + "openmoji/1F9D1": [0.0294406973, 0.0139795954, 1.22477064, 0.000567103329, 0.0282421388, 0.0, "8c9e18017d12bdd9"], + "openmoji/1F9D1-1F3FC-200D-1FA70": [0.0276884958, 0.0251984634, 2.10769231, 0.000556008308, 0.0317218593, 0.0, "b03ae19693ba4d97"], + "openmoji/1F9D1-1F3FD-200D-1F527": [0.0464943908, 0.0268043427, 1.36639676, 0.000883294444, 0.0478095683, 0.0, "b699b2813528b3d7"], + "openmoji/1F9D1-200D-1F393": [0.0402000658, 0.021972697, 0.384297521, 0.000720538956, 0.0513245559, 0.000991778858, "5822f3097aacf364"], + "openmoji/1F9D6-1F3FD-200D-2642-FE0F": [0.0384263583, 0.0226992659, 1.30563003, 0.000680691563, 0.035412328, 0.0, "e357ece229d47201"], + "openmoji/1FA8B": [0.037995439, 0.0375049207, 0.598557692, 0.000564091548, 0.0654896204, 0.0, "da2d729d1bae7cc0"], + "openmoji/1FAC4-1F3FD": [0.0272837896, 0.0215076501, 1.01446945, 0.000549121934, 0.0382591623, 0.000404022375, "53ae290205441007"], + "openmoji/25FC": [0.00289498735, 0.00437691322, 0.75, 0.000162655735, 0.000379874979, 0.0, "670980c021a26bf6"], + "openmoji/2705": [0.0306948591, 0.0096404209, 1.21052632, 0.000808396668, 0.0122796594, 0.0, "7075fca119826774"], + "openmoji/E056": [0.0694164857, 0.011940836, 0.429429429, 0.00130547408, 0.0225629478, 0.0, "41e8bff0138b6887"], + "openmoji/E1D1": [0.0337388366, 0.0129246627, 0.653179191, 0.000617791608, 0.0373845926, 0.0, "eae79c9da0d8050f"], + "openmoji/E30B": [0.0337791517, 0.0140498187, 1.23076923, 0.00132501649, 0.0464324156, 0.0, "187a18521e84e007"], + "simple-icons/alchemy": [0.028940022, 0.0078568865, 0.769811321, 0.00067053223, 0.0539531477, 0.0, "4af8825e70a006e0"], + "simple-icons/appletv": [0.013630324, 0.0158415195, 1.53216374, 0.000389002642, 0.021839269, 0.0, "c5cff9a7ba1cd5dc"], + "simple-icons/atlassian": [0.0598804541, 0.0104834941, 2.70769231, 0.00116300036, 0.105866292, 0.0, "4973dea19d67bd52"], + "simple-icons/autocad": [0.0190907586, 0.00695729883, 1.90322581, 0.000966855325, 0.0271857619, 0.0, "c95111a0be594576"], + "simple-icons/bandrautomation": [0.038581457, 0.0130374695, 0.995454545, 0.0010726928, 0.02573939, 0.0, "2cfb2af24229441b"], + "simple-icons/bim": [0.0208919067, 0.0126637439, 1.26241135, 0.000590066367, 0.0143380022, 0.0, "45079d60f6231c89"], + "simple-icons/boosty": [0.0333144069, 0.00588235549, 1.36363636, 0.000563614594, 0.04960404, 0.0, "841cadea991eec40"], + "simple-icons/changedetection": [0.0467261001, 0.0110461826, 0.795744681, 0.00116021011, 0.034367523, 0.0, "bafd345030c5a69d"], + "simple-icons/cocos": [0.115296394, 0.022516565, 0.609737828, 0.00223226589, 0.0540191682, 0.000202888895, "4235df7912e35d71"], + "simple-icons/contentstack": [0.0446389392, 0.0139524535, 1.01960784, 0.00112916471, 0.0388934058, 0.0, "f7db247e0def18c8"], + "simple-icons/debridlink": [0.0197443832, 0.00905972081, 1.40606061, 0.000476037996, 0.0235568731, 0.0, "8a1d808b362e87bc"], + "simple-icons/elixir": [0.0123852622, 0.0059978371, 1.30188679, 0.000266535731, 0.0290623059, 0.0, "ef17b7f5151c4e62"], + "simple-icons/fampay": [0.0123960664, 0.011361669, 1.67914439, 0.000365998392, 0.0202150437, 0.0, "a820214b4d091501"], + "simple-icons/fluxer": [0.0323215574, 0.0102345845, 1.10526316, 0.000812698796, 0.0468499796, 0.0, "27211ef45ea7114d"], + "simple-icons/googlechrome": [0.0423211791, 0.00966399086, 2.42857143, 0.000909359369, 0.0521681631, 0.0, "d8ce364407dc7230"], + "simple-icons/h2database": [0.0511105247, 0.00958154316, 1.2565445, 0.00118871825, 0.0486542625, 0.0, "4a195957ef5c28c2"], + "simple-icons/hitachi": [0.00835633185, 0.0264254553, 0.734693878, 0.000617878221, 0.0314187007, 0.0, "13ec30c9c5b96283"], + "simple-icons/infinityfree": [0.0429380015, 0.0288310435, 0.983050847, 0.0008530083, 0.0503911176, 0.0, "5620759c74f6643e"], + "simple-icons/jdoodle": [0.0387756005, 0.0134254804, 0.806532663, 0.000794703141, 0.0438424176, 3.71388543e-05, "f43012806c50c052"], + "simple-icons/kleinanzeigen": [0.0463218987, 0.00846919402, 1.20666667, 0.000918444537, 0.0468753491, 0.0, "0a5d6763f5af5d37"], + "simple-icons/leetcode": [0.0208931752, 0.0088557606, 1.56321839, 0.0006956773, 0.0502061322, 0.0, "3f99165852c8897c"], + "simple-icons/looker": [0.0266694799, 0.0159346434, 1.70165746, 0.000589294767, 0.0369393557, 0.000154097432, "a100c1fb1e799da6"], + "simple-icons/mamp": [0.0232438743, 0.0091958369, 1.425, 0.000554507365, 0.0379658601, 0.0, "6cb47fccd4f7faa5"], + "simple-icons/microeditor": [0.035565313, 0.0126641998, 0.604081633, 0.000912943215, 0.0469702541, 0.000577421521, "3674104f8c7c4cb2"], + "simple-icons/mysql": [0.047893744, 0.0260067829, 0.684914842, 0.000922398933, 0.0391293018, 0.0, "2cb689ae9352ffaa"], + "simple-icons/notion": [0.11430575, 0.00836782595, 1.66853933, 0.00178740162, 0.0647750269, 0.0, "86f9f463f9f0c520"], + "simple-icons/osano": [0.0204074029, 0.00796492921, 3.82142857, 0.000589425908, 0.0373413918, 0.0, "e941f6358279a9c2"], + "simple-icons/phpstorm": [0.0098586902, 0.010618174, 0.958333333, 0.00044534725, 0.0378328748, 0.0, "dc2497a268d6c6ba"], + "simple-icons/playerfm": [0.0334405228, 0.0105428089, 0.897222222, 0.000956033822, 0.0367139611, 0.0, "87e17340f307cca8"], + "simple-icons/premierleague": [0.0538202673, 0.0327947412, 1.8957346, 0.00100096606, 0.0474478159, 0.0, "dc0d5652600518d2"], + "simple-icons/pronounsdotpage": [0.0334125012, 0.010065434, 2.13953488, 0.000636329001, 0.0438686073, 0.0, "ef58f09bffa47dfa"], + "simple-icons/purescript": [0.00433801487, 0.0123683155, 2.55555556, 0.000503104588, 0.0426583207, 0.0, "12c8a2bab6e880ee"], + "simple-icons/redsys": [0.0260655507, 0.0103139702, 1.91549296, 0.000723915815, 0.0456403139, 0.0, "90df8442df4d8791"], + "simple-icons/sagemath": [0.104504876, 0.0272331202, 1.00707214, 0.00193410751, 0.0470301175, 8.69318254e-05, "a8da2e5759aa5d68"], + "simple-icons/slackware": [0.0204966869, 0.00759317376, 0.933649289, 0.000752871623, 0.0556284478, 0.0, "e8a69b5e57ba83f5"], + "simple-icons/sparkar": [0.0102074007, 0.00758961972, 3.16666667, 0.00029061627, 0.011379203, 0.0, "dd05311557147130"], + "simple-icons/stmicroelectronics": [0.0412437432, 0.00855771647, 1.27272727, 0.000669376168, 0.0495960358, 0.00076375031, "f655136be4ce58ec"], + "simple-icons/ubiquiti": [0.0197612345, 0.010911829, 0.884955752, 0.000390306814, 0.0295225426, 0.0, "4dbc5e0672ae35dc"], + "simple-icons/visa": [0.0219171681, 0.0175777254, 1.50735294, 0.000391468609, 0.0223085134, 0.0, "8eadc0e2fe0167e3"], + "simple-icons/wxt": [0.0324151628, 0.0161404406, 1.79896907, 0.000930311857, 0.0356279278, 0.0, "339b5250545bc19c"], + "synthetic/gradient_linear": [0.0854770467, 0.0034204243, 1.0, 0.000332257623, 0.337472378, 0.0381622787, "df1fa421bd6a2bf9"], + "synthetic/mosaic_grid6": [0.0773499906, 0.021074623, 2.45045045, 0.00051629846, 0.264316278, 0.0506000785, "559e6abb8e24c0eb"], + "synthetic/prim_ellipse": [0.00235147518, 0.00398260463, 1.0, 7.40450123e-05, 0.0131581307, 0.0, "3c562886b2293c07"], + "synthetic/prim_star5": [0.00882482808, 0.00685395697, 1.58333333, 0.000159045449, 0.0455970835, 8.57894327e-05, "c0c9e16cfec1e2e5"], + "synthetic/symmetry_rot3": [0.00693180272, 0.00633217241, 1.38888889, 0.000140176402, 0.0217202098, 0.0, "d57142694d2f0e9b"], + "twemoji/1f17e": [0.00963708386, 0.0120851178, 1.7, 0.000221028036, 0.0179514332, 0.0, "45b3f0866fccd6b5"], + "twemoji/1f1f8": [0.00844647363, 0.0146874752, 1.53846154, 0.00020297688, 0.0336609124, 0.0, "68a1f0af076cac9e"], + "twemoji/1f1fa": [0.0139346365, 0.0127482911, 1.68181818, 0.000325130386, 0.0703548664, 0.0, "bd0ca2077c180236"], + "twemoji/1f325": [0.0100964885, 0.0136663456, 1.75956284, 0.000152316657, 0.0328764813, 0.0, "59f39e5d250f34bf"], + "twemoji/1f369": [0.017749466, 0.0109597669, 0.552434457, 0.000319407351, 0.0282950711, 0.0, "65dd18a901541f02"], + "twemoji/1f3ca-1f3fe-200d-2640-fe0f": [0.0196793135, 0.0156862508, 1.03144654, 0.000326524634, 0.0359664518, 0.0, "e983a8c4f78039c3"], + "twemoji/1f3cc-1f3fb-200d-2640-fe0f": [0.0292421039, 0.0320733075, 1.82857143, 0.00041065496, 0.0645838369, 0.000176942019, "9e759089ab32f6b4"], + "twemoji/1f42b": [0.0194559023, 0.0186887674, 2.10227273, 0.000307956099, 0.044816073, 0.0, "b88000d86b3de590"], + "twemoji/1f468-1f3fb-200d-1f91d-200d-1f468-1f3fd": [0.030490689, 0.0297884297, 1.2787234, 0.000581901113, 0.0424357688, 0.0, "8754ed4690341b5e"], + "twemoji/1f468-1f3fc-200d-1f9b0": [0.0160181038, 0.0122806397, 0.73553719, 0.00024770599, 0.0416025049, 0.0, "6a7c581fe4c57cbe"], + "twemoji/1f468-1f3fe-200d-2764-fe0f-200d-1f48b-200d-1f468-1f3ff": [0.0194544066, 0.0134557354, 0.650362319, 0.000411822344, 0.0333839606, 0.0, "c21b76f38322f357"], + "twemoji/1f469-1f3fb-200d-1f37c": [0.0450986624, 0.0226900156, 0.885333333, 0.000560925051, 0.0746618886, 0.00265676429, "12d702a8d4fce762"], + "twemoji/1f469-1f3fc-200d-2764-fe0f-200d-1f468-1f3fc": [0.0289706141, 0.0172471151, 1.1548913, 0.000435398193, 0.0428994551, 0.0, "043aa99f1f103a55"], + "twemoji/1f469-1f3fe": [0.0151780881, 0.00474925068, 0.450757576, 0.000308147748, 0.0330671945, 0.0, "c25f1f0d14cfb39d"], + "twemoji/1f469-1f3ff-200d-1f91d-200d-1f468-1f3fc": [0.0374840945, 0.0291667169, 1.3512931, 0.000633589632, 0.0372019036, 0.0, "1d4f7c8bb0e86ef4"], + "twemoji/1f469-200d-1f467-200d-1f467": [0.00955860503, 0.0206535075, 0.791666667, 0.000263124763, 0.0318409122, 0.0, "e0e960d4d4922452"], + "twemoji/1f470-1f3fc-200d-2640-fe0f": [0.0221954845, 0.00930953201, 1.14324324, 0.000400068151, 0.062634494, 0.0284122812, "03cfd504129d2eb5"], + "twemoji/1f481-1f3fc-200d-2640-fe0f": [0.0245149601, 0.0135517303, 1.00675676, 0.000303360866, 0.0469771781, 0.0, "8d12580a0adbb820"], + "twemoji/1f486-1f3ff": [0.0274858195, 0.0210494557, 1.55942623, 0.000615523139, 0.0423565514, 0.000340486748, "f573424811266fea"], + "twemoji/1f4e6": [0.0250190739, 0.0102225249, 0.905737705, 0.000375515781, 0.0620398499, 0.0, "0eb13b12df1ad928"], + "twemoji/1f53a": [0.0154791716, 0.00407036187, 1.25, 0.000112461275, 0.0660477497, 0.0, "fe201aa2b72896ac"], + "twemoji/1f57a-1f3fb": [0.0456225313, 0.0337288015, 0.621062992, 0.000681499427, 0.079293726, 3.29429688e-05, "92580d73a4c93174"], + "twemoji/1f635": [0.0128781153, 0.00781291773, 0.484848485, 0.000356173114, 0.0349389027, 0.0, "b2f146d6f4f08a7c"], + "twemoji/1f646-1f3fb-200d-2640-fe0f": [0.0322314985, 0.012054629, 1.15217391, 0.000519480731, 0.038245819, 0.0, "1f88d4c948781468"], + "twemoji/1f648": [0.0335555077, 0.021206778, 1.04075235, 0.000697184063, 0.0411502272, 0.0, "ceb312682e9e5833"], + "twemoji/1f64d-1f3fd": [0.0155270891, 0.0148835204, 1.62890625, 0.000322581356, 0.0330631625, 0.0, "78c4221e31bd739b"], + "twemoji/1f6a3-1f3ff-200d-2642-fe0f": [0.0291424543, 0.0238731187, 1.70792079, 0.000344259664, 0.0359889984, 2.01619038e-05, "bf9dcbc8adb9b34c"], + "twemoji/1f6d6": [0.0319693871, 0.038525656, 1.22727273, 0.000483488984, 0.157937298, 0.00280078667, "8dcf1e0455c431d4"], + "twemoji/1f7eb": [0.00271723117, 0.0155106716, 2.75, 7.26165599e-05, 0.03574447, 0.0, "292f3be10121f9bf"], + "twemoji/1f91c-1f3fe": [0.013509932, 0.010283385, 0.981132075, 0.000193297936, 0.0755111928, 0.0, "c2bdef39e43688d5"], + "twemoji/1f938-1f3fe": [0.0271177534, 0.0367973567, 0.638790036, 0.000427285995, 0.0624547076, 0.0, "66bf333dae9bb58c"], + "twemoji/1f977-1f3fb": [0.0228983685, 0.0276505131, 1.83898305, 0.000524100906, 0.0282453227, 0.0, "0e4ee3730e67dc5e"], + "twemoji/1f9a8": [0.0526419468, 0.0172544114, 2.15533981, 0.00115870556, 0.04645713, 0.0, "d54e7065d6c02055"], + "twemoji/1f9c9": [0.0212478247, 0.0155536076, 1.42560554, 0.000408327178, 0.0572143505, 0.0007255443, "c2559c9045bf2eda"], + "twemoji/1f9d1-1f3fd-200d-1f9af-200d-27a1-fe0f": [0.0293370262, 0.0311551256, 1.05, 0.00041436858, 0.0542142177, 0.0, "0d0f3893ab7281ad"], + "twemoji/1f9d1-1f3ff-200d-2764-fe0f-200d-1f9d1-1f3fb": [0.0366308503, 0.0192840321, 1.22641509, 0.000643871666, 0.0438740502, 4.54182714e-05, "c58f3c2a4085f1ab"], + "twemoji/1f9d4-1f3fd": [0.0254157819, 0.00993999963, 0.903703704, 0.000399553683, 0.0439921665, 0.0, "660a50392eba94f1"], + "twemoji/1f9d8-1f3fe": [0.0315906368, 0.0277947726, 1.32152231, 0.000492185762, 0.0590933007, 0.0, "10393f789c9be347"], + "twemoji/1f9e9": [0.0109099243, 0.0111541837, 0.816666667, 0.000205724384, 0.0339469807, 0.0, "9bb13264c702eb81"], + "twemoji/1faa3": [0.02138629, 0.0109570548, 3.11111111, 0.00049877289, 0.0291995234, 0.0, "14bd563d40363d04"], + "twemoji/1fae5": [0.0213012695, 0.0202865758, 1.86507937, 0.000254555722, 0.045017486, 0.000413307804, "803c8efce9bd4021"], + "twemoji/2196": [0.00224900688, 0.0141946903, 2.42857143, 0.000146235645, 0.00807090877, 0.0, "267459223d773b63"], + "twemoji/271d": [0.0199998431, 0.0151455344, 1.61538462, 0.000180519724, 0.0258833171, 0.0, "dd0343857d65f74c"] + } + }, + "quality-web": { + "tier": "web", + "args": [], + "summary": { + "de00": 0.1870159390644777, + "turning_gap": 2.0953488218228897, + "ratio_gap": 0.5027520647436745, + "geom": 0.33361460910326274, + "turning": 0.02182175994525005, + "ratio": 1.7648330202232183, + "self_res": 0.0036067805493703066, + "geom_far": 0.13825905035307, + "n": 246 + }, + "icons": { + "lucide/app-window-mac": [0.0609476194, 0.00880789354, 6.5, 0.00174406869, 0.10585489, 0.0, "99af59b54b7cded3"], + "lucide/audio-lines-x": [0.0848891363, 0.0102838142, 6.1875, 0.00237225485, 0.124613116, 0.0, "39d75fabd2f6cc0d"], + "lucide/badge-russian-ruble": [0.0384124443, 0.0160607445, 1.91549296, 0.00322019611, 0.0250511747, 2.10160862e-05, "6f0f4d47a26922b2"], + "lucide/bath": [0.0233207848, 0.00434082634, 1.37837838, 0.00212843134, 0.00685771649, 0.0, "64449e8569015ff6"], + "lucide/bell": [0.0371148065, 0.00740026071, 1.57142857, 0.00206757337, 0.0421525043, 0.0, "f6dfb129f4bf89a7"], + "lucide/birdhouse": [0.0443482883, 0.00473410193, 1.27272727, 0.0024787744, 0.012168728, 0.0, "c95e7ed8a56cddf1"], + "lucide/book-heart": [0.0694449544, 0.00876520966, 1.7704918, 0.0026563725, 0.0810425925, 0.0, "0ce2ac121726c5f3"], + "lucide/bug": [0.0494863689, 0.00638417372, 1.7027027, 0.00324553903, 0.0239225163, 0.0, "46cc288486b4c042"], + "lucide/cat": [0.0386785343, 0.014124898, 2.8028169, 0.00277036778, 0.0249967368, 2.39661906e-05, "953c66d0b07b42b1"], + "lucide/chess-king": [0.0536103174, 0.00637422715, 1.2125, 0.00266747549, 0.043112501, 0.0, "59860328ad60bc28"], + "lucide/circle-arrow-right": [0.041101072, 0.00412214057, 2.88888889, 0.00322438707, 0.0221732421, 0.0, "f9259276e0bf4b6d"], + "lucide/closed-caption": [0.056088198, 0.00629988588, 1.6, 0.00240659318, 0.0796072841, 0.0, "b40fe63b2c4ec3a1"], + "lucide/cooking-pot": [0.0605293289, 0.0042930437, 1.13636364, 0.00256289216, 0.00400872927, 0.0, "da27e6aefb1b8be6"], + "lucide/diff": [0.0622042678, 0.00879262728, 10.6666667, 0.00134688721, 0.165988894, 0.0, "3de2fc21dec8e3c9"], + "lucide/equal": [0.0574440397, 0.00303952539, 1.25, 0.000986421597, 0.220790337, 0.0, "3db08a03018bd186"], + "lucide/file-digit": [0.0649745092, 0.0106335416, 2.6440678, 0.00238588243, 0.0859258819, 0.0, "d89546f192e90a8d"], + "lucide/focus": [0.0464403555, 0.0079321016, 1.12765957, 0.00209475472, 0.0512745985, 0.0, "820e098220dd226d"], + "lucide/folder-open": [0.0419018827, 0.0061830725, 1.17567568, 0.0023906373, 0.0234581744, 0.0, "a131a5ad43f7c81d"], + "lucide/git-compare": [0.0470430739, 0.00807028159, 1.5, 0.00225267163, 0.0153772842, 0.0, "e630706fd1352d7b"], + "lucide/hard-drive-download": [0.0668542609, 0.00786945239, 3.5, 0.00214534299, 0.0812699492, 0.0, "64b7de6c22992dd9"], + "lucide/ice-cream-cone": [0.0300746672, 0.0104846147, 2.20588235, 0.00189107843, 0.0372268734, 0.0, "1a0b73ba96b8d4bc"], + "lucide/iteration-ccw": [0.0222634245, 0.00431157885, 3.46153846, 0.0019627451, 0.0283681866, 0.0, "bd4f1d8c4f71d7ec"], + "lucide/list-checks": [0.0359852612, 0.00620491299, 1.71428571, 0.00165281864, 0.0931873691, 0.0, "063ff4f2aa94804f"], + "lucide/message-circle-dashed-check": [0.0208396856, 0.00542783275, 1.09375, 0.00280843116, 0.0222503852, 0.0, "dfef9a4b9f858848"], + "lucide/messages-square": [0.0660844073, 0.0120030195, 1.27848101, 0.00241818652, 0.0657127951, 0.0, "2ae0aa48be13b654"], + "lucide/navigation-2-off": [0.0359235927, 0.00553091227, 2.3125, 0.00235223025, 0.0229671905, 0.00743645024, "f14f9e001ceb9163"], + "lucide/omega": [0.02653482, 0.00646968478, 0.720930233, 0.0018575734, 0.0189849207, 0.0, "bc86c092ae951b2a"], + "lucide/panel-right": [0.141605407, 0.00582687985, 7.0, 0.00228985283, 0.226786726, 0.0, "ec92ecf42841fe1f"], + "lucide/pen-line": [0.0293669943, 0.00636607038, 1.47222222, 0.00235676463, 0.0403552111, 0.0, "657310410929ceb9"], + "lucide/phone-forwarded": [0.0498187728, 0.00627594825, 1.07954545, 0.00318455882, 0.0107447459, 0.0, "306585cbdca6d4b9"], + "lucide/rectangle-goggles": [0.0094574187, 0.00622846034, 1.13114754, 0.00202181377, 0.00538197997, 0.0, "00f88bbe6a7a03ac"], + "lucide/save-pen": [0.0698654205, 0.00642981566, 1.17021277, 0.00334926462, 0.0077967207, 0.0, "5fb0f33d6661e728"], + "lucide/shapes": [0.0346372761, 0.00891738605, 2.11764706, 0.00251855399, 0.0117220054, 0.0, "b47162e524757f7a"], + "lucide/shopping-cart-plus": [0.0478248298, 0.0090410351, 1.55813953, 0.0025695588, 0.0264485077, 0.0, "2b0a576f1ac14bbf"], + "lucide/sparkle": [0.0168476868, 0.010686239, 1.31428571, 0.00193208328, 0.0133623775, 0.0, "d6de50f9185eb565"], + "lucide/square-minus": [0.126757011, 0.0046391314, 2.5, 0.00223303935, 0.218308687, 0.0, "427371975e741bfd"], + "lucide/swiss-franc": [0.0247754455, 0.00341473873, 1.75, 0.00124634802, 0.0229983112, 0.0, "ffd2e4384d0ae4d7"], + "lucide/ticket-minus": [0.0647516325, 0.0119727442, 1.55555556, 0.00211321074, 0.0951551247, 0.0, "4e07b78ae98229c5"], + "lucide/undo": [0.0227790512, 0.00384922535, 0.95, 0.00129139714, 0.0383259798, 0.0, "35e56e753465fbd1"], + "lucide/vegan": [0.0522731468, 0.0112731753, 5.82142857, 0.00367955863, 0.0312330459, 0.0, "e1a6656c943d6ffb"], + "material-icons/12mp": [0.109256394, 0.0165569169, 0.9125, 0.00266651972, 0.142608602, 0.0, "997090c4c9dc5243"], + "material-icons/admin_panel_settings": [0.0393373594, 0.00974764135, 0.745901639, 0.00248249993, 0.0324906558, 0.0, "04bf625cafdfc121"], + "material-icons/arrow_drop_down": [0.00782307703, 0.00627497545, 2.0, 0.000404828403, 0.138342834, 0.0, "f321c8505b4b7ed9"], + "material-icons/bento": [0.116186783, 0.00907937816, 0.6375, 0.00201691198, 0.211261637, 0.0, "e94ff1f8f3620da6"], + "material-icons/border_left": [0.0821623504, 0.0256927285, 0.794117647, 0.00181860302, 0.15699926, 0.0, "242652ef55cd2f99"], + "material-icons/call": [0.0226812828, 0.0111063803, 0.596330275, 0.00154808804, 0.0394650083, 0.0, "a5895d3460729a02"], + "material-icons/chair": [0.0784937739, 0.0119284251, 0.853658537, 0.0022527941, 0.113354042, 0.0, "153cb7adcce315e9"], + "material-icons/closed_caption": [0.0678392798, 0.0125473129, 0.884057971, 0.00185654394, 0.109030473, 0.0, "cdb18d30a403e784"], + "material-icons/crop_landscape": [0.072103031, 0.00549350404, 0.45, 0.00127409329, 0.185890186, 0.0, "c4ea941f04e5b44e"], + "material-icons/dining": [0.179346442, 0.0133653415, 1.02083333, 0.00303421589, 0.211826509, 0.0, "46839706ecc2b5e1"], + "material-icons/double_arrow": [0.0586755015, 0.00804783018, 2.15, 0.00164794107, 0.11164399, 0.0, "ace9b5804a658d96"], + "material-icons/dynamic_feed": [0.0845943317, 0.00939993895, 0.736842105, 0.00171874999, 0.156578516, 0.0, "91d70074df0aebb6"], + "material-icons/expand_circle_down": [0.0217136256, 0.00961391938, 0.816666667, 0.00288899522, 0.0242954001, 0.0, "a2e04be4137a5472"], + "material-icons/flight": [0.0380823649, 0.00984687037, 1.27272727, 0.00125328428, 0.103585792, 0.0, "7c8efa6fd4c20274"], + "material-icons/free_breakfast": [0.0500847511, 0.00700310301, 0.802816901, 0.00179490203, 0.0852571564, 0.0, "089ec7acf8c03629"], + "material-icons/group_remove": [0.0512931496, 0.0139430534, 1.23134328, 0.00225888263, 0.0745930037, 0.0, "a1b6630709be2eca"], + "material-icons/headset": [0.0707944557, 0.0114861697, 1.59302326, 0.00179566164, 0.0902016424, 0.0, "7df0d5fd74185115"], + "material-icons/houseboat": [0.0497248806, 0.0211468775, 1.28947368, 0.00209580897, 0.0714057794, 0.0, "7b4c61dfa2fccff5"], + "material-icons/javascript": [0.0213396754, 0.0172602603, 1.125, 0.000669583271, 0.0678006532, 0.0, "b5e9091084db9893"], + "material-icons/laptop": [0.103958018, 0.00687097288, 1.1875, 0.00163857837, 0.182672754, 0.0, "ffadd69def207583"], + "material-icons/lyrics": [0.114536248, 0.0156247866, 1.65420561, 0.00247484492, 0.145967389, 0.000170423104, "f8ace9ffb40e18f7"], + "material-icons/miscellaneous_services": [0.0661985278, 0.0286190783, 0.913793103, 0.00196095579, 0.0767094397, 0.0, "09b977ea8d3d3410"], + "material-icons/music_note": [0.0517199263, 0.00842027873, 0.867924528, 0.00121036754, 0.121882335, 0.00214521942, "ffe7fcc8a85c02d1"], + "material-icons/no_food": [0.164704874, 0.0169018074, 2.82926829, 0.00335700996, 0.140850798, 0.00514514728, "16a56a557be940be"], + "material-icons/notifications_paused": [0.0829544663, 0.0136421032, 1.35869565, 0.00194125006, 0.132467688, 0.0, "2a8f80b5568ec130"], + "material-icons/perm_media": [0.12329971, 0.0138906747, 3.0125, 0.00282653887, 0.140020601, 1.88808793e-05, "0e88c6f5ccc548a1"], + "material-icons/phone_iphone": [0.0694505647, 0.00684943684, 0.544117647, 0.00151186273, 0.157695441, 0.0, "a39e87359b064bec"], + "material-icons/polyline": [0.0801319852, 0.0144263132, 1.44827586, 0.00155330892, 0.156451919, 0.0, "e515254156b66844"], + "material-icons/qr_code": [0.10544382, 0.0212425447, 1.125, 0.00225426489, 0.136664822, 0.0, "772f2702d33e6957"], + "material-icons/report": [0.0442575999, 0.00867993382, 1.26829268, 0.00195181381, 0.077892265, 0.0, "fdbdbb7ab2a4613e"], + "material-icons/rule_folder": [0.0808644816, 0.0116139309, 1.25, 0.00222615199, 0.114493899, 0.0, "07c4b7d1ef61ce6b"], + "material-icons/sd_card_alert": [0.0817945302, 0.0101181037, 1.02, 0.0020405394, 0.0883414544, 0.0, "1f820ef444a6f24a"], + "material-icons/settings_overscan": [0.0332443342, 0.00943949356, 0.65625, 0.00184620102, 0.0537640822, 0.0, "63bfcc6a349be557"], + "material-icons/sms_failed": [0.121622346, 0.00837519332, 1.24, 0.00195007352, 0.209945507, 0.0, "fac1f23adc135947"], + "material-icons/storage": [0.133961707, 0.00999683999, 0.875, 0.00215769629, 0.253969059, 0.0, "1b329f2ba200bbf5"], + "material-icons/table_rows": [0.0928001925, 0.00698504961, 0.535714286, 0.00187517167, 0.15876299, 0.0, "d9225d91cdb93af8"], + "material-icons/transfer_within_a_station": [0.0767049715, 0.0183324282, 1.53703704, 0.00231595594, 0.0933829837, 0.0, "2c1ea895f6e68135"], + "material-icons/two_wheeler": [0.0731350631, 0.0223587318, 2.0, 0.00242550205, 0.0912713456, 0.0, "45309eb1fb755143"], + "material-icons/video_camera_back": [0.0903879255, 0.00920999342, 1.27586207, 0.0021875489, 0.137821917, 0.0, "fe847ec818d3c597"], + "material-icons/view_week": [0.120673284, 0.00719677246, 0.535714286, 0.00202257372, 0.206960815, 0.0, "0c200468dc244b90"], + "noto-emoji/emoji_u0030": [0.087342374, 0.014928202, 1.27777778, 0.00116806361, 0.73697239, 0.0647493937, "7c4d1ab143c58712"], + "noto-emoji/emoji_u1f36a": [0.491202056, 0.0377630818, 0.800518135, 0.008433979, 0.686817086, 0.193530552, "39abe7ae11cc6762"], + "noto-emoji/emoji_u1f39e": [0.428347558, 0.0335639453, 1.03924419, 0.005884232, 0.908106136, 0.159189771, "212bc515cae15751"], + "noto-emoji/emoji_u1f3c2_1f3fd": [1.139902, 0.0381495632, 0.530551416, 0.0130923763, 2.32439849, 1.14366084, "a7d773c9ad269553"], + "noto-emoji/emoji_u1f3c4_1f3fe": [0.415303618, 0.0646680858, 0.732421875, 0.00996731129, 0.224310066, 0.0172261444, "3e4c1ccb4488d5c0"], + "noto-emoji/emoji_u1f3cb_200d_2642": [0.338117123, 0.0740154383, 0.477419355, 0.00696864352, 1.76458678, 0.897393618, "04ce25db40ec77cb"], + "noto-emoji/emoji_u1f41b": [0.224430531, 0.0427305095, 1.2530541, 0.00653674826, 0.127585805, 0.000171879031, "da800384dd940c0f"], + "noto-emoji/emoji_u1f44d_1f3fc": [0.303401232, 0.0362423674, 1.24376731, 0.004186715, 0.16780218, 0.00229464721, "f263df6ab610eb1d"], + "noto-emoji/emoji_u1f468_1f3fb_200d_2764_200d_1f468_1f3fd": [0.422167003, 0.03590905, 0.660326087, 0.00671045715, 0.753512953, 0.159939729, "4cf469063f737e10"], + "noto-emoji/emoji_u1f468_1f3ff_200d_1f393": [0.546373129, 0.0340009412, 0.926289926, 0.00551477959, 1.23029905, 0.441267084, "3856030366b7a3b6"], + "noto-emoji/emoji_u1f469_1f3fb_200d_1f52c": [0.852952778, 0.0441695233, 0.864140481, 0.0098542152, 0.811267353, 0.301491795, "787842082c8db110"], + "noto-emoji/emoji_u1f469_1f3fc_200d_1f91d_200d_1f468_1f3fb": [0.384277463, 0.0465824481, 0.417867435, 0.0074955062, 1.63586252, 0.710225245, "3e6b879a78ce73b7"], + "noto-emoji/emoji_u1f469_1f3fe_200d_1faef_200d_1f469_1f3fd": [0.513067722, 0.0667521153, 0.505925251, 0.00824066158, 1.9389489, 0.974141902, "d836f55d8abec9c1"], + "noto-emoji/emoji_u1f469_200d_1f469_200d_1f466_200d_1f466": [0.0669898316, 0.0241205966, 0.963576159, 0.00429568626, 0.0758197077, 0.000241977791, "03c1038aa7c2d7d8"], + "noto-emoji/emoji_u1f46c_1f3fd": [0.368954122, 0.0523658159, 0.353667954, 0.00655442011, 2.50968158, 1.59506647, "69f28e613dcb2b31"], + "noto-emoji/emoji_u1f470_1f3fb_200d_2640": [0.539990246, 0.0350862295, 0.847031963, 0.00883043185, 1.79127617, 1.00208078, "920e6d7d1e5cceef"], + "noto-emoji/emoji_u1f482_1f3ff_200d_2640": [0.721039176, 0.0463182018, 0.900201613, 0.00746847177, 8.02271253, 7.37986521, "1626643ae8821e6a"], + "noto-emoji/emoji_u1f4d8": [0.195979372, 0.0104437342, 1.33809524, 0.00482758181, 0.338457674, 0.154182886, "84e2073c524861ef"], + "noto-emoji/emoji_u1f520": [0.266864538, 0.0160350501, 0.716894977, 0.0037346324, 0.082528795, 0.0, "fabf184b80849add"], + "noto-emoji/emoji_u1f56f": [0.524787784, 0.0229539773, 0.286941581, 0.00520504871, 2.19902586, 1.01798289, "140a9e94d66aa59a"], + "noto-emoji/emoji_u1f5a8": [0.630479097, 0.0284001957, 1.59302326, 0.0101062013, 2.51885459, 1.71603612, "7beef378ff67c41b"], + "noto-emoji/emoji_u1f62d": [0.297029018, 0.0300936987, 1.29279279, 0.0101736998, 0.825041608, 0.0634175235, "01cdc5e6e062cbbd"], + "noto-emoji/emoji_u1f64b_1f3fe_200d_2640": [0.470180213, 0.022747289, 0.530075188, 0.00636980403, 1.34572034, 0.735388279, "aecec2141bede435"], + "noto-emoji/emoji_u1f6c0_1f3ff": [0.460150301, 0.0589370509, 0.714778608, 0.00710805506, 0.597657016, 0.161595712, "98362c78aa6c8568"], + "noto-emoji/emoji_u1f90d": [0.0191884395, 0.0117393641, 0.982954545, 0.00110946072, 0.148858947, 0.00250495729, "e01b84fc08af2ad7"], + "noto-emoji/emoji_u1f91c_1f3fe": [0.254903615, 0.0250545028, 1.11555556, 0.00349080097, 0.201291951, 0.0236327989, "f6840f0a0fbbe245"], + "noto-emoji/emoji_u1f926_1f3ff": [0.78242439, 0.0559502255, 1.00152905, 0.00671136426, 1.25886057, 0.417602472, "ab7f275a4aa50b3e"], + "noto-emoji/emoji_u1f932": [0.346782357, 0.0346753676, 0.966131907, 0.00685131457, 0.17825615, 0.00744223895, "e0a15278fbd3b0ab"], + "noto-emoji/emoji_u1f93c_1f3fe_200d_2640": [0.450929195, 0.0659671016, 0.53299725, 0.00809805561, 1.58015565, 0.744396698, "98b9aa1a66aa8cf0"], + "noto-emoji/emoji_u1f987": [0.34343186, 0.0370034476, 0.846551724, 0.00507442839, 1.24951563, 0.519246279, "e4e07d9115797f7a"], + "noto-emoji/emoji_u1f9be": [0.499262482, 0.0374384157, 1.06107784, 0.00586394547, 0.834777952, 0.328494636, "f7419e4fdfc879f1"], + "noto-emoji/emoji_u1f9ce_1f3fd_200d_2642": [0.143014744, 0.0349956387, 0.508578431, 0.00310235284, 0.387934905, 0.0195379837, "b20d917f8211baf9"], + "noto-emoji/emoji_u1f9cf_1f3fc": [0.44845435, 0.0366820292, 0.974595843, 0.0065707434, 1.05350704, 0.431091706, "1ca92259964d442a"], + "noto-emoji/emoji_u1f9d1_1f3fc_200d_1f37c": [0.303269029, 0.05701656, 0.796275395, 0.00725118397, 0.452847822, 0.201142937, "2313779adf61994f"], + "noto-emoji/emoji_u1f9d1_1f3fd_200d_1f91d_200d_1f9d1_1f3ff": [0.449767232, 0.0701898317, 0.54460665, 0.0076654572, 0.951898313, 0.307932303, "b23f3323e7bf7b67"], + "noto-emoji/emoji_u1f9d1_1f3fe_200d_1f9bc_200d_27a1": [0.272515923, 0.0742746014, 0.90726817, 0.00597282732, 0.698758572, 0.229752766, "b983ea58a79982a0"], + "noto-emoji/emoji_u1f9d6_1f3fe_200d_2642": [1.21783841, 0.0344463461, 0.756578947, 0.0130279325, 1.18685549, 0.798331353, "39ec64929d20269e"], + "noto-emoji/emoji_u1f9dd_1f3fd_200d_2640": [0.617132902, 0.0476327797, 0.975182482, 0.00877516251, 1.29894934, 0.557451159, "3da8e449c2e73557"], + "noto-emoji/emoji_u1f9ed": [0.303404123, 0.0395442945, 1.76160338, 0.00904230308, 0.190786383, 0.0183454232, "06203a7a552221de"], + "noto-emoji/emoji_u1faa5": [0.112482466, 0.0404869956, 0.666666667, 0.00471907668, 0.828179593, 0.295940126, "144a13d821a9d234"], + "noto-emoji/emoji_u1faf1_1f3fc_200d_1faf2_1f3ff": [0.358083129, 0.046949864, 0.904326123, 0.00442636432, 0.1741711, 0.0135378446, "3afde698c4e30c63"], + "noto-emoji/emoji_u26bd": [0.12244606, 0.0357961854, 2.04761905, 0.00436394569, 0.106478653, 0.00277705832, "6453e4e987e08ab5"], + "noto-emoji/emoji_u2b05": [0.25222826, 0.00941511483, 1.26923077, 0.00265033473, 0.0880642243, 4.06106637e-05, "c8056e5c1e2393f2"], + "openmoji/1F195": [0.177981943, 0.0110459364, 3.55882353, 0.00668910099, 0.168377128, 0.00015888382, "6947ae9948c06c60"], + "openmoji/1F1FF-1F1F2": [0.134657681, 0.0121303489, 2.9375, 0.0030335458, 0.140650905, 0.0, "ddf4cee549d95880"], + "openmoji/1F361": [0.125978678, 0.0379699939, 3.33571429, 0.00280214031, 0.105093746, 0.00861852293, "e8579da5bb9e900a"], + "openmoji/1F38A": [0.180563271, 0.0438777107, 2.76041667, 0.00431091525, 0.111583164, 0.00208169192, "b3b031bd3202fa6e"], + "openmoji/1F3A9": [0.0826301947, 0.0102559976, 1.05970149, 0.00269526988, 0.0424622919, 0.0, "146dd82360ba95de"], + "openmoji/1F3C3-1F3FF-200D-2642-FE0F": [0.113402173, 0.0257052014, 1.75647668, 0.00237572705, 0.0764328792, 0.000572643811, "9b5849e46d8614f8"], + "openmoji/1F3CC-FE0F-200D-2640-FE0F": [0.0633181855, 0.0244950706, 1.09375, 0.00352130714, 0.0365999587, 2.3552097e-05, "ba14aa84aea3e9e7"], + "openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F": [0.196531162, 0.00749980596, 3.4, 0.00324270432, 0.11986155, 0.00331204933, "bf44359d695c694d"], + "openmoji/1F442-1F3FF": [0.152666464, 0.0220979115, 2.39473684, 0.00272073527, 0.104776638, 0.0038267067, "f605f2d223d727a8"], + "openmoji/1F468-1F3FC-200D-1F3ED": [0.206481308, 0.0464848598, 0.571317829, 0.00526155205, 0.105432885, 0.00253353649, "def265b4cf29917c"], + "openmoji/1F468-1F3FF-200D-1F9B0": [0.14774476, 0.0199392902, 0.826923077, 0.00331058819, 0.0707020911, 0.0, "328a3ba08135e15d"], + "openmoji/1F468-200D-1F9B1": [0.193162933, 0.0481421215, 1.4266055, 0.00498214876, 0.0963125837, 0.0, "37db3a86fd04654c"], + "openmoji/1F469-1F3FC-200D-2764-FE0F-200D-1F48B-200D-1F469-1F3FC": [0.22542794, 0.0358174066, 1.93809524, 0.00633218139, 0.0627325632, 0.000685019496, "a9904a3f7edf2817"], + "openmoji/1F469-1F3FF-200D-1F9B2": [0.103003889, 0.0143005976, 1.09868421, 0.00264933798, 0.0870494894, 0.0, "fada6eb9d298b69d"], + "openmoji/1F481-1F3FB-200D-2642-FE0F": [0.201925129, 0.0187379566, 1.18518519, 0.00423071068, 0.0664355211, 0.0, "ab4e886aca3c7ef1"], + "openmoji/1F49B": [0.114606977, 0.00961090142, 1.43181818, 0.00279574329, 0.0441450996, 0.00145239289, "47c09f888ee03599"], + "openmoji/1F517": [0.140648246, 0.026998139, 1.86363636, 0.0029054, 0.0956391545, 0.00204563969, "82363b4622a7ab88"], + "openmoji/1F646-1F3FC": [0.286632597, 0.023893253, 0.927947598, 0.0056499429, 0.0750336716, 0.0, "c5afc99a3416a947"], + "openmoji/1F6B4-1F3FD-200D-2640-FE0F": [0.0553840697, 0.0212666483, 1.24431818, 0.00360257365, 0.0212225166, 0.0, "047e97a82aea2119"], + "openmoji/1F6E0": [0.145369932, 0.0266711769, 1.625, 0.00429935474, 0.0524371269, 0.00154943702, "044afefd5690d00b"], + "openmoji/1F938-1F3FB": [0.119569361, 0.0229878684, 1.21052632, 0.00272206706, 0.0730961949, 0.000697431584, "322af7f87e58b1ac"], + "openmoji/1F93E-1F3FE": [0.133603171, 0.0300096521, 2.03111111, 0.00342290848, 0.0976435534, 0.000194025938, "60ac5f6c54c2c3e5"], + "openmoji/1F9B3": [0.140229657, 0.0110217636, 2.22727273, 0.00214040023, 0.123048701, 0.00928545191, "006ef0bf718e9ca6"], + "openmoji/1F9D1": [0.1563541, 0.0194983824, 1.28440367, 0.00421135593, 0.0650075115, 0.0, "ca7f2e85b2d96844"], + "openmoji/1F9D1-1F3FC-200D-1FA70": [0.134467408, 0.0356308105, 1.89615385, 0.00312625826, 0.0899072894, 0.00261480561, "0091f34029b6caa8"], + "openmoji/1F9D1-1F3FD-200D-1F527": [0.314631432, 0.0504000737, 1.94534413, 0.00561575172, 0.110471285, 0.00282340405, "6a243534768021f3"], + "openmoji/1F9D1-200D-1F393": [0.120270185, 0.0310350852, 0.44731405, 0.0037554088, 0.0980655354, 0.00209596028, "98f947901bdd0d2e"], + "openmoji/1F9D6-1F3FD-200D-2642-FE0F": [0.182903618, 0.0271112876, 1.07774799, 0.00392886437, 0.0903328573, 0.0, "e08385b036f9045e"], + "openmoji/1FA8B": [0.229820743, 0.0445080515, 0.52724359, 0.00480193645, 0.189208222, 0.00392719708, "11fbe25590e2ab67"], + "openmoji/1FAC4-1F3FD": [0.140849426, 0.0353673844, 0.935691318, 0.00367888878, 0.0839557329, 0.000359649726, "ef01afd87e08bc77"], + "openmoji/25FC": [0.0898652151, 0.00566665342, 0.75, 0.00175232848, 0.112106269, 0.00512635475, "43fc14e2843ee682"], + "openmoji/2705": [0.136182457, 0.0154189645, 1.44736842, 0.00339104561, 0.0659201899, 0.0, "9c61f96c46c0788e"], + "openmoji/E056": [0.225486979, 0.0510484212, 1.53453453, 0.0067357677, 0.0745969299, 7.10853153e-05, "5134065faf934c08"], + "openmoji/E1D1": [0.115376055, 0.0183371629, 0.699421965, 0.00246493472, 0.130042027, 0.00571362157, "74cc026ec4f02fa1"], + "openmoji/E30B": [0.167320743, 0.0230030472, 1.35897436, 0.0043803677, 0.0666583884, 1.53061741e-05, "408e1934dfab14d9"], + "simple-icons/alchemy": [0.0574064367, 0.016289372, 0.879245283, 0.0016631271, 0.0426356771, 0.0, "ca15669be527ec19"], + "simple-icons/appletv": [0.0582955144, 0.0239982985, 1.78947368, 0.00193106011, 0.0568126525, 0.0, "d5cb115d9de4fcd0"], + "simple-icons/atlassian": [0.0679179877, 0.0161379315, 2.76923077, 0.00233123265, 0.10727688, 0.0, "87167bc07342cf20"], + "simple-icons/autocad": [0.043220371, 0.00914882052, 2.12903226, 0.00182876049, 0.0401202605, 0.0, "0d39ce95590b92b9"], + "simple-icons/bandrautomation": [0.0868249014, 0.0167140579, 0.877272727, 0.00269924011, 0.0571261226, 0.0, "4d7eaccd08383cf4"], + "simple-icons/bim": [0.0931706205, 0.016319941, 1.16312057, 0.00245894631, 0.0842586064, 0.0, "4e0b4763b411f215"], + "simple-icons/boosty": [0.0460431613, 0.00939438921, 2.45454545, 0.00188385544, 0.0577044797, 0.0, "9b667fe5e9e0b392"], + "simple-icons/changedetection": [0.0951501876, 0.022775283, 1.12765957, 0.00440703705, 0.0579976839, 0.0, "8eca583b05c96a47"], + "simple-icons/cocos": [0.247042969, 0.0396348923, 0.737827715, 0.00605670083, 0.090714979, 0.0, "79c8d4e4db6ed868"], + "simple-icons/contentstack": [0.141609684, 0.019001014, 0.904411765, 0.00340323197, 0.0899888105, 0.0, "9f279a0a1166f4c5"], + "simple-icons/debridlink": [0.0524432622, 0.0127243139, 1.21212121, 0.00150795572, 0.0530447718, 0.0, "7920fd3d33f96759"], + "simple-icons/elixir": [0.0201702323, 0.00796904475, 1.20754717, 0.00100196071, 0.0404411136, 0.0, "742b05a07978f762"], + "simple-icons/fampay": [0.068380177, 0.0200141164, 2.21925134, 0.00236998894, 0.069367102, 0.0, "2314b09f1a0999fd"], + "simple-icons/fluxer": [0.0784572959, 0.0163980586, 1.39912281, 0.00288701151, 0.0634888015, 0.0, "bb27423523a54cb1"], + "simple-icons/googlechrome": [0.100361764, 0.0138728588, 3.53846154, 0.0031648681, 0.0786957462, 4.26882269e-05, "0ef1c62bdfe6b0e9"], + "simple-icons/h2database": [0.118630603, 0.018111788, 2.41884817, 0.00367018534, 0.0551007293, 6.81517987e-05, "6edbd23ad8c14905"], + "simple-icons/hitachi": [0.0411669761, 0.033442172, 0.646258503, 0.0013365834, 0.0122077314, 0.0, "423decd623f03584"], + "simple-icons/infinityfree": [0.0984492004, 0.0357363979, 1.21065375, 0.00296259322, 0.0820246374, 0.0, "081cece1693034ef"], + "simple-icons/jdoodle": [0.103862546, 0.0197959576, 0.690954774, 0.00269602961, 0.0675256701, 0.0, "71d05719cea90f4d"], + "simple-icons/kleinanzeigen": [0.0853866115, 0.0113605762, 1.32, 0.00283197919, 0.0630474608, 0.0, "b8ce4e95eef5691a"], + "simple-icons/leetcode": [0.0667607039, 0.0135313552, 1.7816092, 0.00230566598, 0.0823579802, 0.0, "12f9f1cb48e2c331"], + "simple-icons/looker": [0.0770459846, 0.0246595898, 2.43093923, 0.0025738976, 0.0750246254, 0.0, "2c6cc81f9e553ea7"], + "simple-icons/mamp": [0.0681715757, 0.0139550091, 1.69166667, 0.0022637255, 0.0688215023, 0.0, "2aad7240ea03ecb0"], + "simple-icons/microeditor": [0.0858589858, 0.0192033477, 0.644897959, 0.00285591837, 0.0774557337, 0.0, "9298239d93efd929"], + "simple-icons/mysql": [0.0951053053, 0.0360929151, 0.591240876, 0.00314127444, 0.0643745394, 0.0, "006de5ef92380784"], + "simple-icons/notion": [0.116289973, 0.0179358886, 2.34831461, 0.00397909665, 0.0409570315, 4.45831257e-05, "788924794f4241f9"], + "simple-icons/osano": [0.0461739749, 0.0132215938, 6.89285714, 0.00208384055, 0.0562211341, 0.0, "881e1fb59afd6bf7"], + "simple-icons/phpstorm": [0.0516208075, 0.0144438015, 1.00694444, 0.00163397042, 0.0632324332, 0.0, "82ebdd44046aa858"], + "simple-icons/playerfm": [0.0903761089, 0.0157971473, 0.991666667, 0.00362797105, 0.0665630065, 0.0, "e03ff3cd2a11e76a"], + "simple-icons/premierleague": [0.153535932, 0.0606019928, 2.87203791, 0.00371689512, 0.0966244104, 1.94768011e-05, "52e18d7d0336c818"], + "simple-icons/pronounsdotpage": [0.0832425654, 0.0174310538, 2.51162791, 0.00250635366, 0.0825482883, 0.0, "bb5d5cd97660ff14"], + "simple-icons/purescript": [0.0241041016, 0.015733983, 3.11111111, 0.00183200196, 0.0557808518, 0.0, "2ff8ac8d2f2bf687"], + "simple-icons/redsys": [0.0633615032, 0.0171606167, 2.0, 0.00219807471, 0.0828705562, 0.0, "e6446be7d764b780"], + "simple-icons/sagemath": [0.154823154, 0.045771456, 1.52192362, 0.00656407792, 0.0551265345, 0.000172112229, "3432eaf4c796f0a0"], + "simple-icons/slackware": [0.0895981416, 0.0148832004, 0.976303318, 0.00271835783, 0.10424545, 0.0, "df99d8c8525c7dc7"], + "simple-icons/sparkar": [0.0616620742, 0.0124361188, 6.75, 0.0022302235, 0.059597145, 0.0, "b3a3881f3e06fd8d"], + "simple-icons/stmicroelectronics": [0.0606662259, 0.0138252064, 1.34415584, 0.00165535684, 0.0322922305, 3.0550833e-05, "e465a1aa20d4689b"], + "simple-icons/ubiquiti": [0.0740733296, 0.0141330359, 0.92920354, 0.00202626805, 0.0846343236, 0.0, "e7bc47497bed033e"], + "simple-icons/visa": [0.0590032376, 0.0240220185, 2.11764706, 0.00203541992, 0.0665625458, 0.0, "d0f049bb87e81c8f"], + "simple-icons/wxt": [0.07400354, 0.0247407113, 2.03608247, 0.00276350044, 0.0855667858, 0.0, "7d45116dfc0e2692"], + "synthetic/gradient_linear": [0.242372856, 0.0146004251, 10.4166667, 0.00311974692, 0.836210555, 0.229829369, "ff39e662b2b1d5b8"], + "synthetic/mosaic_grid6": [0.765491188, 0.0205589184, 1.32432432, 0.00734366896, 2.26269067, 1.58641964, "f8ba1768202db649"], + "synthetic/prim_ellipse": [0.00444973353, 0.00509762187, 1.0, 0.00129173207, 0.0172429567, 0.0, "e69de82d291730e7"], + "synthetic/prim_star5": [0.234759599, 0.00870247891, 1.08333333, 0.00375108654, 0.620633027, 0.175279486, "72cc73b3ea6317a8"], + "synthetic/symmetry_rot3": [0.0419511758, 0.00901408443, 1.77777778, 0.00219316175, 0.0486478551, 0.0, "71a86d2acbe7a1e8"], + "twemoji/1f17e": [0.365702838, 0.0156970055, 1.775, 0.00326391403, 0.0604550914, 0.0, "a4cede48b694e01d"], + "twemoji/1f1f8": [0.140265688, 0.0189590122, 1.70192308, 0.00247175922, 0.0660009026, 0.0, "ac0ccf5b794365f5"], + "twemoji/1f1fa": [0.144526124, 0.0162936447, 1.55681818, 0.00250381231, 0.0588029135, 0.0, "6d76b4d3f61c91dc"], + "twemoji/1f325": [0.25867328, 0.0189867577, 1.45901639, 0.00288574374, 0.116533837, 0.000128411942, "49070a83317cd5db"], + "twemoji/1f369": [0.269402027, 0.0177174727, 0.56741573, 0.0064143464, 0.108127011, 0.000197384102, "cca2c0969a4e5ea7"], + "twemoji/1f3ca-1f3fe-200d-2640-fe0f": [0.23209548, 0.0204644586, 0.886792453, 0.00420285948, 0.135728728, 0.000133407439, "9086332edf13d126"], + "twemoji/1f3cc-1f3fb-200d-2640-fe0f": [0.228398532, 0.0377336763, 1.54693878, 0.00384278968, 0.250759538, 0.0242853216, "fbbeeabe92166ed8"], + "twemoji/1f42b": [0.243883625, 0.0250503575, 1.89015152, 0.0036575729, 0.0835281322, 0.0, "6028cc1f83fc19bb"], + "twemoji/1f468-1f3fb-200d-1f91d-200d-1f468-1f3fd": [0.335775942, 0.0395204748, 0.961702128, 0.00594939897, 0.225680764, 0.0332120063, "bf868d578170c48d"], + "twemoji/1f468-1f3fc-200d-1f9b0": [0.252668202, 0.0166347225, 0.67768595, 0.00358214858, 0.0973761618, 0.000569951196, "07ff08965e7bb974"], + "twemoji/1f468-1f3fe-200d-2764-fe0f-200d-1f48b-200d-1f468-1f3ff": [0.372347832, 0.0212387339, 0.653985507, 0.00377382198, 0.084834111, 0.00184071844, "cd01c104c81ff525"], + "twemoji/1f469-1f3fb-200d-1f37c": [0.358894467, 0.0325702959, 0.765333333, 0.00530695263, 0.290514113, 0.0794135905, "f94a53be08f40125"], + "twemoji/1f469-1f3fc-200d-2764-fe0f-200d-1f468-1f3fc": [0.276004374, 0.0274223265, 1.3451087, 0.00539152231, 0.16622226, 0.0173843054, "5003b8604a5ba531"], + "twemoji/1f469-1f3fe": [0.382269591, 0.00770944068, 0.526515152, 0.00328169134, 0.0674170605, 0.0, "1959ec3cc1ff9451"], + "twemoji/1f469-1f3ff-200d-1f91d-200d-1f468-1f3fc": [0.344712585, 0.041605907, 1.25107759, 0.00681662466, 0.239734206, 0.0426688569, "97865e3ccd256325"], + "twemoji/1f469-200d-1f467-200d-1f467": [0.154255435, 0.0260368913, 0.640625, 0.00342423306, 0.103096915, 0.000268919243, "926a7330a632881b"], + "twemoji/1f470-1f3fc-200d-2640-fe0f": [0.32378307, 0.0144645484, 1.06486486, 0.00540059293, 0.173740762, 0.0555467754, "073cf549a867348b"], + "twemoji/1f481-1f3fc-200d-2640-fe0f": [0.202072412, 0.018866213, 0.929054054, 0.00471904082, 0.242054123, 0.0374521974, "7d4869b3a9bad201"], + "twemoji/1f486-1f3ff": [0.363654524, 0.0295197694, 1.31147541, 0.00400971342, 0.102220628, 0.000575645173, "0b15f572a161edd2"], + "twemoji/1f4e6": [0.386900812, 0.016200193, 1.40983607, 0.00464742258, 0.309632456, 0.0398129951, "a85f4f3e72441825"], + "twemoji/1f53a": [0.0984523892, 0.00630254881, 1.625, 0.00164945249, 0.308742221, 0.0, "995e037486794dba"], + "twemoji/1f57a-1f3fb": [0.249970257, 0.044592287, 0.492125984, 0.00373997516, 0.219343827, 0.0383477084, "91185f10aa5634b3"], + "twemoji/1f635": [0.0523226969, 0.0104539878, 0.643939394, 0.00484087924, 0.0933223261, 0.0, "1b1b55a515fcbafb"], + "twemoji/1f646-1f3fb-200d-2640-fe0f": [0.359680951, 0.0154564505, 1.14906832, 0.0052579171, 0.0727674451, 0.000111180206, "a71838e38eaefb74"], + "twemoji/1f648": [0.217802525, 0.0285844108, 0.808777429, 0.0059078862, 0.103016239, 0.000865575716, "43492a477d37027e"], + "twemoji/1f64d-1f3fd": [0.240777284, 0.0185338288, 1.48046875, 0.00358340307, 0.113503443, 0.000935039802, "d5b3bf522a184cff"], + "twemoji/1f6a3-1f3ff-200d-2642-fe0f": [0.265592277, 0.0301005475, 1.38613861, 0.00459047221, 0.247568988, 0.00808525596, "11ea68cd6e5c7197"], + "twemoji/1f6d6": [0.318854898, 0.045935428, 0.966830467, 0.0045038918, 0.377609107, 0.0342917246, "b7055226789fa7ed"], + "twemoji/1f7eb": [0.436600268, 0.0193549901, 2.6875, 0.00052027317, 0.0742001365, 0.0, "e898e0c5755d755e"], + "twemoji/1f91c-1f3fe": [0.190174237, 0.0137308448, 0.740566038, 0.002022492, 0.174792911, 0.00201917109, "440aa0276eed9789"], + "twemoji/1f938-1f3fe": [0.239510298, 0.0450614175, 0.391459075, 0.00483385567, 0.32196236, 0.0301606811, "8c6c7fa2a9143a54"], + "twemoji/1f977-1f3fb": [0.365496188, 0.0413468814, 1.77118644, 0.0039496189, 0.145280147, 0.0247808322, "d5de040a26585ab9"], + "twemoji/1f9a8": [0.395044446, 0.0238078905, 2.10679612, 0.00514156837, 0.0752149464, 0.000545733713, "24eac6eb2499da2e"], + "twemoji/1f9c9": [0.172776654, 0.0208611029, 1.35294118, 0.00341041666, 0.144572398, 0.00781729449, "8071a9d45f0efdcb"], + "twemoji/1f9d1-1f3fd-200d-1f9af-200d-27a1-fe0f": [0.182796001, 0.0500867251, 0.90625, 0.00412891293, 0.251097058, 0.0366129644, "c63e67155f8aca3c"], + "twemoji/1f9d1-1f3ff-200d-2764-fe0f-200d-1f9d1-1f3fb": [0.489402622, 0.029730793, 1.32075472, 0.00468093436, 0.0959729689, 0.000619805248, "045d48cef2bd8a89"], + "twemoji/1f9d4-1f3fd": [0.240092218, 0.0146127004, 0.848148148, 0.00416656304, 0.0866333117, 0.0, "d2c31ab1f1a60ed1"], + "twemoji/1f9d8-1f3fe": [0.246840194, 0.0398295515, 1.06955381, 0.00482563255, 0.218953731, 0.0141736075, "54d550bce4e0348d"], + "twemoji/1f9e9": [0.151014566, 0.024383147, 0.995833333, 0.00338128256, 0.133230782, 0.0, "42fbe3b7edfab50a"], + "twemoji/1faa3": [0.192593887, 0.013455671, 2.92592593, 0.00436012214, 0.0981679334, 0.0, "4d54ec04e02c0222"], + "twemoji/1fae5": [0.355773032, 0.047019797, 2.15873016, 0.00407829089, 0.343446765, 0.0556917808, "4b243eb8f741660b"], + "twemoji/2196": [0.144685596, 0.0179907801, 2.52380952, 0.00205475395, 0.0722276018, 0.0, "f213bb7bf1416a34"], + "twemoji/271d": [0.238236845, 0.0194153741, 1.63461538, 0.00147207535, 0.0497013439, 0.0, "8673ac0f5e0f51d5"] } }, "fast-128ss": { @@ -794,259 +1069,263 @@ "fast" ], "summary": { - "de00": 0.3272947353441719, - "turning": 0.08915116534000106, - "ratio": 2.206000729098915, - "self_res": 0.004836093223955657, + "de00": 0.2844587557422103, + "turning_gap": 2.9248292053504192, + "ratio_gap": 0.6062328846353512, + "geom": 0.1497389337474883, + "turning": 0.08895011297504189, + "ratio": 2.0331867087598345, + "self_res": 0.004563406866506936, + "geom_far": 0.022197417702940248, "n": 246 }, "icons": { - "lucide/app-window-mac": [0.185710743, 0.0371192036, 8.5, 0.00333347707, "4370df162cc57da9"], - "lucide/audio-lines-x": [0.332456619, 0.0641148949, 15.5, 0.00524950214, "ce68f446b6585644"], - "lucide/badge-russian-ruble": [0.641719759, 0.0950633274, 4.50704225, 0.00859518629, "b342d5c35c3bd8d4"], - "lucide/bath": [0.35237214, 0.0862550352, 5.02702703, 0.00468678167, "698e0d5d61d189f5"], - "lucide/bell": [0.346836388, 0.0390675443, 3.33333333, 0.00515256403, "87ee26d921ad3b7d"], - "lucide/birdhouse": [0.275581568, 0.056761581, 6.22727273, 0.00416475162, "0967f866c221b8e9"], - "lucide/book-heart": [0.308683425, 0.0358413459, 2.59016393, 0.00503815291, "72ab193329ff7af3"], - "lucide/bug": [0.522912979, 0.0846357426, 4.56756757, 0.00725289201, "c8535989c573d997"], - "lucide/cat": [0.377898425, 0.0503732441, 2.11267606, 0.00529330363, "323f05704d7a7c2c"], - "lucide/chess-king": [0.313565493, 0.0557457707, 2.1, 0.00498046866, "e7e28356264db1ec"], - "lucide/circle-arrow-right": [0.0926338956, 0.0444818085, 5.66666667, 0.00396848144, "1b572c8f744f875e"], - "lucide/closed-caption": [0.310615987, 0.036426855, 8.6, 0.00485911639, "5e2baec53b323ea7"], - "lucide/cooking-pot": [0.290027887, 0.0519588726, 3.54545455, 0.00434881402, "df2fca847610f62d"], - "lucide/diff": [0.193926901, 0.0651688559, 16.3333333, 0.00301537593, "afd736f2269a0a56"], - "lucide/equal": [0.112944782, 0.0334218714, 8.0, 0.00236840337, "2ea95b516b87876a"], - "lucide/file-digit": [0.34182924, 0.0597096519, 4.0, 0.00528875599, "0327fc83f9b6911c"], - "lucide/focus": [0.352155775, 0.0776105187, 4.14893617, 0.00501565402, "0bdb1d354afea7da"], - "lucide/folder-open": [0.392631322, 0.031312089, 2.35135135, 0.0054079541, "50571eecb96455d8"], - "lucide/git-compare": [0.340108961, 0.0543249216, 5.21428571, 0.00468295207, "fadbbe611ef1d3d6"], - "lucide/hard-drive-download": [0.295192927, 0.0490689637, 9.4375, 0.00426527997, "56bdc389b3369f54"], - "lucide/ice-cream-cone": [0.238506734, 0.0480459133, 3.82352941, 0.00369083206, "752711bcb5baef56"], - "lucide/iteration-ccw": [0.246504098, 0.0487804003, 8.92307692, 0.00378274359, "f0b92cc14b7da876"], - "lucide/list-checks": [0.257982641, 0.0627430729, 10.1428571, 0.00379782286, "b984a60607941df4"], - "lucide/message-circle-dashed-check": [0.478847235, 0.0807460604, 4.9375, 0.00629045069, "457f58c4459db212"], - "lucide/messages-square": [0.335977137, 0.0453659054, 2.55696203, 0.00520234928, "074e7fa8d541e7cd"], - "lucide/navigation-2-off": [0.249188572, 0.060150561, 8.375, 0.00405201642, "e07f3766c3650c0d"], - "lucide/omega": [0.293658346, 0.0394449229, 2.41860465, 0.00411113631, "417bca2ab27bbd4f"], - "lucide/panel-right": [0.256172717, 0.0218055423, 12.25, 0.00546228746, "425dae62220f84ce"], - "lucide/pen-line": [0.228113547, 0.0253682809, 2.88888889, 0.00430836389, "5978ad9b79c0b040"], - "lucide/phone-forwarded": [0.477118254, 0.044335808, 2.61363636, 0.00652262382, "4561145d896f10d5"], - "lucide/rectangle-goggles": [0.293809593, 0.030356696, 2.16393443, 0.0045046336, "88fbfea0aff3e2ae"], - "lucide/save-pen": [0.403666854, 0.0456457209, 2.70212766, 0.00586416246, "3bfe1a2ad3093863"], - "lucide/shapes": [0.224023134, 0.0599412851, 4.20588235, 0.00392420171, "71dfdbd4bf379a58"], - "lucide/shopping-cart-plus": [0.370610327, 0.0728212512, 4.65116279, 0.0052885171, "b47b6161157083f5"], - "lucide/sparkle": [0.215609342, 0.0472725079, 2.34285714, 0.00305223651, "3e061fe5975a88ab"], - "lucide/square-minus": [0.26608482, 0.022879731, 16.5, 0.00555396033, "b06e3de17a2b9913"], - "lucide/swiss-franc": [0.20040907, 0.066583951, 13.75, 0.00242800242, "48df91b2c19241d4"], - "lucide/ticket-minus": [0.330384284, 0.0460451383, 3.62962963, 0.00478204479, "b573d0a9dbe4cad5"], - "lucide/undo": [0.187916756, 0.0494075176, 3.8, 0.00263408571, "becbb0421b889b06"], - "lucide/vegan": [0.424452007, 0.0455704725, 7.64285714, 0.00589647517, "de4b747385788254"], - "material-icons/12mp": [0.412461638, 0.0688747076, 1.5125, 0.00640007434, "af8195d5ac3c9201"], - "material-icons/admin_panel_settings": [0.225710794, 0.047479702, 1.05737705, 0.00335453986, "276f8d7a3bb6ccb9"], - "material-icons/arrow_drop_down": [0.0350502543, 0.0496446402, 3.0, 0.000845157367, "0a29f1249b136eba"], - "material-icons/bento": [0.217312485, 0.0395486051, 1.0875, 0.00473513082, "53ca403e8e094c2a"], - "material-icons/border_left": [0.351888776, 0.168218861, 1.86764706, 0.00473465258, "a606c953a0c3cba7"], - "material-icons/call": [0.32593596, 0.0565559325, 1.1559633, 0.00397302955, "8cbe983df3581a5e"], - "material-icons/chair": [0.440689743, 0.0544408988, 1.2195122, 0.00594721781, "aa7aa27517b5ae1c"], - "material-icons/closed_caption": [0.309099436, 0.0542349812, 1.11594203, 0.00436365465, "6610b1bb01aacd07"], - "material-icons/crop_landscape": [0.158616483, 0.0233012644, 1.7, 0.00306492206, "89ad5cf4e3c237a7"], - "material-icons/dining": [0.418693274, 0.0446230914, 1.09722222, 0.00742426887, "58d7c7159ecd5c6e"], - "material-icons/double_arrow": [0.092873618, 0.0655869828, 2.8, 0.00148016226, "6127a12ee09a336b"], - "material-icons/dynamic_feed": [0.267208517, 0.0595856969, 1.73684211, 0.00427174242, "f1fe87528d2f21c6"], - "material-icons/expand_circle_down": [0.0641659945, 0.0339357057, 0.35, 0.00339140068, "1519383fd02ae61d"], - "material-icons/flight": [0.112343751, 0.0536199698, 1.45454545, 0.00208165776, "be6e218867ec93be"], - "material-icons/free_breakfast": [0.228617027, 0.0480120376, 1.74647887, 0.00403358601, "12e9e2b402fc02a7"], - "material-icons/group_remove": [0.264372647, 0.0558650848, 0.947761194, 0.00376838236, "c0537f973273d322"], - "material-icons/headset": [0.257491529, 0.0434756147, 1.18604651, 0.00338613451, "239c19fdcd16e8ad"], - "material-icons/houseboat": [0.398658842, 0.082569121, 1.51315789, 0.00488688145, "201bd56169c92f09"], - "material-icons/javascript": [0.174566761, 0.120544195, 1.1875, 0.00196964038, "320b4fe79141f10a"], - "material-icons/laptop": [0.179584295, 0.0508409287, 1.625, 0.0037944715, "a670ed54db770102"], - "material-icons/lyrics": [0.309328556, 0.0723488808, 1.57009346, 0.00502379145, "1b9edd124e9cba0c"], - "material-icons/miscellaneous_services": [0.332327664, 0.117970373, 0.672413793, 0.00415350217, "8e87c39e3e202944"], - "material-icons/music_note": [0.10909576, 0.0687812696, 1.05660377, 0.00158523861, "d2e835a60011c86e"], - "material-icons/no_food": [0.268442392, 0.0534356377, 1.97560976, 0.00540149165, "3384654f955b9184"], - "material-icons/notifications_paused": [0.278263837, 0.062868313, 1.82608696, 0.00397877395, "e4e5ff14a8a88d35"], - "material-icons/perm_media": [0.218644485, 0.0301172797, 1.4, 0.00484212209, "625c090cdd764190"], - "material-icons/phone_iphone": [0.141642347, 0.0484394104, 1.14705882, 0.00320661929, "b66e972adbb2af71"], - "material-icons/polyline": [0.171987161, 0.0728148969, 1.51724138, 0.00284926477, "018293d390a123e8"], - "material-icons/qr_code": [0.344963044, 0.104247236, 2.22916667, 0.00450439425, "11610c8b661952fb"], - "material-icons/report": [0.166474447, 0.0363624442, 1.73170732, 0.00253212149, "19ec5e49aed482a5"], - "material-icons/rule_folder": [0.272131324, 0.0551856935, 1.45238095, 0.00449625636, "07fcf043d53f393f"], - "material-icons/sd_card_alert": [0.240270272, 0.0343625967, 1.56, 0.00412956625, "ee28fd0221f9e870"], - "material-icons/settings_overscan": [0.194451049, 0.0428227836, 1.8125, 0.00408073841, "6e1150a12f27c465"], - "material-icons/sms_failed": [0.227611065, 0.0512309722, 1.72, 0.00455178646, "8a145bc7feaca37c"], - "material-icons/storage": [0.234608009, 0.0661021149, 2.625, 0.0057143257, "2d12544c811160cf"], - "material-icons/table_rows": [0.207334891, 0.0309522582, 1.64285714, 0.00419419212, "b5c3f4ed75429067"], - "material-icons/transfer_within_a_station": [0.24456878, 0.0967250309, 1.30555556, 0.0037468404, "ac009574aa3f47b8"], - "material-icons/two_wheeler": [0.215971172, 0.0890961942, 0.971014493, 0.003265979, "7d22c66fe5725468"], - "material-icons/video_camera_back": [0.186994776, 0.0698499619, 2.27586207, 0.00406230846, "1893061ad6ceada9"], - "material-icons/view_week": [0.193248123, 0.0500851673, 1.42857143, 0.00457332795, "ed6aeb922d78fd66"], - "noto-emoji/emoji_u0030": [0.200073808, 0.0741918814, 1.09259259, 0.00249768444, "5f3e2fb14d39c49b"], - "noto-emoji/emoji_u1f36a": [0.820866108, 0.16115655, 1.2417962, 0.00915568229, "7768c444a52df7eb"], - "noto-emoji/emoji_u1f39e": [1.33048439, 0.108601612, 1.00872093, 0.0122558177, "b39716f90a2b7e10"], - "noto-emoji/emoji_u1f3c2_1f3fd": [1.26329327, 0.139265097, 0.791356185, 0.0113199661, "4173c192b306f0ae"], - "noto-emoji/emoji_u1f3c4_1f3fe": [0.780294955, 0.232649255, 0.775, 0.0102006765, "34199d0ff054d3b4"], - "noto-emoji/emoji_u1f3cb_200d_2642": [0.66585356, 0.369864133, 0.644239631, 0.00719138747, "07172f797f6f4670"], - "noto-emoji/emoji_u1f41b": [0.388025165, 0.16558219, 1.54973822, 0.00442166161, "04257bbcb657dd0f"], - "noto-emoji/emoji_u1f44d_1f3fc": [0.289531469, 0.126713446, 1.22160665, 0.00405694498, "b0c8675ae26465b6"], - "noto-emoji/emoji_u1f468_1f3fb_200d_2764_200d_1f468_1f3fd": [0.721440852, 0.127637098, 0.803442029, 0.00788867474, "3121487b5502d6d1"], - "noto-emoji/emoji_u1f468_1f3ff_200d_1f393": [0.918802381, 0.145976797, 1.12039312, 0.00921146944, "ab38d2421d83322e"], - "noto-emoji/emoji_u1f469_1f3fb_200d_1f52c": [1.20233095, 0.182039658, 1.55083179, 0.0114884349, "adc8fb97fb083778"], - "noto-emoji/emoji_u1f469_1f3fc_200d_1f91d_200d_1f468_1f3fb": [0.754489005, 0.180626561, 0.484149856, 0.00844657701, "383bd4008106f07a"], - "noto-emoji/emoji_u1f469_1f3fe_200d_1faef_200d_1f469_1f3fd": [0.978150606, 0.24252106, 0.568824066, 0.0106971012, "3251aa9ae4061cde"], - "noto-emoji/emoji_u1f469_200d_1f469_200d_1f466_200d_1f466": [0.465088308, 0.0637871611, 0.841059603, 0.00612520287, "5bb7680798c446e6"], - "noto-emoji/emoji_u1f46c_1f3fd": [0.776843429, 0.220664035, 0.395366795, 0.00841660425, "4f61a5d86dab6e79"], - "noto-emoji/emoji_u1f470_1f3fb_200d_2640": [0.913554192, 0.133796877, 1.35616438, 0.0114273196, "5b3aa9462ed7dc00"], - "noto-emoji/emoji_u1f482_1f3ff_200d_2640": [0.710701883, 0.149393657, 0.760080645, 0.00896317512, "afb146f0146bccd7"], - "noto-emoji/emoji_u1f4d8": [0.208591521, 0.0367844871, 1.3047619, 0.00379239698, "c0a472f097c63188"], - "noto-emoji/emoji_u1f520": [0.118464477, 0.0596513635, 0.735159817, 0.00202970183, "51dc6ceb78a6db25"], - "noto-emoji/emoji_u1f56f": [0.485260606, 0.147660684, 1.04123711, 0.00426189834, "78622f7f8c25264b"], - "noto-emoji/emoji_u1f5a8": [0.494243443, 0.0872262597, 1.59767442, 0.00644493476, "4a9c8ead0a39fc1a"], - "noto-emoji/emoji_u1f62d": [1.07784295, 0.109873345, 1.51651652, 0.00886725169, "732758ce65841b2c"], - "noto-emoji/emoji_u1f64b_1f3fe_200d_2640": [0.820308626, 0.119318687, 0.819548872, 0.00942133833, "fbae602cb8e5b27c"], - "noto-emoji/emoji_u1f6c0_1f3ff": [0.699750245, 0.298153125, 1.06382979, 0.0068097231, "edb5b5d864a0ae78"], - "noto-emoji/emoji_u1f90d": [0.0504896902, 0.0575133626, 1.21590909, 0.000893456163, "9c9f5db43c618803"], - "noto-emoji/emoji_u1f91c_1f3fe": [0.245362043, 0.091960208, 1.42222222, 0.00412594574, "68036c15f27d12fa"], - "noto-emoji/emoji_u1f926_1f3ff": [1.02265203, 0.174665165, 0.986238532, 0.0107090697, "f4b5c7295e5dcc10"], - "noto-emoji/emoji_u1f932": [0.411065459, 0.132027655, 1.09982175, 0.00513468171, "c461e3faa5395855"], - "noto-emoji/emoji_u1f93c_1f3fe_200d_2640": [0.971017897, 0.248456366, 0.575618698, 0.0111067211, "cb83f312a711841c"], - "noto-emoji/emoji_u1f987": [0.742096305, 0.14936713, 0.998275862, 0.008174791, "aec05791726ef4fb"], - "noto-emoji/emoji_u1f9be": [0.60540688, 0.199048947, 1.40598802, 0.00584342191, "b72ddf15c7ff0646"], - "noto-emoji/emoji_u1f9ce_1f3fd_200d_2642": [0.287083119, 0.191637502, 0.691176471, 0.00352219562, "1287388044081e04"], - "noto-emoji/emoji_u1f9cf_1f3fc": [0.589500308, 0.135500602, 1.08198614, 0.00599421328, "959fb6e8ad0c764d"], - "noto-emoji/emoji_u1f9d1_1f3fc_200d_1f37c": [0.534786105, 0.257611574, 0.98758465, 0.00644727098, "e34663090d715fc8"], - "noto-emoji/emoji_u1f9d1_1f3fd_200d_1f91d_200d_1f9d1_1f3ff": [0.999623537, 0.289409385, 0.653284672, 0.0116260266, "1aace90ac2342221"], - "noto-emoji/emoji_u1f9d1_1f3fe_200d_1f9bc_200d_27a1": [0.685739398, 0.352296751, 0.948621554, 0.00777735049, "c7a7be70c10fbfae"], - "noto-emoji/emoji_u1f9d6_1f3fe_200d_2642": [0.694824874, 0.133913627, 1.20833333, 0.00730934041, "95bcaeda0917ffa0"], - "noto-emoji/emoji_u1f9dd_1f3fd_200d_2640": [1.12138271, 0.228583511, 1.27007299, 0.0113618104, "a8d8f5056360dc79"], - "noto-emoji/emoji_u1f9ed": [0.311286271, 0.129939008, 1.6814346, 0.0043834853, "a9aee2b6e66149cf"], - "noto-emoji/emoji_u1faa5": [0.162420228, 0.242282086, 1.05902778, 0.00223627617, "9ed650592e450b48"], - "noto-emoji/emoji_u1faf1_1f3fc_200d_1faf2_1f3ff": [0.431536794, 0.170266579, 0.906821963, 0.00577204162, "7d052cc740aa8cff"], - "noto-emoji/emoji_u26bd": [0.523475587, 0.120842121, 1.73593074, 0.00656910287, "9e4dfd9fc8723f18"], - "noto-emoji/emoji_u2b05": [0.057560198, 0.0328402362, 1.1025641, 0.000856071652, "7746488a495b201e"], - "openmoji/1F195": [0.282797933, 0.0719463345, 6.94117647, 0.0051785605, "c0daa7d11e447cc5"], - "openmoji/1F1FF-1F1F2": [0.12538597, 0.0526324588, 2.41666667, 0.00260711857, "e61945883e5370d9"], - "openmoji/1F361": [0.296219081, 0.0799386607, 1.84285714, 0.00412182789, "d798bf9a62b7bf31"], - "openmoji/1F38A": [0.453896821, 0.105855229, 1.765625, 0.00534460275, "37e6d11614a22673"], - "openmoji/1F3A9": [0.25191465, 0.0403989254, 1.62686567, 0.00440263608, "680eed5f9ecb4959"], - "openmoji/1F3C3-1F3FF-200D-2642-FE0F": [0.234728247, 0.0979795032, 1.77202073, 0.00326705002, "0d6cdf26ff562197"], - "openmoji/1F3CC-FE0F-200D-2640-FE0F": [0.608263433, 0.121180372, 1.29296875, 0.00653294707, "5f36d6eda12a45b6"], - "openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F": [0.083631292, 0.0279642507, 3.6, 0.00382303423, "815fad596f65c6c1"], - "openmoji/1F442-1F3FF": [0.239113912, 0.0872077752, 3.42105263, 0.0028888674, "5b0dc5b56215a827"], - "openmoji/1F468-1F3FC-200D-1F3ED": [0.685219586, 0.174840622, 0.56744186, 0.00875883084, "d999ee2e0cfb262a"], - "openmoji/1F468-1F3FF-200D-1F9B0": [0.318721026, 0.0896200517, 1.15384615, 0.0040032845, "e14a3789a5ef6756"], - "openmoji/1F468-200D-1F9B1": [0.67901516, 0.164790768, 1.21788991, 0.00740602799, "90396655a80d0f43"], - "openmoji/1F469-1F3FC-200D-2764-FE0F-200D-1F48B-200D-1F469-1F3FC": [0.877756715, 0.109306324, 1.77619048, 0.00908509735, "6e1289d460b556f1"], - "openmoji/1F469-1F3FF-200D-1F9B2": [0.223988101, 0.0775158703, 1.39473684, 0.00298636523, "1bd66012f5dc4ab0"], - "openmoji/1F481-1F3FB-200D-2642-FE0F": [0.48415941, 0.0960394057, 1.62222222, 0.00634235702, "fbb5650247b95628"], - "openmoji/1F49B": [0.167540506, 0.0345469192, 0.886363636, 0.00220308988, "8965dfe4d66d7a1e"], - "openmoji/1F517": [0.407957494, 0.0925405048, 1.83216783, 0.00548072113, "757a63e1b1f23188"], - "openmoji/1F646-1F3FC": [0.613615692, 0.0780968153, 0.965065502, 0.00701190019, "176a0c1ac9180b10"], - "openmoji/1F6B4-1F3FD-200D-2640-FE0F": [0.46395421, 0.118020316, 2.06818182, 0.00617369218, "b027168d538a64fe"], - "openmoji/1F6E0": [0.403581709, 0.109390042, 1.9375, 0.00523658143, "199b59d24bb36442"], - "openmoji/1F938-1F3FB": [0.372529268, 0.0927473842, 1.59649123, 0.00465087406, "7fe551c3b041a543"], - "openmoji/1F93E-1F3FE": [0.399378985, 0.0986332045, 1.77777778, 0.00483221607, "ac410d9d9cf6bbc1"], - "openmoji/1F9B3": [0.273929924, 0.0698201213, 4.12121212, 0.00299347867, "f506740003cafa6b"], - "openmoji/1F9D1": [0.406867743, 0.0896705077, 1.49541284, 0.00464513339, "b958c0aecb12f8e4"], - "openmoji/1F9D1-1F3FC-200D-1FA70": [0.511360466, 0.130415414, 1.74615385, 0.00598643022, "6c835f78ed849564"], - "openmoji/1F9D1-1F3FD-200D-1F527": [0.542833686, 0.135805618, 1.07287449, 0.00694017857, "58d7a5f6cf32ab37"], - "openmoji/1F9D1-200D-1F393": [0.59319067, 0.123658382, 0.388429752, 0.00742608123, "b4462b63c21b997d"], - "openmoji/1F9D6-1F3FD-200D-2642-FE0F": [0.453608274, 0.141346473, 1.32439678, 0.00619149441, "6f5e473cdcd39df3"], - "openmoji/1FA8B": [0.369469732, 0.140395496, 0.429487179, 0.00391992787, "ae59baea30d8de0e"], - "openmoji/1FAC4-1F3FD": [0.372191817, 0.111556408, 0.893890675, 0.00486537209, "73cad235105fff0c"], - "openmoji/25FC": [0.108519986, 0.033345695, 1.0, 0.00202923943, "43aa07a05c0b5f31"], - "openmoji/2705": [0.285441458, 0.0543289693, 1.85526316, 0.00404101657, "f4cad673663313ab"], - "openmoji/E056": [0.564562082, 0.0765682077, 0.807807808, 0.00732708769, "274e374aab0f99bb"], - "openmoji/E1D1": [0.343904525, 0.0739189621, 0.98265896, 0.00574624026, "22b130dd368faa2d"], - "openmoji/E30B": [0.33616823, 0.112526243, 1.55555556, 0.00573227787, "bb1e746214074589"], - "simple-icons/alchemy": [0.199416161, 0.0349085731, 0.39245283, 0.00283155218, "47ba3ed192649faa"], - "simple-icons/appletv": [0.30572018, 0.0926097636, 1.30994152, 0.00435886765, "3ba35d218e6a4dd0"], - "simple-icons/atlassian": [0.245094091, 0.0233765897, 0.984615385, 0.00312906876, "6b53f86be90dc537"], - "simple-icons/autocad": [0.155439422, 0.0340393793, 1.4516129, 0.00445101829, "59b5fcf5e0a4e6b3"], - "simple-icons/bandrautomation": [0.410600513, 0.102471925, 1.13636364, 0.00644339761, "466c3cc69c784dae"], - "simple-icons/bim": [0.301137745, 0.0892839764, 1.34751773, 0.00484643085, "b2815f2313f7655d"], - "simple-icons/boosty": [0.16817148, 0.0552660709, 1.90909091, 0.00233537261, "27413076a39617fe"], - "simple-icons/changedetection": [0.465900511, 0.0496295885, 0.565957447, 0.00660400325, "415035369117ea61"], - "simple-icons/cocos": [0.949200809, 0.125200546, 0.46741573, 0.0128293512, "716f9df2e4edc4d1"], - "simple-icons/contentstack": [0.475014776, 0.0593447141, 0.578431373, 0.00951047335, "347520a86f87e2eb"], - "simple-icons/debridlink": [0.323845893, 0.0411976769, 0.63030303, 0.00430142274, "675c8a70b2ed8bfb"], - "simple-icons/elixir": [0.18953377, 0.0288220204, 1.13207547, 0.00228415104, "8fb95905284ebcb2"], - "simple-icons/fampay": [0.356670469, 0.0462118482, 0.79144385, 0.00470521254, "3b271fadba7855d0"], - "simple-icons/fluxer": [0.457473308, 0.0513652309, 1.00877193, 0.00570738548, "5fbc3efd8245bca9"], - "simple-icons/googlechrome": [0.303088397, 0.0496551373, 1.85714286, 0.00414512446, "56fba37335378a23"], - "simple-icons/h2database": [0.444306761, 0.0573597313, 0.921465969, 0.00689577544, "987c21760d388d6f"], - "simple-icons/hitachi": [0.320584059, 0.167280175, 0.843537415, 0.00418390008, "4642146dc066877c"], - "simple-icons/infinityfree": [0.679077506, 0.181699977, 0.900726392, 0.0080523314, "590e984a2f43b924"], - "simple-icons/jdoodle": [0.397483021, 0.0802536195, 0.738693467, 0.00595798856, "9b423286f7440ed4"], - "simple-icons/kleinanzeigen": [0.355286568, 0.0366278793, 1.2, 0.0054445751, "85a06894d3535783"], - "simple-icons/leetcode": [0.295380414, 0.041063737, 1.03448276, 0.00461473642, "152a5149bd50de8b"], - "simple-icons/looker": [0.303738832, 0.0743880366, 1.10497238, 0.00438735029, "55577826cffed578"], - "simple-icons/mamp": [0.331317455, 0.0887067431, 1.66666667, 0.00414751843, "b4a9148445a19bf5"], - "simple-icons/microeditor": [0.422833025, 0.0553192456, 0.395918367, 0.00549675478, "77fa960f7559c701"], - "simple-icons/mysql": [0.679875791, 0.148773859, 0.562043796, 0.0086382702, "6ef5261efeafdc81"], - "simple-icons/notion": [0.369160414, 0.0402015249, 1.31460674, 0.00668299152, "0a6048df7940bb45"], - "simple-icons/osano": [0.14111723, 0.0391882985, 3.35714286, 0.00220372831, "1a3f9fac1affe142"], - "simple-icons/phpstorm": [0.264509141, 0.0491851736, 1.01388889, 0.00378561602, "12f2cdc3f94d1608"], - "simple-icons/playerfm": [0.440882862, 0.0525950421, 0.694444444, 0.0058713425, "48bad3c97dd4faef"], - "simple-icons/premierleague": [0.65465486, 0.149954852, 1.10900474, 0.00778976083, "2b04b979ab360590"], - "simple-icons/pronounsdotpage": [0.261774331, 0.0401507234, 0.76744186, 0.00396776386, "0ebe373c0899e368"], - "simple-icons/purescript": [0.206668168, 0.0918436987, 2.37037037, 0.00291508692, "756aa9d6c71d88c9"], - "simple-icons/redsys": [0.243667319, 0.0562124316, 0.915492958, 0.00297851558, "cb4826d9df545a5d"], - "simple-icons/sagemath": [0.97571224, 0.120955604, 0.882602546, 0.0123865455, "1240031ccc3db96c"], - "simple-icons/slackware": [0.257138997, 0.0384039027, 0.663507109, 0.00493547088, "d9fff652f3016055"], - "simple-icons/sparkar": [0.111130938, 0.045683556, 2.66666667, 0.00212593842, "35fdba7472271f9f"], - "simple-icons/stmicroelectronics": [0.209835544, 0.0424446214, 0.766233766, 0.00343256909, "726943c93dc2918e"], - "simple-icons/ubiquiti": [0.548573017, 0.0664331881, 0.575221239, 0.00647283858, "807d5b35ebdeaea0"], - "simple-icons/visa": [0.28623262, 0.0861037936, 1.42647059, 0.00371763925, "ce9a6497b75c611a"], - "simple-icons/wxt": [0.390765309, 0.0687414871, 1.20618557, 0.00562815974, "5bf6bdce177b47b3"], - "synthetic/gradient_linear": [0.111574046, 0.0138968071, 3.83333333, 0.000468335114, "d0ee620ff7dd84c9"], - "synthetic/mosaic_grid6": [0.117222466, 0.0814038648, 2.36936937, 0.00241951854, "793a6cda544e52c9"], - "synthetic/prim_ellipse": [0.00541907735, 0.015931088, 1.2, 0.000333339704, "a523fe154043e9c2"], - "synthetic/prim_star5": [0.0635904968, 0.0373922834, 3.83333333, 0.000854013429, "8616a8671ffd7142"], - "synthetic/symmetry_rot3": [0.102902867, 0.0254568404, 2.22222222, 0.0010906544, "b3b4499b55f6d9ab"], - "twemoji/1f17e": [0.124316983, 0.020308806, 1.2, 0.001734021, "8bf4761322bcf04c"], - "twemoji/1f1f8": [0.124092899, 0.0305955796, 1.5, 0.00172855111, "29ecd43debbbca14"], - "twemoji/1f1fa": [0.109056331, 0.0224402294, 1.38636364, 0.00162618759, "4ebdaa7206316c67"], - "twemoji/1f325": [0.0889859274, 0.0777550038, 1.35519126, 0.00115353765, "4ea5320bfb79d0de"], - "twemoji/1f369": [0.311694086, 0.0800989938, 0.595505618, 0.00378244952, "4759167b909ccaa0"], - "twemoji/1f3ca-1f3fe-200d-2640-fe0f": [0.197849721, 0.0814962952, 1.1509434, 0.00283944979, "23abde2f197bb70c"], - "twemoji/1f3cc-1f3fb-200d-2640-fe0f": [0.265726358, 0.13587819, 1.09387755, 0.00308689591, "9b4a9ab82264fd66"], - "twemoji/1f42b": [0.253856033, 0.0905467812, 1.04924242, 0.00329118571, "34bc577fecfeee72"], - "twemoji/1f468-1f3fb-200d-1f91d-200d-1f468-1f3fd": [0.470312536, 0.133373211, 0.795744681, 0.00598468771, "a9747d4e79c2a71c"], - "twemoji/1f468-1f3fc-200d-1f9b0": [0.172407776, 0.0869246176, 1.07438017, 0.00216924795, "5fb6a41b7096951f"], - "twemoji/1f468-1f3fe-200d-2764-fe0f-200d-1f48b-200d-1f468-1f3ff": [0.243959993, 0.111517428, 0.775362319, 0.0031963326, "3596a4227f79dcd5"], - "twemoji/1f469-1f3fb-200d-1f37c": [0.495177597, 0.101088258, 0.786666667, 0.0052193962, "53918e8ab9a2f872"], - "twemoji/1f469-1f3fc-200d-2764-fe0f-200d-1f468-1f3fc": [0.248587996, 0.0839921999, 1.23369565, 0.00316714216, "3ddc86ab464ea000"], - "twemoji/1f469-1f3fe": [0.186165944, 0.0506429174, 1.15151515, 0.00244491617, "68e0142047de51c7"], - "twemoji/1f469-1f3ff-200d-1f91d-200d-1f468-1f3fc": [0.595627546, 0.134421443, 0.950431034, 0.00754350424, "7701c471e6693d7f"], - "twemoji/1f469-200d-1f467-200d-1f467": [0.164842635, 0.0632221428, 0.588541667, 0.00236076373, "7e0da8fb184683ee"], - "twemoji/1f470-1f3fc-200d-2640-fe0f": [0.186767593, 0.0562382068, 1.25405405, 0.00254234415, "135ec139e6078a82"], - "twemoji/1f481-1f3fc-200d-2640-fe0f": [0.173147485, 0.0761087382, 1.25675676, 0.00233766157, "f704fde835ad10e4"], - "twemoji/1f486-1f3ff": [0.470079124, 0.153565834, 1.4795082, 0.00531014381, "1e31117f845f579e"], - "twemoji/1f4e6": [0.101616226, 0.0580617548, 0.860655738, 0.00153435348, "24625066669d8991"], - "twemoji/1f53a": [0.0152242528, 0.0248725679, 1.0, 0.000356854522, "5ab05d01e469937f"], - "twemoji/1f57a-1f3fb": [0.420593262, 0.166393104, 0.547244094, 0.00514644338, "2f7044d2b94c495e"], - "twemoji/1f635": [0.261238396, 0.0680652192, 0.893939394, 0.0029523531, "9e1adcb8ed882ed0"], - "twemoji/1f646-1f3fb-200d-2640-fe0f": [0.347923934, 0.0653285081, 1.43478261, 0.00414552493, "d07ea9b458805dc0"], - "twemoji/1f648": [0.242447793, 0.107649806, 0.704284222, 0.00330817956, "32593de4512cfaf0"], - "twemoji/1f64d-1f3fd": [0.23588185, 0.0907879072, 1.2265625, 0.00277593173, "d71499233187d772"], - "twemoji/1f6a3-1f3ff-200d-2642-fe0f": [0.242335707, 0.0814782702, 0.930693069, 0.00331278075, "d5278647fc5a51b3"], - "twemoji/1f6d6": [0.287381709, 0.226841712, 1.44226044, 0.00337755005, "e4c666e4eb053180"], - "twemoji/1f7eb": [0.216007546, 0.0354407659, 1.75, 0.00274092727, "a00abab80f072ea3"], - "twemoji/1f91c-1f3fe": [0.111033395, 0.0692612156, 1.20754717, 0.00156234484, "df9a12872b246f20"], - "twemoji/1f938-1f3fe": [0.312877506, 0.263783305, 0.535587189, 0.00402108906, "b0ce93b7b0322a25"], - "twemoji/1f977-1f3fb": [0.383524597, 0.136757902, 1.07627119, 0.0058795088, "558db96d4ff0153d"], - "twemoji/1f9a8": [0.671174347, 0.0871131213, 1.96440129, 0.00860785414, "587b6cc7dbf0106c"], - "twemoji/1f9c9": [0.168000445, 0.0955402213, 1.66089965, 0.00260109873, "cc0a096103b940c1"], - "twemoji/1f9d1-1f3fd-200d-1f9af-200d-27a1-fe0f": [0.344545275, 0.173582585, 0.5775, 0.00402462762, "0b12ee04df982606"], - "twemoji/1f9d1-1f3ff-200d-2764-fe0f-200d-1f9d1-1f3fb": [0.336702913, 0.0972947002, 1.30188679, 0.00467482628, "f1223df74f1b1858"], - "twemoji/1f9d4-1f3fd": [0.317495942, 0.0703256864, 1.0962963, 0.00393564161, "58ad928891f65076"], - "twemoji/1f9d8-1f3fe": [0.32275933, 0.166882754, 0.939632546, 0.00409666495, "35a05de99ce2e938"], - "twemoji/1f9e9": [0.140459791, 0.0657728691, 0.75, 0.00210482092, "fc00831922fb8a78"], - "twemoji/1faa3": [0.306248873, 0.0982275784, 5.37037037, 0.00367478258, "9701476359f184b1"], - "twemoji/1fae5": [0.206479177, 0.143980161, 2.15873016, 0.00245860894, "ecbe6fad9d2d1b28"], - "twemoji/2196": [0.0525793917, 0.0498555923, 2.28571429, 0.000705394661, "5ec1cd1b9ac65126"], - "twemoji/271d": [0.106190212, 0.0382652206, 1.30769231, 0.0014677915, "934aea8ada069948"] + "lucide/app-window-mac": [0.125598088, 0.0371055263, 6.08333333, 0.0031913009, 0.0317413763, 0.0, "fd917fbb43783feb"], + "lucide/audio-lines-x": [0.271918058, 0.0647555644, 13.75, 0.00521335937, 0.0551544865, 0.0, "6b2fc9cd4b1bcc42"], + "lucide/badge-russian-ruble": [0.625537097, 0.11447701, 4.36619718, 0.00853726268, 0.135142129, 0.0, "99538c3fb50a551e"], + "lucide/bath": [0.255576998, 0.0759449206, 4.75675676, 0.00430812454, 0.0734495755, 0.0, "cf33a2e21c6064a3"], + "lucide/bell": [0.294154406, 0.0393384879, 3.52380952, 0.00461832667, 0.0936520654, 0.0, "7299b336d1688e24"], + "lucide/birdhouse": [0.16129069, 0.0576529156, 5.68181818, 0.00326286792, 0.0469943453, 0.0, "1c8868f71964a624"], + "lucide/book-heart": [0.259445369, 0.0361613263, 2.36065574, 0.00517434534, 0.047982812, 0.0, "67988a35899a5d14"], + "lucide/bug": [0.459001511, 0.0847523153, 4.24324324, 0.00692114746, 0.105368892, 0.0, "a105552b873386a1"], + "lucide/cat": [0.388058692, 0.0513008746, 2.22535211, 0.00529497908, 0.0976337988, 0.0, "a45546778084262d"], + "lucide/chess-king": [0.254976839, 0.0552127215, 2.175, 0.00489597628, 0.0666332712, 0.0, "95ed28b003570cc2"], + "lucide/circle-arrow-right": [0.11369621, 0.0380836999, 6.11111111, 0.00412477972, 0.0269824057, 0.0, "5f29a34798a8d439"], + "lucide/closed-caption": [0.21471177, 0.0366502749, 8.6, 0.00462885806, 0.0500549799, 0.0, "81cb72d4043e5bb8"], + "lucide/cooking-pot": [0.210945666, 0.0519548187, 3.63636364, 0.00450319797, 0.0544857086, 0.0, "9eae660410b1ecc1"], + "lucide/diff": [0.112433091, 0.0504578148, 14.0, 0.00285979616, 0.0306899711, 0.0, "816d87332d5a5294"], + "lucide/equal": [0.0452252552, 0.034897838, 5.5, 0.00230952236, 0.0271296164, 0.0, "671a0553e34f8158"], + "lucide/file-digit": [0.304759324, 0.0720036046, 3.86440678, 0.00530599011, 0.0811567654, 0.0, "8be8086397447719"], + "lucide/focus": [0.32556659, 0.0761483506, 3.63829787, 0.0049194335, 0.110354442, 0.0, "780e214cedf9b26a"], + "lucide/folder-open": [0.284748405, 0.0310205643, 2.43243243, 0.0048562442, 0.0606730781, 0.0, "3ac46babee53f896"], + "lucide/git-compare": [0.24954918, 0.0546902655, 5.0, 0.00441296166, 0.0918928725, 0.0, "fb35abb4e7bbadd9"], + "lucide/hard-drive-download": [0.233464554, 0.0479468386, 8.9375, 0.00411999272, 0.057587573, 0.0, "bf4a89394708301f"], + "lucide/ice-cream-cone": [0.213264868, 0.0490926324, 3.52941176, 0.00350557198, 0.0823389786, 0.0, "897190989d35fbb5"], + "lucide/iteration-ccw": [0.224514663, 0.0476152144, 8.15384615, 0.00349216838, 0.077599252, 0.0, "70ff2ef172195c24"], + "lucide/list-checks": [0.231194764, 0.0635886592, 9.14285714, 0.00386819267, 0.0875933021, 0.0, "8aab9bb576f910e1"], + "lucide/message-circle-dashed-check": [0.519877136, 0.0811756294, 4.84375, 0.0067260745, 0.138539867, 0.0, "ebbdf416142ed3c1"], + "lucide/messages-square": [0.226675764, 0.0384805984, 2.07594937, 0.00470856344, 0.0664506947, 0.0, "8155c56d3486b414"], + "lucide/navigation-2-off": [0.138271838, 0.0474580129, 6.375, 0.00264222384, 0.035277789, 0.0, "176cfb8590e92b81"], + "lucide/omega": [0.262515545, 0.0388701402, 2.41860465, 0.00368484785, 0.097693629, 0.0, "95ebc20df8284a50"], + "lucide/panel-right": [0.125624478, 0.0215602722, 9.25, 0.00552404067, 0.0285685325, 0.0, "ea688b57ecddb9d4"], + "lucide/pen-line": [0.119925752, 0.0257076858, 2.16666667, 0.00337560265, 0.0339580408, 0.0, "de62cb2e56bcb5aa"], + "lucide/phone-forwarded": [0.404591024, 0.0432144741, 2.20454545, 0.00604607118, 0.0928593655, 0.0, "cc73c91fd889fabb"], + "lucide/rectangle-goggles": [0.194806755, 0.0311441121, 2.13114754, 0.0040146769, 0.0561596968, 0.0, "24ca7170e69ea259"], + "lucide/save-pen": [0.32175523, 0.0460186835, 2.23404255, 0.00605181605, 0.0766920379, 0.0, "aeba41099a64a6fe"], + "lucide/shapes": [0.171095699, 0.0553273988, 3.26470588, 0.00364583358, 0.0510401055, 0.0, "c87c410a0cb06ff8"], + "lucide/shopping-cart-plus": [0.314185739, 0.0708721495, 4.41860465, 0.0049869311, 0.0714088303, 0.0, "38f03bc9022ea2ca"], + "lucide/sparkle": [0.308857173, 0.0483442188, 2.68571429, 0.00410156278, 0.0861487819, 0.0, "348ea5adf4c93154"], + "lucide/square-minus": [0.129992396, 0.0219318882, 11.0, 0.00531771779, 0.02891987, 0.0, "0f05313bfc76be8f"], + "lucide/swiss-franc": [0.156445652, 0.0654714175, 13.25, 0.00232029334, 0.0569106277, 0.0, "bde2aa327a39f5cb"], + "lucide/ticket-minus": [0.234774411, 0.0469125498, 3.40740741, 0.00453120191, 0.0596911635, 0.0, "7c421bc0dc0e6361"], + "lucide/undo": [0.146684691, 0.0486948735, 3.3, 0.00250459556, 0.0883607866, 0.0, "c65ad7671f3fcbde"], + "lucide/vegan": [0.386240631, 0.0448901977, 7.64285714, 0.00603362406, 0.0864453961, 0.0, "e086455e7612876c"], + "material-icons/12mp": [0.327397972, 0.0772899843, 1.45, 0.00636608573, 0.0459036176, 0.0, "462dc51d7b585874"], + "material-icons/admin_panel_settings": [0.168283254, 0.0463670706, 1.02459016, 0.00291700172, 0.0473600508, 0.0, "f913d42b9fabceeb"], + "material-icons/arrow_drop_down": [0.0128676733, 0.0588817008, 3.33333333, 0.000711119443, 0.0107898106, 0.0, "d5a05a3697815670"], + "material-icons/bento": [0.153607503, 0.0420462158, 1.1875, 0.00486438209, 0.0355732416, 0.0, "4785dc07dda4c64a"], + "material-icons/border_left": [0.252503663, 0.174266349, 2.08823529, 0.00443976885, 0.0554281931, 0.0, "d4b62921d3f64504"], + "material-icons/call": [0.291278332, 0.0571187639, 1.19266055, 0.00367168337, 0.131345142, 0.0, "528b95eabf1a2c29"], + "material-icons/chair": [0.298544377, 0.0560192624, 1.13414634, 0.00556975743, 0.0614257771, 0.0, "b9f686c6bfc78567"], + "material-icons/closed_caption": [0.25016138, 0.0536196337, 1.14492754, 0.00418318203, 0.0406353834, 0.0, "16149760d043e591"], + "material-icons/crop_landscape": [0.078274779, 0.0233259745, 1.7, 0.00297540403, 0.0178860101, 0.0, "c8c2575ede3774ac"], + "material-icons/dining": [0.222283572, 0.0444119989, 1.02777778, 0.0075037335, 0.0342532124, 0.0, "dbc84acee57ca68d"], + "material-icons/double_arrow": [0.0732547715, 0.0659449927, 2.6, 0.00142247824, 0.0313710823, 0.0, "4ca0281ea5990429"], + "material-icons/dynamic_feed": [0.195021495, 0.0610816986, 1.89473684, 0.00414919341, 0.0380145707, 0.0, "adb3e91ce64b7061"], + "material-icons/expand_circle_down": [0.0402147248, 0.0335700831, 0.316666667, 0.00328895729, 0.0251205206, 0.0, "cc2bcf5f94a41cbe"], + "material-icons/flight": [0.0759445876, 0.0670381876, 1.5, 0.00166901236, 0.0424701555, 0.0, "b7f7cd2897dd8d31"], + "material-icons/free_breakfast": [0.196427241, 0.0474999222, 1.74647887, 0.00397590175, 0.058364784, 0.0, "fad87540cf98e844"], + "material-icons/group_remove": [0.198496997, 0.0558404273, 0.873134328, 0.00358168664, 0.0452435559, 0.0, "bc862e4d737ce506"], + "material-icons/headset": [0.226886839, 0.0451580846, 1.48837209, 0.00317741837, 0.0572131548, 0.0, "18daa89423690e65"], + "material-icons/houseboat": [0.369825125, 0.0902808018, 1.40789474, 0.00465877773, 0.0857070425, 0.0, "a696d4cd11d3bb51"], + "material-icons/javascript": [0.161069259, 0.137641379, 1.22916667, 0.00181477854, 0.0866072353, 0.0, "516a5bca6bc2a1e7"], + "material-icons/laptop": [0.119689345, 0.0350122011, 1.54166667, 0.00359700504, 0.0193627776, 0.0, "09d04aa95000aa54"], + "material-icons/lyrics": [0.194782197, 0.0660537507, 1.4953271, 0.0048414045, 0.0347912515, 0.0, "d82119b7fa6a6339"], + "material-icons/miscellaneous_services": [0.2790564, 0.116493175, 0.551724138, 0.00350437569, 0.0919641807, 0.0, "7dc62bdc5027d72d"], + "material-icons/music_note": [0.0675600469, 0.0659826653, 0.981132075, 0.00136168243, 0.0307249643, 0.0, "6ce9602c3dc836e0"], + "material-icons/no_food": [0.178444132, 0.0555833236, 1.75609756, 0.00505777961, 0.0333500945, 0.0, "6aa4da40e0758c35"], + "material-icons/notifications_paused": [0.235363975, 0.0699530362, 1.7826087, 0.00407236116, 0.0589064396, 0.0, "eaebb3340f870cc4"], + "material-icons/perm_media": [0.136370286, 0.0294569451, 1.25, 0.00477247033, 0.0199955243, 0.0, "f0228f3f5c3c48b6"], + "material-icons/phone_iphone": [0.0646785945, 0.0482490397, 0.970588235, 0.00297396793, 0.0167517017, 0.0, "9875c6b07872e326"], + "material-icons/polyline": [0.119554162, 0.0766802337, 1.86206897, 0.00239975867, 0.0236719491, 0.0, "31ad05c30bf7ca88"], + "material-icons/qr_code": [0.201375842, 0.116911701, 2.375, 0.00425594533, 0.0207098124, 0.0, "b390f35cd153e324"], + "material-icons/report": [0.0647933111, 0.0372905087, 1.68292683, 0.00215609721, 0.0126865802, 0.0, "f52717351886fb6e"], + "material-icons/rule_folder": [0.171549127, 0.0552076919, 1.38095238, 0.00421669148, 0.0326756971, 0.0, "d821dd91f81194e5"], + "material-icons/sd_card_alert": [0.0992991254, 0.0360029588, 1.76, 0.00359269674, 0.0201184974, 0.0, "be52aa419a466c3b"], + "material-icons/settings_overscan": [0.1298168, 0.0540114418, 1.65625, 0.00390313822, 0.0705211448, 0.0, "28bc61291dff0dc8"], + "material-icons/sms_failed": [0.105201669, 0.0526069277, 1.84, 0.00446035294, 0.0173841701, 0.0, "978a16d04ca06ed6"], + "material-icons/storage": [0.094249174, 0.0679184522, 2.875, 0.00546874991, 0.0171127558, 0.0, "f5d3e7b7f31bc296"], + "material-icons/table_rows": [0.121323846, 0.0320799435, 1.96428571, 0.00417791633, 0.0283088456, 0.0, "2bb8a9ef7d8bc2e5"], + "material-icons/transfer_within_a_station": [0.185430884, 0.0969545822, 1.17592593, 0.00362979691, 0.0392389535, 0.0, "42de9c521e07f3ac"], + "material-icons/two_wheeler": [0.183046192, 0.0891650317, 1.0, 0.00306851254, 0.0509747445, 0.0, "4cb1766d1b589547"], + "material-icons/video_camera_back": [0.119290426, 0.0821182305, 2.13793103, 0.00392491976, 0.0234598845, 0.0, "ae5bdae1aacff00d"], + "material-icons/view_week": [0.0838879868, 0.0501097363, 1.32142857, 0.00460875267, 0.0132419281, 0.0, "cf8e8616587bce31"], + "noto-emoji/emoji_u0030": [0.182208121, 0.0752313882, 1.14814815, 0.00243598828, 1.13986313, 0.457088716, "1ca62e35e5a413bc"], + "noto-emoji/emoji_u1f36a": [0.790068746, 0.163491602, 1.26770294, 0.00862821937, 0.571318029, 0.18435343, "502c5cb74fefa192"], + "noto-emoji/emoji_u1f39e": [1.24985039, 0.105379898, 1.0377907, 0.010886427, 1.07572373, 0.375656332, "2f75f30d78d9672b"], + "noto-emoji/emoji_u1f3c2_1f3fd": [1.25090003, 0.14343884, 0.794336811, 0.0111690452, 1.39696839, 0.433723701, "f464e6d1865b99cb"], + "noto-emoji/emoji_u1f3c4_1f3fe": [0.733057916, 0.230085256, 0.7484375, 0.00967160705, 0.199727168, 0.000648549058, "ff450034e4fbfc73"], + "noto-emoji/emoji_u1f3cb_200d_2642": [0.643769026, 0.361432006, 0.624884793, 0.00690215593, 0.704203603, 0.160252546, "e6d305a493aa94bc"], + "noto-emoji/emoji_u1f41b": [0.394373029, 0.163507654, 1.48691099, 0.00439395849, 0.134073402, 0.0, "0c49b9ae503f3c26"], + "noto-emoji/emoji_u1f44d_1f3fc": [0.296354562, 0.129766856, 1.22160665, 0.00414510025, 0.144304568, 0.0, "adec3e03efa97907"], + "noto-emoji/emoji_u1f468_1f3fb_200d_2764_200d_1f468_1f3fd": [0.702757537, 0.125032507, 0.744565217, 0.00763086369, 0.53714883, 0.0328511753, "dd6eba5531530581"], + "noto-emoji/emoji_u1f468_1f3ff_200d_1f393": [0.898203731, 0.148430546, 1.13022113, 0.0089202011, 0.686953213, 0.166981247, "83abbdbb5ce52ed1"], + "noto-emoji/emoji_u1f469_1f3fb_200d_1f52c": [1.18263292, 0.18234237, 1.52680222, 0.0113678165, 0.918866988, 0.371424002, "fba7cdeb41476a6a"], + "noto-emoji/emoji_u1f469_1f3fc_200d_1f91d_200d_1f468_1f3fb": [0.729150236, 0.172475968, 0.457252642, 0.00827229675, 0.78524142, 0.027685521, "552adc95ca6d84ca"], + "noto-emoji/emoji_u1f469_1f3fe_200d_1faef_200d_1f469_1f3fd": [0.966063976, 0.235994254, 0.550592525, 0.0106646121, 1.10429231, 0.345400212, "3985bf61551693aa"], + "noto-emoji/emoji_u1f469_200d_1f469_200d_1f466_200d_1f466": [0.381300181, 0.0642491137, 0.725165563, 0.00576092163, 0.0598476464, 0.0, "44eead750bb30937"], + "noto-emoji/emoji_u1f46c_1f3fd": [0.781266153, 0.202960665, 0.360617761, 0.00843623467, 1.13142309, 0.313598882, "6db425e6153382dc"], + "noto-emoji/emoji_u1f470_1f3fb_200d_2640": [0.896702766, 0.141915704, 1.38356164, 0.0115726665, 1.00314909, 0.209256716, "438e3d05fa9de680"], + "noto-emoji/emoji_u1f482_1f3ff_200d_2640": [0.654932082, 0.150364647, 0.737903226, 0.00827999786, 1.20979279, 0.702627539, "130f930bb98bf6cf"], + "noto-emoji/emoji_u1f4d8": [0.219779193, 0.0363123209, 1.22857143, 0.00418397598, 0.102817338, 0.0, "0556c4e8e853fbb9"], + "noto-emoji/emoji_u1f520": [0.103760779, 0.0626056864, 0.712328767, 0.00185283087, 0.0573672991, 0.0, "aec36473eccc8dd8"], + "noto-emoji/emoji_u1f56f": [0.489256263, 0.140777174, 1.04810997, 0.00428472506, 0.826974809, 0.0368802901, "77e990fb7059db73"], + "noto-emoji/emoji_u1f5a8": [0.483421564, 0.0983421622, 1.61627907, 0.00668171793, 0.932557503, 0.465135379, "4c80ab4a9918694e"], + "noto-emoji/emoji_u1f62d": [1.01744485, 0.106481909, 1.48648649, 0.00843851268, 0.670733509, 0.123683254, "12b12ddb7c986319"], + "noto-emoji/emoji_u1f64b_1f3fe_200d_2640": [0.80836463, 0.119937677, 0.807017544, 0.00916942488, 1.3122852, 0.579541285, "7c954adcc5928c8a"], + "noto-emoji/emoji_u1f6c0_1f3ff": [0.690814197, 0.304926033, 1.0546291, 0.00672948314, 0.252653384, 0.00108762946, "5bf6373eb17a526e"], + "noto-emoji/emoji_u1f90d": [0.042845428, 0.0479786746, 1.09090909, 0.000824211573, 0.103686957, 0.0, "30f2c645410a7c45"], + "noto-emoji/emoji_u1f91c_1f3fe": [0.218162507, 0.0956757423, 1.45777778, 0.00348688825, 0.123220005, 6.47503966e-05, "52e338074101b108"], + "noto-emoji/emoji_u1f926_1f3ff": [0.982574224, 0.173718771, 1.00152905, 0.0104172817, 0.846769446, 0.238755809, "ca8d15d8c34f5318"], + "noto-emoji/emoji_u1f932": [0.386205882, 0.137294854, 1.06060606, 0.00500787329, 0.139051313, 0.0, "4a81fa46139129e2"], + "noto-emoji/emoji_u1f93c_1f3fe_200d_2640": [0.928039134, 0.246810606, 0.576535289, 0.0106961951, 0.833164575, 0.208417665, "25a1fc29d5c99ea9"], + "noto-emoji/emoji_u1f987": [0.72085315, 0.145976207, 0.934482759, 0.00785710011, 0.728545714, 0.259167283, "925d13082df5b697"], + "noto-emoji/emoji_u1f9be": [0.570836246, 0.188206396, 1.3508982, 0.00539470464, 0.37794021, 0.0262404321, "8a88e618ff999765"], + "noto-emoji/emoji_u1f9ce_1f3fd_200d_2642": [0.266921431, 0.212227035, 0.718137255, 0.00332672079, 0.340052867, 0.0247202611, "e783a8c32807f4f1"], + "noto-emoji/emoji_u1f9cf_1f3fc": [0.566194475, 0.137590474, 1.06581986, 0.00586276269, 0.741681146, 0.133555013, "29430163a322d9ac"], + "noto-emoji/emoji_u1f9d1_1f3fc_200d_1f37c": [0.540472269, 0.240716714, 0.910835214, 0.00637094164, 0.283550288, 0.0406728903, "71c156deed55c986"], + "noto-emoji/emoji_u1f9d1_1f3fd_200d_1f91d_200d_1f9d1_1f3ff": [0.991392016, 0.291926896, 0.644363341, 0.0115754092, 0.703041988, 0.0802105632, "43aa1e3c25523aaa"], + "noto-emoji/emoji_u1f9d1_1f3fe_200d_1f9bc_200d_27a1": [0.651242971, 0.337873749, 0.899122807, 0.00746761635, 0.457058343, 0.0760853657, "ac7ae2ae298101cd"], + "noto-emoji/emoji_u1f9d6_1f3fe_200d_2642": [0.696063399, 0.132847011, 1.19736842, 0.00728064636, 0.672768885, 0.27218843, "5bf12e1e93380ce3"], + "noto-emoji/emoji_u1f9dd_1f3fd_200d_2640": [1.11151505, 0.220696092, 1.23576642, 0.0113064433, 0.934236734, 0.213638493, "b37082e16a366def"], + "noto-emoji/emoji_u1f9ed": [0.275801063, 0.122504945, 1.58438819, 0.00402369862, 0.102696018, 0.000753732241, "5bb2dd20e11af6ef"], + "noto-emoji/emoji_u1faa5": [0.165842101, 0.196670245, 0.854166667, 0.00225425907, 0.351847799, 0.0166015466, "7074e0fbd6ab7ef5"], + "noto-emoji/emoji_u1faf1_1f3fc_200d_1faf2_1f3ff": [0.408735752, 0.169349989, 0.8718802, 0.0056178309, 0.157400191, 0.0, "1a28b9bbb4c29920"], + "noto-emoji/emoji_u26bd": [0.58578068, 0.117382952, 1.74458874, 0.00721605122, 0.161285552, 0.000849119605, "2a4c7847b892ece6"], + "noto-emoji/emoji_u2b05": [0.0527792983, 0.0328953225, 1.0, 0.000815233216, 0.0355696809, 0.0, "b233aecb11050057"], + "openmoji/1F195": [0.198840231, 0.0777707182, 6.29411765, 0.00451932382, 0.105258991, 0.0, "37ec640ade31972c"], + "openmoji/1F1FF-1F1F2": [0.0571669154, 0.0566406383, 2.125, 0.00259172032, 0.0552697436, 0.0, "f7cff564b9e61dbe"], + "openmoji/1F361": [0.228368655, 0.0808578675, 1.8, 0.00354498555, 0.102709256, 0.0, "a8bd0e3e401eabd6"], + "openmoji/1F38A": [0.351595402, 0.108084374, 1.671875, 0.00466114329, 0.0843546096, 0.0, "9950e605183173b4"], + "openmoji/1F3A9": [0.196154684, 0.0500130218, 1.50746269, 0.00357971271, 0.0710247282, 0.0, "2880613ad2c0e70c"], + "openmoji/1F3C3-1F3FF-200D-2642-FE0F": [0.237764657, 0.102467873, 1.66839378, 0.00326071936, 0.104483362, 0.0, "c79fd0f2d4b69bb0"], + "openmoji/1F3CC-FE0F-200D-2640-FE0F": [0.456955612, 0.111169758, 1.21484375, 0.00539054489, 0.107936009, 0.0, "5dcdc0c3c0b20eff"], + "openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F": [0.0504977033, 0.027972543, 3.8, 0.00376008451, 0.0458912854, 0.0, "a611bf6164501e8c"], + "openmoji/1F442-1F3FF": [0.214605749, 0.0895697707, 3.31578947, 0.00254325569, 0.118180906, 0.0, "b28c4e2d854f9d33"], + "openmoji/1F468-1F3FC-200D-1F3ED": [0.626058996, 0.173104187, 0.531782946, 0.00818622205, 0.127387215, 0.0, "9d9e0802663d46d2"], + "openmoji/1F468-1F3FF-200D-1F9B0": [0.321473092, 0.0848898482, 1.07692308, 0.00408158498, 0.12597098, 0.0, "62627a2de6921379"], + "openmoji/1F468-200D-1F9B1": [0.619376838, 0.149318024, 1.10321101, 0.0068986793, 0.149304922, 0.0, "11416845a88ac298"], + "openmoji/1F469-1F3FC-200D-2764-FE0F-200D-1F48B-200D-1F469-1F3FC": [0.80039227, 0.10295258, 1.71428571, 0.0084929876, 0.134386765, 0.0, "6756f4d2b23ad03d"], + "openmoji/1F469-1F3FF-200D-1F9B2": [0.197986856, 0.076867635, 1.32894737, 0.00259653851, 0.0978012844, 0.0, "6379ff29a30e0207"], + "openmoji/1F481-1F3FB-200D-2642-FE0F": [0.450783521, 0.0956008234, 1.51111111, 0.00604144484, 0.112620364, 0.0, "ba63f8822d6527c2"], + "openmoji/1F49B": [0.140361682, 0.0340756736, 0.931818182, 0.00175446144, 0.0596760014, 0.0, "68db96e6540f9961"], + "openmoji/1F517": [0.336193442, 0.0878949881, 1.74825175, 0.00507720001, 0.11501878, 0.0, "594c49112fce955e"], + "openmoji/1F646-1F3FC": [0.527846873, 0.0899537476, 0.917030568, 0.00645047287, 0.112258854, 0.0, "b4923dc3d3750caf"], + "openmoji/1F6B4-1F3FD-200D-2640-FE0F": [0.41137594, 0.113282181, 1.92045455, 0.0055432599, 0.0939702025, 0.0, "20919f74e45d9f41"], + "openmoji/1F6E0": [0.408662409, 0.111861573, 1.88392857, 0.0052168346, 0.0896599675, 0.0, "c2d471d28930a062"], + "openmoji/1F938-1F3FB": [0.353283435, 0.0902891837, 1.61403509, 0.00457631005, 0.114770785, 0.0, "9ed95fddf552f32d"], + "openmoji/1F93E-1F3FE": [0.39514932, 0.0913174639, 1.59111111, 0.00491173612, 0.142986372, 0.0, "d80c34b5e14da85e"], + "openmoji/1F9B3": [0.209012419, 0.0770652402, 3.81818182, 0.0025685369, 0.108746918, 0.0, "345a50fbe15dae3b"], + "openmoji/1F9D1": [0.397497445, 0.0812783863, 1.28440367, 0.00492201699, 0.125257861, 0.0, "0904dd73784e1c94"], + "openmoji/1F9D1-1F3FC-200D-1FA70": [0.420599431, 0.131470378, 1.73846154, 0.00510207564, 0.121199622, 0.0, "dfd80b0511214e84"], + "openmoji/1F9D1-1F3FD-200D-1F527": [0.488984376, 0.141343922, 1.07692308, 0.00664076582, 0.100424671, 0.0, "ee64f225e8f394d3"], + "openmoji/1F9D1-200D-1F393": [0.505737245, 0.123298938, 0.415289256, 0.00608922774, 0.167226064, 0.00519046279, "54bf215b7655b440"], + "openmoji/1F9D6-1F3FD-200D-2642-FE0F": [0.42651698, 0.15886453, 1.37801609, 0.00587826036, 0.129305519, 0.0, "e97fe14db8ef1c69"], + "openmoji/1FA8B": [0.319846243, 0.14795601, 0.442307692, 0.00357496552, 0.117325567, 0.0, "f0228c9f088afbf0"], + "openmoji/1FAC4-1F3FD": [0.3478688, 0.108832847, 0.903536977, 0.00468968926, 0.116350175, 0.0, "68999d76f29888d0"], + "openmoji/25FC": [0.0752176046, 0.0222703386, 0.916666667, 0.00175446144, 0.115235831, 0.0, "b596a7a534edf6d5"], + "openmoji/2705": [0.257704258, 0.0547655525, 1.77631579, 0.00413007801, 0.0728765405, 0.0, "eb5b338a8a2c9504"], + "openmoji/E056": [0.506752253, 0.0796851484, 0.78978979, 0.00713153509, 0.105042675, 0.0, "ca6442258dd23461"], + "openmoji/E1D1": [0.344318926, 0.0759417412, 0.936416185, 0.00603035279, 0.208201805, 0.0, "af2980913af21258"], + "openmoji/E30B": [0.24806571, 0.0891167859, 1.30769231, 0.00532170758, 0.0454034311, 0.0, "ec1a81e17fc5073d"], + "simple-icons/alchemy": [0.0868740901, 0.0390038749, 0.324528302, 0.00195144955, 0.0291109483, 0.0, "96c15dc5772f779a"], + "simple-icons/appletv": [0.269235373, 0.0949156488, 1.20467836, 0.00379255717, 0.0957002312, 0.0, "5e972193ca81947e"], + "simple-icons/atlassian": [0.164158151, 0.0235730269, 1.07692308, 0.00233537261, 0.0714803603, 0.0, "8ca7251128ccded1"], + "simple-icons/autocad": [0.102243066, 0.0373621437, 1.29032258, 0.00430118339, 0.050857578, 0.0, "3a1a64c544bc9c0b"], + "simple-icons/bandrautomation": [0.316691995, 0.103805843, 1.13636364, 0.00614659861, 0.0972147582, 0.0, "85bc2406a89ee545"], + "simple-icons/bim": [0.248483807, 0.0907292845, 1.43262411, 0.00437849527, 0.0527557867, 0.0, "917e84d646fc2000"], + "simple-icons/boosty": [0.144960195, 0.0567060812, 1.72727273, 0.0021477195, 0.046985063, 0.0, "0df46fc28d983d9d"], + "simple-icons/changedetection": [0.352456123, 0.0492263755, 0.50212766, 0.00565113733, 0.0542915755, 0.0, "caa6aa68128b2986"], + "simple-icons/cocos": [0.832981169, 0.13727263, 0.486891386, 0.011963848, 0.0852093727, 0.0, "f2ac342c893eaeea"], + "simple-icons/contentstack": [0.323626995, 0.0596820719, 0.583333333, 0.0082330443, 0.0631543408, 0.0, "bb9919052454288c"], + "simple-icons/debridlink": [0.235418603, 0.0501897177, 0.56969697, 0.00360825472, 0.100041012, 0.0, "8f0e1137564d7df5"], + "simple-icons/elixir": [0.157271624, 0.0283635086, 1.09433962, 0.00196820428, 0.0963985131, 0.0, "d1f9a40ccc3ed6fd"], + "simple-icons/fampay": [0.228378817, 0.0475318204, 0.823529412, 0.00322600733, 0.0728705517, 0.0, "bcb264f20510330e"], + "simple-icons/fluxer": [0.379550397, 0.0499589453, 0.99122807, 0.004985495, 0.0941628849, 0.0, "504ff67923349f1b"], + "simple-icons/googlechrome": [0.281888187, 0.049170198, 1.48351648, 0.00419491017, 0.0603088389, 0.0, "56f7670a0faedc52"], + "simple-icons/h2database": [0.35858503, 0.0574893052, 0.931937173, 0.00619159779, 0.0783675392, 0.0, "f8f388860782e531"], + "simple-icons/hitachi": [0.264583677, 0.197534808, 0.823129252, 0.0036161535, 0.081085494, 0.0, "08e2b22b2d9689f5"], + "simple-icons/infinityfree": [0.575627267, 0.186118613, 0.871670702, 0.00708079571, 0.1337469, 0.0, "cf048a5ae56644aa"], + "simple-icons/jdoodle": [0.38015908, 0.087964115, 0.683417085, 0.00560853258, 0.0885887916, 0.0, "3cf50ac0f9d3ff4b"], + "simple-icons/kleinanzeigen": [0.266370177, 0.0348352523, 1.09333333, 0.00498477742, 0.0746104425, 0.0, "78e689613b35d1ab"], + "simple-icons/leetcode": [0.170473829, 0.0404277063, 0.931034483, 0.00358240469, 0.0552602643, 0.0, "8b7c63f4d3018451"], + "simple-icons/looker": [0.298055887, 0.0734787963, 1.01657459, 0.00437993044, 0.0916877882, 0.0, "57cc25c0d47c3d2f"], + "simple-icons/mamp": [0.316747755, 0.0714121454, 1.26666667, 0.00421645213, 0.0975158123, 0.0, "04c7c5c5e1bf084f"], + "simple-icons/microeditor": [0.317293882, 0.0555737389, 0.404081633, 0.0043490543, 0.0827216521, 0.0, "e34364e338ea59c8"], + "simple-icons/mysql": [0.62371105, 0.143982209, 0.518248175, 0.00812509563, 0.119515522, 0.0, "05497d9171ba0240"], + "simple-icons/notion": [0.350060195, 0.0401399489, 1.20224719, 0.00666312501, 0.0457039719, 0.0, "254792f6eef4b46a"], + "simple-icons/osano": [0.144964963, 0.0310607412, 2.78571429, 0.0022499233, 0.0562381858, 0.0, "96b56e499fa94bc5"], + "simple-icons/phpstorm": [0.208171353, 0.0486506331, 1.13888889, 0.00323390611, 0.0661979771, 0.0, "82119065b67c7a17"], + "simple-icons/playerfm": [0.408339739, 0.0520501017, 0.677777778, 0.00556856021, 0.0833747938, 0.0, "c8c241db20145d8e"], + "simple-icons/premierleague": [0.624760866, 0.154993578, 1.05687204, 0.00761383632, 0.11843468, 0.0, "fba5925d71cfde86"], + "simple-icons/pronounsdotpage": [0.202385768, 0.0398139486, 0.790697674, 0.00337129459, 0.0646285421, 0.0, "70c0c7f8d7cc5dad"], + "simple-icons/purescript": [0.137390062, 0.0910964378, 2.07407407, 0.00257999194, 0.033582427, 0.0, "b3b96e8b0bb82746"], + "simple-icons/redsys": [0.236826718, 0.057358822, 0.85915493, 0.00288851862, 0.0915123173, 0.0, "8a1cc91bc4e8cae2"], + "simple-icons/sagemath": [0.835392356, 0.115700767, 0.780763791, 0.0113343475, 0.0817880021, 0.0, "a0eadd3e41793327"], + "simple-icons/slackware": [0.288683116, 0.039194356, 0.663507109, 0.0051796115, 0.0998705157, 0.0, "c2eca10b6d6c2736"], + "simple-icons/sparkar": [0.0479912497, 0.0342215512, 1.75, 0.0014545517, 0.0118144673, 0.0, "53c426735b36325f"], + "simple-icons/stmicroelectronics": [0.151569217, 0.0435713779, 0.727272727, 0.00333802472, 0.0416831932, 0.0, "396132a68536bcc2"], + "simple-icons/ubiquiti": [0.458037764, 0.083186203, 0.619469027, 0.00554773724, 0.127774582, 0.0, "396599d29f0cda13"], + "simple-icons/visa": [0.229193151, 0.0868248057, 1.26470588, 0.00321619376, 0.067921933, 0.0, "6f1149fe9e3c5504"], + "simple-icons/wxt": [0.376087159, 0.0687606233, 1.17525773, 0.00550896162, 0.0953683684, 0.000157633667, "3fe6f90b83a16c63"], + "synthetic/gradient_linear": [0.109082982, 0.0137487265, 3.33333333, 0.000411368994, 0.0254374004, 0.0, "d4973a66d41ffa66"], + "synthetic/mosaic_grid6": [0.105412677, 0.0816970572, 2.36036036, 0.00237897155, 0.0703066577, 0.0, "ca940811ed0e77b5"], + "synthetic/prim_ellipse": [0.0, 0.0159309544, 1.2, 0.000347860478, 0.0, 0.0, "fa54876979a52315"], + "synthetic/prim_star5": [0.0375538431, 0.031121445, 2.91666667, 0.000573411293, 0.0470617231, 0.0, "9b691dd833cbb356"], + "synthetic/symmetry_rot3": [0.0771582499, 0.0254492146, 2.38888889, 0.000915447541, 0.0674125423, 0.0, "31a56c6814dfa6ab"], + "twemoji/1f17e": [0.139008656, 0.0183976053, 0.95, 0.00173487642, 0.0909592523, 0.0, "702da2232ca8e26b"], + "twemoji/1f1f8": [0.111131951, 0.029435709, 1.25, 0.00153385138, 0.101648775, 0.0, "3f9a8d1f85607aaa"], + "twemoji/1f1fa": [0.110441349, 0.0212454301, 1.29545455, 0.00162416743, 0.0940743889, 0.0, "d91f89e3c254ce48"], + "twemoji/1f325": [0.0766317323, 0.0799602834, 1.30054645, 0.00105537986, 0.0928070069, 0.0, "7bd38799be4c2e92"], + "twemoji/1f369": [0.284164071, 0.0808535323, 0.595505618, 0.00346453651, 0.110503233, 0.0, "efee69a1c0daee24"], + "twemoji/1f3ca-1f3fe-200d-2640-fe0f": [0.209875628, 0.080937135, 1.13207547, 0.00295633427, 0.129678565, 0.000168523152, "bd9802829bb3bcd0"], + "twemoji/1f3cc-1f3fb-200d-2640-fe0f": [0.271854579, 0.132144853, 0.991836735, 0.0030243611, 0.159689678, 0.0, "ea8651e55a014180"], + "twemoji/1f42b": [0.216373309, 0.0888556581, 1.04924242, 0.00287977117, 0.128203069, 0.0, "3331a0d9e97e18b7"], + "twemoji/1f468-1f3fb-200d-1f91d-200d-1f468-1f3fd": [0.433456331, 0.138317314, 0.740425532, 0.00574926892, 0.165442925, 0.0, "09d365c983cb3307"], + "twemoji/1f468-1f3fc-200d-1f9b0": [0.131076559, 0.088736526, 1.09917355, 0.0016946746, 0.0932918263, 0.0, "cb72e0721ba8833a"], + "twemoji/1f468-1f3fe-200d-2764-fe0f-200d-1f48b-200d-1f468-1f3ff": [0.214084879, 0.103112031, 0.77173913, 0.00299166818, 0.122257917, 0.0, "9cce3652928f6613"], + "twemoji/1f469-1f3fb-200d-1f37c": [0.468589932, 0.103962786, 0.794666667, 0.00489819469, 0.207444984, 0.00253115896, "42e587c681966adb"], + "twemoji/1f469-1f3fc-200d-2764-fe0f-200d-1f468-1f3fc": [0.240038216, 0.0848908071, 1.31521739, 0.00296094548, 0.21776043, 0.0744398185, "3d82883e04d36a4f"], + "twemoji/1f469-1f3fe": [0.176251695, 0.0489023489, 1.11363636, 0.00248396979, 0.085774951, 0.0, "771f6e357ffa7cec"], + "twemoji/1f469-1f3ff-200d-1f91d-200d-1f468-1f3fc": [0.528724909, 0.134173729, 0.862068966, 0.00706425682, 0.206208692, 0.00737435058, "aa6bee6d0152b9d0"], + "twemoji/1f469-200d-1f467-200d-1f467": [0.135629818, 0.0530350748, 0.515625, 0.00205572206, 0.095538937, 0.0, "314815b4abb3deb7"], + "twemoji/1f470-1f3fc-200d-2640-fe0f": [0.168967783, 0.0557460844, 1.22162162, 0.00238070148, 0.132941994, 0.0, "371fbc011bd09d72"], + "twemoji/1f481-1f3fc-200d-2640-fe0f": [0.152794257, 0.0771468692, 1.30405405, 0.00225988892, 0.109245301, 0.00066491358, "fe43cd0d5a01e45e"], + "twemoji/1f486-1f3ff": [0.468548834, 0.141713556, 1.43442623, 0.00480778143, 0.289141383, 0.00350474404, "a1e179b1ae60def4"], + "twemoji/1f4e6": [0.0976417512, 0.0602519551, 0.827868852, 0.00148656091, 0.059544722, 0.0, "a1dc20309f9dfb7d"], + "twemoji/1f53a": [0.0084836781, 0.0248276653, 1.0, 0.000335869874, 0.0188259451, 0.0, "041b09fd18ad3712"], + "twemoji/1f57a-1f3fb": [0.372633308, 0.167562739, 0.56496063, 0.0047248113, 0.136214759, 0.0, "55c21632dd6d67ae"], + "twemoji/1f635": [0.208913863, 0.0685176598, 0.848484848, 0.00252811029, 0.101322195, 0.0, "e7cb9195bd4c649e"], + "twemoji/1f646-1f3fb-200d-2640-fe0f": [0.304935306, 0.066009894, 1.41614907, 0.00382757932, 0.0871298724, 0.0, "8cc32fdc3d1ff2c1"], + "twemoji/1f648": [0.226033941, 0.108133597, 0.648902821, 0.00311830547, 0.0988544396, 4.01357855e-05, "302001ad87ba8f72"], + "twemoji/1f64d-1f3fd": [0.218839467, 0.089378402, 1.28125, 0.00268077548, 0.105863765, 0.0, "1dd3c01b54d38759"], + "twemoji/1f6a3-1f3ff-200d-2642-fe0f": [0.24085407, 0.0861191782, 0.98019802, 0.00332908705, 0.141067416, 0.0, "32346cc52b34bcff"], + "twemoji/1f6d6": [0.270508438, 0.224231187, 1.32186732, 0.00331721175, 0.243222321, 0.00017265116, "b774a93d33bc2bd3"], + "twemoji/1f7eb": [0.0384582467, 0.0127544177, 1.25, 0.000528040517, 0.177357916, 0.0, "f7f0f09c38358d0a"], + "twemoji/1f91c-1f3fe": [0.0971757472, 0.0743028239, 1.20754717, 0.00154605939, 0.101813265, 0.000106055484, "daea5ea9b986c195"], + "twemoji/1f938-1f3fe": [0.287322551, 0.272683175, 0.501779359, 0.00369404466, 0.167885858, 0.000293892093, "041ac6c3e4e48e1b"], + "twemoji/1f977-1f3fb": [0.346510053, 0.135450437, 1.09745763, 0.00559652364, 0.11101769, 0.0, "8894a20e9639b6ec"], + "twemoji/1f9a8": [0.632975578, 0.0811332378, 1.84142395, 0.00831721257, 0.133452476, 0.0, "4511ce4f29824446"], + "twemoji/1f9c9": [0.153140455, 0.0985538049, 1.57785467, 0.00243788981, 0.126791018, 0.0, "9d8a901a0c1ae907"], + "twemoji/1f9d1-1f3fd-200d-1f9af-200d-27a1-fe0f": [0.336111724, 0.169783439, 0.5575, 0.00392546365, 0.15731175, 0.00178211046, "96de3c2b46ca860b"], + "twemoji/1f9d1-1f3ff-200d-2764-fe0f-200d-1f9d1-1f3fb": [0.299102843, 0.0940905787, 1.24056604, 0.00413429597, 0.0999197787, 0.0, "60752cf9c6c3a838"], + "twemoji/1f9d4-1f3fd": [0.307146311, 0.0693068034, 1.12592593, 0.00373451598, 0.135678606, 0.000154707647, "f41ece3b53ffaf03"], + "twemoji/1f9d8-1f3fe": [0.317530304, 0.176475995, 0.926509186, 0.00402571261, 0.160074816, 0.000123371727, "b96af6b89eff30c3"], + "twemoji/1f9e9": [0.142357498, 0.0666260704, 0.816666667, 0.00215234188, 0.114536705, 0.0, "c46099707b751732"], + "twemoji/1faa3": [0.281465322, 0.0977930954, 5.37037037, 0.00350481644, 0.133731769, 0.0, "51c4672f4ad6ee70"], + "twemoji/1fae5": [0.187719971, 0.144999334, 1.96031746, 0.00232894649, 0.157995168, 0.00372222525, "47127d7a5a9d089d"], + "twemoji/2196": [0.0474223681, 0.048607018, 1.80952381, 0.000674811483, 0.0477431446, 0.0, "3b07a0ded6751881"], + "twemoji/271d": [0.0828246996, 0.0318489474, 1.05769231, 0.00131571537, 0.0976863715, 0.0, "26732d3ca24814da"] } }, "fast-512ss": { @@ -1056,259 +1335,263 @@ "fast" ], "summary": { - "de00": 0.09953048708125962, - "turning": 0.024479031841762266, - "ratio": 3.3227753675163827, - "self_res": 0.0012377521109046051, + "de00": 0.09016257718069866, + "turning_gap": 3.832678722015223, + "ratio_gap": 0.9224514505927441, + "geom": 0.31672658377147955, + "turning": 0.024173764951338682, + "ratio": 3.2493751142231675, + "self_res": 0.0011808349319379404, + "geom_far": 0.1627899606450969, "n": 246 }, "icons": { - "lucide/app-window-mac": [0.0521059372, 0.00936531847, 12.5833333, 0.000546623662, "bf3e9c9b667dcf60"], - "lucide/audio-lines-x": [0.0815916881, 0.0151857123, 20.0, 0.000895107631, "9279c0c7edf792cf"], - "lucide/badge-russian-ruble": [0.102209978, 0.0210882576, 6.95774648, 0.00155443698, "9daf15ad64fa5f4f"], - "lucide/bath": [0.0741692707, 0.0190809018, 6.59459459, 0.000693317445, "b6c40696ba871144"], - "lucide/bell": [0.0623405613, 0.0101695165, 4.9047619, 0.000975934148, "f91f47264439eb0b"], - "lucide/birdhouse": [0.0590819046, 0.0134375156, 7.40909091, 0.000862719782, "d362c1ff751971e7"], - "lucide/book-heart": [0.0944812, 0.00808546327, 3.96721311, 0.000976233277, "cfa4347736fa5239"], - "lucide/bug": [0.089242585, 0.0208998377, 7.08108108, 0.00126900757, "8d01333fddf59242"], - "lucide/cat": [0.0780997425, 0.0129553871, 5.21126761, 0.00121050072, "b40505d479dc11c0"], - "lucide/chess-king": [0.0761632919, 0.0144332347, 3.675, 0.00102787383, "480baed3cfe05968"], - "lucide/circle-arrow-right": [0.0476386659, 0.0120448047, 9.44444444, 0.00060918479, "53e4216631270d33"], - "lucide/closed-caption": [0.0866777375, 0.00958914323, 15.9, 0.000927479938, "59303ffa1846536c"], - "lucide/cooking-pot": [0.0755422115, 0.0127501539, 5.0, 0.000734785397, "ef390f77cdf7cfad"], - "lucide/diff": [0.0587487817, 0.0157665471, 20.0, 0.000509808131, "99a7f90f7d9235f4"], - "lucide/equal": [0.0579362698, 0.0084494696, 8.0, 0.00037039959, "262a874cfe96bfe1"], - "lucide/file-digit": [0.074480325, 0.0149811939, 5.62711864, 0.000884635665, "c966330551952538"], - "lucide/focus": [0.0661809444, 0.0194515165, 6.31914894, 0.000970937719, "eec407b4154e1abd"], - "lucide/folder-open": [0.0730125904, 0.00773593855, 3.62162162, 0.000760965049, "74dd2c9137bba1e6"], - "lucide/git-compare": [0.0678229183, 0.0141282458, 7.0, 0.000793501909, "160be1fb2608b53f"], - "lucide/hard-drive-download": [0.079130277, 0.0119917186, 14.75, 0.000819217414, "a7a62abfc153e38e"], - "lucide/ice-cream-cone": [0.0398820043, 0.0145742361, 5.11764706, 0.000643546984, "c25c207402b70920"], - "lucide/iteration-ccw": [0.0573864318, 0.00950672603, 11.0769231, 0.000864529982, "2b090525dcf21db9"], - "lucide/list-checks": [0.0525280088, 0.0153722133, 19.1428571, 0.000558755943, "60d6614ff707cde0"], - "lucide/message-circle-dashed-check": [0.0679403394, 0.0207100577, 7.375, 0.00109136233, "096cb90a2b7b2a11"], - "lucide/messages-square": [0.0743041635, 0.0115312575, 3.84810127, 0.000844155031, "aea5d2c4d36332ba"], - "lucide/navigation-2-off": [0.0297462307, 0.0155339345, 11.5, 0.000537169108, "a849ed1f62215a5a"], - "lucide/omega": [0.0564672835, 0.0117306787, 3.6744186, 0.00081707834, "41d712d0ace71584"], - "lucide/panel-right": [0.116565354, 0.00535021252, 20.5, 0.000911533134, "74baf33142db808c"], - "lucide/pen-line": [0.0519743264, 0.00626705796, 4.61111111, 0.000723835023, "6dd42725833b48c1"], - "lucide/phone-forwarded": [0.0959686413, 0.0124525354, 3.84090909, 0.00128947233, "ff25566617a28829"], - "lucide/rectangle-goggles": [0.0989406183, 0.00749557375, 3.86885246, 0.00081463973, "08453c51070d99b3"], - "lucide/save-pen": [0.0966024175, 0.0111457298, 4.06382979, 0.00113099057, "6e50fd44630df7ea"], - "lucide/shapes": [0.0468926392, 0.0138401357, 4.91176471, 0.000748533115, "05a42f58b2c95022"], - "lucide/shopping-cart-plus": [0.0708221942, 0.018193494, 6.65116279, 0.00088316953, "cee63105d0b512a9"], - "lucide/sparkle": [0.0570425652, 0.0119261251, 2.68571429, 0.000735279347, "63208d17b2626797"], - "lucide/square-minus": [0.120529309, 0.00549965144, 22.0, 0.000871381315, "45ca65ccdc1ab541"], - "lucide/swiss-franc": [0.0366013758, 0.0148247831, 15.25, 0.000365941698, "2e22409bd3a7cf23"], - "lucide/ticket-minus": [0.0817450359, 0.0119523282, 5.96296296, 0.000908825314, "8be428cffaead3ea"], - "lucide/undo": [0.0459129624, 0.0119469265, 5.4, 0.000522807997, "99057d31af72bdd5"], - "lucide/vegan": [0.0777799115, 0.0112676342, 9.85714286, 0.00134103827, "4ae441b34bfec29c"], - "material-icons/12mp": [0.114677966, 0.0205859029, 1.9, 0.000922423729, "63f42dab7c80636a"], - "material-icons/admin_panel_settings": [0.0432724953, 0.0120016078, 1.53278689, 0.000715203292, "db2277273103dfc2"], - "material-icons/arrow_drop_down": [0.00895279646, 0.0122672416, 3.33333333, 0.000153470537, "d2fa90e84f312989"], - "material-icons/bento": [0.106205277, 0.0117231051, 2.0375, 0.00076436071, "6a1bfcb39cc8d33e"], - "material-icons/border_left": [0.0795369819, 0.0454776993, 2.04411765, 0.000559279288, "c0b7a09e3392f690"], - "material-icons/call": [0.0386450551, 0.0185080938, 1.87155963, 0.000642350118, "66b79e2ed3075a4e"], - "material-icons/chair": [0.0816974714, 0.0145485227, 1.93902439, 0.000828806602, "8c43a1c4dc651665"], - "material-icons/closed_caption": [0.0633455962, 0.0137224987, 1.57971014, 0.000571217213, "65b2f7c9d521ac3b"], - "material-icons/crop_landscape": [0.0671314746, 0.0081554396, 2.6, 0.000511842489, "e9901d490f01c9b2"], - "material-icons/dining": [0.158382088, 0.0113722627, 1.88888889, 0.00123086048, "5473848c605d86d8"], - "material-icons/double_arrow": [0.0254829004, 0.0129004882, 3.1, 0.000253580132, "d665a23e0c70ab2e"], - "material-icons/dynamic_feed": [0.0680247396, 0.015582722, 2.68421053, 0.00059492822, "30c3110e3a093805"], - "material-icons/expand_circle_down": [0.0170148574, 0.00838729633, 0.516666667, 0.000708232226, "6ec1884ad740eaba"], - "material-icons/flight": [0.0255986415, 0.0165518886, 1.59090909, 0.000376024429, "6832c092c0217937"], - "material-icons/free_breakfast": [0.070747979, 0.0121167279, 2.67605634, 0.000660675578, "848054d48c1d8069"], - "material-icons/group_remove": [0.0600566119, 0.0154119438, 1.39552239, 0.000768384663, "a9b7e930f461f26a"], - "material-icons/headset": [0.0519640297, 0.0116973625, 2.02325581, 0.000650248665, "c28f2dc967943ee8"], - "material-icons/houseboat": [0.0655832365, 0.0209110554, 2.18421053, 0.000791811384, "6f5d0377fee368c2"], - "material-icons/javascript": [0.0214622505, 0.0361732459, 1.70833333, 0.000228088975, "0a0c389c4412f4aa"], - "material-icons/laptop": [0.081685625, 0.0158798971, 2.875, 0.000629275397, "073e4aa0a47c604a"], - "material-icons/lyrics": [0.0858233124, 0.020803592, 2.11214953, 0.000842644542, "c3008877e613a60c"], - "material-icons/miscellaneous_services": [0.0488049984, 0.0303220484, 0.988505747, 0.000629155722, "e648b1fec2b48520"], - "material-icons/music_note": [0.0283305366, 0.0162982337, 1.28301887, 0.000360077567, "e529f7131a32ee18"], - "material-icons/no_food": [0.0778346062, 0.0150136031, 1.92682927, 0.000918668986, "3b8e867e9e0f10ed"], - "material-icons/notifications_paused": [0.0740843937, 0.0196543688, 1.7173913, 0.000770449231, "1b81bbc91d936331"], - "material-icons/perm_media": [0.0877799764, 0.00787885014, 2.075, 0.000890424941, "ec5ba98c1aeb14a5"], - "material-icons/phone_iphone": [0.0631202981, 0.0121531244, 1.73529412, 0.000505484699, "916e8508838af3c0"], - "material-icons/polyline": [0.0555072501, 0.0191801531, 2.20689655, 0.000443312689, "0581c50f46af1b3e"], - "material-icons/qr_code": [0.104937635, 0.0301100908, 3.02083333, 0.000780128001, "d9c5b805e3e0af22"], - "material-icons/report": [0.0549836457, 0.00935873678, 2.2195122, 0.000543182949, "f1811a4e470235a7"], - "material-icons/rule_folder": [0.0696821511, 0.015015913, 2.35714286, 0.000837034138, "940207f3280a3d3d"], - "material-icons/sd_card_alert": [0.0655637756, 0.00905460432, 2.64, 0.000660167076, "9e38116f91d3b1bb"], - "material-icons/settings_overscan": [0.0521278754, 0.0119975998, 2.46875, 0.000546893105, "cf90a7dd413ed99a"], - "material-icons/sms_failed": [0.088030763, 0.011253534, 2.76, 0.000732796092, "3fc3df9759fdccf1"], - "material-icons/storage": [0.135876656, 0.0158081537, 1.75, 0.000844125403, "47e923c99080cbd1"], - "material-icons/table_rows": [0.10192512, 0.00763250688, 2.10714286, 0.000665986212, "607e3feabb728d2b"], - "material-icons/transfer_within_a_station": [0.0585500076, 0.0249472051, 1.82407407, 0.000661064638, "38bad4428b952850"], - "material-icons/two_wheeler": [0.0434494168, 0.0231026345, 1.33333333, 0.000582571549, "77655f80e80c74b9"], - "material-icons/video_camera_back": [0.0659422055, 0.0146577574, 2.75862069, 0.000613612647, "a5b3f1b3c7032e06"], - "material-icons/view_week": [0.119924262, 0.00715553501, 1.78571429, 0.000743701356, "f1a2efa41dc21a99"], - "noto-emoji/emoji_u0030": [0.158174947, 0.0237135284, 1.46296296, 0.00176031853, "a59e51dcdb04c568"], - "noto-emoji/emoji_u1f36a": [0.454386652, 0.0560681902, 2.82556131, 0.00528130913, "6d25a034112508f3"], - "noto-emoji/emoji_u1f39e": [0.871030629, 0.0950690635, 4.42151163, 0.00711437082, "759d225081185aec"], - "noto-emoji/emoji_u1f3c2_1f3fd": [0.96293366, 0.0393802903, 1.45901639, 0.00771198981, "1a06a69a9c354d9e"], - "noto-emoji/emoji_u1f3c4_1f3fe": [0.174942508, 0.0570592236, 1.2234375, 0.00192513783, "59a04ee378c4fb13"], - "noto-emoji/emoji_u1f3cb_200d_2642": [0.323148549, 0.114934397, 1.39447005, 0.00342069962, "097f5b33c02680b1"], - "noto-emoji/emoji_u1f41b": [0.0586194061, 0.0382894724, 1.93542757, 0.000725140504, "41cae5d03340333c"], - "noto-emoji/emoji_u1f44d_1f3fc": [0.0592986979, 0.0338771529, 2.19944598, 0.000842516136, "b5f19f510f349b08"], - "noto-emoji/emoji_u1f468_1f3fb_200d_2764_200d_1f468_1f3fd": [0.377779186, 0.0444108126, 1.70833333, 0.00331269321, "e2a5397f788d6a74"], - "noto-emoji/emoji_u1f468_1f3ff_200d_1f393": [0.649122238, 0.0724831429, 2.995086, 0.00534251099, "ffd7cee6b43c9ac9"], - "noto-emoji/emoji_u1f469_1f3fb_200d_1f52c": [0.828346133, 0.0498099392, 2.67652495, 0.0077083637, "fa4115a4a9a7bcef"], - "noto-emoji/emoji_u1f469_1f3fc_200d_1f91d_200d_1f468_1f3fb": [0.393448293, 0.0531666867, 0.891930836, 0.00425546756, "60b56df29465e04a"], - "noto-emoji/emoji_u1f469_1f3fe_200d_1faef_200d_1f469_1f3fd": [0.560133338, 0.0798000622, 1.17502279, 0.00569818122, "869f23ab0846bcab"], - "noto-emoji/emoji_u1f469_200d_1f469_200d_1f466_200d_1f466": [0.0897386894, 0.01733887, 1.2384106, 0.00142578513, "83dc6079f7751499"], - "noto-emoji/emoji_u1f46c_1f3fd": [0.318519533, 0.0585798502, 0.736679537, 0.00300532137, "5c16b5512060309a"], - "noto-emoji/emoji_u1f470_1f3fb_200d_2640": [0.489903152, 0.0518619471, 2.71689498, 0.00686234748, "0c8ebdea3246a2ac"], - "noto-emoji/emoji_u1f482_1f3ff_200d_2640": [0.396930754, 0.033193664, 1.27217742, 0.00471973792, "c8e85b098ef9f6a8"], - "noto-emoji/emoji_u1f4d8": [0.0724320784, 0.0100754678, 2.0, 0.000898082741, "8832607545ec47a5"], - "noto-emoji/emoji_u1f520": [0.0251421891, 0.0181874993, 1.24657534, 0.000460667303, "4dace02eb9dc248e"], - "noto-emoji/emoji_u1f56f": [0.340624243, 0.0485635371, 2.15120275, 0.0028892383, "32994375bf519922"], - "noto-emoji/emoji_u1f5a8": [0.1635672, 0.0219652026, 2.71162791, 0.00223930809, "9720c336def0d769"], - "noto-emoji/emoji_u1f62d": [0.602088511, 0.0234576105, 2.61261261, 0.00395675004, "c7e61714a9456ea7"], - "noto-emoji/emoji_u1f64b_1f3fe_200d_2640": [0.655076981, 0.0259985766, 1.32330827, 0.00682785874, "d27fe759ddfa8082"], - "noto-emoji/emoji_u1f6c0_1f3ff": [0.250707567, 0.114945534, 2.9453709, 0.00233572046, "0bfcfbf057beb8c0"], - "noto-emoji/emoji_u1f90d": [0.0122510102, 0.0385821837, 3.45454545, 0.00021150049, "1099e6be446a12ca"], - "noto-emoji/emoji_u1f91c_1f3fe": [0.0513656512, 0.0275838064, 2.57333333, 0.00070683501, "ba118baa128c29f3"], - "noto-emoji/emoji_u1f926_1f3ff": [0.785926044, 0.0590442543, 2.13914373, 0.0055471044, "e2972509e220572e"], - "noto-emoji/emoji_u1f932": [0.0910633728, 0.0352991376, 2.0285205, 0.000984014361, "bf88e914e9a29e13"], - "noto-emoji/emoji_u1f93c_1f3fe_200d_2640": [0.516431689, 0.0694263672, 1.1411549, 0.00559995323, "f69cc062994dd023"], - "noto-emoji/emoji_u1f987": [0.483753741, 0.0393376598, 1.57413793, 0.00469140615, "3017eace24fc0ced"], - "noto-emoji/emoji_u1f9be": [0.24340871, 0.086690058, 3.77245509, 0.00214594253, "1860f2b00e44b8bd"], - "noto-emoji/emoji_u1f9ce_1f3fd_200d_2642": [0.126876339, 0.0405661878, 0.990196078, 0.00130440202, "ff75d6a776a21824"], - "noto-emoji/emoji_u1f9cf_1f3fc": [0.448420137, 0.0458666888, 2.18475751, 0.00406803424, "e87b7ebec6e4c08e"], - "noto-emoji/emoji_u1f9d1_1f3fc_200d_1f37c": [0.143928349, 0.0564546826, 1.59706546, 0.00138952245, "a875b04833780368"], - "noto-emoji/emoji_u1f9d1_1f3fd_200d_1f91d_200d_1f9d1_1f3ff": [0.439034998, 0.0830866631, 1.35198702, 0.00481137959, "dc0495fca1dea51f"], - "noto-emoji/emoji_u1f9d1_1f3fe_200d_1f9bc_200d_27a1": [0.189626262, 0.0751539154, 1.44172932, 0.00203736336, "896aa29f29fd5ab3"], - "noto-emoji/emoji_u1f9d6_1f3fe_200d_2642": [0.524330616, 0.0394419982, 2.2872807, 0.00507040741, "7d3c5ed3c6946edd"], - "noto-emoji/emoji_u1f9dd_1f3fd_200d_2640": [0.542709529, 0.0458976286, 1.99854015, 0.005992861, "f58d3c3016db2414"], - "noto-emoji/emoji_u1f9ed": [0.0778830051, 0.0305336114, 2.46202532, 0.000906089263, "ea9055af617ce24a"], - "noto-emoji/emoji_u1faa5": [0.0385043547, 0.0737554842, 1.92708333, 0.000548543525, "e4b7cb5e2dc3dcee"], - "noto-emoji/emoji_u1faf1_1f3fc_200d_1faf2_1f3ff": [0.0780100822, 0.0420250315, 1.64725458, 0.00103788625, "4d70ed1a04a17cc0"], - "noto-emoji/emoji_u26bd": [0.0873887166, 0.0321234289, 2.91774892, 0.00132819812, "08683dc2d4e6bd76"], - "noto-emoji/emoji_u2b05": [0.0122114392, 0.00842534508, 2.06410256, 0.000209655249, "6f45e64f6b0ebe65"], - "openmoji/1F195": [0.078510128, 0.0169861946, 11.8235294, 0.000816905405, "49a2e1415904342c"], - "openmoji/1F1FF-1F1F2": [0.0551898256, 0.0135024447, 2.875, 0.000239916946, "1e08a7314e997961"], - "openmoji/1F361": [0.0565975495, 0.0219221171, 2.61428571, 0.000855928287, "37e9fdaedb40df3a"], - "openmoji/1F38A": [0.0735367611, 0.0251046705, 2.30729167, 0.000982537982, "b9c3ef20f718e1b9"], - "openmoji/1F3A9": [0.0591842644, 0.0106231802, 2.19402985, 0.000765773526, "c7a92eac057a138f"], - "openmoji/1F3C3-1F3FF-200D-2642-FE0F": [0.0337881483, 0.0273195825, 2.77720207, 0.000586604467, "cd8f5114c3973e74"], - "openmoji/1F3CC-FE0F-200D-2640-FE0F": [0.101362862, 0.0282414264, 2.12890625, 0.00130565744, "c7cf8e35542ff403"], - "openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F": [0.0369084552, 0.00698907979, 5.6, 0.000328936643, "3b665f914d911ac7"], - "openmoji/1F442-1F3FF": [0.0434250161, 0.0398424356, 8.92982456, 0.000566762348, "641aa4878603bac1"], - "openmoji/1F468-1F3FC-200D-1F3ED": [0.101101287, 0.0470826863, 0.868217054, 0.00144893315, "9a0514bea1ad9d2a"], - "openmoji/1F468-1F3FF-200D-1F9B0": [0.0572667308, 0.0221804036, 1.99230769, 0.000756365655, "2ab8c17180373fd9"], - "openmoji/1F468-200D-1F9B1": [0.0990948603, 0.0360438079, 1.72018349, 0.00119678269, "b0ee8fb99a88d11b"], - "openmoji/1F469-1F3FC-200D-2764-FE0F-200D-1F48B-200D-1F469-1F3FC": [0.146912426, 0.027448559, 2.73809524, 0.00161038293, "815404450844ce94"], - "openmoji/1F469-1F3FF-200D-1F9B2": [0.0391218513, 0.0214706604, 2.18421053, 0.000558760541, "853b55f6517e9ffc"], - "openmoji/1F481-1F3FB-200D-2642-FE0F": [0.0822090209, 0.023872476, 2.52592593, 0.00120294059, "1199cc529337f953"], - "openmoji/1F49B": [0.0376462266, 0.00902202027, 1.36363636, 0.000510042533, "ce6ad8db4d534a38"], - "openmoji/1F517": [0.0779842734, 0.023854487, 2.74125874, 0.00100305618, "9ec0eff3ff155f91"], - "openmoji/1F646-1F3FC": [0.100084998, 0.0222179549, 1.63318777, 0.00121701567, "10a1a49bd362e136"], - "openmoji/1F6B4-1F3FD-200D-2640-FE0F": [0.0663619936, 0.0267744373, 3.26136364, 0.00126196409, "0b236c46528afb00"], - "openmoji/1F6E0": [0.0768114999, 0.0329582402, 3.97321429, 0.0012188704, "1eb8985b5449b7be"], - "openmoji/1F938-1F3FB": [0.0625392646, 0.0265704906, 3.18421053, 0.000875469996, "bb296bd02f7ea230"], - "openmoji/1F93E-1F3FE": [0.0684093684, 0.0341294575, 3.32444444, 0.000874375284, "3e232f4dfb5e1d38"], - "openmoji/1F9B3": [0.054485023, 0.0182154303, 5.63636364, 0.000665451633, "71faa7f238b1f870"], - "openmoji/1F9D1": [0.0794569775, 0.02356967, 2.29357798, 0.000926958397, "d8d270c186c3032f"], - "openmoji/1F9D1-1F3FC-200D-1FA70": [0.0778567716, 0.0374129493, 3.64615385, 0.000995218055, "7e48f01453fbbb48"], - "openmoji/1F9D1-1F3FD-200D-1F527": [0.0992130712, 0.0357737911, 1.92307692, 0.00139237789, "4ddb8ade4cb2c982"], - "openmoji/1F9D1-200D-1F393": [0.0750030354, 0.0317721317, 0.644628099, 0.0011724931, "400d6d1df1f2445d"], - "openmoji/1F9D6-1F3FD-200D-2642-FE0F": [0.0831374377, 0.0369709145, 2.50938338, 0.00106368109, "43bd4268da99a145"], - "openmoji/1FA8B": [0.066989094, 0.0476933778, 1.02724359, 0.000799376285, "c32551ce5813477d"], - "openmoji/1FAC4-1F3FD": [0.0705181435, 0.0329885377, 1.65916399, 0.00103340659, "d8322b1b1b9e3980"], - "openmoji/25FC": [0.00456328504, 0.00557597409, 1.83333333, 0.000179694616, "97c495757954e70f"], - "openmoji/2705": [0.0749644265, 0.0153946045, 2.98684211, 0.000907691894, "f67efcc1cf8975b6"], - "openmoji/E056": [0.138036713, 0.0177445018, 0.975975976, 0.00163758069, "aa273b46f715f45e"], - "openmoji/E1D1": [0.0916030109, 0.0160019421, 1.14450867, 0.000640166341, "78c875588c9e1677"], - "openmoji/E30B": [0.0856378898, 0.0249448928, 2.01709402, 0.00161952584, "46df7d923a5f6a28"], - "simple-icons/alchemy": [0.0249208063, 0.00798609571, 0.543396226, 0.000517168141, "eabf6da1658f9bae"], - "simple-icons/appletv": [0.0499959067, 0.0315064645, 1.68421053, 0.000751869287, "fb6559ce1eb58635"], - "simple-icons/atlassian": [0.0519835353, 0.00610730473, 1.81538462, 0.000863826892, "4c0a39bd1975f472"], - "simple-icons/autocad": [0.0496520214, 0.00809797413, 1.67741935, 0.00107396452, "3fd43689a522e458"], - "simple-icons/bandrautomation": [0.0725800097, 0.0225242163, 1.4, 0.00153839996, "029b72c2744d4373"], - "simple-icons/bim": [0.0388382934, 0.0216404422, 1.88652482, 0.000879130617, "b874dbe5f8f05803"], - "simple-icons/boosty": [0.0443525054, 0.0133951821, 2.63636364, 0.000607823371, "8c358c501f5524b1"], - "simple-icons/changedetection": [0.0911448076, 0.0142364601, 0.970212766, 0.00144502206, "ab8fd77888e354a2"], - "simple-icons/cocos": [0.171937853, 0.0307499654, 0.808988764, 0.00284612249, "ffe776ee9f3fc44f"], - "simple-icons/contentstack": [0.0894329622, 0.0154664526, 1.34313725, 0.00156691344, "877ebd8a9e4fdfea"], - "simple-icons/debridlink": [0.0477609485, 0.0102677477, 1.16363636, 0.000818993023, "ec8dba146ccd8195"], - "simple-icons/elixir": [0.0373416282, 0.00761650766, 1.77358491, 0.000513593026, "1ec05b567889ddb9"], - "simple-icons/fampay": [0.0525390953, 0.0135071218, 1.47593583, 0.000844364578, "e884996f921f36b1"], - "simple-icons/fluxer": [0.0824512392, 0.0157766624, 1.46491228, 0.00127512624, "14ff62ba397dc4f7"], - "simple-icons/googlechrome": [0.0592817701, 0.0115584865, 2.27472527, 0.00105955836, "12c477a7676cff28"], - "simple-icons/h2database": [0.0907953382, 0.01560411, 1.29842932, 0.00159131235, "9ffb3b776da325e0"], - "simple-icons/hitachi": [0.0461807251, 0.0433741119, 0.857142857, 0.000775655208, "7f087aa989787aff"], - "simple-icons/infinityfree": [0.0613019094, 0.0422116481, 1.18159806, 0.00105641701, "2e30b0be23b0c555"], - "simple-icons/jdoodle": [0.0856062397, 0.0200270522, 1.04020101, 0.00104619947, "049a5a853ddcb1d5"], - "simple-icons/kleinanzeigen": [0.0643116832, 0.0117733679, 1.86666667, 0.00133786688, "0bedc22b107573fa"], - "simple-icons/leetcode": [0.0525321402, 0.0108392251, 1.4137931, 0.00100881525, "29065d4bc3868597"], - "simple-icons/looker": [0.0663382262, 0.0191523475, 1.25966851, 0.00101595116, "70cc40ab016577d1"], - "simple-icons/mamp": [0.0608779788, 0.0169336661, 2.41666667, 0.000888106471, "53219a4cc507b9b0"], - "simple-icons/microeditor": [0.0722912699, 0.0178138155, 0.702040816, 0.00106908788, "74974b65a79e8e23"], - "simple-icons/mysql": [0.107483886, 0.036742328, 0.807785888, 0.00163285481, "a2a5f49f4818f1d6"], - "simple-icons/notion": [0.0705532059, 0.0109159146, 2.28089888, 0.00147966866, "0cf7311372548717"], - "simple-icons/osano": [0.0415750965, 0.0121046213, 4.85714286, 0.000630083203, "9c8d4599721c70f1"], - "simple-icons/phpstorm": [0.0414640382, 0.0134376716, 1.59722222, 0.000715771748, "3af7ec8a4cb5ca08"], - "simple-icons/playerfm": [0.102658436, 0.0146780396, 1.08888889, 0.00147510588, "829be5786bef3d6b"], - "simple-icons/premierleague": [0.106209986, 0.0432435564, 1.72985782, 0.00152011949, "205c350c055637ca"], - "simple-icons/pronounsdotpage": [0.0462920628, 0.0127615109, 1.56976744, 0.000765691919, "f5682b11a3f13f7b"], - "simple-icons/purescript": [0.0483778641, 0.0180423807, 3.96296296, 0.000758810434, "4e805245c0f4d180"], - "simple-icons/redsys": [0.0527059361, 0.0128088633, 1.1971831, 0.000786785095, "e8c9ee0bf1f89ab9"], - "simple-icons/sagemath": [0.10125047, 0.0379187746, 1.23903819, 0.00181608042, "1685f00af2ee1d1a"], - "simple-icons/slackware": [0.0795588717, 0.00991919769, 1.17535545, 0.00126217084, "d3d454b76696b39e"], - "simple-icons/sparkar": [0.0364653394, 0.0130915034, 3.33333333, 0.000477091555, "4f084297918bf131"], - "simple-icons/stmicroelectronics": [0.0541204326, 0.0107846405, 1.32467532, 0.00078748801, "0d7ebfc1f7ced195"], - "simple-icons/ubiquiti": [0.055700358, 0.0170050828, 0.681415929, 0.000697281677, "3489520ad6ca30c0"], - "simple-icons/visa": [0.0478769913, 0.0224863213, 1.82352941, 0.000700857083, "7bb4a13705176420"], - "simple-icons/wxt": [0.0716281086, 0.0193537978, 1.8556701, 0.00111635984, "0ac676d01eb12c27"], - "synthetic/gradient_linear": [0.095657222, 0.00346932404, 7.66666667, 0.000401839585, "e8b7e1ff41f36bd7"], - "synthetic/mosaic_grid6": [0.0701047331, 0.0303661568, 4.52252252, 0.000453610584, "39ce240d4a9a3422"], - "synthetic/prim_ellipse": [0.00235147611, 0.00398260463, 1.2, 7.4045005e-05, "9c28a439ccf4b01f"], - "synthetic/prim_star5": [0.0112211285, 0.00684078856, 3.25, 0.000155325484, "4ec45f3598e0b2c3"], - "synthetic/symmetry_rot3": [0.0235970747, 0.00647277025, 3.72222222, 0.000253739709, "71b64f75443d87b1"], - "twemoji/1f17e": [0.034617193, 0.00500740075, 1.475, 0.0004248716, "41ef7e4ad3d18453"], - "twemoji/1f1f8": [0.0230489597, 0.00750373067, 1.88461538, 0.000331536372, "69d21ebb1137ae94"], - "twemoji/1f1fa": [0.0200465843, 0.00530980287, 1.65909091, 0.000313943892, "b7cb235e93d1b456"], - "twemoji/1f325": [0.0188936684, 0.0199158691, 1.79234973, 0.000237436456, "23824d40b8816f58"], - "twemoji/1f369": [0.0573655888, 0.0219787356, 1.44569288, 0.000679579622, "f7a6faa028f90f3c"], - "twemoji/1f3ca-1f3fe-200d-2640-fe0f": [0.0445829518, 0.0210998222, 2.05660377, 0.000551555364, "9ffe794b5b58ae89"], - "twemoji/1f3cc-1f3fb-200d-2640-fe0f": [0.0469488464, 0.0379537042, 2.04081633, 0.000532346603, "bfa9d933849c94cd"], - "twemoji/1f42b": [0.0462781005, 0.0228901403, 1.67045455, 0.000580060121, "83d90580273a5983"], - "twemoji/1f468-1f3fb-200d-1f91d-200d-1f468-1f3fd": [0.0754264519, 0.039948007, 1.4, 0.00104386872, "1ccf065e1f3e9667"], - "twemoji/1f468-1f3fc-200d-1f9b0": [0.0326251201, 0.022859931, 1.72727273, 0.000390752888, "e18218182f50bd36"], - "twemoji/1f468-1f3fe-200d-2764-fe0f-200d-1f48b-200d-1f468-1f3ff": [0.0484398454, 0.0267296739, 1.30072464, 0.000665838888, "177088080ae41c2a"], - "twemoji/1f469-1f3fb-200d-1f37c": [0.0815660581, 0.0409331705, 1.89333333, 0.000852065859, "1abf91d4f008726c"], - "twemoji/1f469-1f3fc-200d-2764-fe0f-200d-1f468-1f3fc": [0.103887871, 0.0213402999, 2.16847826, 0.00124000688, "43770038b17eedc3"], - "twemoji/1f469-1f3fe": [0.0546468347, 0.015861068, 1.67424242, 0.000829892291, "e40ac42b37de29d7"], - "twemoji/1f469-1f3ff-200d-1f91d-200d-1f468-1f3fc": [0.114682369, 0.0372393528, 1.60560345, 0.00145306613, "ad6e55fe5343ae79"], - "twemoji/1f469-200d-1f467-200d-1f467": [0.0322033837, 0.0147596592, 0.875, 0.000428125582, "58ebf7be48b3407d"], - "twemoji/1f470-1f3fc-200d-2640-fe0f": [0.0472792387, 0.0140943319, 2.32432432, 0.000497918983, "05d8eb8f21d74d51"], - "twemoji/1f481-1f3fc-200d-2640-fe0f": [0.0402243696, 0.0197361747, 1.97972973, 0.000500548165, "b4003273749afcec"], - "twemoji/1f486-1f3ff": [0.0486859381, 0.0327399095, 2.15983607, 0.000843108923, "0e6dc9ba8010ce99"], - "twemoji/1f4e6": [0.0318478532, 0.0144616197, 1.76229508, 0.000432019209, "ef31a71ae2d8d2bf"], - "twemoji/1f53a": [0.00998949166, 0.00641357812, 2.33333333, 7.31234904e-05, "2769711d80960d5e"], - "twemoji/1f57a-1f3fb": [0.0806358606, 0.0581169575, 1.1003937, 0.00102663995, "0a36713ac1e1b84e"], - "twemoji/1f635": [0.0435599387, 0.0171911712, 1.23484848, 0.00049885246, "c63e26aad9429eaf"], - "twemoji/1f646-1f3fb-200d-2640-fe0f": [0.0672643483, 0.0157983644, 2.38509317, 0.000789327023, "5196931e427d4f35"], - "twemoji/1f648": [0.0567497425, 0.0259795962, 1.28213166, 0.000941257982, "2fb3584ef0c8b630"], - "twemoji/1f64d-1f3fd": [0.0373310521, 0.0254135561, 2.40625, 0.000505392498, "7fd393a6b72caad0"], - "twemoji/1f6a3-1f3ff-200d-2642-fe0f": [0.0513201468, 0.0229113186, 1.84158416, 0.000512214552, "b016ba18b299f6c2"], - "twemoji/1f6d6": [0.0666128546, 0.0581199133, 2.05651106, 0.000789522601, "615ab020a7038694"], - "twemoji/1f7eb": [0.0288967434, 0.00877493468, 2.5, 0.000355658151, "8c09265d3a055db0"], - "twemoji/1f91c-1f3fe": [0.0213638321, 0.0159830607, 2.09433962, 0.000311409734, "8d4b829f1543ce06"], - "twemoji/1f938-1f3fe": [0.0527022742, 0.0653624892, 1.06227758, 0.000697863696, "acf5696779e947b5"], - "twemoji/1f977-1f3fb": [0.0579559468, 0.0519799452, 2.52966102, 0.000958261255, "2c1723bb2f24803a"], - "twemoji/1f9a8": [0.131032154, 0.0223146549, 3.08414239, 0.0022491354, "517cc9030e810ca4"], - "twemoji/1f9c9": [0.037817318, 0.0276114108, 2.46020761, 0.000485672645, "34a4cb9dbdd9ed24"], - "twemoji/1f9d1-1f3fd-200d-1f9af-200d-27a1-fe0f": [0.0541242845, 0.042772535, 1.055, 0.000670033798, "fcb00fe463d97722"], - "twemoji/1f9d1-1f3ff-200d-2764-fe0f-200d-1f9d1-1f3fb": [0.0575181171, 0.0258216826, 2.25943396, 0.000810437195, "6656a27a05b1e883"], - "twemoji/1f9d4-1f3fd": [0.0501631312, 0.0172767576, 1.8, 0.000614071207, "cb0075534025878b"], - "twemoji/1f9d8-1f3fe": [0.0590806864, 0.038742511, 1.49343832, 0.00073085801, "5b27ce8f4b333400"], - "twemoji/1f9e9": [0.025780106, 0.0165100495, 1.23333333, 0.000375119067, "03cde6c1fe89ffe1"], - "twemoji/1faa3": [0.038319923, 0.0118364725, 5.85185185, 0.000512709317, "27fea7803c2f93b8"], - "twemoji/1fae5": [0.0338911042, 0.0346370957, 2.63492063, 0.000359898171, "c945050945779214"], - "twemoji/2196": [0.0103027932, 0.00812157996, 2.19047619, 0.000177218186, "aaa3e7b3b83f46d3"], - "twemoji/271d": [0.0220716037, 0.00937371824, 1.80769231, 0.000204249794, "5704c9fae6c5578d"] + "lucide/app-window-mac": [0.0535820089, 0.00932546782, 13.4166667, 0.000546100084, 0.0201641303, 0.0, "6692a6356c512b9b"], + "lucide/audio-lines-x": [0.06026439, 0.0151700863, 19.5, 0.000893521763, 0.0373432866, 0.0, "3ce787771ff0fe85"], + "lucide/badge-russian-ruble": [0.0919336528, 0.0213074487, 7.29577465, 0.0014599968, 0.0917342021, 0.0, "2aab3670eb8ed8d7"], + "lucide/bath": [0.0635184497, 0.019181249, 6.54054054, 0.000659748155, 0.0325190359, 0.0, "579c7c481cb4031d"], + "lucide/bell": [0.0588286333, 0.010046961, 5.04761905, 0.000932835683, 0.0831931974, 0.0, "2b4b86ab3c6ca857"], + "lucide/birdhouse": [0.0341659933, 0.0134785673, 7.5, 0.000707364467, 0.0269954602, 0.0, "1d506bf421a46717"], + "lucide/book-heart": [0.0841270462, 0.00813366815, 3.73770492, 0.00085561414, 0.0303676983, 0.0, "d0716ede9facd163"], + "lucide/bug": [0.0837492272, 0.0208059424, 6.64864865, 0.00128197763, 0.073536033, 0.0, "9735ebef25d70dea"], + "lucide/cat": [0.0779209509, 0.0130421025, 5.26760563, 0.00124170631, 0.0913734704, 0.0, "a0aa64021b94c460"], + "lucide/chess-king": [0.0739949495, 0.0143665358, 3.775, 0.000995665905, 0.0569566805, 0.0, "ec1c8934ee423597"], + "lucide/circle-arrow-right": [0.0413744263, 0.0120584236, 10.7777778, 0.000588435738, 0.0352481082, 0.0, "adf230ace24d41e8"], + "lucide/closed-caption": [0.0822539553, 0.00963470632, 15.0, 0.00088091084, 0.0400218027, 0.0, "b1299111427a1bd6"], + "lucide/cooking-pot": [0.0520801023, 0.0127465555, 4.95454545, 0.000674947107, 0.0241802471, 0.0, "35625856b222d0d7"], + "lucide/diff": [0.0272760857, 0.0122280322, 18.0, 0.00044328277, 0.0139894275, 0.0, "be670fb6921cca92"], + "lucide/equal": [0.0146765551, 0.00844898965, 8.0, 0.00036568733, 0.0124517497, 0.0, "75e753fe44f992e8"], + "lucide/file-digit": [0.0649564415, 0.0144168469, 5.83050847, 0.000862555404, 0.0436978559, 0.0, "2b732e2bbc19d825"], + "lucide/focus": [0.0489178374, 0.0194937209, 6.40425532, 0.000849420903, 0.0546631628, 0.0, "5561524d1f4d941f"], + "lucide/folder-open": [0.0577134229, 0.0077802149, 3.78378378, 0.000767756428, 0.0331052566, 0.0, "13cd7496cd38b22e"], + "lucide/git-compare": [0.0534990095, 0.0141476319, 6.42857143, 0.000745421741, 0.0508711903, 0.0, "f60b93b8a03907cb"], + "lucide/hard-drive-download": [0.0551591888, 0.0120642601, 14.75, 0.000651011709, 0.0255161052, 0.0, "23218e38d8eb428e"], + "lucide/ice-cream-cone": [0.0364169478, 0.0121716813, 4.70588235, 0.000613507989, 0.0508807742, 0.0, "19184ba746433d08"], + "lucide/iteration-ccw": [0.0508771352, 0.00947438225, 10.6153846, 0.000823421113, 0.0762729163, 0.0, "e697c6d29db018d5"], + "lucide/list-checks": [0.0336747095, 0.0154423552, 19.2857143, 0.000535867701, 0.0379409854, 0.0, "54586fc55be3d76f"], + "lucide/message-circle-dashed-check": [0.068898201, 0.021217786, 7.5, 0.00116110407, 0.0872232199, 0.0, "84ce98c5f73272e3"], + "lucide/messages-square": [0.0655549243, 0.00979356915, 3.51898734, 0.000790031219, 0.0353323773, 0.0, "578949ef3310eb73"], + "lucide/navigation-2-off": [0.0189123247, 0.0129856273, 10.75, 0.00043318505, 0.0257559721, 0.0, "39694c7215b48dd8"], + "lucide/omega": [0.0526444092, 0.0101693025, 3.1627907, 0.000810929865, 0.0838004012, 0.0, "a77fc305e7aa5cae"], + "lucide/panel-right": [0.0500424765, 0.00535987643, 20.75, 0.000959538447, 0.0212475938, 0.0, "fe60387f94f7e548"], + "lucide/pen-line": [0.0401414298, 0.00630249133, 5.16666667, 0.000782790827, 0.044387568, 0.0, "2734216537ff9e7c"], + "lucide/phone-forwarded": [0.088781409, 0.0123385719, 4.0, 0.00128535845, 0.0730621275, 0.0, "623468d0f93ec96f"], + "lucide/rectangle-goggles": [0.0601870008, 0.00741216441, 3.90163934, 0.000690535002, 0.0333480683, 0.0, "70de0d2aa4b2896f"], + "lucide/save-pen": [0.0650571734, 0.0110692069, 4.10638298, 0.00109404011, 0.0409192555, 0.0, "06bb87dfa9d807b9"], + "lucide/shapes": [0.0246111173, 0.0138262326, 4.67647059, 0.000661094498, 0.0200092254, 0.0, "7c84cddae23ef3ef"], + "lucide/shopping-cart-plus": [0.0630519092, 0.0181047908, 6.69767442, 0.000873146753, 0.0452764333, 0.0, "2e03d16332e872e8"], + "lucide/sparkle": [0.0785894766, 0.0125888255, 2.94285714, 0.0010640762, 0.0911393165, 0.0, "645fe5566fab2274"], + "lucide/square-minus": [0.0184245892, 0.00551824649, 21.5, 0.000874582969, 0.0172797831, 0.0, "49b9d6c58b803ada"], + "lucide/swiss-franc": [0.0259455126, 0.0148951012, 14.75, 0.000351041876, 0.0204713586, 0.0, "1b9ca56d053d0697"], + "lucide/ticket-minus": [0.0665197372, 0.011862054, 6.0, 0.000853923673, 0.046368073, 0.0, "ff2fb162907cb1d8"], + "lucide/undo": [0.0341692083, 0.0122757425, 5.2, 0.000540699635, 0.0731282662, 0.0, "18283e31dd0e858a"], + "lucide/vegan": [0.0778897256, 0.0100039891, 9.64285714, 0.00140347949, 0.0819426578, 0.0, "02f75be79024da1d"], + "material-icons/12mp": [0.0968987644, 0.0205447461, 1.95, 0.000904472137, 0.0128135434, 0.0, "78a3b556714b96f9"], + "material-icons/admin_panel_settings": [0.0328512564, 0.0119752084, 1.36885246, 0.000642858737, 0.0354740705, 0.0, "b0fa17358e1fd02d"], + "material-icons/arrow_drop_down": [0.00698490255, 0.0146492908, 3.66666667, 0.000148982639, 0.0336935222, 0.0, "c47c7bc816be2505"], + "material-icons/bento": [0.0472411849, 0.011744227, 2.0375, 0.000794085383, 0.0142868941, 0.0, "d0b1f52bc74eac69"], + "material-icons/border_left": [0.0649046749, 0.0461628386, 2.26470588, 0.000579654472, 0.00696066439, 0.0, "1361ac8ce8694ad4"], + "material-icons/call": [0.0340182781, 0.0185236233, 1.66972477, 0.000608376926, 0.0775696776, 0.0, "59e4c15d0b9f92e8"], + "material-icons/chair": [0.0572573207, 0.0147763706, 1.84146341, 0.000883618428, 0.0352402622, 0.0, "1031ceb3197c372a"], + "material-icons/closed_caption": [0.072836794, 0.0137442428, 1.76811594, 0.000701440498, 0.0245168816, 0.0, "c3db3c4c080c19aa"], + "material-icons/crop_landscape": [0.0488970391, 0.00814173951, 2.5, 0.000503734453, 0.0123337881, 0.0, "4e218b6d0c9cc1f0"], + "material-icons/dining": [0.0823986009, 0.0113919534, 1.94444444, 0.00117736508, 0.0167739729, 0.0, "0044df622302aed1"], + "material-icons/double_arrow": [0.0180547908, 0.0128974645, 2.6, 0.000260910339, 0.0148560535, 0.0, "b10b2135a3523962"], + "material-icons/dynamic_feed": [0.0516970977, 0.0155581061, 2.47368421, 0.00065781828, 0.0235458158, 0.0, "7d372c366c41b743"], + "material-icons/expand_circle_down": [0.015354719, 0.00838735037, 0.416666667, 0.000688306056, 0.0405509078, 0.0, "153676134bc6eda4"], + "material-icons/flight": [0.0141104162, 0.0165659713, 1.95454545, 0.000264829723, 0.0122968279, 0.0, "89567312c61051e5"], + "material-icons/free_breakfast": [0.0556560457, 0.0120554423, 2.70422535, 0.000640435319, 0.0271612748, 0.0, "ec6f39c1f6bfcd36"], + "material-icons/group_remove": [0.056435883, 0.0152071947, 1.36567164, 0.000802552502, 0.0360606987, 0.0, "5221d5d709083465"], + "material-icons/headset": [0.0467426032, 0.0109537934, 1.86046512, 0.000613896933, 0.0407142656, 0.0, "2b8c42441185af31"], + "material-icons/houseboat": [0.060705848, 0.0208713298, 2.06578947, 0.000781339768, 0.0519472146, 0.0, "88820326e8630bdc"], + "material-icons/javascript": [0.0232941359, 0.0365932663, 2.02083333, 0.000308407092, 0.0556382851, 0.0, "e4cbdd87c6b33c82"], + "material-icons/laptop": [0.073585555, 0.0137446959, 3.20833333, 0.000598383835, 0.00965764364, 0.0, "59acfa48f0ebe616"], + "material-icons/lyrics": [0.0671941265, 0.019255327, 2.14953271, 0.000787084224, 0.0192276969, 0.0, "7976923d8988d12a"], + "material-icons/miscellaneous_services": [0.0304770898, 0.0302435458, 0.954022989, 0.00051686907, 0.0404965867, 0.0, "b3cb817d5d4db3f2"], + "material-icons/music_note": [0.0276163667, 0.0161651736, 1.24528302, 0.0003687391, 0.0385950842, 0.0, "7dd4e4a8ca140f5e"], + "material-icons/no_food": [0.0569478869, 0.0146814104, 1.95121951, 0.000888405659, 0.0129516868, 0.0, "5fd96319fbfe38b7"], + "material-icons/notifications_paused": [0.0574651249, 0.0170825886, 1.76086957, 0.000812455721, 0.0503071717, 0.0, "c8acda7f64a2d50b"], + "material-icons/perm_media": [0.081084922, 0.00787837958, 2.225, 0.0008739396, 0.0174312277, 0.0, "a052989a16f1dd21"], + "material-icons/phone_iphone": [0.0425628759, 0.0121055803, 1.82352941, 0.000500278838, 0.010291385, 0.0, "9dafa9d53e886067"], + "material-icons/polyline": [0.0433994271, 0.0191025588, 2.06896552, 0.000359853118, 0.00330312454, 0.0, "ebad3b1db35c4d8c"], + "material-icons/qr_code": [0.100432448, 0.030013255, 2.66666667, 0.00069481344, 0.00861125169, 0.0, "7bec074eda0203c9"], + "material-icons/report": [0.0412005857, 0.00933533608, 2.56097561, 0.000484765711, 0.0241034056, 0.0, "7603accaaef2c61c"], + "material-icons/rule_folder": [0.062748298, 0.0150580203, 2.23809524, 0.000808162324, 0.0200077549, 0.0, "d12baa2714956724"], + "material-icons/sd_card_alert": [0.0500686653, 0.00868571116, 2.56, 0.000651026668, 0.0165071035, 0.0, "37e2d23d36e87bc0"], + "material-icons/settings_overscan": [0.035139069, 0.0132431584, 2.0625, 0.000533235027, 0.00852188546, 0.0, "fdeeadac4cca8fad"], + "material-icons/sms_failed": [0.0500208065, 0.011221066, 2.84, 0.000759319228, 0.0185420614, 0.0, "cc767871f266a905"], + "material-icons/storage": [0.129371092, 0.015837834, 2.75, 0.000861822336, 0.00414126085, 0.0, "14798d327cca9347"], + "material-icons/table_rows": [0.0944773108, 0.0076237515, 2.67857143, 0.000624787528, 0.00528213992, 0.0, "6387a2a6c5b822af"], + "material-icons/transfer_within_a_station": [0.0484347045, 0.0262818763, 1.52777778, 0.000637293793, 0.0206789521, 0.0, "4534d0076415f379"], + "material-icons/two_wheeler": [0.0408333801, 0.0229070561, 1.28985507, 0.000588929397, 0.0342220492, 0.0, "6089b888bf0fbc34"], + "material-icons/video_camera_back": [0.0557896607, 0.0146575588, 2.48275862, 0.000605519628, 0.00973355935, 0.0, "ad753e620ce841fc"], + "material-icons/view_week": [0.0998925865, 0.00717433738, 2.17857143, 0.000756895693, 0.00789163523, 0.0, "dfdd5851dc024d81"], + "noto-emoji/emoji_u0030": [0.157801762, 0.0295749366, 1.57407407, 0.00174474029, 4.91369108, 3.1281888, "199b041039647f1b"], + "noto-emoji/emoji_u1f36a": [0.455941737, 0.0572136336, 2.78929188, 0.00529635558, 1.60093563, 0.744301835, "a647949beb35169c"], + "noto-emoji/emoji_u1f39e": [0.860022485, 0.124315851, 4.44767442, 0.00707427738, 4.06965444, 2.63462873, "acb6f51eeeeb2502"], + "noto-emoji/emoji_u1f3c2_1f3fd": [0.958755434, 0.0389566433, 1.38152012, 0.00765447831, 5.14964128, 3.76700081, "04a85f847ec46b2b"], + "noto-emoji/emoji_u1f3c4_1f3fe": [0.160731912, 0.0543659194, 1.16796875, 0.00175079342, 0.232740936, 0.0944003963, "ad687391d1c9da23"], + "noto-emoji/emoji_u1f3cb_200d_2642": [0.315114349, 0.118253684, 1.36497696, 0.0033758441, 2.89521061, 1.75248406, "32d1afd322b01824"], + "noto-emoji/emoji_u1f41b": [0.0571726784, 0.0386772815, 1.91273997, 0.000698651129, 0.0820359468, 0.0, "62e19b7a8d87c967"], + "noto-emoji/emoji_u1f44d_1f3fc": [0.0565070435, 0.034899222, 2.1468144, 0.000798251771, 0.0986576373, 0.0, "306957457b421886"], + "noto-emoji/emoji_u1f468_1f3fb_200d_2764_200d_1f468_1f3fd": [0.379296631, 0.042931733, 1.61956522, 0.00332764513, 1.56869415, 0.713584278, "99bd7c7c41934934"], + "noto-emoji/emoji_u1f468_1f3ff_200d_1f393": [0.633041918, 0.0708435587, 2.72481572, 0.0049544354, 2.31621436, 1.18766921, "4ce0101b2aebdf3d"], + "noto-emoji/emoji_u1f469_1f3fb_200d_1f52c": [0.826497614, 0.0496403302, 2.5323475, 0.0076455283, 1.72832489, 1.09183316, "8ed808bad5df6996"], + "noto-emoji/emoji_u1f469_1f3fc_200d_1f91d_200d_1f468_1f3fb": [0.391385704, 0.0510239085, 0.844380403, 0.00424485467, 2.93330062, 1.80932466, "bce20d70cf07a2fd"], + "noto-emoji/emoji_u1f469_1f3fe_200d_1faef_200d_1f469_1f3fd": [0.55038023, 0.0795452765, 1.15952598, 0.00550602609, 3.6751704, 2.55298871, "30886f3ac789dd11"], + "noto-emoji/emoji_u1f469_200d_1f469_200d_1f466_200d_1f466": [0.0812702179, 0.0167715987, 1.21854305, 0.00136413984, 0.0726493516, 0.0, "cd353ce4861700c8"], + "noto-emoji/emoji_u1f46c_1f3fd": [0.313389271, 0.0568780036, 0.707335907, 0.00297577516, 3.80965529, 2.64340129, "46073414eab5b29e"], + "noto-emoji/emoji_u1f470_1f3fb_200d_2640": [0.481336951, 0.0521146656, 2.5890411, 0.00666896114, 3.40115515, 2.21048965, "bb40e60eb4fa2b09"], + "noto-emoji/emoji_u1f482_1f3ff_200d_2640": [0.392121375, 0.0332157133, 1.28326613, 0.0046503921, 4.55509922, 4.03488634, "ee4aaf810aab57aa"], + "noto-emoji/emoji_u1f4d8": [0.0538925081, 0.0103361218, 2.08571429, 0.000913286756, 0.0432135909, 0.0, "0f83c39e8cc15b9d"], + "noto-emoji/emoji_u1f520": [0.0209534317, 0.0189767805, 1.23287671, 0.000421583973, 0.0577739892, 0.0, "50d1396ae8f5c6db"], + "noto-emoji/emoji_u1f56f": [0.339815557, 0.0488179745, 2.19587629, 0.00283787213, 2.94747032, 1.33536756, "8b698f29cf636258"], + "noto-emoji/emoji_u1f5a8": [0.145443663, 0.0218153171, 2.62790698, 0.00220411248, 3.15113115, 2.39524931, "f2e325432882cf4a"], + "noto-emoji/emoji_u1f62d": [0.599489927, 0.0229636517, 2.46846847, 0.003856736, 2.40960271, 1.02341231, "d4a0520f5ababe1b"], + "noto-emoji/emoji_u1f64b_1f3fe_200d_2640": [0.65399766, 0.0260349441, 1.30325815, 0.00680426275, 3.14936586, 2.2194289, "971f3b1fd996a72d"], + "noto-emoji/emoji_u1f6c0_1f3ff": [0.248359993, 0.114026575, 2.92581944, 0.00232130778, 0.527191295, 0.0778789401, "7b908605e64cf000"], + "noto-emoji/emoji_u1f90d": [0.0114285294, 0.0287815928, 2.76136364, 0.000191894054, 0.112410177, 0.0, "e67e4fe409b8abd5"], + "noto-emoji/emoji_u1f91c_1f3fe": [0.049134139, 0.0271912744, 2.47111111, 0.000691011373, 0.0974005915, 0.0, "320148b5bc9ec442"], + "noto-emoji/emoji_u1f926_1f3ff": [0.763005197, 0.0590827949, 2.12079511, 0.00513697742, 2.98020983, 1.79303758, "773526cef3502b7a"], + "noto-emoji/emoji_u1f932": [0.0846354067, 0.0343535392, 1.97682709, 0.000951928727, 0.108668184, 0.000278614043, "6ebb400c051f4858"], + "noto-emoji/emoji_u1f93c_1f3fe_200d_2640": [0.505079865, 0.0680691521, 1.12373969, 0.00546922954, 2.33010731, 1.35731724, "2a0a5c62f696052a"], + "noto-emoji/emoji_u1f987": [0.475283235, 0.0395964038, 1.55, 0.00458692247, 2.57179001, 1.39765343, "b010ae33c5f27eb6"], + "noto-emoji/emoji_u1f9be": [0.233422235, 0.0850488593, 3.64071856, 0.00196904247, 0.920231495, 0.28503201, "2c3f4e897024bd36"], + "noto-emoji/emoji_u1f9ce_1f3fd_200d_2642": [0.121671587, 0.0432636862, 1.02696078, 0.00121760194, 0.721843903, 0.232068161, "494e53a08fb585d2"], + "noto-emoji/emoji_u1f9cf_1f3fc": [0.443683147, 0.0451339951, 2.07852194, 0.00395600451, 2.55361969, 1.56274324, "2fa13ded0b39491b"], + "noto-emoji/emoji_u1f9d1_1f3fc_200d_1f37c": [0.139860094, 0.0553099752, 1.58916479, 0.00131543959, 0.392076501, 0.245285403, "f3ff7d96c8eae454"], + "noto-emoji/emoji_u1f9d1_1f3fd_200d_1f91d_200d_1f9d1_1f3ff": [0.429084748, 0.0813406618, 1.30656934, 0.00467320392, 2.6323636, 1.68353348, "3300b5fe4abc4034"], + "noto-emoji/emoji_u1f9d1_1f3fe_200d_1f9bc_200d_27a1": [0.179972783, 0.0738187854, 1.37406015, 0.00192910468, 1.22565197, 0.675429477, "cb3577eb7b03d73f"], + "noto-emoji/emoji_u1f9d6_1f3fe_200d_2642": [0.521744609, 0.0380725806, 2.16885965, 0.0050495523, 1.4407987, 1.03587566, "f34f0ceb1aa5fd55"], + "noto-emoji/emoji_u1f9dd_1f3fd_200d_2640": [0.540685952, 0.0462849342, 1.95474453, 0.00594670558, 2.59076444, 1.64595766, "33035794271f789f"], + "noto-emoji/emoji_u1f9ed": [0.0765844658, 0.0304949879, 2.47468354, 0.00087940105, 0.122899477, 0.0407158368, "ecfa6726663d8110"], + "noto-emoji/emoji_u1faa5": [0.0343924835, 0.0654094365, 1.74305556, 0.000514766434, 1.05519822, 0.612504447, "bed88f1252154f38"], + "noto-emoji/emoji_u1faf1_1f3fc_200d_1faf2_1f3ff": [0.0742971897, 0.0412156257, 1.60732113, 0.000972143374, 0.099447482, 0.0, "2f99b408b2879b4a"], + "noto-emoji/emoji_u26bd": [0.0824861079, 0.0334807678, 3.09090909, 0.00132172497, 0.091351383, 0.0, "ab5520995ba190a3"], + "noto-emoji/emoji_u2b05": [0.0119557157, 0.00902060867, 2.06410256, 0.000207955949, 0.049450064, 0.0, "fc73ff89a4be2e89"], + "openmoji/1F195": [0.0463907458, 0.0169782024, 11.0, 0.000650696864, 0.0392687911, 0.0, "23c40797134d91e2"], + "openmoji/1F1FF-1F1F2": [0.0299275815, 0.0134609245, 2.83333333, 0.000234985331, 0.00702747645, 0.0, "39857e3539586ef8"], + "openmoji/1F361": [0.0518132634, 0.0222292356, 2.6, 0.000760161958, 0.0825512626, 0.0, "2174ad691bfc1924"], + "openmoji/1F38A": [0.064399913, 0.0251227579, 2.328125, 0.000874475518, 0.0671359791, 0.0, "59661aed9bc898dd"], + "openmoji/1F3A9": [0.0526584685, 0.0080598108, 1.94029851, 0.000732526474, 0.0403844333, 0.0, "8fb0d4bc405c592a"], + "openmoji/1F3C3-1F3FF-200D-2642-FE0F": [0.0320990123, 0.0272968058, 2.71502591, 0.000560156535, 0.0685727624, 0.0, "b0959383c4e619fa"], + "openmoji/1F3CC-FE0F-200D-2640-FE0F": [0.0862571895, 0.0281300666, 1.98828125, 0.0011639531, 0.0941834643, 0.0, "39cb3ac46d1d13fe"], + "openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F": [0.0202810112, 0.00698765825, 5.6, 0.000330258015, 0.0108927539, 0.0, "4174849fa7a5ba30"], + "openmoji/1F442-1F3FF": [0.0367010795, 0.0278506957, 6.45614035, 0.000486662379, 0.0863432403, 0.0, "4c426657b2360888"], + "openmoji/1F468-1F3FC-200D-1F3ED": [0.0956372023, 0.0460705412, 0.858914729, 0.00138793385, 0.0755800746, 0.0, "d2ce1f5f73a1db2e"], + "openmoji/1F468-1F3FF-200D-1F9B0": [0.0516986735, 0.0222540756, 1.81538462, 0.000733722642, 0.077967988, 0.0, "e77967aa4bf0a814"], + "openmoji/1F468-200D-1F9B1": [0.0922592804, 0.0362278074, 1.69724771, 0.00115402904, 0.100037857, 0.0, "84860cb76883ea1c"], + "openmoji/1F469-1F3FC-200D-2764-FE0F-200D-1F48B-200D-1F469-1F3FC": [0.135698318, 0.0269130239, 2.71428571, 0.00150360714, 0.0900020789, 0.0, "f780f054cd59e1ef"], + "openmoji/1F469-1F3FF-200D-1F9B2": [0.0327533223, 0.0214090429, 2.14473684, 0.000526705466, 0.0697169787, 0.0, "f049669fb1626575"], + "openmoji/1F481-1F3FB-200D-2642-FE0F": [0.0727282092, 0.022667184, 2.36296296, 0.00108965568, 0.0725652705, 0.0, "2f2c99a432858542"], + "openmoji/1F49B": [0.0349970795, 0.00986220835, 1.34090909, 0.00047914093, 0.0602498378, 0.0, "a720fa3e426d6f72"], + "openmoji/1F517": [0.0658794045, 0.0248380067, 2.81818182, 0.000924303487, 0.0735351066, 0.0, "181f595e95d1b3d3"], + "openmoji/1F646-1F3FC": [0.0907878131, 0.0199680759, 1.52838428, 0.00120033848, 0.0757337414, 0.0, "bbcfcf817ea0cda9"], + "openmoji/1F6B4-1F3FD-200D-2640-FE0F": [0.0588995926, 0.0260243714, 2.95454545, 0.0011255797, 0.0569638296, 0.0, "5e61afb3ee3276e7"], + "openmoji/1F6E0": [0.0509327091, 0.033054769, 3.67857143, 0.000804356532, 0.0469196835, 0.0, "6c7ef81c9e4ea22b"], + "openmoji/1F938-1F3FB": [0.0666280463, 0.0261491277, 3.13157895, 0.000966805674, 0.0957289425, 0.0, "ac7d6ec5c10be437"], + "openmoji/1F93E-1F3FE": [0.059585426, 0.03383554, 3.22666667, 0.000801174261, 0.08154411, 0.0, "ec1df13bf1212e99"], + "openmoji/1F9B3": [0.0472065583, 0.0169166851, 5.54545455, 0.000590759097, 0.101838037, 0.0, "647a15b48deb1d4f"], + "openmoji/1F9D1": [0.072061941, 0.0236391052, 2.2293578, 0.000937451783, 0.0830587853, 0.0, "0d1aa862d07b24db"], + "openmoji/1F9D1-1F3FC-200D-1FA70": [0.0701997951, 0.0368683047, 3.36923077, 0.00091575674, 0.0795144247, 0.0, "ed74970315003de4"], + "openmoji/1F9D1-1F3FD-200D-1F527": [0.090236716, 0.0345151899, 1.77327935, 0.00132719567, 0.106099703, 0.0, "addb61e6bc764551"], + "openmoji/1F9D1-200D-1F393": [0.0629117861, 0.0301670631, 0.607438017, 0.000971559435, 0.0643333886, 0.0, "9232e94eb7ca34b3"], + "openmoji/1F9D6-1F3FD-200D-2642-FE0F": [0.0763704553, 0.0356952681, 2.49865952, 0.0010170982, 0.0881723325, 0.0, "bb786c686925e3b2"], + "openmoji/1FA8B": [0.0702438504, 0.0491433922, 1.01282051, 0.000813158753, 0.10144439, 1.61304484e-05, "fbc3a6e67afafc87"], + "openmoji/1FAC4-1F3FD": [0.0608155094, 0.030050226, 1.55305466, 0.00088100991, 0.0829124179, 0.0, "edd577d3a77dee3c"], + "openmoji/25FC": [0.00440486148, 0.00557585832, 1.83333333, 0.000178019269, 0.00283445177, 0.0, "ac9f45b9b241d333"], + "openmoji/2705": [0.0630550832, 0.0151786056, 2.65789474, 0.000909952447, 0.060258947, 0.0, "210fd1a1f48de070"], + "openmoji/E056": [0.126658708, 0.015746754, 1.00900901, 0.00144548621, 0.08031902, 0.0, "c222f1946209d6f3"], + "openmoji/E1D1": [0.034479633, 0.0159442524, 1.1734104, 0.000621785934, 0.0279410887, 0.0, "e068b5b2cf1a01ed"], + "openmoji/E30B": [0.0725583881, 0.0267576922, 2.04273504, 0.00155586796, 0.0882371349, 0.0, "272102df68789b97"], + "simple-icons/alchemy": [0.0328622907, 0.00787336599, 0.430188679, 0.000447995029, 0.0213021457, 0.0, "bb400f654e0437c4"], + "simple-icons/appletv": [0.0428134687, 0.0312849323, 1.52046784, 0.000692704169, 0.0631568048, 0.0, "aeab146839158962"], + "simple-icons/atlassian": [0.0383060165, 0.00601486952, 1.84615385, 0.000622663298, 0.0752814007, 0.0, "cd68d94379b474d1"], + "simple-icons/autocad": [0.0340771712, 0.0093648932, 1.4516129, 0.000920000253, 0.0316901217, 0.0, "9201aa3c0552b4ed"], + "simple-icons/bandrautomation": [0.0437429287, 0.0224729538, 1.44545455, 0.00122311176, 0.080313626, 0.0, "d82320946c65a89e"], + "simple-icons/bim": [0.0278633479, 0.0218731074, 1.71631206, 0.000747890037, 0.0332089142, 1.94545485e-05, "a18c46802a6e82fd"], + "simple-icons/boosty": [0.0357369371, 0.0101650369, 2.63636364, 0.000545785937, 0.0503420384, 0.0, "cd1c328f14367ad9"], + "simple-icons/changedetection": [0.0863893256, 0.0139456058, 0.931914894, 0.00130704977, 0.0502060449, 0.0, "8df5e0ee4c00551a"], + "simple-icons/cocos": [0.126876906, 0.027765687, 0.761048689, 0.00262198341, 0.0746462058, 0.0, "43fbe44adde75d40"], + "simple-icons/contentstack": [0.0604080297, 0.0149585642, 1.23039216, 0.00134085864, 0.0510254102, 0.0, "d49f422b70388271"], + "simple-icons/debridlink": [0.0375052057, 0.010183053, 1.09090909, 0.000717462273, 0.0575108529, 0.0, "bd1f1b271f85f403"], + "simple-icons/elixir": [0.0293553937, 0.00861459434, 1.8490566, 0.000467906269, 0.087091318, 0.0, "db4b0c0a281c1ea1"], + "simple-icons/fampay": [0.0477451086, 0.0124888486, 1.37967914, 0.000732406974, 0.0634123876, 0.0, "d96f8dbf02bc543b"], + "simple-icons/fluxer": [0.0744619668, 0.0156048859, 1.43859649, 0.00115854607, 0.0895593719, 0.0, "5fafc30161354365"], + "simple-icons/googlechrome": [0.0513330661, 0.0119316995, 2.18681319, 0.0010416517, 0.058948861, 0.0, "73e608bdf2d2ad3c"], + "simple-icons/h2database": [0.0781008005, 0.0158816169, 1.21465969, 0.00150468119, 0.0707360167, 0.0, "dce93ac5c570bd2b"], + "simple-icons/hitachi": [0.0324364677, 0.0454148231, 0.931972789, 0.000747411337, 0.0740779488, 0.0, "500f9fed6a563070"], + "simple-icons/infinityfree": [0.053966023, 0.0440517517, 1.16707022, 0.00102887617, 0.0653127593, 0.0, "55e929f47a391ba9"], + "simple-icons/jdoodle": [0.0545437336, 0.0199033149, 0.959798995, 0.00101783604, 0.0592550421, 0.0, "6c987d5f0b47d31b"], + "simple-icons/kleinanzeigen": [0.0623762496, 0.0115077615, 1.89333333, 0.00125841622, 0.0765280717, 0.0, "fcfe0df62cf00532"], + "simple-icons/leetcode": [0.0391746238, 0.0104523016, 1.35632184, 0.00086640002, 0.0838754558, 0.0, "d5fc592095864087"], + "simple-icons/looker": [0.0550718978, 0.0189696197, 1.27071823, 0.000869272277, 0.0675387029, 0.0, "11f06a1ec8c50b49"], + "simple-icons/mamp": [0.0533747971, 0.0164625865, 2.33333333, 0.000816599466, 0.074713063, 0.0, "b0a32ceabc5f302f"], + "simple-icons/microeditor": [0.0737500042, 0.0175011324, 0.624489796, 0.0010849149, 0.0847017638, 0.0, "512d247a0a944815"], + "simple-icons/mysql": [0.0932200029, 0.0360091911, 0.778588808, 0.00153693405, 0.0828422781, 0.0, "e862b10f59a30ea2"], + "simple-icons/notion": [0.0473275669, 0.0109397084, 2.06741573, 0.00128393748, 0.0309894496, 0.0, "3f4b674ee9248c24"], + "simple-icons/osano": [0.0401537903, 0.0123665571, 4.5, 0.000614016608, 0.0604549728, 0.0, "7a4c8689255abdb5"], + "simple-icons/phpstorm": [0.0374765433, 0.013168807, 1.59722222, 0.00072527118, 0.0678627192, 0.0, "7e7e8c9a58ba879d"], + "simple-icons/playerfm": [0.0879812986, 0.0149137507, 1.14444444, 0.00130836631, 0.0778154207, 0.0, "9fcd3fb68b9d8f7a"], + "simple-icons/premierleague": [0.0923362821, 0.038929833, 1.60663507, 0.00136347755, 0.0758466845, 0.0, "6e6c99ee91af19c8"], + "simple-icons/pronounsdotpage": [0.0434515625, 0.0128218319, 1.48837209, 0.00074263924, 0.0503026697, 0.0, "4ad2034c328244a7"], + "simple-icons/purescript": [0.0338199325, 0.0179522033, 3.2962963, 0.000608481583, 0.0516628483, 0.0, "b22485c0100f9fd1"], + "simple-icons/redsys": [0.0517316051, 0.0128191052, 1.29577465, 0.000791661849, 0.0903076164, 0.0, "7776adaa177aaa69"], + "simple-icons/sagemath": [0.0762961879, 0.033862991, 1.05516266, 0.00161008642, 0.0342037219, 0.0, "dab4fea043784164"], + "simple-icons/slackware": [0.0664004162, 0.0101148649, 1.18483412, 0.0011959899, 0.100201523, 0.0, "30dab5073660b89b"], + "simple-icons/sparkar": [0.01831498, 0.0130826367, 3.33333333, 0.000323531218, 0.0134542342, 0.0, "0bb24663e695d8f1"], + "simple-icons/stmicroelectronics": [0.0425270014, 0.0106303294, 1.32467532, 0.000767576974, 0.0378533747, 0.0, "40b48081f6dbd44c"], + "simple-icons/ubiquiti": [0.0364403427, 0.0215234455, 0.654867257, 0.000577694795, 0.0457587418, 0.0, "71e3a58d8b441dce"], + "simple-icons/visa": [0.027793508, 0.0225478467, 1.77941176, 0.000503061339, 0.0374957424, 0.0, "b16613399b944025"], + "simple-icons/wxt": [0.069486469, 0.0193772477, 1.83505155, 0.00102356554, 0.0688871857, 0.0, "4ed04fbaa5c1044d"], + "synthetic/gradient_linear": [0.0956573635, 0.00346932404, 7.66666667, 0.000401839701, 0.323549172, 0.0381622787, "d2640e6431defeee"], + "synthetic/mosaic_grid6": [0.070085302, 0.0297625317, 4.07207207, 0.000454070425, 0.115620937, 0.0, "fc07afb179eb54c2"], + "synthetic/prim_ellipse": [0.00235147518, 0.00398260463, 1.2, 7.40450123e-05, 0.0131581307, 0.0, "592d101d720ea30b"], + "synthetic/prim_star5": [0.00603735726, 0.00863000561, 3.41666667, 0.000112062342, 0.0279244604, 0.0, "2d6a8774e5b03941"], + "synthetic/symmetry_rot3": [0.0226231497, 0.00645942427, 3.61111111, 0.000231230471, 0.0657404296, 0.0, "e9868a1966c80677"], + "twemoji/1f17e": [0.0381181985, 0.0050158809, 1.475, 0.000437479262, 0.0849997191, 6.34326262e-05, "ace27f294cb6a25c"], + "twemoji/1f1f8": [0.0209649261, 0.0074781724, 1.82692308, 0.000315089797, 0.0849660612, 7.39800272e-05, "478a4e9b48dde7df"], + "twemoji/1f1fa": [0.0163747277, 0.00530138906, 1.68181818, 0.0002942461, 0.0864597791, 6.94177271e-05, "dce24477bac34077"], + "twemoji/1f325": [0.0191402156, 0.020069597, 1.71584699, 0.000240816924, 0.0922194065, 0.0, "ba3d8fbb21c0e1a8"], + "twemoji/1f369": [0.0481081009, 0.0220045487, 1.44194757, 0.000592754979, 0.0700823424, 0.0, "495bc55614d9957b"], + "twemoji/1f3ca-1f3fe-200d-2640-fe0f": [0.041994147, 0.0209093259, 1.89937107, 0.000533996557, 0.0949974363, 0.0, "26a73971cff2590d"], + "twemoji/1f3cc-1f3fb-200d-2640-fe0f": [0.045063708, 0.0349589014, 1.90612245, 0.000535184401, 0.0994944972, 0.0, "8760fc964201b798"], + "twemoji/1f42b": [0.0409837738, 0.0224780337, 1.63257576, 0.000548409473, 0.0922467991, 0.0, "f989df4f34946ebc"], + "twemoji/1f468-1f3fb-200d-1f91d-200d-1f468-1f3fd": [0.069050096, 0.0385966633, 1.36382979, 0.000982133322, 0.0971998417, 2.12924078e-05, "33249fb81f7d3b72"], + "twemoji/1f468-1f3fc-200d-1f9b0": [0.0294050295, 0.0229371758, 1.73553719, 0.000373679533, 0.0806897165, 0.0, "b0e8eca4776839dc"], + "twemoji/1f468-1f3fe-200d-2764-fe0f-200d-1f48b-200d-1f468-1f3ff": [0.0423244201, 0.0257880796, 1.23188406, 0.000594867044, 0.0875429614, 0.0, "9d69836f45c1ae0d"], + "twemoji/1f469-1f3fb-200d-1f37c": [0.079304412, 0.0368287464, 1.76266667, 0.000871914206, 0.113941127, 0.0, "2651971664889e2e"], + "twemoji/1f469-1f3fc-200d-2764-fe0f-200d-1f468-1f3fc": [0.10053695, 0.0212681101, 2.22826087, 0.00120600709, 0.554852938, 0.435621168, "1e2025462ee95804"], + "twemoji/1f469-1f3fe": [0.040067926, 0.0154016788, 1.63636364, 0.000570708944, 0.0698386906, 0.0, "959d85f36444a817"], + "twemoji/1f469-1f3ff-200d-1f91d-200d-1f468-1f3fc": [0.100730456, 0.0386496243, 1.5862069, 0.00137215399, 0.184338716, 0.0782476176, "a1646a963e6d1f67"], + "twemoji/1f469-200d-1f467-200d-1f467": [0.027691694, 0.0145846072, 0.859375, 0.000416321418, 0.0799688699, 5.23699214e-05, "defdc023dec92c16"], + "twemoji/1f470-1f3fc-200d-2640-fe0f": [0.0402931906, 0.0139978974, 2.42162162, 0.000496404537, 0.103941391, 0.0, "ccc07290d79a634f"], + "twemoji/1f481-1f3fc-200d-2640-fe0f": [0.0298392754, 0.0197123471, 1.93243243, 0.000380274141, 0.0633680207, 0.0, "519689dc7ffdfc1f"], + "twemoji/1f486-1f3ff": [0.0464302786, 0.0331510055, 2.06147541, 0.000791241007, 0.0690643319, 1.36194699e-05, "cdca69b369cd2ed0"], + "twemoji/1f4e6": [0.0271816216, 0.0154562727, 1.72131148, 0.000358962192, 0.0536004668, 0.0, "efe05ef7ae0da645"], + "twemoji/1f53a": [0.00327507476, 0.00633136404, 2.0, 5.03323135e-05, 0.0153190598, 0.0, "05a76aecf9fd69fa"], + "twemoji/1f57a-1f3fb": [0.0757193938, 0.0544982107, 1.09448819, 0.000983489328, 0.11851233, 0.0, "db1e0dd85192fd37"], + "twemoji/1f635": [0.0427222587, 0.0172677674, 1.25757576, 0.000482992356, 0.0682881027, 0.0, "81bb5d680180dec4"], + "twemoji/1f646-1f3fb-200d-2640-fe0f": [0.0568904281, 0.015702991, 2.40993789, 0.000711018685, 0.0654402743, 0.0, "617e2b91449da17c"], + "twemoji/1f648": [0.0429806449, 0.0254272171, 1.25705329, 0.000690458051, 0.0662655759, 0.0, "e4e5cdb40ddba225"], + "twemoji/1f64d-1f3fd": [0.0395203903, 0.0237229135, 2.3125, 0.000518891495, 0.0793921582, 0.0, "2c3e4b3701bb1a00"], + "twemoji/1f6a3-1f3ff-200d-2642-fe0f": [0.0531712025, 0.0223134242, 1.78712871, 0.000527538883, 0.0769378251, 0.000241942846, "d18e3934ac5458fc"], + "twemoji/1f6d6": [0.0605229251, 0.0582354687, 2.06142506, 0.000766624522, 0.499497918, 0.172565942, "d695bbbbc7a9d12b"], + "twemoji/1f7eb": [0.00543011632, 0.00324073684, 2.0, 7.83094365e-05, 0.0980209177, 0.00036849969, "409ccee7f51d772c"], + "twemoji/1f91c-1f3fe": [0.0182446912, 0.0178549986, 2.1509434, 0.000302417873, 0.0798463866, 0.0, "f113d5badae5fde5"], + "twemoji/1f938-1f3fe": [0.0526651479, 0.0665685814, 1.03558719, 0.000716337643, 0.115551203, 0.0, "657d5b3fb291fdd0"], + "twemoji/1f977-1f3fb": [0.0539817587, 0.0389109461, 2.06355932, 0.000921515923, 0.0792691316, 0.0, "ea0a869e35cdf98e"], + "twemoji/1f9a8": [0.108613968, 0.0237601778, 3.14239482, 0.00166860444, 0.0975512004, 0.0, "d2ac90c938867b06"], + "twemoji/1f9c9": [0.0321553573, 0.0242615927, 2.28027682, 0.000432575209, 0.0865766841, 0.0, "fb6d8869fffe4340"], + "twemoji/1f9d1-1f3fd-200d-1f9af-200d-27a1-fe0f": [0.0460451357, 0.041483304, 1.025, 0.000599912368, 0.0874053666, 2.00793399e-05, "4de6e4ab1c10186f"], + "twemoji/1f9d1-1f3ff-200d-2764-fe0f-200d-1f9d1-1f3fb": [0.0521588065, 0.0249123346, 2.19339623, 0.00075563346, 0.0714126621, 0.0, "663c12c66aa1f7be"], + "twemoji/1f9d4-1f3fd": [0.0479521342, 0.0171411845, 1.74074074, 0.000625513436, 0.0872543321, 1.92105531e-05, "68277705f611c65f"], + "twemoji/1f9d8-1f3fe": [0.0576390028, 0.0389088581, 1.49081365, 0.000740809657, 0.113631525, 4.60108752e-05, "d4c511c20a1a2570"], + "twemoji/1f9e9": [0.0252104066, 0.0166765846, 1.18333333, 0.000374908821, 0.0760319362, 0.0, "538e3d5ab9aa8746"], + "twemoji/1faa3": [0.0319517553, 0.0118637654, 5.92592593, 0.000453101558, 0.0617383539, 0.0, "dc2e98a7af126075"], + "twemoji/1fae5": [0.0294602606, 0.0341972005, 2.49206349, 0.000369031419, 0.0725603181, 0.0, "c7471277a7bf50a3"], + "twemoji/2196": [0.0051640938, 0.00811992341, 2.0952381, 0.000154927373, 0.0243443172, 8.77272692e-05, "ec6ba8afff634ad6"], + "twemoji/271d": [0.0111579318, 0.0102242281, 1.61538462, 0.00020660786, 0.0470285384, 7.83156343e-05, "c4a0a45d48fc7fea"] } }, "fast-512ssop": { @@ -1318,259 +1601,529 @@ "fast" ], "summary": { - "de00": 0.09077620128289883, - "turning": 0.018803526371068247, - "ratio": 3.6200053569755033, - "self_res": 0.0011613345906392547, + "de00": 0.07994181618937124, + "turning_gap": 2.5068701190104554, + "ratio_gap": 1.0096942120118366, + "geom": 0.2817227206501695, + "turning": 0.01842347821328446, + "ratio": 3.5135104629117757, + "self_res": 0.0010896202792346921, + "geom_far": 0.14232388150532085, + "n": 246 + }, + "icons": { + "lucide/app-window-mac": [0.0552786477, 0.00695746405, 13.4166667, 0.00055112649, 0.0206516577, 0.0, "20b023fb07ab2e8d"], + "lucide/audio-lines-x": [0.0468108431, 0.0108660361, 19.5, 0.000872294127, 0.0360153658, 0.0, "9738ec99abf03b21"], + "lucide/badge-russian-ruble": [0.0918856412, 0.0151621954, 7.23943662, 0.00149049936, 0.0939015396, 0.0, "d0bf2ec586bc28c3"], + "lucide/bath": [0.0640312061, 0.0125080165, 6.75675676, 0.000658656063, 0.0324503337, 0.0, "f8709d197b8ffefe"], + "lucide/bell": [0.0590288602, 0.00710975787, 5.23809524, 0.000930890907, 0.0830750588, 0.0, "668a5af291cb938c"], + "lucide/birdhouse": [0.0367360748, 0.00993984587, 8.0, 0.000648109592, 0.0317779649, 0.0, "081f31701763375a"], + "lucide/book-heart": [0.0846005231, 0.00656302667, 3.86885246, 0.000858725747, 0.0307162515, 0.0, "6dfde875e4d64f31"], + "lucide/bug": [0.085079208, 0.0149077565, 6.75675676, 0.00131814985, 0.0758699956, 0.0, "53b59379def8872b"], + "lucide/cat": [0.0770707428, 0.00935516017, 5.46478873, 0.00122677675, 0.0902130536, 0.0, "c8e516b2e2273690"], + "lucide/chess-king": [0.0762077123, 0.0101658616, 3.775, 0.00104778504, 0.0621720815, 0.0, "4dda2ea96b3b4906"], + "lucide/circle-arrow-right": [0.0576798357, 0.00588111793, 11.1111111, 0.000591382792, 0.0213451835, 0.0, "1cdf4bc234bf0afc"], + "lucide/closed-caption": [0.083009392, 0.00748172076, 15.7, 0.000872907462, 0.0393944513, 0.0, "836719ecb947905a"], + "lucide/cooking-pot": [0.0603122264, 0.00918032126, 5.18181818, 0.000685029838, 0.0254772718, 0.0, "35c5df7cd336ea16"], + "lucide/diff": [0.0257858224, 0.00765642003, 19.3333333, 0.000445062964, 0.0140861286, 0.0, "511c5c5b34c8c1ea"], + "lucide/equal": [0.0146765308, 0.00533210645, 9.0, 0.00036568733, 0.0124517497, 0.0, "4e2e7255332cee04"], + "lucide/file-digit": [0.0641551539, 0.0103991055, 5.66101695, 0.00086800073, 0.0435004529, 0.0, "7476ff055c63754b"], + "lucide/focus": [0.0582479686, 0.0119413701, 6.63829787, 0.000776821922, 0.0605331988, 0.0, "d24a1707ec73aa7b"], + "lucide/folder-open": [0.0625166744, 0.00605309495, 3.86486486, 0.000798214227, 0.0367998764, 0.0, "732d0c23c85314f3"], + "lucide/git-compare": [0.0632903054, 0.00958552157, 6.35714286, 0.000778033631, 0.0547897737, 0.0, "0e020c55bdd64482"], + "lucide/hard-drive-download": [0.0552511737, 0.00870007802, 15.25, 0.000650622824, 0.0254582893, 0.0, "7ad7c4aec888443c"], + "lucide/ice-cream-cone": [0.0363832042, 0.00818746756, 4.94117647, 0.000612131727, 0.0504799409, 0.0, "4db8209fc43094e8"], + "lucide/iteration-ccw": [0.0495069288, 0.00669500567, 10.9230769, 0.000754726585, 0.0676008607, 0.0, "071c531925a144e1"], + "lucide/list-checks": [0.0351134464, 0.00980009116, 19.2857143, 0.00054173189, 0.0388868077, 0.0, "ae85b3a672435a9c"], + "lucide/message-circle-dashed-check": [0.0689019859, 0.0142674496, 7.53125, 0.00117148599, 0.0878611955, 0.0, "2f3511e93a172254"], + "lucide/messages-square": [0.066243872, 0.00735571615, 3.67088608, 0.000786710298, 0.035093769, 0.0, "e625fcfb05a8c8fa"], + "lucide/navigation-2-off": [0.0201552194, 0.0084627514, 11.0, 0.000448264298, 0.0275206918, 0.0, "000acb1a30285303"], + "lucide/omega": [0.0509807616, 0.00704092673, 3.25581395, 0.000772094645, 0.0777135929, 0.0, "7549cd0630f6bcd5"], + "lucide/panel-right": [0.0551103614, 0.0045184219, 21.25, 0.000987782143, 0.0232517337, 0.0, "4705cea076bd66f6"], + "lucide/pen-line": [0.0314064026, 0.00500068305, 5.11111111, 0.000746902777, 0.0424283325, 0.0, "584ed896785ebb39"], + "lucide/phone-forwarded": [0.0890661776, 0.00814957681, 4.04545455, 0.00126547727, 0.0709357172, 0.0, "29f929ae4696dc42"], + "lucide/rectangle-goggles": [0.0552697405, 0.00554957434, 4.06557377, 0.000713064102, 0.0368357602, 0.0, "e10f703f3705372e"], + "lucide/save-pen": [0.0635433123, 0.00850573046, 4.21276596, 0.00107022456, 0.0389093483, 0.0, "622bf7f2f660e65e"], + "lucide/shapes": [0.0276599545, 0.00953389673, 4.88235294, 0.000550812343, 0.0244444687, 0.0, "48639020491bacf4"], + "lucide/shopping-cart-plus": [0.0643188804, 0.0128620374, 6.46511628, 0.000902078638, 0.0474902652, 0.0, "c8e6cb3875090ee0"], + "lucide/sparkle": [0.0817124695, 0.00859080422, 3.05714286, 0.00110739924, 0.0955246348, 0.0, "b929ed18dd6c0573"], + "lucide/square-minus": [0.0226856507, 0.00460262739, 22.5, 0.000931429386, 0.0230908534, 0.0, "b66244e77f65ee93"], + "lucide/swiss-franc": [0.0270635895, 0.00877783757, 16.25, 0.000349845126, 0.0204012512, 0.0, "9f5049e4418bee4e"], + "lucide/ticket-minus": [0.0666699409, 0.00864455072, 6.22222222, 0.000849375967, 0.0464246655, 0.0, "e5d880d3a20528c5"], + "lucide/undo": [0.0333822072, 0.00720322683, 5.5, 0.000536092091, 0.0726910864, 0.0, "efa02ab89e339777"], + "lucide/vegan": [0.0799911246, 0.00780829574, 9.92857143, 0.00140968768, 0.0824016789, 0.0, "76f0a42c86a2c278"], + "material-icons/12mp": [0.0963123366, 0.0155480848, 2.0, 0.000904008455, 0.012787865, 0.0, "f9eec88a5de21929"], + "material-icons/admin_panel_settings": [0.0333017781, 0.00856985907, 1.31147541, 0.000633449177, 0.0350964753, 0.0, "dc8d201d99176a61"], + "material-icons/arrow_drop_down": [0.00698489835, 0.00538550118, 5.0, 0.000148982639, 0.0336935222, 0.0, "0d52fd4dd981884d"], + "material-icons/bento": [0.0471614823, 0.00837195677, 2.1375, 0.000793816056, 0.0142868941, 0.0, "d512ff4dbe35b9d1"], + "material-icons/border_left": [0.0649046749, 0.0304582699, 2.32352941, 0.00057965453, 0.00696066439, 0.0, "8e7c7f5587b9e72b"], + "material-icons/call": [0.0346100889, 0.0092876112, 1.72477064, 0.000613971788, 0.078342214, 0.0, "24b5898969122d67"], + "material-icons/chair": [0.0572580397, 0.0105912401, 1.8902439, 0.000882945315, 0.0350252733, 0.0, "718458a62593fe34"], + "material-icons/closed_caption": [0.070290722, 0.00996356319, 1.76811594, 0.000669486995, 0.0220827055, 0.0, "2d71f01920ec574d"], + "material-icons/crop_landscape": [0.0439092591, 0.00454927826, 2.7, 0.00049906713, 0.0111173824, 0.0, "4525212c9b04931a"], + "material-icons/dining": [0.0826532841, 0.00884525356, 2.0, 0.00117884623, 0.0167314713, 0.0, "e0bafa4bb178ccd9"], + "material-icons/double_arrow": [0.0180547778, 0.00772937864, 3.0, 0.000260910339, 0.0148560535, 0.0, "26be8c3e88f32762"], + "material-icons/dynamic_feed": [0.051179532, 0.0105424135, 2.57894737, 0.000655709067, 0.0232235647, 0.0, "17f3a7f9ed9fd6e1"], + "material-icons/expand_circle_down": [0.0118021602, 0.00538360763, 0.633333333, 0.000418749027, 0.0125987549, 0.0, "f04491e972b593b8"], + "material-icons/flight": [0.014132387, 0.00928485646, 2.13636364, 0.000265547831, 0.0124056494, 0.0, "bbb86eaf0f8dc7f2"], + "material-icons/free_breakfast": [0.0556961372, 0.00845957847, 2.81690141, 0.000639058999, 0.0273323694, 0.0, "8f15823b4fc27592"], + "material-icons/group_remove": [0.0505339019, 0.0113385839, 1.88059701, 0.00069830037, 0.0363715668, 0.0, "b8e967be601b7d20"], + "material-icons/headset": [0.0467766337, 0.00768756276, 1.95348837, 0.000610860239, 0.039931299, 0.0, "65929d60d790c6e5"], + "material-icons/houseboat": [0.0611233376, 0.0136081273, 2.11842105, 0.000783478899, 0.0520333269, 0.0, "54fa81de1b0b196a"], + "material-icons/javascript": [0.021497285, 0.0155950167, 2.0625, 0.000290620112, 0.0516336101, 0.0, "70f258c6cd5bd17d"], + "material-icons/laptop": [0.0643301159, 0.0093473, 4.54166667, 0.000754194334, 0.00875005785, 0.0, "bb9005e760756be1"], + "material-icons/lyrics": [0.0653923303, 0.0143064009, 2.56074766, 0.000781899958, 0.0185956446, 0.0, "0423fd5b1d02040e"], + "material-icons/miscellaneous_services": [0.0315875448, 0.0175327189, 0.925287356, 0.000524259114, 0.0418177137, 0.0, "a4fbf014de687465"], + "material-icons/music_note": [0.0278713163, 0.00868852688, 1.18867925, 0.000370070542, 0.0393008228, 0.0, "a11e80cd56066790"], + "material-icons/no_food": [0.0535277277, 0.0117914421, 2.12195122, 0.000866190589, 0.011607221, 0.0, "75502c2e8e46f141"], + "material-icons/notifications_paused": [0.0564582273, 0.0112393792, 1.93478261, 0.000821985013, 0.0510889102, 0.0, "943543012ef0202c"], + "material-icons/perm_media": [0.0765639842, 0.00815328202, 3.9, 0.00108458579, 0.0166994381, 0.0, "4e294a68a1a87125"], + "material-icons/phone_iphone": [0.044856973, 0.00810292562, 1.83823529, 0.000506397279, 0.0104679529, 0.0, "eb668ae1716ed512"], + "material-icons/polyline": [0.0433994196, 0.0115531143, 2.20689655, 0.000359853118, 0.00330312454, 0.0, "f90ed14fa75104c7"], + "material-icons/qr_code": [0.100432441, 0.021487921, 2.75, 0.000694813498, 0.00861125169, 0.0, "4ef8c377f9316c36"], + "material-icons/report": [0.0412005559, 0.00668334644, 2.75609756, 0.00048476574, 0.0241034056, 0.0, "f4a8e76b0c28ffd1"], + "material-icons/rule_folder": [0.05756386, 0.0106992283, 2.33333333, 0.000804123236, 0.0195012295, 0.0, "f04aea970d77eef4"], + "material-icons/sd_card_alert": [0.0500178598, 0.00641206711, 2.72, 0.000650308677, 0.0164852687, 0.0, "250e3b1a3e48945c"], + "material-icons/settings_overscan": [0.0371053293, 0.00972905208, 2.15625, 0.000536944892, 0.00872358689, 0.0, "402362c8b0727f9d"], + "material-icons/sms_failed": [0.0604085848, 0.00807309599, 3.0, 0.000763822056, 0.0191069991, 0.0, "bf272795bebc14fb"], + "material-icons/storage": [0.129371047, 0.011187174, 2.91666667, 0.000861822336, 0.00414126085, 0.0, "a9149acd655e9d51"], + "material-icons/table_rows": [0.0944773257, 0.00599519839, 2.82142857, 0.000624787586, 0.00528213992, 0.0, "de98b64f442e2ae6"], + "material-icons/transfer_within_a_station": [0.0490281954, 0.016437847, 1.58333333, 0.000646837987, 0.0213927433, 0.0, "95a85dd88b7a01fe"], + "material-icons/two_wheeler": [0.0423819833, 0.0185798957, 2.26086957, 0.000600165455, 0.0363897532, 0.0, "fb89a843f5ea64c4"], + "material-icons/video_camera_back": [0.0581764281, 0.00987515524, 2.37931034, 0.000596947735, 0.00993179885, 0.0, "98076bc8b4ded623"], + "material-icons/view_week": [0.0989119858, 0.00566060058, 2.32142857, 0.000752677151, 0.00736801962, 0.0, "b49984e1e1d8bcca"], + "noto-emoji/emoji_u0030": [0.044124119, 0.00543716011, 0.907407407, 0.000469626626, 0.876188914, 0.147199657, "41b6906aa749fa2c"], + "noto-emoji/emoji_u1f36a": [0.297814071, 0.0338780816, 1.37651123, 0.00324716023, 0.996608032, 0.254265846, "962b1c98abb1e399"], + "noto-emoji/emoji_u1f39e": [0.490413874, 0.0217096732, 0.828488372, 0.00382286985, 1.92413546, 0.912976288, "712f521f815adafb"], + "noto-emoji/emoji_u1f3c2_1f3fd": [0.718683362, 0.0333138927, 1.30104322, 0.00425306289, 3.34993597, 2.16341195, "89fca72e9235accf"], + "noto-emoji/emoji_u1f3c4_1f3fe": [0.104148082, 0.0480144532, 1.17734375, 0.00152331579, 0.117625076, 0.0163901164, "852429ad78e45fe9"], + "noto-emoji/emoji_u1f3cb_200d_2642": [0.244226366, 0.0957422324, 1.39354839, 0.00255634566, 2.11669956, 1.15882791, "5ec2d851ce1ae10a"], + "noto-emoji/emoji_u1f41b": [0.0580197908, 0.0302307487, 1.93368237, 0.000710526016, 0.0837551022, 0.0, "557579dcde66e7fd"], + "noto-emoji/emoji_u1f44d_1f3fc": [0.0563554503, 0.0287916079, 2.13573407, 0.000793372281, 0.0999683217, 0.0, "8e92436d67e51d4a"], + "noto-emoji/emoji_u1f468_1f3fb_200d_2764_200d_1f468_1f3fd": [0.259505123, 0.0317501253, 1.2173913, 0.00226361165, 1.01739058, 0.387127376, "56c5a3419bc1af59"], + "noto-emoji/emoji_u1f468_1f3ff_200d_1f393": [0.601620436, 0.0462187365, 1.86732187, 0.00505794957, 2.00856981, 0.904605741, "dbc8f284c9665a08"], + "noto-emoji/emoji_u1f469_1f3fb_200d_1f52c": [0.764356613, 0.0429402702, 2.0831793, 0.00720111607, 1.29874092, 0.697986992, "3e874e3f2c8c6f18"], + "noto-emoji/emoji_u1f469_1f3fc_200d_1f91d_200d_1f468_1f3fb": [0.316424221, 0.0400181576, 0.768491835, 0.00356609374, 2.67298024, 1.60428582, "3d2a9fbf572f53cc"], + "noto-emoji/emoji_u1f469_1f3fe_200d_1faef_200d_1f469_1f3fd": [0.386363715, 0.0582846903, 1.03828624, 0.00383790955, 2.36961171, 1.48869487, "003d48e738d51870"], + "noto-emoji/emoji_u1f469_200d_1f469_200d_1f466_200d_1f466": [0.0799354836, 0.0141354163, 1.27152318, 0.00135287119, 0.0689952836, 0.0, "5eb5840b62f6a845"], + "noto-emoji/emoji_u1f46c_1f3fd": [0.273949057, 0.046699313, 0.640926641, 0.0025969611, 3.11270528, 2.07165613, "9bb2be5b594a76ae"], + "noto-emoji/emoji_u1f470_1f3fb_200d_2640": [0.544889331, 0.0251773926, 1.82420091, 0.00847009849, 3.0725811, 1.88756547, "e7a52dc3d2225514"], + "noto-emoji/emoji_u1f482_1f3ff_200d_2640": [0.389490932, 0.0250932136, 1.09375, 0.00460043503, 4.62603533, 4.12362012, "d33caae72a79d6dc"], + "noto-emoji/emoji_u1f4d8": [0.177540883, 0.00911896436, 2.17142857, 0.0034902934, 2.13394254, 1.90413161, "30e6ace657e46ac6"], + "noto-emoji/emoji_u1f520": [0.0210223328, 0.0150756692, 1.23744292, 0.000420190161, 0.0553124126, 0.0, "7d5fe85d2e426640"], + "noto-emoji/emoji_u1f56f": [0.296562284, 0.0373400823, 1.6185567, 0.00220238161, 2.83781533, 1.31237984, "d2109a4ec7665331"], + "noto-emoji/emoji_u1f5a8": [0.0894772783, 0.019984415, 2.66046512, 0.00192874577, 2.9795737, 2.3235321, "f2aef9582503f789"], + "noto-emoji/emoji_u1f62d": [0.415368319, 0.019959662, 1.45345345, 0.00318644871, 1.54134818, 0.410526039, "adfa8e1badcea805"], + "noto-emoji/emoji_u1f64b_1f3fe_200d_2640": [0.245862007, 0.0180556757, 0.977443609, 0.0022129782, 0.992068292, 0.41287031, "8e0c84385c03097d"], + "noto-emoji/emoji_u1f6c0_1f3ff": [0.202036694, 0.0851608323, 2.41288097, 0.00188686885, 0.484611511, 0.0414735056, "df44b1a181b6d266"], + "noto-emoji/emoji_u1f90d": [0.0132454615, 0.0125506826, 2.125, 0.000215148902, 0.140803037, 0.0, "f577f03ffac40bad"], + "noto-emoji/emoji_u1f91c_1f3fe": [0.0490199178, 0.020198565, 2.56888889, 0.000689946581, 0.0986741179, 0.0, "2b5384659c618fb9"], + "noto-emoji/emoji_u1f926_1f3ff": [0.588369548, 0.0442312552, 1.91437309, 0.00504344376, 3.70518886, 2.4605739, "8f788153ae4e21a1"], + "noto-emoji/emoji_u1f932": [0.0844984353, 0.0306188169, 2.00891266, 0.000955100404, 0.111497857, 0.000296027421, "c42251a43aa892d4"], + "noto-emoji/emoji_u1f93c_1f3fe_200d_2640": [0.370378613, 0.0557657276, 0.995417049, 0.00396798318, 2.00518424, 1.10873988, "c7c73463dbd424a6"], + "noto-emoji/emoji_u1f987": [0.268100113, 0.0288636883, 1.5862069, 0.00298492867, 2.064859, 0.990096588, "0bfb103cfb04d089"], + "noto-emoji/emoji_u1f9be": [0.151884139, 0.0706417756, 3.56407186, 0.00151372177, 0.826875228, 0.19481112, "29b215e72ec26531"], + "noto-emoji/emoji_u1f9ce_1f3fd_200d_2642": [0.0872669071, 0.0280253511, 0.81372549, 0.000919471669, 0.442490332, 0.0858301961, "977b760ca9f81e1f"], + "noto-emoji/emoji_u1f9cf_1f3fc": [0.355799317, 0.0457220502, 2.1108545, 0.00321542588, 2.22809764, 1.33942726, "65730c07ffa2e1e9"], + "noto-emoji/emoji_u1f9d1_1f3fc_200d_1f37c": [0.0909467489, 0.0469987954, 1.60496614, 0.00114023534, 0.393958676, 0.245285403, "9ae315ce3bfac9e2"], + "noto-emoji/emoji_u1f9d1_1f3fd_200d_1f91d_200d_1f9d1_1f3ff": [0.243651971, 0.0711866788, 1.20843471, 0.00268429518, 0.625335188, 0.186682305, "61b58ada31773a7f"], + "noto-emoji/emoji_u1f9d1_1f3fe_200d_1f9bc_200d_27a1": [0.13216798, 0.0591648229, 1.45676692, 0.00159389025, 1.20898578, 0.746695701, "7227a6a75f720f04"], + "noto-emoji/emoji_u1f9d6_1f3fe_200d_2642": [0.390668124, 0.0385361625, 2.16008772, 0.00398006057, 1.63840608, 1.2759771, "d97e977b14952be7"], + "noto-emoji/emoji_u1f9dd_1f3fd_200d_2640": [0.564619005, 0.0496777365, 1.90072993, 0.00632250914, 2.23491913, 1.43254369, "873ec07f9a40aabb"], + "noto-emoji/emoji_u1f9ed": [0.0584579408, 0.0257254804, 2.42405063, 0.000793157786, 0.0656638823, 2.34989439e-05, "1d1eb1ecc420ac6c"], + "noto-emoji/emoji_u1faa5": [0.0343851149, 0.0481989622, 1.76388889, 0.000507279939, 1.05595151, 0.612584584, "7122734a63e6dcb1"], + "noto-emoji/emoji_u1faf1_1f3fc_200d_1faf2_1f3ff": [0.0734243095, 0.035922365, 1.6655574, 0.000967013242, 0.0999901694, 0.0, "9cac77f42c22eb0f"], + "noto-emoji/emoji_u26bd": [0.0752104595, 0.0262915356, 3.10822511, 0.00121317839, 0.0839983435, 0.0, "f73a9041b4409d5f"], + "noto-emoji/emoji_u2b05": [0.131025299, 0.00701677274, 2.20512821, 0.0025441933, 7.8058623, 7.51966094, "e21943891dcd4c50"], + "openmoji/1F195": [0.0465364531, 0.0124171426, 11.1176471, 0.000645760854, 0.0392843063, 0.0, "0ce0521cc5b36e22"], + "openmoji/1F1FF-1F1F2": [0.0300390925, 0.00974982663, 3.0, 0.000234905558, 0.00687835228, 0.0, "b790150a9a77ae41"], + "openmoji/1F361": [0.0519414544, 0.0157690843, 2.65714286, 0.000761049509, 0.0827960402, 0.0, "25f4e7aa4613df22"], + "openmoji/1F38A": [0.0644286498, 0.0176937676, 2.36979167, 0.000873735175, 0.0670310791, 0.0, "fb58255fe7babb47"], + "openmoji/1F3A9": [0.0548989102, 0.00780229379, 2.19402985, 0.000731629028, 0.0427636233, 0.0, "676ec8fc00087644"], + "openmoji/1F3C3-1F3FF-200D-2642-FE0F": [0.0326151587, 0.0174665066, 2.7357513, 0.000560546061, 0.0691614708, 0.0, "7391d09f55cf5561"], + "openmoji/1F3CC-FE0F-200D-2640-FE0F": [0.0931013003, 0.0188697748, 2.01171875, 0.00120482605, 0.0994587676, 0.0, "bb81a636cc0a3659"], + "openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F": [0.0203631241, 0.00581828423, 6.0, 0.00032989899, 0.0108589255, 0.0, "3a6e989f1efa48c3"], + "openmoji/1F442-1F3FF": [0.040480841, 0.02018131, 6.52631579, 0.000517696782, 0.0882864215, 0.0, "879f0f931e178c67"], + "openmoji/1F468-1F3FC-200D-1F3ED": [0.0950755328, 0.0340100988, 0.865116279, 0.00136683846, 0.0751047282, 0.0, "4b38c7b9e3c34554"], + "openmoji/1F468-1F3FF-200D-1F9B0": [0.0514230765, 0.0157304136, 1.84615385, 0.000730556902, 0.0773644357, 0.0, "422a054816ada848"], + "openmoji/1F468-200D-1F9B1": [0.0930372849, 0.024841245, 1.70642202, 0.0011641708, 0.100898362, 0.0, "c950157f3627f530"], + "openmoji/1F469-1F3FC-200D-2764-FE0F-200D-1F48B-200D-1F469-1F3FC": [0.138886109, 0.021569788, 2.68571429, 0.00152033882, 0.093093708, 0.0, "62b25f70455c107b"], + "openmoji/1F469-1F3FF-200D-1F9B2": [0.0327402093, 0.0140598374, 2.19736842, 0.000525859708, 0.0697169787, 0.0, "ef7ae66d60fed2f5"], + "openmoji/1F481-1F3FB-200D-2642-FE0F": [0.0726642534, 0.0173426034, 2.39259259, 0.00108859001, 0.0715700227, 0.0, "4557183b27f01326"], + "openmoji/1F49B": [0.0337039158, 0.00726687118, 1.43181818, 0.000487667887, 0.0616530798, 0.0, "7582362553b71893"], + "openmoji/1F517": [0.0742517412, 0.0236081069, 3.53846154, 0.00100326538, 0.0996935012, 0.0, "dfbd8d1ec84da56a"], + "openmoji/1F646-1F3FC": [0.0900029689, 0.0154316462, 1.54585153, 0.00120424258, 0.075453482, 0.0, "919d553bc5385061"], + "openmoji/1F6B4-1F3FD-200D-2640-FE0F": [0.0670987293, 0.0181515925, 2.97159091, 0.00105769839, 0.0662123357, 0.0, "eacfd35aed1e1067"], + "openmoji/1F6E0": [0.059527725, 0.0242555066, 3.625, 0.000896224461, 0.063007985, 4.07642776e-05, "d6d0013148c892e7"], + "openmoji/1F938-1F3FB": [0.0650403351, 0.0195883839, 3.21052632, 0.000937857025, 0.0927315177, 0.0, "bed00dde0bbd4e78"], + "openmoji/1F93E-1F3FE": [0.0583323091, 0.0258186367, 3.36, 0.000797531044, 0.0811467031, 0.0, "95492b3d9e2b3b44"], + "openmoji/1F9B3": [0.0410102457, 0.0112205856, 5.51515152, 0.000536326494, 0.0933494097, 0.0, "4ce57b44a93828fa"], + "openmoji/1F9D1": [0.0696764812, 0.0167695994, 2.28440367, 0.000910361297, 0.081588401, 0.0, "cef45c359b46a562"], + "openmoji/1F9D1-1F3FC-200D-1FA70": [0.0703525841, 0.02746034, 3.44615385, 0.000917741389, 0.079861012, 0.0, "6936cdc81e273f72"], + "openmoji/1F9D1-1F3FD-200D-1F527": [0.0882125422, 0.0273242664, 1.78137652, 0.0013242882, 0.0883911599, 0.0, "e26e78b53b20bf64"], + "openmoji/1F9D1-200D-1F393": [0.06289801, 0.0217534279, 0.607438017, 0.000969042827, 0.063986266, 0.0, "ca23b670c882d5b9"], + "openmoji/1F9D6-1F3FD-200D-2642-FE0F": [0.0773991123, 0.0245423456, 2.41823056, 0.00104047987, 0.0972747971, 0.0, "ff254856c8c961fb"], + "openmoji/1FA8B": [0.0688210949, 0.0375022741, 1.02884615, 0.000800333451, 0.10002491, 1.61304484e-05, "55f2ff5f690a1667"], + "openmoji/1FAC4-1F3FD": [0.0628666654, 0.0229715723, 1.59163987, 0.000891831412, 0.0851081917, 0.0, "e5c23454c9dd1059"], + "openmoji/25FC": [0.00440486148, 0.00438187455, 2.16666667, 0.00017801924, 0.00283445177, 0.0, "78fa203571ebc8ed"], + "openmoji/2705": [0.0652440637, 0.0117000496, 2.71052632, 0.000917127996, 0.0594451257, 0.0, "bf6cd4e9f2d93b30"], + "openmoji/E056": [0.119155847, 0.0127774135, 0.978978979, 0.00130672066, 0.0677221384, 0.0, "c2389aca56ae7dbd"], + "openmoji/E1D1": [0.0357666463, 0.01228305, 1.19075145, 0.000628392911, 0.0285901268, 0.0, "2e1b21fabf1b1a0a"], + "openmoji/E30B": [0.0725583881, 0.0203521493, 2.07692308, 0.00155586796, 0.0882371349, 0.0, "d9137462c4bea6c1"], + "simple-icons/alchemy": [0.0320680887, 0.00767919854, 0.762264151, 0.000445413258, 0.0200645674, 0.0, "7ad4e628c42c6e7c"], + "simple-icons/appletv": [0.0407451801, 0.0171272554, 2.47953216, 0.000671476882, 0.0587170945, 0.0, "541ed732c8de11fd"], + "simple-icons/atlassian": [0.0428768732, 0.0101191912, 3.69230769, 0.000839726999, 0.0800047109, 0.0, "f5c569c34e31175b"], + "simple-icons/autocad": [0.0348083675, 0.00777757446, 2.5483871, 0.00101630774, 0.0317433228, 0.0, "d36536d240771114"], + "simple-icons/bandrautomation": [0.0433586612, 0.0156613985, 1.87272727, 0.0012210866, 0.0793210613, 0.0, "84d74201f039f02d"], + "simple-icons/bim": [0.0299013164, 0.0167933216, 2.41134752, 0.000822995731, 0.0323334596, 7.78181939e-05, "92701ad0ab4bf8c2"], + "simple-icons/boosty": [0.0414072648, 0.00910327291, 5.18181818, 0.000626506808, 0.058275522, 0.0, "60a79ad30836a617"], + "simple-icons/changedetection": [0.0824002996, 0.0126998738, 1.16382979, 0.00141417421, 0.0497312545, 0.0, "c9785a244f19750e"], + "simple-icons/cocos": [0.129626319, 0.0217195226, 0.801498127, 0.00269451737, 0.0726088632, 0.0, "5912b7e7fffe5b5e"], + "simple-icons/contentstack": [0.0647270158, 0.0141258189, 1.58823529, 0.00134901237, 0.0517987145, 0.0, "e35f967c5625a338"], + "simple-icons/debridlink": [0.0369422734, 0.010210379, 2.27878788, 0.000708882697, 0.05611467, 0.0, "ae02b453e001a7ad"], + "simple-icons/elixir": [0.0314942338, 0.00807389409, 3.69811321, 0.000509481702, 0.0885731132, 0.0, "91cf1eff2b670e08"], + "simple-icons/fampay": [0.0474654362, 0.0103243067, 2.44919786, 0.000736443501, 0.0636234496, 0.0, "6277aa77453b643f"], + "simple-icons/fluxer": [0.0729468018, 0.0131667452, 1.96491228, 0.00127914862, 0.0898469126, 0.0, "9d9fe48e55708bac"], + "simple-icons/googlechrome": [0.0540936626, 0.0116702769, 4.53846154, 0.0010619954, 0.0618904872, 0.0, "933975a521fe5690"], + "simple-icons/h2database": [0.0803830475, 0.01201414, 1.78010471, 0.00149914064, 0.0688095099, 0.0, "294bc73254dc212b"], + "simple-icons/hitachi": [0.0319716707, 0.028590785, 1.13605442, 0.000749040104, 0.0733651336, 0.0, "b795b0b9d7ad2dd3"], + "simple-icons/infinityfree": [0.051952865, 0.0299559951, 1.6125908, 0.00099694496, 0.0627160549, 0.0, "0177833da57b3f02"], + "simple-icons/jdoodle": [0.0530832373, 0.0158073741, 1.36683417, 0.000965038023, 0.053034284, 0.0, "625898819ee428c3"], + "simple-icons/kleinanzeigen": [0.0657343715, 0.0112292872, 2.84, 0.00136737933, 0.0785094358, 0.0, "d41beed93fbd44a7"], + "simple-icons/leetcode": [0.040715415, 0.00953797588, 2.48275862, 0.000897001184, 0.0844473339, 0.0, "6767ce3d8baabd12"], + "simple-icons/looker": [0.0548234954, 0.0146749911, 2.06629834, 0.000873393379, 0.068595371, 0.0, "db18af3351c809b3"], + "simple-icons/mamp": [0.0539948083, 0.0134105518, 4.76666667, 0.000911032956, 0.0806188635, 0.0, "bf3a3f972c81a971"], + "simple-icons/microeditor": [0.0698017702, 0.0140298607, 0.869387755, 0.00117431243, 0.0838854093, 0.0, "0e5d511ff94db98d"], + "simple-icons/mysql": [0.090618059, 0.0259703573, 0.866180049, 0.00151896954, 0.0812074342, 0.0, "33d4314809adf923"], + "simple-icons/notion": [0.0639068335, 0.00865893167, 2.74157303, 0.00136835349, 0.0327413803, 0.0, "e7bd14c6f4cb8e48"], + "simple-icons/osano": [0.0382946581, 0.0113877015, 8.39285714, 0.000728588144, 0.0617243685, 0.0, "445f6c9cf0859b2a"], + "simple-icons/phpstorm": [0.0399555154, 0.0126906346, 1.61111111, 0.000743476965, 0.0694916346, 0.0, "71b4339adf58f772"], + "simple-icons/playerfm": [0.0880769566, 0.0123557783, 1.44444444, 0.00141005625, 0.0797584558, 0.0, "27ae78ae4a1cac8c"], + "simple-icons/premierleague": [0.0929565504, 0.030727304, 2.68246445, 0.00136977679, 0.0767877481, 0.0, "8aab79340000bd3e"], + "simple-icons/pronounsdotpage": [0.0406841561, 0.0113069761, 2.88372093, 0.000733496912, 0.0484396079, 0.0, "1c8d1fad6e63407c"], + "simple-icons/purescript": [0.033801727, 0.0135134068, 4.96296296, 0.000610069255, 0.0529707685, 0.0, "d67e6ea11338e7d6"], + "simple-icons/redsys": [0.0524452031, 0.00996732384, 2.3943662, 0.000923191721, 0.0909157485, 0.0, "c68cbdb9ddff626e"], + "simple-icons/sagemath": [0.0779535323, 0.0272026931, 1.29844413, 0.00169032346, 0.0345198376, 0.0, "6030c90369846504"], + "simple-icons/slackware": [0.0638961792, 0.00774906193, 1.37440758, 0.0011918582, 0.101920379, 0.0, "6d0eb35801ae3f2d"], + "simple-icons/sparkar": [0.0183236059, 0.0121503749, 6.16666667, 0.000318844395, 0.0134542342, 0.0, "941dbdb97625b0b7"], + "simple-icons/stmicroelectronics": [0.0448358655, 0.00887054323, 2.0, 0.000765497156, 0.0378295075, 0.0, "6ac65a3f996d606d"], + "simple-icons/ubiquiti": [0.0365498029, 0.0133933319, 1.17699115, 0.000582883367, 0.0437202235, 0.0, "ba1d1ee95b71f667"], + "simple-icons/visa": [0.0254903771, 0.016171584, 2.63235294, 0.000469366671, 0.0340319884, 0.0, "84fae87069161be5"], + "simple-icons/wxt": [0.069458127, 0.0179428405, 2.81443299, 0.00113653613, 0.067771366, 0.0, "a332c9b9d9d9a65c"], + "synthetic/gradient_linear": [0.0956573635, 0.00346932404, 7.66666667, 0.000401839701, 0.323549172, 0.0381622787, "d2640e6431defeee"], + "synthetic/mosaic_grid6": [0.070085302, 0.0297625317, 4.07207207, 0.000454070425, 0.115620937, 0.0, "fc07afb179eb54c2"], + "synthetic/prim_ellipse": [0.00235147518, 0.00398260463, 1.2, 7.40450123e-05, 0.0131581307, 0.0, "592d101d720ea30b"], + "synthetic/prim_star5": [0.00603735726, 0.00863000561, 3.41666667, 0.000112062342, 0.0279244604, 0.0, "2d6a8774e5b03941"], + "synthetic/symmetry_rot3": [0.0226231497, 0.00645942427, 3.61111111, 0.000231230471, 0.0657404296, 0.0, "e9868a1966c80677"], + "twemoji/1f17e": [0.039195165, 0.0120494687, 2.375, 0.00047743172, 0.0850314355, 6.34326262e-05, "f79dd04e626fe855"], + "twemoji/1f1f8": [0.0214184187, 0.0146642892, 2.51923077, 0.000346053537, 0.0849290712, 7.39800272e-05, "d3fd4b0c18b0e573"], + "twemoji/1f1fa": [0.0168204345, 0.0126037651, 2.5, 0.00032293098, 0.0859391461, 6.94177271e-05, "5a201736ca8cec9e"], + "twemoji/1f325": [0.0205954071, 0.0146486858, 2.49180328, 0.000247448013, 0.112726519, 0.0, "512c706cde7594a8"], + "twemoji/1f369": [0.0479537435, 0.0166159571, 1.43820225, 0.000545561546, 0.0683245014, 0.0, "1deac8fac20e89a1"], + "twemoji/1f3ca-1f3fe-200d-2640-fe0f": [0.0422533303, 0.0173918268, 2.79245283, 0.000525583338, 0.0947465076, 0.0, "c8350e8085dd8f38"], + "twemoji/1f3cc-1f3fb-200d-2640-fe0f": [0.0444343127, 0.0319446162, 2.97142857, 0.000540425768, 0.0997068277, 0.0, "9359baabacab8774"], + "twemoji/1f42b": [0.0413800329, 0.0173224431, 3.28409091, 0.000548890152, 0.0927055102, 0.0, "ecd2757c399a334c"], + "twemoji/1f468-1f3fb-200d-1f91d-200d-1f468-1f3fd": [0.0684441477, 0.0348028767, 2.20638298, 0.000983283855, 0.0973169499, 2.12924078e-05, "7ccce0083f109fa5"], + "twemoji/1f468-1f3fc-200d-1f9b0": [0.0284380615, 0.015678146, 1.76859504, 0.000357005774, 0.0787309041, 0.0, "519b1b4b077bac6b"], + "twemoji/1f468-1f3fe-200d-2764-fe0f-200d-1f48b-200d-1f468-1f3ff": [0.042286858, 0.0225874368, 1.51811594, 0.000595659367, 0.0877048448, 0.0, "bdec56b1a9e7130d"], + "twemoji/1f469-1f3fb-200d-1f37c": [0.080276452, 0.0298080741, 1.768, 0.000861463312, 0.112755801, 0.0, "d790c47b108cdbda"], + "twemoji/1f469-1f3fc-200d-2764-fe0f-200d-1f468-1f3fc": [0.0425495543, 0.0229026455, 2.82065217, 0.000536141684, 0.0670392735, 0.0, "39106a34e32588bd"], + "twemoji/1f469-1f3fe": [0.040294636, 0.0113883776, 1.66666667, 0.000567621959, 0.0697805078, 0.0, "cdd7e06a011670a6"], + "twemoji/1f469-1f3ff-200d-1f91d-200d-1f468-1f3fc": [0.0841685012, 0.0341451555, 2.46336207, 0.00118263718, 0.0866692323, 3.86312602e-05, "55a5d2945087d3ba"], + "twemoji/1f469-200d-1f467-200d-1f467": [0.0264670122, 0.019458522, 1.04166667, 0.000438613555, 0.0790523963, 5.23699214e-05, "b873b3bc78737c98"], + "twemoji/1f470-1f3fc-200d-2640-fe0f": [0.0401791967, 0.0118089552, 2.61081081, 0.000495187182, 0.102617609, 0.0, "0c818bd7910f4b43"], + "twemoji/1f481-1f3fc-200d-2640-fe0f": [0.0298754945, 0.0181183276, 2.41891892, 0.00040484115, 0.0657614468, 0.0, "6c2bdd6ee8cac525"], + "twemoji/1f486-1f3ff": [0.0422367826, 0.0268100494, 2.56557377, 0.000717709307, 0.072401102, 0.0, "0fb2319dfd3ab65b"], + "twemoji/1f4e6": [0.0280837193, 0.012119867, 1.78688525, 0.000350677874, 0.0536193468, 0.0, "c53860dd9f3d5669"], + "twemoji/1f53a": [0.00367336301, 0.004152246, 2.33333333, 4.92669351e-05, 0.0163235883, 0.0, "d7c14e3cd21bc818"], + "twemoji/1f57a-1f3fb": [0.0744833574, 0.0366972862, 1.02755906, 0.000956097792, 0.11418033, 0.0, "0ccf92db107743f8"], + "twemoji/1f635": [0.0417333432, 0.0139984848, 1.53030303, 0.000505680509, 0.0671476637, 0.0, "267eab29d975ff7e"], + "twemoji/1f646-1f3fb-200d-2640-fe0f": [0.0602730624, 0.0144939015, 2.82608696, 0.00078133354, 0.0663081825, 0.0, "1aa86d95ffe13491"], + "twemoji/1f648": [0.0413381532, 0.0236746874, 1.46603971, 0.000734568341, 0.0644276251, 0.0, "96c8f46fc76fffd5"], + "twemoji/1f64d-1f3fd": [0.037057884, 0.0173170855, 3.0, 0.000495142012, 0.0740168588, 0.0, "84cb89677a8e3db3"], + "twemoji/1f6a3-1f3ff-200d-2642-fe0f": [0.0482263006, 0.0260616823, 2.62376238, 0.000477637834, 0.0683891778, 0.000241942846, "44e0152e7efe2c39"], + "twemoji/1f6d6": [0.0495086238, 0.0450924742, 2.2039312, 0.000688728411, 0.32785863, 0.0873866266, "9cb2ca5e79fe37be"], + "twemoji/1f7eb": [0.00583867822, 0.0154158589, 4.25, 0.000106658183, 0.0950729201, 0.000184249845, "1b0d9af08ebd65c4"], + "twemoji/1f91c-1f3fe": [0.0188094061, 0.0138271329, 2.9245283, 0.000325721834, 0.0808447948, 0.0, "72c1539ff64e58e4"], + "twemoji/1f938-1f3fe": [0.0533529297, 0.0460251007, 1.03380783, 0.000724842364, 0.117786271, 0.0, "67391d95b7840643"], + "twemoji/1f977-1f3fb": [0.0527887791, 0.0299854292, 2.69915254, 0.000895398844, 0.0776039457, 0.0, "3305067f44d794bd"], + "twemoji/1f9a8": [0.11075376, 0.0182203449, 3.19417476, 0.00168525346, 0.0992555893, 0.0, "b93cfe2d1ae18b26"], + "twemoji/1f9c9": [0.0332068689, 0.0189329299, 2.32179931, 0.000443621859, 0.0853032799, 0.0, "b2e948b6d965d7c2"], + "twemoji/1f9d1-1f3fd-200d-1f9af-200d-27a1-fe0f": [0.0454642884, 0.0325398458, 1.65, 0.000596982019, 0.0867025897, 2.00793399e-05, "12cfe24a2f7362f7"], + "twemoji/1f9d1-1f3ff-200d-2764-fe0f-200d-1f9d1-1f3fb": [0.049400717, 0.0261202336, 2.80660377, 0.000731524546, 0.0699592774, 0.0, "172f9f6ed7a8e426"], + "twemoji/1f9d4-1f3fd": [0.0480773188, 0.0119272147, 2.34814815, 0.00066340511, 0.0895211773, 1.92105531e-05, "a2718d9cadbc1f61"], + "twemoji/1f9d8-1f3fe": [0.0597321317, 0.0327355809, 2.11286089, 0.000773030391, 0.119413558, 4.60108752e-05, "0c73747bdd7c67b8"], + "twemoji/1f9e9": [0.0252048299, 0.0103989548, 1.21666667, 0.000373725634, 0.0752472029, 0.0, "7c76dcc88370fab1"], + "twemoji/1faa3": [0.0320807323, 0.0108376991, 6.44444444, 0.000458945491, 0.0624890509, 0.0, "582ddf0fcabb9125"], + "twemoji/1fae5": [0.0298563018, 0.0301721717, 3.6984127, 0.000373107468, 0.0744945986, 0.0, "ef8b0d831d8001c4"], + "twemoji/2196": [0.00565106608, 0.0157387646, 3.80952381, 0.000184001212, 0.0238618172, 8.77272692e-05, "b3c3e9e5b487793a"], + "twemoji/271d": [0.0119371517, 0.0170878973, 2.30769231, 0.00023510911, 0.0470676962, 7.83156343e-05, "7b6acb367bef5a63"] + } + }, + "fast-web": { + "tier": "web", + "args": [ + "--mode", + "fast" + ], + "summary": { + "de00": 0.18735115401889674, + "turning_gap": 8.421230700249982, + "ratio_gap": 1.1932620320017082, + "geom": 0.32926900392112585, + "turning": 0.04089146405107482, + "ratio": 4.12836829024529, + "self_res": 0.0038115667002409288, + "geom_far": 0.13741261399132776, "n": 246 }, "icons": { - "lucide/app-window-mac": [0.0506757908, 0.00698765545, 12.75, 0.000556676474, "b1ac82609a2d8eb3"], - "lucide/audio-lines-x": [0.0730638355, 0.0109103779, 21.125, 0.000903844077, "dced20665b8ce85b"], - "lucide/badge-russian-ruble": [0.100817107, 0.0151572387, 6.98591549, 0.00155445153, "149d183a8a804419"], - "lucide/bath": [0.0738043785, 0.0124874102, 6.81081081, 0.000674333598, "ff8ebf4322d22893"], - "lucide/bell": [0.0587249994, 0.00722008295, 5.14285714, 0.000911757525, "f91e0f307bb3a529"], - "lucide/birdhouse": [0.0606618971, 0.00989264346, 7.72727273, 0.000794907857, "6b8faa29d3dfafc3"], - "lucide/book-heart": [0.0872778445, 0.00656225613, 4.16393443, 0.000865337672, "23a83206928f5a3a"], - "lucide/bug": [0.0947614238, 0.0149285191, 7.0, 0.00133161328, "273eb4bfcc3d6c36"], - "lucide/cat": [0.0823275223, 0.00933223661, 5.46478873, 0.00124094367, "df85f9ab032fc7a5"], - "lucide/chess-king": [0.0815741047, 0.0102168346, 3.825, 0.00110147521, "134388204a33a957"], - "lucide/circle-arrow-right": [0.0627174154, 0.00588356816, 10.2222222, 0.000602737011, "97f0549a050c5e9d"], - "lucide/closed-caption": [0.0977626443, 0.00744594288, 15.4, 0.00105604285, "5f79dfef7988e784"], - "lucide/cooking-pot": [0.0752712414, 0.00920516097, 5.09090909, 0.000731883047, "1b999b6cbc7bcefd"], - "lucide/diff": [0.0586357974, 0.00943767394, 21.3333333, 0.000507878314, "47733a70b16598c4"], - "lucide/equal": [0.0579362698, 0.00533257376, 9.0, 0.00037039959, "72c7540c93f3aa18"], - "lucide/file-digit": [0.0711388737, 0.0107549951, 6.10169492, 0.000944788277, "3a74f354e59ce59c"], - "lucide/focus": [0.0719852298, 0.0119258786, 6.46808511, 0.000822837639, "fd8bf61791cb2583"], - "lucide/folder-open": [0.0754152313, 0.00604941984, 3.83783784, 0.000833533762, "605770659aea342b"], - "lucide/git-compare": [0.0702328235, 0.0095799615, 6.5, 0.000796583772, "ba1707c05d3c8c90"], - "lucide/hard-drive-download": [0.0786494538, 0.00865688135, 15.375, 0.000826607458, "fd12f5c087dbcf4e"], - "lucide/ice-cream-cone": [0.0418868549, 0.00955283297, 5.35294118, 0.000641482533, "3d786bd12dec714a"], - "lucide/iteration-ccw": [0.0614516102, 0.00666855374, 11.3846154, 0.000879145635, "75b5e7ee04f3e482"], - "lucide/list-checks": [0.0453972891, 0.00981413785, 20.1428571, 0.000552323356, "fbd3c19964543ec1"], - "lucide/message-circle-dashed-check": [0.0716703683, 0.0141984737, 7.46875, 0.00108959724, "88edb26d40876711"], - "lucide/messages-square": [0.0790697858, 0.00736819861, 3.84810127, 0.000879115716, "52fb90a42889fcef"], - "lucide/navigation-2-off": [0.029947998, 0.0110232891, 11.5, 0.0005420011, "d6ff3a120123b957"], - "lucide/omega": [0.054678984, 0.00706681292, 3.53488372, 0.000828716671, "901db166b10c3dbd"], - "lucide/panel-right": [0.127253994, 0.00451383452, 22.0, 0.000931040675, "1d57e685c62b20ee"], - "lucide/pen-line": [0.0529157408, 0.00498617853, 5.38888889, 0.000760096882, "4acdfaf48ee1d063"], - "lucide/phone-forwarded": [0.0973749682, 0.00813928836, 4.0, 0.00132968358, "04f3306fefe25ca5"], - "lucide/rectangle-goggles": [0.0810374841, 0.0055581108, 4.2295082, 0.00072827813, "b3be1ecbfd687a65"], - "lucide/save-pen": [0.0962817818, 0.00855060547, 4.17021277, 0.00114174664, "f7b89b4857b72bbb"], - "lucide/shapes": [0.0490286872, 0.00950897172, 5.23529412, 0.000645611319, "31cce80a365ea0d7"], - "lucide/shopping-cart-plus": [0.0695886165, 0.0129528335, 6.41860465, 0.00086611585, "8d506f7bf979e3c2"], - "lucide/sparkle": [0.0581843667, 0.00823830794, 2.85714286, 0.000763119198, "44fcacdd9e706b61"], - "lucide/square-minus": [0.120908149, 0.00459095688, 23.0, 0.000878472405, "3577d1ce05cf5b2d"], - "lucide/swiss-franc": [0.0384480022, 0.00876042044, 15.75, 0.000355215598, "cbeb84cac57b8e82"], - "lucide/ticket-minus": [0.0901982784, 0.00870348155, 6.07407407, 0.00102115737, "6dc1fbd618589781"], - "lucide/undo": [0.0480293259, 0.00710800059, 5.4, 0.000562211673, "39cfd96a442b24c2"], - "lucide/vegan": [0.0804436058, 0.00866795579, 10.0, 0.00142940495, "7752cfc1747a124d"], - "material-icons/12mp": [0.114097573, 0.0155788184, 1.95, 0.000913253578, "517cae77fc054290"], - "material-icons/admin_panel_settings": [0.0429928489, 0.00861978851, 1.40983607, 0.000706287508, "a0d6ac85d1b6c560"], - "material-icons/arrow_drop_down": [0.00895279646, 0.00491062889, 4.66666667, 0.000153470537, "ef3c607bc821f71c"], - "material-icons/bento": [0.106579967, 0.0083609421, 2.1375, 0.000770299637, "880530c45f6bff20"], - "material-icons/border_left": [0.0795369819, 0.0300257883, 2.10294118, 0.000559279404, "14ba307bac0929b8"], - "material-icons/call": [0.0383125767, 0.00928489244, 1.9266055, 0.000641497434, "ea6eb07a0c9ded28"], - "material-icons/chair": [0.086674735, 0.0104068683, 2.0, 0.000864829228, "564f37ed86dd100d"], - "material-icons/closed_caption": [0.066564627, 0.00992648138, 1.5942029, 0.000545352115, "87e4bac358621f0c"], - "material-icons/crop_landscape": [0.0739276409, 0.00453375458, 2.5, 0.000471302163, "1c2a89d42f845e0d"], - "material-icons/dining": [0.156910479, 0.00883245072, 1.94444444, 0.00121640938, "1f4183576cb697bf"], - "material-icons/double_arrow": [0.025482893, 0.00773019675, 3.5, 0.000253580132, "7dda897bba0c74b0"], - "material-icons/dynamic_feed": [0.0755919665, 0.0105604608, 2.78947368, 0.000595182588, "0c77133bf2611491"], - "material-icons/expand_circle_down": [0.0180874895, 0.00538453286, 0.833333333, 0.000408471824, "f84b0ab5b48ec5e2"], - "material-icons/flight": [0.0255986284, 0.0092772057, 1.77272727, 0.000376024516, "615a1fffb053d011"], - "material-icons/free_breakfast": [0.0690089762, 0.00849171784, 2.76056338, 0.000675007002, "96039a293d989942"], - "material-icons/group_remove": [0.0542383306, 0.0113693126, 1.95522388, 0.00064894557, "9cdcc7b0f1467550"], - "material-icons/headset": [0.0584863834, 0.0081102755, 2.18604651, 0.00068776746, "1031c8be02e1a784"], - "material-icons/houseboat": [0.0656380951, 0.0136262226, 2.23684211, 0.000784945034, "1dc6e0bcf2e57a65"], - "material-icons/javascript": [0.0207396466, 0.0152128786, 1.77083333, 0.000211079911, "41e0f07e62888d8c"], - "material-icons/laptop": [0.0823929384, 0.0105757249, 5.25, 0.000749906234, "09d8a3c54096485f"], - "material-icons/lyrics": [0.08576902, 0.0161469428, 2.59813084, 0.000840050459, "cf2e78e1019d48c4"], - "material-icons/miscellaneous_services": [0.0505315885, 0.0175624959, 0.959770115, 0.00063395797, "b072b71229660bda"], - "material-icons/music_note": [0.02528942, 0.00871072597, 1.26415094, 0.000340046623, "badf4ba5d0fe37e1"], - "material-icons/no_food": [0.0778890774, 0.0118075082, 2.02439024, 0.000925520493, "4d855b1eec974349"], - "material-icons/notifications_paused": [0.0745117441, 0.0127636563, 1.91304348, 0.000763582764, "afee61d173da7a45"], - "material-icons/perm_media": [0.0883321762, 0.0081189476, 3.775, 0.00112742337, "9578ce72976670c6"], - "material-icons/phone_iphone": [0.0652552471, 0.00810491365, 1.98529412, 0.000543332368, "08a67de78ae9d3b9"], - "material-icons/polyline": [0.0554397255, 0.0115942886, 2.34482759, 0.000441607204, "82f81ca127e2e6e0"], - "material-icons/qr_code": [0.104774795, 0.021555656, 3.10416667, 0.00077631342, "ec19d170b79f43ab"], - "material-icons/report": [0.0549714714, 0.00669715195, 2.41463415, 0.000544289884, "b6e0bc028b627677"], - "material-icons/rule_folder": [0.0642203316, 0.0107083073, 2.45238095, 0.000820653688, "d872b4fe7e831ac2"], - "material-icons/sd_card_alert": [0.0645586178, 0.00662909594, 2.8, 0.000656741438, "0718c04388fd17e6"], - "material-icons/settings_overscan": [0.0481715538, 0.00891422969, 2.625, 0.000555135717, "fece223187fc7c62"], - "material-icons/sms_failed": [0.0884431377, 0.00809283635, 2.92, 0.000741158845, "9611fbea187f9038"], - "material-icons/storage": [0.135961488, 0.0111697427, 1.91666667, 0.000845920586, "67d916b7a4a55e63"], - "material-icons/table_rows": [0.101638325, 0.00600085404, 2.25, 0.000659643207, "871a1d9fa306a3c1"], - "material-icons/transfer_within_a_station": [0.059570618, 0.0149368029, 1.86111111, 0.000664924213, "b1de7113026f9ad1"], - "material-icons/two_wheeler": [0.0453074761, 0.0187865106, 2.28985507, 0.000610419957, "4468341849b534ed"], - "material-icons/video_camera_back": [0.0704291314, 0.0101134585, 2.86206897, 0.000638640136, "23804609a9188f9e"], - "material-icons/view_week": [0.119494617, 0.00566738617, 2.10714286, 0.00075409835, "e9f9db450c4b2900"], - "noto-emoji/emoji_u0030": [0.0513942428, 0.00543715893, 0.907407407, 0.000472548767, "4628fe01101e40a2"], - "noto-emoji/emoji_u1f36a": [0.362891376, 0.027873273, 2.2642487, 0.00398435956, "58f682b81c8939cb"], - "noto-emoji/emoji_u1f39e": [0.517609298, 0.0216358716, 0.825581395, 0.00404411182, "3bc8758037e0b2de"], - "noto-emoji/emoji_u1f3c2_1f3fd": [0.756292105, 0.0346497151, 1.41132638, 0.00442567095, "d269621af2015cb7"], - "noto-emoji/emoji_u1f3c4_1f3fe": [0.110965706, 0.0502897923, 1.2328125, 0.00163234642, "eab2da7a7bb8a5ab"], - "noto-emoji/emoji_u1f3cb_200d_2642": [0.249132812, 0.0937524546, 1.41382488, 0.00257879589, "542c8e84b56dcf5f"], - "noto-emoji/emoji_u1f41b": [0.0584173016, 0.0298627189, 1.93019197, 0.000723560748, "1a31be87b8c9c473"], - "noto-emoji/emoji_u1f44d_1f3fc": [0.0618202537, 0.0278698571, 2.13019391, 0.000900054059, "32572470a3c4b546"], - "noto-emoji/emoji_u1f468_1f3fb_200d_2764_200d_1f468_1f3fd": [0.265160978, 0.0319185978, 1.25, 0.00234633801, "a6ca3405a09b0204"], - "noto-emoji/emoji_u1f468_1f3ff_200d_1f393": [0.620645702, 0.0442057531, 2.03194103, 0.00513703516, "1633b7419ca7b8da"], - "noto-emoji/emoji_u1f469_1f3fb_200d_1f52c": [0.788310826, 0.0421684781, 2.10720887, 0.00744756078, "3a89de25ad0c6504"], - "noto-emoji/emoji_u1f469_1f3fc_200d_1f91d_200d_1f468_1f3fb": [0.315021694, 0.0440528896, 0.87271854, 0.00352671999, "9418205b9134800b"], - "noto-emoji/emoji_u1f469_1f3fe_200d_1faef_200d_1f469_1f3fd": [0.390411317, 0.0605656622, 1.05651778, 0.00388803892, "40fb79f0ccc0f2d1"], - "noto-emoji/emoji_u1f469_200d_1f469_200d_1f466_200d_1f466": [0.0915924162, 0.0141934469, 1.28145695, 0.00143498427, "68ee92c0b575e603"], - "noto-emoji/emoji_u1f46c_1f3fd": [0.28815046, 0.0506919697, 0.681081081, 0.00274217431, "ce375325933b66d1"], - "noto-emoji/emoji_u1f470_1f3fb_200d_2640": [0.56046474, 0.0243516178, 1.7739726, 0.00858793687, "b90d32cae3a49816"], - "noto-emoji/emoji_u1f482_1f3ff_200d_2640": [0.399583876, 0.0253251431, 1.0625, 0.00473386561, "b830f5544e9a4545"], - "noto-emoji/emoji_u1f4d8": [0.206408203, 0.00914263903, 2.08571429, 0.00346723082, "24c76bd40003721b"], - "noto-emoji/emoji_u1f520": [0.0244602785, 0.0146603568, 1.25114155, 0.000450687745, "243c3321704a8a13"], - "noto-emoji/emoji_u1f56f": [0.315184623, 0.0364349437, 1.59793814, 0.00227597845, "9be24f8113894190"], - "noto-emoji/emoji_u1f5a8": [0.103268392, 0.0193567532, 2.69767442, 0.00203200639, "c41f2872b46581c5"], - "noto-emoji/emoji_u1f62d": [0.50535059, 0.0191575921, 1.40540541, 0.00420859875, "93b855e847af9d89"], - "noto-emoji/emoji_u1f64b_1f3fe_200d_2640": [0.316701561, 0.0181124545, 1.00250627, 0.00332217221, "071ff43b54ec4e3a"], - "noto-emoji/emoji_u1f6c0_1f3ff": [0.203920156, 0.0858532491, 2.43588269, 0.00190765795, "4a6c687b4e6993c3"], - "noto-emoji/emoji_u1f90d": [0.013489252, 0.0130914861, 2.27272727, 0.000224289368, "f228bebf543c5cef"], - "noto-emoji/emoji_u1f91c_1f3fe": [0.0523916781, 0.0206937997, 2.61333333, 0.000726931554, "5cf19f9e185ce099"], - "noto-emoji/emoji_u1f926_1f3ff": [0.609167755, 0.044461094, 1.90519878, 0.00535687059, "8714d4b8285fae6f"], - "noto-emoji/emoji_u1f932": [0.0921015814, 0.0309307547, 2.04991087, 0.000992604182, "1bc12aadb4545f3d"], - "noto-emoji/emoji_u1f93c_1f3fe_200d_2640": [0.419608653, 0.0552369667, 0.988084326, 0.0045900871, "ca605f55a47471a5"], - "noto-emoji/emoji_u1f987": [0.271837682, 0.0286940401, 1.58275862, 0.00299861119, "bb248d87cd362270"], - "noto-emoji/emoji_u1f9be": [0.15921171, 0.0734307028, 3.61437126, 0.00164897647, "3745f058603b4005"], - "noto-emoji/emoji_u1f9ce_1f3fd_200d_2642": [0.0969884396, 0.0277308629, 0.889705882, 0.00102458789, "aff2f8dfc46a80cf"], - "noto-emoji/emoji_u1f9cf_1f3fc": [0.374329209, 0.0492244489, 2.56812933, 0.00336758443, "8cb53c46318ee536"], - "noto-emoji/emoji_u1f9d1_1f3fc_200d_1f37c": [0.0938899666, 0.0480802135, 1.62979684, 0.00118465035, "73b06d95d4f6a545"], - "noto-emoji/emoji_u1f9d1_1f3fd_200d_1f91d_200d_1f9d1_1f3ff": [0.253591478, 0.0703585635, 1.24776967, 0.00276070461, "15bbe49b4bf8b1ba"], - "noto-emoji/emoji_u1f9d1_1f3fe_200d_1f9bc_200d_27a1": [0.142266288, 0.0615987943, 1.47932331, 0.00173157372, "85ed2758ec370f6d"], - "noto-emoji/emoji_u1f9d6_1f3fe_200d_2642": [0.413615912, 0.0398504784, 2.23245614, 0.00430088444, "c211a6fc2eeda69b"], - "noto-emoji/emoji_u1f9dd_1f3fd_200d_2640": [0.572563648, 0.0490895012, 1.90510949, 0.00640191371, "6f8feb0ab6721888"], - "noto-emoji/emoji_u1f9ed": [0.0598929003, 0.0252382414, 2.41561181, 0.00081631518, "e400fa86d743d1af"], - "noto-emoji/emoji_u1faa5": [0.0393567979, 0.0531403092, 1.94444444, 0.000551640231, "d9caceeef90afd19"], - "noto-emoji/emoji_u1faf1_1f3fc_200d_1faf2_1f3ff": [0.0762268752, 0.0353923178, 1.67720466, 0.00100039318, "5b9de730c365b967"], - "noto-emoji/emoji_u26bd": [0.0839598402, 0.0262233656, 2.93506494, 0.00126081461, "048ac14a682b43a9"], - "noto-emoji/emoji_u2b05": [0.131103426, 0.00684337542, 2.02564103, 0.00252622715, "7d1cb6e26348e8a1"], - "openmoji/1F195": [0.0774547681, 0.0124234812, 12.0588235, 0.000812535465, "61a20bb6769c8680"], - "openmoji/1F1FF-1F1F2": [0.0551420972, 0.00990978243, 3.08333333, 0.000239946865, "75d7d07fc9217b71"], - "openmoji/1F361": [0.0602812171, 0.0155045879, 2.71428571, 0.000867566734, "442f822f8f75af2f"], - "openmoji/1F38A": [0.0736705214, 0.0176775317, 2.34895833, 0.000984466053, "49205412c5bc2ac9"], - "openmoji/1F3A9": [0.0609182268, 0.0170520094, 3.55223881, 0.000771097315, "e526a01a08835836"], - "openmoji/1F3C3-1F3FF-200D-2642-FE0F": [0.0385444984, 0.0210126854, 3.1865285, 0.000625385961, "ab0cf88a53c81f63"], - "openmoji/1F3CC-FE0F-200D-2640-FE0F": [0.114400201, 0.0199839837, 2.07421875, 0.00140554889, "3ad80ea2f3b34efc"], - "openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F": [0.0368116498, 0.00581938566, 6.0, 0.000327769783, "b116418a6491db9d"], - "openmoji/1F442-1F3FF": [0.0469850414, 0.0320028341, 9.70175439, 0.000594275072, "6d3b533a3342cf3f"], - "openmoji/1F468-1F3FC-200D-1F3ED": [0.101354033, 0.0350148521, 0.852713178, 0.00144955481, "467e4882c4b78fac"], - "openmoji/1F468-1F3FF-200D-1F9B0": [0.0578487255, 0.0156070652, 1.98461538, 0.000760346418, "28da14a591fabf1c"], - "openmoji/1F468-200D-1F9B1": [0.104530722, 0.0253756054, 1.7293578, 0.00123364327, "f21135bbc4978947"], - "openmoji/1F469-1F3FC-200D-2764-FE0F-200D-1F48B-200D-1F469-1F3FC": [0.146898657, 0.0219068393, 2.76190476, 0.00160860072, "86cb2c5ec1f83548"], - "openmoji/1F469-1F3FF-200D-1F9B2": [0.0386000052, 0.0140923889, 2.23684211, 0.00055655191, "296640cb2d12c4c0"], - "openmoji/1F481-1F3FB-200D-2642-FE0F": [0.0804261193, 0.0183908436, 2.57777778, 0.00118571729, "c19fbb9bf415579d"], - "openmoji/1F49B": [0.0441390984, 0.0074565655, 1.43181818, 0.00054105866, "e85e4b79ccf91749"], - "openmoji/1F517": [0.0707833096, 0.0220985024, 3.5034965, 0.00102056901, "23a4e199c0d15c1d"], - "openmoji/1F646-1F3FC": [0.102070488, 0.0171187214, 1.63755459, 0.0012637818, "c2dc0b53d2eabec4"], - "openmoji/1F6B4-1F3FD-200D-2640-FE0F": [0.0741311833, 0.0187779142, 3.30113636, 0.00118374277, "1afe24b42f238355"], - "openmoji/1F6E0": [0.0807210058, 0.0268814598, 4.02678571, 0.00125595799, "c9eef2cceec64139"], - "openmoji/1F938-1F3FB": [0.0638172701, 0.0187999004, 3.25438596, 0.00088666525, "f21d94c265cce2c0"], - "openmoji/1F93E-1F3FE": [0.0659245327, 0.025997406, 3.42222222, 0.000831579266, "0fce864c66e6284e"], - "openmoji/1F9B3": [0.0471269041, 0.0112840086, 5.57575758, 0.000619461935, "309b95645fab536a"], - "openmoji/1F9D1": [0.0807356536, 0.0166131672, 2.36697248, 0.000944169995, "8c6627a0085ec1ca"], - "openmoji/1F9D1-1F3FC-200D-1FA70": [0.0772183239, 0.0277456537, 3.70769231, 0.000993531663, "c712d2690073a296"], - "openmoji/1F9D1-1F3FD-200D-1F527": [0.0973706022, 0.0298049708, 1.95546559, 0.00139608921, "eb658362a73f8401"], - "openmoji/1F9D1-200D-1F393": [0.0741153061, 0.0236948253, 0.708677686, 0.00112482219, "b84fc5e20b103db3"], - "openmoji/1F9D6-1F3FD-200D-2642-FE0F": [0.0844521299, 0.0303450809, 2.71313673, 0.00109748088, "abf73a4f7f0fc795"], - "openmoji/1FA8B": [0.0664686039, 0.0364470186, 1.05608974, 0.000779903668, "fb3d899e6684894c"], - "openmoji/1FAC4-1F3FD": [0.0721741393, 0.0247881151, 1.71061093, 0.00104360154, "cbb4e2a1756b19f9"], - "openmoji/25FC": [0.00456328504, 0.00438192222, 2.16666667, 0.000179694573, "d6aea1887b767544"], - "openmoji/2705": [0.0763055235, 0.0118209828, 3.01315789, 0.000949425797, "7a7c15fded99d878"], - "openmoji/E056": [0.127390921, 0.0141723325, 0.951951952, 0.00147827261, "aee27e7027c75d2b"], - "openmoji/E1D1": [0.0908643752, 0.012371021, 1.15028902, 0.000636181852, "78a98f8594950b2c"], - "openmoji/E30B": [0.0856378898, 0.0190283481, 2.05128205, 0.00161952572, "feac4fb9a66731ab"], - "simple-icons/alchemy": [0.0236168075, 0.00769258922, 0.920754717, 0.000495907327, "9bf1b1eb28b272c7"], - "simple-icons/appletv": [0.0526933447, 0.0172267562, 2.59649123, 0.000773454492, "fb0ab06acbaff04f"], - "simple-icons/atlassian": [0.0496069975, 0.0101532888, 3.75384615, 0.000823262613, "210be36b2ca09030"], - "simple-icons/autocad": [0.0513536558, 0.00707347368, 2.83870968, 0.0011884257, "cf51ebcfcded83db"], - "simple-icons/bandrautomation": [0.071652405, 0.0156985501, 1.76363636, 0.00153366907, "52ccd1e933c48f50"], - "simple-icons/bim": [0.0394879244, 0.0159280872, 2.56737589, 0.000924628985, "a734859b7a9aaf97"], - "simple-icons/boosty": [0.0408952683, 0.0116948948, 5.54545455, 0.000574297796, "d9d8a7ef0f76cc22"], - "simple-icons/changedetection": [0.0831047222, 0.012994882, 1.21489362, 0.00147219526, "1f312a29a05c9945"], - "simple-icons/cocos": [0.174689263, 0.0237856845, 0.907865169, 0.00278140977, "2d78ee9e16da5d41"], - "simple-icons/contentstack": [0.0881911144, 0.014601311, 1.78921569, 0.00156498339, "f1460d02bfe69830"], - "simple-icons/debridlink": [0.0465311073, 0.0101849586, 2.37575758, 0.000787980214, "d4353fd029a7c36f"], - "simple-icons/elixir": [0.0361650325, 0.00765949961, 3.77358491, 0.000535040628, "30b260441770cce4"], - "simple-icons/fampay": [0.0505310073, 0.0108443522, 2.62032086, 0.000822800444, "a7b3974fee761395"], - "simple-icons/fluxer": [0.0774546042, 0.0135144907, 2.04385965, 0.00133421982, "5f377ae7df8fb750"], - "simple-icons/googlechrome": [0.0631863773, 0.0115322024, 5.10989011, 0.00106642151, "c2d55e5b882bee7b"], - "simple-icons/h2database": [0.095723182, 0.0120473946, 2.05235602, 0.00157533295, "8e6d41b3d4ed5a18"], - "simple-icons/hitachi": [0.046378307, 0.0285210625, 1.04761905, 0.000788503152, "436cff06866ad2a7"], - "simple-icons/infinityfree": [0.0634701326, 0.0296761763, 1.66585956, 0.00107588642, "3d810ac0c91574f9"], - "simple-icons/jdoodle": [0.0868471935, 0.0158108615, 1.50251256, 0.00111859955, "f51a5fad647aa4ae"], - "simple-icons/kleinanzeigen": [0.0699825436, 0.0112183136, 2.78666667, 0.00146427692, "d6c4e039273b2aa7"], - "simple-icons/leetcode": [0.0521380156, 0.0105234308, 2.68965517, 0.000994439004, "eb91f05a83df24f8"], - "simple-icons/looker": [0.0663056076, 0.0147869593, 2.0441989, 0.00103777426, "6bcad3dead77cc53"], - "simple-icons/mamp": [0.061213512, 0.0130233303, 4.7, 0.000947697787, "2110eb7ee55509bc"], - "simple-icons/microeditor": [0.07173457, 0.0144383981, 0.93877551, 0.00116826699, "59e5605fd316bf13"], - "simple-icons/mysql": [0.102989167, 0.0267720801, 0.888077859, 0.00160015945, "dcb2ca0b105be435"], - "simple-icons/notion": [0.0709426999, 0.00864304685, 2.97752809, 0.00150861032, "fbde0979e47ab062"], - "simple-icons/osano": [0.0363641344, 0.0114598717, 9.10714286, 0.000680704368, "92f75db5c4174003"], - "simple-icons/phpstorm": [0.0475174077, 0.01277998, 1.59722222, 0.000748817634, "1983ed05240fbf46"], - "simple-icons/playerfm": [0.100411713, 0.0129501018, 1.41111111, 0.00151741225, "f0ec5bf20614a74e"], - "simple-icons/premierleague": [0.10292761, 0.0345884587, 2.97156398, 0.00147420308, "ce52eb34e1258934"], - "simple-icons/pronounsdotpage": [0.0492399745, 0.0106758796, 3.11627907, 0.000837278843, "c5406cdceeca9014"], - "simple-icons/purescript": [0.0464540198, 0.0135226115, 5.85185185, 0.000736212183, "bcae13632beeaf9a"], - "simple-icons/redsys": [0.068317987, 0.0104699627, 2.36619718, 0.00129534036, "2b2965cfb5d67e2d"], - "simple-icons/sagemath": [0.103149019, 0.0294416198, 1.48231966, 0.00190322462, "19902e6b449a865a"], - "simple-icons/slackware": [0.0828510895, 0.00772639003, 1.32701422, 0.00131545414, "1ec797c1d15b7c88"], - "simple-icons/sparkar": [0.0364653394, 0.0113003623, 6.0, 0.000473470922, "9abfdaf56c7e63c0"], - "simple-icons/stmicroelectronics": [0.0569425821, 0.00909232303, 2.02597403, 0.000808792189, "9c68370b863ff56c"], - "simple-icons/ubiquiti": [0.051692076, 0.0116130976, 1.18584071, 0.00067168707, "6d2eb12d56d49f08"], - "simple-icons/visa": [0.0408986434, 0.0164728179, 2.85294118, 0.000614508695, "8ec66654ddcebaec"], - "simple-icons/wxt": [0.0695248023, 0.0179972545, 2.80412371, 0.0011625319, "62036ca5156ce43a"], - "synthetic/gradient_linear": [0.095657222, 0.00346932404, 7.66666667, 0.000401839585, "e8b7e1ff41f36bd7"], - "synthetic/mosaic_grid6": [0.0701047331, 0.0303661568, 4.52252252, 0.000453610584, "39ce240d4a9a3422"], - "synthetic/prim_ellipse": [0.00235147611, 0.00398260463, 1.2, 7.4045005e-05, "9c28a439ccf4b01f"], - "synthetic/prim_star5": [0.0112211285, 0.00684078856, 3.25, 0.000155325484, "4ec45f3598e0b2c3"], - "synthetic/symmetry_rot3": [0.0235970747, 0.00647277025, 3.72222222, 0.000253739709, "71b64f75443d87b1"], - "twemoji/1f17e": [0.0329152308, 0.0120147146, 2.375, 0.000466333353, "67aba6d5baa50543"], - "twemoji/1f1f8": [0.0252492595, 0.0147108004, 2.51923077, 0.00038262186, "b69e781bf9fbf734"], - "twemoji/1f1fa": [0.022898702, 0.0125875284, 2.40909091, 0.000338196784, "0237641e4febfe5a"], - "twemoji/1f325": [0.0194234755, 0.0147066101, 2.6557377, 0.000240387351, "f4e31ce469013f18"], - "twemoji/1f369": [0.0577881634, 0.0165135845, 1.44569288, 0.000612002041, "1d8e1949386296dc"], - "twemoji/1f3ca-1f3fe-200d-2640-fe0f": [0.0438326448, 0.0174659103, 2.91823899, 0.000544110953, "fde13b807d65516f"], - "twemoji/1f3cc-1f3fb-200d-2640-fe0f": [0.0461697653, 0.0331086887, 3.09387755, 0.000538992346, "6553af263ddc4234"], - "twemoji/1f42b": [0.0484360419, 0.0175611364, 3.26893939, 0.000606607704, "271c300caf0ecec6"], - "twemoji/1f468-1f3fb-200d-1f91d-200d-1f468-1f3fd": [0.0760687068, 0.0356494883, 2.25744681, 0.00104659155, "a379011fe76e6a8c"], - "twemoji/1f468-1f3fc-200d-1f9b0": [0.034265779, 0.0155493295, 1.76033058, 0.000393297902, "abaf05c9fd946378"], - "twemoji/1f468-1f3fe-200d-2764-fe0f-200d-1f48b-200d-1f468-1f3ff": [0.0484102778, 0.0233349621, 1.5942029, 0.000665714906, "e64a394eac11939a"], - "twemoji/1f469-1f3fb-200d-1f37c": [0.0829144567, 0.0337465781, 1.92533333, 0.000847291725, "096abdaa91a22f08"], - "twemoji/1f469-1f3fc-200d-2764-fe0f-200d-1f468-1f3fc": [0.0464641415, 0.0227647815, 2.70652174, 0.000548813201, "4074ca8cf407e81b"], - "twemoji/1f469-1f3fe": [0.0540625378, 0.0116801315, 1.70454545, 0.000817142951, "7959f6121607d1e3"], - "twemoji/1f469-1f3ff-200d-1f91d-200d-1f468-1f3fc": [0.0975702479, 0.0332050043, 2.47844828, 0.00126628857, "3f9461a31099faa8"], - "twemoji/1f469-200d-1f467-200d-1f467": [0.033540979, 0.0196770526, 1.0625, 0.000452253647, "3b700789caf5f677"], - "twemoji/1f470-1f3fc-200d-2640-fe0f": [0.0449222513, 0.0118842338, 2.51891892, 0.00048852124, "0cbe1e5d339b24a8"], - "twemoji/1f481-1f3fc-200d-2640-fe0f": [0.0391061716, 0.0182071772, 2.44594595, 0.000537389889, "7a7eb9d66c4a8ac6"], - "twemoji/1f486-1f3ff": [0.0491053239, 0.0268555491, 2.66393443, 0.000870590331, "b844f9f048987401"], - "twemoji/1f4e6": [0.032841906, 0.0121091835, 1.7704918, 0.000431718858, "9f2f5ef34cfbbcf5"], - "twemoji/1f53a": [0.0101405354, 0.00417861735, 2.66666667, 7.27834195e-05, "ca00a79a7007d4d5"], - "twemoji/1f57a-1f3fb": [0.0785305947, 0.037816925, 1.05905512, 0.000996039715, "9e384289c8feb41c"], - "twemoji/1f635": [0.0429286435, 0.0140095542, 1.56818182, 0.000517046836, "1d3f44b9e9d95a1b"], - "twemoji/1f646-1f3fb-200d-2640-fe0f": [0.0682811067, 0.0145835124, 2.8447205, 0.000845466799, "b03c4bafe75e2c42"], - "twemoji/1f648": [0.0571140647, 0.0231510662, 1.49947753, 0.000995445065, "05c032bcc57786b1"], - "twemoji/1f64d-1f3fd": [0.0372827239, 0.0185868977, 3.1171875, 0.000507507648, "88391b12487f1000"], - "twemoji/1f6a3-1f3ff-200d-2642-fe0f": [0.0518613681, 0.0263033883, 2.68316832, 0.000486269855, "b3d04ebde5500d85"], - "twemoji/1f6d6": [0.0527417138, 0.0494618919, 2.23587224, 0.000652597286, "92ad10ecdd97c335"], - "twemoji/1f7eb": [0.0268802475, 0.0154461612, 4.75, 0.000369920657, "f31b708d200b42ba"], - "twemoji/1f91c-1f3fe": [0.0230331291, 0.0155202163, 3.03773585, 0.000346694025, "ecb2d33187be34d1"], - "twemoji/1f938-1f3fe": [0.05384022, 0.0470814705, 1.0658363, 0.000719696051, "fcffcef21ae1ba17"], - "twemoji/1f977-1f3fb": [0.0570310913, 0.0324038029, 2.93644068, 0.000946764078, "5e544595d62394f7"], - "twemoji/1f9a8": [0.129652768, 0.0182589714, 3.11003236, 0.0021966577, "cee3dee5ac597023"], - "twemoji/1f9c9": [0.0367522463, 0.0199669819, 2.52249135, 0.000480108312, "5990ba1226c68228"], - "twemoji/1f9d1-1f3fd-200d-1f9af-200d-27a1-fe0f": [0.0516627766, 0.0330929138, 1.695, 0.000653463474, "f38cca39c2b5eb15"], - "twemoji/1f9d1-1f3ff-200d-2764-fe0f-200d-1f9d1-1f3fb": [0.0560506918, 0.0263664933, 2.88679245, 0.000790378544, "84102deabb999da0"], - "twemoji/1f9d4-1f3fd": [0.050238952, 0.0120760108, 2.42962963, 0.000640978571, "641cad9e7f8516a1"], - "twemoji/1f9d8-1f3fe": [0.05967094, 0.0332610206, 2.12598425, 0.000746181759, "db8727aa293c94c2"], - "twemoji/1f9e9": [0.0260333829, 0.0103127752, 1.26666667, 0.000376787357, "162db0470b0f72f1"], - "twemoji/1faa3": [0.038817782, 0.0108677688, 6.37037037, 0.000516125932, "7a272629afd2402f"], - "twemoji/1fae5": [0.0348743461, 0.0301934167, 4.07142857, 0.000371377799, "2657a1ebab25fe64"], - "twemoji/2196": [0.0109809143, 0.0157412512, 3.9047619, 0.000210875602, "ff0c663900186e23"], - "twemoji/271d": [0.0231837127, 0.0152729789, 2.5, 0.000243694754, "b5de4b1dd00f6448"] + "lucide/app-window-mac": [0.0648170635, 0.00890543707, 11.9166667, 0.00194615184, 0.114642843, 0.0, "42312b5d77ef9fa2"], + "lucide/audio-lines-x": [0.0847221315, 0.0140065967, 19.5, 0.0026990443, 0.100940761, 0.0, "375b6b7df5785c09"], + "lucide/badge-russian-ruble": [0.122400299, 0.018005827, 7.07042254, 0.00369039201, 0.11212082, 0.0, "4b6a7a06c33c0a00"], + "lucide/bath": [0.0740209669, 0.0143663486, 6.43243243, 0.00203389698, 0.108990802, 0.0, "a6b77d046f6ff691"], + "lucide/bell": [0.0741399378, 0.0091274266, 5.0, 0.00236725458, 0.075747506, 0.0, "6db7ad11b723ac5a"], + "lucide/birdhouse": [0.0601083115, 0.0170911543, 8.81818182, 0.00243374985, 0.0726834836, 0.0, "abc186b6bae363fc"], + "lucide/book-heart": [0.100862592, 0.00843224846, 4.52459016, 0.00283073517, 0.0991470616, 0.0, "af058acb27238120"], + "lucide/bug": [0.117854372, 0.0191539736, 6.54054054, 0.0035280881, 0.107755154, 0.0, "d72fb69dc531d508"], + "lucide/cat": [0.0969852209, 0.011756731, 4.90140845, 0.00302169123, 0.0868055424, 0.0, "fc3dd49773673bd2"], + "lucide/chess-king": [0.095665805, 0.0150878539, 3.65, 0.00275252457, 0.124990226, 0.0, "25f10c692dc4366c"], + "lucide/circle-arrow-right": [0.058108829, 0.00792510628, 9.55555556, 0.00276325992, 0.0317054503, 0.0, "b796596a206c2220"], + "lucide/closed-caption": [0.103919454, 0.00949093823, 13.6, 0.0026346324, 0.110440946, 0.0, "fd8943742e97f3c9"], + "lucide/cooking-pot": [0.0868807584, 0.0106803553, 5.86363636, 0.00246227928, 0.0987238534, 0.0, "37922cd1a6af2fb6"], + "lucide/diff": [0.0673651844, 0.0106961603, 20.6666667, 0.00136615196, 0.167804784, 0.0, "9b0e6bdad3e69ccc"], + "lucide/equal": [0.0595721863, 0.00684352562, 9.0, 0.00099639711, 0.227304337, 0.0, "56f2a1fd95b2bfab"], + "lucide/file-digit": [0.0929191113, 0.014318008, 5.66101695, 0.00253828429, 0.097984446, 0.0, "de4adebb05b1e356"], + "lucide/focus": [0.0888392776, 0.0153361983, 6.72340426, 0.00228676479, 0.115455048, 0.0, "62ac2a4573c4c436"], + "lucide/folder-open": [0.10405758, 0.00779712448, 3.7027027, 0.00251904409, 0.111133687, 0.0, "bea6fce6772234f7"], + "lucide/git-compare": [0.0855354667, 0.0122031077, 5.85714286, 0.00224384805, 0.106890145, 0.0, "74e48bbe9244a7b0"], + "lucide/hard-drive-download": [0.0816313028, 0.0110163795, 11.75, 0.00237556361, 0.106714625, 0.0, "cbd578d8f693260b"], + "lucide/ice-cream-cone": [0.0460486785, 0.0122334402, 5.29411765, 0.00203051465, 0.0546058272, 0.0, "13c13e922fa0ad20"], + "lucide/iteration-ccw": [0.0690391883, 0.0085263427, 10.1538462, 0.00217497535, 0.0848080282, 0.0, "59a9d1c2dd9fe86c"], + "lucide/list-checks": [0.0549888834, 0.012531914, 14.8571429, 0.00178098038, 0.0875857536, 0.0, "4bd852a3c677315d"], + "lucide/message-circle-dashed-check": [0.0789596885, 0.0183734574, 7.375, 0.00301999995, 0.0847098478, 0.0, "60dad9840ebab949"], + "lucide/messages-square": [0.116088748, 0.00931905235, 3.5443038, 0.00258801482, 0.126278558, 0.0, "f9e40951e918592d"], + "lucide/navigation-2-off": [0.0337358266, 0.0106228942, 11.5, 0.00231860299, 0.0322341516, 0.0, "7395529a7c8ec274"], + "lucide/omega": [0.0724496692, 0.00899511308, 3.11627907, 0.0021280637, 0.0970074814, 0.0, "6a1407dc02a8e91f"], + "lucide/panel-right": [0.156222254, 0.00639849851, 18.0, 0.00274328445, 0.162818802, 0.0, "050ef3d2d9701fcd"], + "lucide/pen-line": [0.0509784929, 0.00634803282, 4.0, 0.00252671563, 0.0572442014, 0.0, "7b1ef0f334cc7b55"], + "lucide/phone-forwarded": [0.128993139, 0.0103770839, 3.61363636, 0.00366088212, 0.120170941, 0.0, "5be9051e94d0895d"], + "lucide/rectangle-goggles": [0.10015136, 0.00712921903, 3.21311475, 0.00202879915, 0.166474426, 0.0, "13c9d8e4dc33fcf1"], + "lucide/save-pen": [0.122067392, 0.0127443732, 3.61702128, 0.00331014674, 0.11023424, 0.0, "c2c3673f21cb5210"], + "lucide/shapes": [0.0548335165, 0.0127428276, 5.05882353, 0.00237406837, 0.0836100563, 0.0, "b5777a7ff5416ea0"], + "lucide/shopping-cart-plus": [0.0852730125, 0.0165111971, 6.55813953, 0.00278098043, 0.0804656413, 0.0, "0bfe3f556de4f694"], + "lucide/sparkle": [0.0673239753, 0.0107217231, 2.97142857, 0.00229007355, 0.0682871396, 0.0, "6e989b050ed489ac"], + "lucide/square-minus": [0.140187606, 0.00588972505, 18.5, 0.0026412257, 0.169187392, 0.0, "c8f444da575aa992"], + "lucide/swiss-franc": [0.0490796268, 0.0112276262, 15.5, 0.00118732837, 0.119698813, 0.0, "9f6d9e326831da36"], + "lucide/ticket-minus": [0.0910086259, 0.010766477, 5.33333333, 0.00253036758, 0.107399705, 0.0, "4d8eb9f5f187e8b3"], + "lucide/undo": [0.0550462753, 0.00918585515, 5.4, 0.00141017151, 0.123528756, 0.0, "33a68b6d22685129"], + "lucide/vegan": [0.109197594, 0.0100584475, 9.71428571, 0.00375852943, 0.0791350944, 0.0, "69c14056787ca9aa"], + "material-icons/12mp": [0.133085936, 0.0170394792, 1.85, 0.00299419113, 0.136100996, 0.0, "23c2054c66869b1d"], + "material-icons/admin_panel_settings": [0.0509458445, 0.0108844138, 1.16393443, 0.00250122533, 0.0510894571, 0.0, "66d55107a186298b"], + "material-icons/arrow_drop_down": [0.0127086993, 0.00707987718, 5.0, 0.000420759781, 0.127321467, 0.0, "9c19378e4562a53e"], + "material-icons/bento": [0.117470399, 0.0160289498, 2.3375, 0.00222112751, 0.170967715, 0.0, "cdeb7612b1aa59c4"], + "material-icons/border_left": [0.0986687392, 0.0338667365, 2.42647059, 0.00212693634, 0.123518354, 0.0, "670b7bdcd2feefa0"], + "material-icons/call": [0.0513100028, 0.0108776137, 1.48623853, 0.00166063732, 0.088638948, 0.0, "3a3a0bf21ee6694f"], + "material-icons/chair": [0.110372044, 0.0118247429, 1.70731707, 0.00255803927, 0.122391171, 0.0, "a028d9bb83c28b9f"], + "material-icons/closed_caption": [0.0782116652, 0.0158338756, 1.68115942, 0.00205294113, 0.101920277, 0.0, "3c8647b3515ae12b"], + "material-icons/crop_landscape": [0.0818725079, 0.00756959031, 2.75, 0.00144264719, 0.15348432, 0.0, "19c226087b8cb64f"], + "material-icons/dining": [0.176575348, 0.011279524, 1.73611111, 0.00337257353, 0.182716008, 0.0, "36f91725ad46f60b"], + "material-icons/double_arrow": [0.0316264443, 0.0101768773, 4.2, 0.00143174035, 0.0697993335, 0.0, "0fa9963752247c53"], + "material-icons/dynamic_feed": [0.0918872207, 0.0110635327, 2.0, 0.00192671572, 0.14216405, 0.0, "b0f187c3f2270fe8"], + "material-icons/expand_circle_down": [0.0128126331, 0.00688464164, 0.433333333, 0.0023643137, 0.0101390252, 0.0, "b7fe9e8e724e4315"], + "material-icons/flight": [0.035644494, 0.0125410743, 2.40909091, 0.00125757349, 0.0910144754, 0.0, "669ce62ded1d9a9e"], + "material-icons/free_breakfast": [0.0781790018, 0.0102653935, 2.67605634, 0.00179534312, 0.120778689, 0.0, "dcf491ce8bed0d83"], + "material-icons/group_remove": [0.065900892, 0.0135166186, 1.80597015, 0.00240940508, 0.0798179973, 0.0, "75041591feb3a6ca"], + "material-icons/headset": [0.0615924597, 0.0099493747, 1.58139535, 0.0019355393, 0.0879628034, 0.0, "3f96979141522bb6"], + "material-icons/houseboat": [0.0793770254, 0.0157063331, 2.21052632, 0.00240544113, 0.0925110714, 0.0, "5b4bb1fecb5482fe"], + "material-icons/javascript": [0.0302472785, 0.0204945702, 1.64583333, 0.000813333318, 0.0776526149, 0.0, "fa4bd5f7be4b3621"], + "material-icons/laptop": [0.0888298601, 0.0119961536, 4.70833333, 0.0018272968, 0.154310013, 0.0, "71c8a2af8ad38326"], + "material-icons/lyrics": [0.107969575, 0.0200521042, 2.46728972, 0.00247493037, 0.122406395, 0.0, "3c4ad2c983c63c21"], + "material-icons/miscellaneous_services": [0.0617449656, 0.0221428769, 0.856321839, 0.00207566167, 0.0724631476, 0.0, "cf4066a37be3cf0e"], + "material-icons/music_note": [0.0433795378, 0.0115748819, 1.30188679, 0.00105203432, 0.0803892752, 0.0, "ebc2feff4daddf64"], + "material-icons/no_food": [0.0951038674, 0.0139646961, 2.36585366, 0.00283987727, 0.0931673323, 0.0, "b8d2d3e86447b0e1"], + "material-icons/notifications_paused": [0.0891904235, 0.0171463487, 2.19565217, 0.00215764716, 0.128408953, 0.0, "6e5d25c971399fd7"], + "material-icons/perm_media": [0.114996888, 0.0101146278, 3.4, 0.00303290854, 0.112152423, 0.0, "32a7b4abdebb1b77"], + "material-icons/phone_iphone": [0.074181363, 0.00762289124, 1.30882353, 0.00166345597, 0.110771117, 0.0, "c28f6571e82ef6e4"], + "material-icons/polyline": [0.0634722635, 0.0275113905, 2.62068966, 0.00142519607, 0.132671516, 0.0, "7d0d84cfbeca4532"], + "material-icons/qr_code": [0.0999738276, 0.0267366514, 2.64583333, 0.00228098035, 0.117138555, 0.0, "d88344e0f8bf974c"], + "material-icons/report": [0.0536955148, 0.00833109274, 1.97560976, 0.00198394619, 0.123059486, 0.0, "491d976c7589258f"], + "material-icons/rule_folder": [0.0695536286, 0.0128867076, 2.02380952, 0.00241512246, 0.0844517004, 0.0, "af410fb6016bc622"], + "material-icons/sd_card_alert": [0.0869260505, 0.00897231297, 2.96, 0.00190068642, 0.148772373, 0.0, "0c13a59c5b4f9a9f"], + "material-icons/settings_overscan": [0.0445632748, 0.0122194899, 2.15625, 0.00199924037, 0.0592330757, 0.0, "dbd03063b2c79714"], + "material-icons/sms_failed": [0.119500659, 0.0115693469, 3.04, 0.00215519615, 0.182885749, 0.0, "e709521d75495217"], + "material-icons/storage": [0.146717086, 0.017153364, 3.375, 0.00226002443, 0.247821227, 0.0, "07a3545f2c0a5b77"], + "material-icons/table_rows": [0.109449454, 0.0107552198, 2.64285714, 0.00202357862, 0.169129508, 0.0, "9b61d0522215c01d"], + "material-icons/transfer_within_a_station": [0.0519387424, 0.0210197014, 1.56481481, 0.00224142149, 0.0641185033, 0.0, "9911d9ff02348035"], + "material-icons/two_wheeler": [0.0481306314, 0.0275592691, 2.4057971, 0.0021676477, 0.0613371643, 0.0, "b336939844315c47"], + "material-icons/video_camera_back": [0.0873040184, 0.0128736577, 2.82758621, 0.0022057842, 0.135893628, 0.0, "085d847ce2e6e022"], + "material-icons/view_week": [0.118390001, 0.012116551, 2.64285714, 0.00227946066, 0.169544983, 0.0, "93b8323d8e3be564"], + "noto-emoji/emoji_u0030": [0.0955837741, 0.00695468614, 0.907407407, 0.00118306372, 1.0450284, 0.154214954, "40d8d2b962920da2"], + "noto-emoji/emoji_u1f36a": [0.493850112, 0.0783625291, 1.84455959, 0.00851481128, 0.794003844, 0.177618573, "3bca579e5afe327d"], + "noto-emoji/emoji_u1f39e": [0.630541384, 0.0294104338, 0.895348837, 0.00681798998, 1.41812613, 0.588153662, "06c7f390475541e2"], + "noto-emoji/emoji_u1f3c2_1f3fd": [0.611426353, 0.108481681, 2.20417288, 0.0100051137, 2.94614687, 1.73700204, "e289c0346162b1ce"], + "noto-emoji/emoji_u1f3c4_1f3fe": [0.514652133, 0.114461111, 1.6453125, 0.010874656, 0.398784419, 0.129747254, "6c258781141e4242"], + "noto-emoji/emoji_u1f3cb_200d_2642": [0.411653191, 0.147759138, 1.2235023, 0.007367271, 2.30816457, 1.23280833, "c7cbad16ebbf448a"], + "noto-emoji/emoji_u1f41b": [0.268448621, 0.18595551, 6.28621291, 0.00682615163, 0.152422325, 0.000481261287, "3b76db6447c81608"], + "noto-emoji/emoji_u1f44d_1f3fc": [0.26888147, 0.0504915436, 2.40720222, 0.00402401108, 0.111412445, 0.000292933687, "9e1aab71c913ff00"], + "noto-emoji/emoji_u1f468_1f3fb_200d_2764_200d_1f468_1f3fd": [0.4607943, 0.0878769148, 1.76630435, 0.00726535963, 0.954276815, 0.308147606, "6fd73fbdd33fff5c"], + "noto-emoji/emoji_u1f468_1f3ff_200d_1f393": [0.865518808, 0.0526083347, 1.04914005, 0.00827746652, 1.69407071, 0.663634684, "e00466a0b0a1b9c1"], + "noto-emoji/emoji_u1f469_1f3fb_200d_1f52c": [1.03115654, 0.103285982, 2.75231054, 0.0115142968, 1.0414513, 0.471932079, "f79ed18656194fcc"], + "noto-emoji/emoji_u1f469_1f3fc_200d_1f91d_200d_1f468_1f3fb": [0.476812303, 0.121819933, 1.22622478, 0.00827549025, 2.17153494, 1.06539358, "c893a39b71172154"], + "noto-emoji/emoji_u1f469_1f3fe_200d_1faef_200d_1f469_1f3fd": [0.507534623, 0.173371567, 1.73655424, 0.00860729534, 2.15569856, 1.2255544, "91455fe9a64bb637"], + "noto-emoji/emoji_u1f469_200d_1f469_200d_1f466_200d_1f466": [0.124367781, 0.024576179, 1.26490066, 0.00482556364, 0.0869967771, 0.000622228604, "ec2319587fa2faf8"], + "noto-emoji/emoji_u1f46c_1f3fd": [0.416767091, 0.0880448164, 0.772200772, 0.00718284305, 2.84565486, 1.74064702, "a7a29376f41a17d6"], + "noto-emoji/emoji_u1f470_1f3fb_200d_2640": [0.923968971, 0.0789767225, 3.03196347, 0.0117574912, 2.45732939, 1.32165277, "cae52a79ed822278"], + "noto-emoji/emoji_u1f482_1f3ff_200d_2640": [0.747311711, 0.125788242, 2.48991935, 0.00758562842, 7.69772132, 7.09272582, "46acf88da31b11e6"], + "noto-emoji/emoji_u1f4d8": [0.268364519, 0.0138883769, 2.21904762, 0.00664638076, 1.72385678, 1.45872706, "12381b10061cb436"], + "noto-emoji/emoji_u1f520": [0.410775423, 0.0541462222, 2.78082192, 0.00420496706, 0.0736771716, 0.000259071906, "67ae40e7bfec7f70"], + "noto-emoji/emoji_u1f56f": [0.49470979, 0.0951401754, 2.5532646, 0.00427774433, 2.39293425, 0.900327862, "1624fb75cef2c610"], + "noto-emoji/emoji_u1f5a8": [0.354911327, 0.048366332, 3.22325581, 0.00530957477, 2.49376962, 1.72408173, "19be285e6e0ec9c0"], + "noto-emoji/emoji_u1f62d": [0.470017076, 0.0359274143, 1.68768769, 0.0111415936, 1.2488879, 0.265451739, "1fe71e8c3cab9751"], + "noto-emoji/emoji_u1f64b_1f3fe_200d_2640": [0.52118355, 0.0299574709, 1.04761905, 0.00689063733, 1.58127063, 0.836814088, "fd0534c3634aed24"], + "noto-emoji/emoji_u1f6c0_1f3ff": [0.447382927, 0.192586394, 3.30649799, 0.00617070217, 0.460377135, 0.0539377607, "0d70326286cbc45f"], + "noto-emoji/emoji_u1f90d": [0.016582977, 0.0174738924, 2.11363636, 0.00105546566, 0.131101032, 0.0, "90f231b030d872b8"], + "noto-emoji/emoji_u1f91c_1f3fe": [0.238940284, 0.0338473739, 2.55555556, 0.00335254078, 0.106037724, 0.000309870615, "ae781dcf46bfba8e"], + "noto-emoji/emoji_u1f926_1f3ff": [0.939405322, 0.0960198998, 2.27370031, 0.00832922384, 2.86731466, 1.72428569, "56825658c80c3f2f"], + "noto-emoji/emoji_u1f932": [0.391543537, 0.0490943824, 1.99465241, 0.00711116847, 0.124014967, 4.46981318e-05, "ec2aec7156ba8d1c"], + "noto-emoji/emoji_u1f93c_1f3fe_200d_2640": [0.504599333, 0.134289318, 1.41979835, 0.0088616414, 1.89090764, 0.944853844, "820aeaaf5935ee25"], + "noto-emoji/emoji_u1f987": [0.493590444, 0.0961720512, 2.77241379, 0.00631505717, 2.02406556, 1.03545497, "504732ae3800975e"], + "noto-emoji/emoji_u1f9be": [0.443319738, 0.152474262, 4.20359281, 0.00557910139, 0.677886102, 0.17841741, "950b374c46faa9fc"], + "noto-emoji/emoji_u1f9ce_1f3fd_200d_2642": [0.154894769, 0.0442499789, 0.882352941, 0.00326960743, 0.448694182, 0.0602938325, "5d561c865940aa3c"], + "noto-emoji/emoji_u1f9cf_1f3fc": [0.464605302, 0.0559106305, 1.96535797, 0.00660019601, 1.42292657, 0.667117237, "f4a09fe7e002dda0"], + "noto-emoji/emoji_u1f9d1_1f3fc_200d_1f37c": [0.36782524, 0.221479561, 3.11286682, 0.00769275287, 0.58973099, 0.298405782, "a84a5a236b3302eb"], + "noto-emoji/emoji_u1f9d1_1f3fd_200d_1f91d_200d_1f9d1_1f3ff": [0.590110481, 0.189486152, 1.85523114, 0.00842374936, 1.14902131, 0.448207705, "0ea00c49729df7c4"], + "noto-emoji/emoji_u1f9d1_1f3fe_200d_1f9bc_200d_27a1": [0.379258066, 0.18989007, 2.53696742, 0.00659958273, 1.50769536, 0.887786975, "2681406739f2885d"], + "noto-emoji/emoji_u1f9d6_1f3fe_200d_2642": [0.749010205, 0.104211976, 3.02412281, 0.00909951795, 1.38669766, 1.00059038, "568d90bd90d7fe98"], + "noto-emoji/emoji_u1f9dd_1f3fd_200d_2640": [0.901975811, 0.165057151, 3.53722628, 0.0124869766, 2.27787896, 1.29760781, "f2927a6d70bd3993"], + "noto-emoji/emoji_u1f9ed": [0.342110634, 0.131598731, 5.94092827, 0.00954152737, 0.301430649, 0.118106811, "6eba7b5924337489"], + "noto-emoji/emoji_u1faa5": [0.139014706, 0.0854021575, 1.86805556, 0.00463439524, 1.14085124, 0.566608035, "26327568442ab087"], + "noto-emoji/emoji_u1faf1_1f3fc_200d_1faf2_1f3ff": [0.330682755, 0.0782085544, 1.91347754, 0.00449845567, 0.142677798, 0.00144087001, "763bd89bc7f190b9"], + "noto-emoji/emoji_u26bd": [0.129089564, 0.0477838344, 3.3030303, 0.00442035124, 0.11356238, 4.45517378e-05, "f3377be94c57fa1a"], + "noto-emoji/emoji_u2b05": [0.382265002, 0.0419788773, 4.57692308, 0.00430196058, 6.52534176, 5.93748209, "fcc7a484980cec65"], + "openmoji/1F195": [0.114184499, 0.0169124547, 12.6470588, 0.00641008094, 0.0482808207, 0.0, "f5eb7df173094fa4"], + "openmoji/1F1FF-1F1F2": [0.150070131, 0.0133171531, 4.375, 0.00325928931, 0.0898695809, 0.0, "efc9c0d4562d58f0"], + "openmoji/1F361": [0.112481095, 0.028381996, 3.4, 0.00308467308, 0.092348779, 0.0, "a1bf29aec8b1ecb3"], + "openmoji/1F38A": [0.228254139, 0.0630650106, 4.48958333, 0.00498714019, 0.219920678, 0.111471245, "602c48798206c5f2"], + "openmoji/1F3A9": [0.117342606, 0.0120667455, 2.11940299, 0.00291346409, 0.0649993611, 0.0, "4624ff53130f6948"], + "openmoji/1F3C3-1F3FF-200D-2642-FE0F": [0.0782744065, 0.0227377174, 2.65284974, 0.00231580064, 0.0714599198, 0.0, "36bb370a474e9573"], + "openmoji/1F3CC-FE0F-200D-2640-FE0F": [0.212959155, 0.0315497766, 2.05859375, 0.00402352121, 0.106973624, 0.0, "3d7316252b317b1e"], + "openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F": [0.176222757, 0.00860234609, 8.0, 0.0031068055, 0.101829281, 0.0, "96e543869c71f9dc"], + "openmoji/1F442-1F3FF": [0.14181751, 0.0265194494, 5.71929825, 0.00272464845, 0.109542414, 0.0, "4bdeb9a79ecf69ee"], + "openmoji/1F468-1F3FC-200D-1F3ED": [0.745298982, 0.118094739, 1.51317829, 0.00932290033, 0.408277044, 0.21476836, "baa4082afed33219"], + "openmoji/1F468-1F3FF-200D-1F9B0": [0.152378306, 0.026173093, 2.01538462, 0.0035985047, 0.0954080501, 0.0, "20e60ea050d27d03"], + "openmoji/1F468-200D-1F9B1": [0.257564396, 0.0952463569, 4.58715596, 0.00533659291, 0.141747937, 0.000107973748, "683931fbfe674548"], + "openmoji/1F469-1F3FC-200D-2764-FE0F-200D-1F48B-200D-1F469-1F3FC": [0.340381354, 0.0710386632, 4.75714286, 0.00742430519, 0.118310478, 0.0, "0ae7d09af3c4375a"], + "openmoji/1F469-1F3FF-200D-1F9B2": [0.149954066, 0.0296839163, 3.01315789, 0.0024426633, 0.0867326001, 3.16889295e-05, "30cfd6cc87b3b89e"], + "openmoji/1F481-1F3FB-200D-2642-FE0F": [0.229892418, 0.0377838037, 3.04444444, 0.00483214809, 0.099672017, 3.74706831e-05, "76a283832c3e9d61"], + "openmoji/1F49B": [0.160190552, 0.0851020064, 9.95454545, 0.00298851309, 0.115006584, 0.000152883462, "cae2f3fba1efef72"], + "openmoji/1F517": [0.179347739, 0.0277794858, 3.0979021, 0.00307431351, 0.10531745, 2.19961257e-05, "5e77aeca1d31895a"], + "openmoji/1F646-1F3FC": [0.342184305, 0.0702036541, 2.91266376, 0.00635074358, 0.0951177006, 0.000163152145, "edca006438f581f4"], + "openmoji/1F6B4-1F3FD-200D-2640-FE0F": [0.19841592, 0.0235782732, 2.5625, 0.00438786717, 0.112193533, 4.05396688e-05, "126af5abb3683f54"], + "openmoji/1F6E0": [0.178205937, 0.0766452458, 6.3125, 0.00468248362, 0.0832343638, 0.000191503451, "9700dad3570f2577"], + "openmoji/1F938-1F3FB": [0.167150438, 0.0242405645, 3.0, 0.00328191975, 0.126771603, 0.000402364375, "dcdca06f97143f52"], + "openmoji/1F93E-1F3FE": [0.140004247, 0.0451839411, 3.53777778, 0.00372025324, 0.113068615, 0.00021827918, "3d6c5564c8db437b"], + "openmoji/1F9B3": [0.163895115, 0.043329531, 10.2727273, 0.00237119268, 0.118340121, 9.87814033e-05, "b448ac66caa67a33"], + "openmoji/1F9D1": [0.209770605, 0.0539114287, 4.00917431, 0.00478096399, 0.112398309, 6.88152909e-05, "df80eb8902bb8570"], + "openmoji/1F9D1-1F3FC-200D-1FA70": [0.153257027, 0.0351506415, 3.32307692, 0.00344669959, 0.103541633, 0.0, "05ac7ad40276c421"], + "openmoji/1F9D1-1F3FD-200D-1F527": [0.207221076, 0.0593000235, 2.1902834, 0.00583259808, 0.0989087736, 0.0, "f23c9127f88668fe"], + "openmoji/1F9D1-200D-1F393": [0.264018506, 0.0622034875, 0.776859504, 0.00489844754, 0.187493174, 0.074586546, "1da2a6a0995521ff"], + "openmoji/1F9D6-1F3FD-200D-2642-FE0F": [0.189378873, 0.0385424285, 2.31635389, 0.00426066993, 0.100046282, 1.99454311e-05, "1095dab84448120c"], + "openmoji/1FA8B": [0.277720749, 0.125102503, 1.84935897, 0.00528741861, 0.18811274, 0.00382384979, "f4aaaf5101e3ceec"], + "openmoji/1FAC4-1F3FD": [0.261633933, 0.0795590249, 2.47266881, 0.00513426447, 0.258116113, 0.121112045, "bd30c639c2d694d6"], + "openmoji/25FC": [0.00917839259, 0.00561218277, 2.58333333, 0.00125122559, 0.0156409948, 0.0, "e68fc20e48f1dfd9"], + "openmoji/2705": [0.17144753, 0.0284308144, 3.81578947, 0.00345710781, 0.0777520188, 4.63085282e-05, "7f2e007c7d7f3b99"], + "openmoji/E056": [0.346384227, 0.078870611, 3.36036036, 0.00734274508, 0.102945754, 0.000113736504, "fd867005341c0c49"], + "openmoji/E1D1": [0.0833389536, 0.0176329756, 1.28323699, 0.0027258005, 0.109306775, 0.00388526267, "be58096943e3eb76"], + "openmoji/E30B": [0.224875033, 0.025598018, 1.8974359, 0.00571272057, 0.149357647, 0.0611175533, "adb3ea8e9b221459"], + "simple-icons/alchemy": [0.0323041789, 0.00995128145, 0.920754717, 0.00157958735, 0.0218237999, 0.0, "1955a93445c089be"], + "simple-icons/appletv": [0.048213765, 0.0228268362, 2.40935673, 0.00210128515, 0.0526724592, 0.0, "8cd1b5f5189e124c"], + "simple-icons/atlassian": [0.0530532151, 0.0129174176, 3.44615385, 0.00215724367, 0.0914503676, 0.0, "3f6fb69f5d0ff376"], + "simple-icons/autocad": [0.0347518511, 0.00992469066, 2.77419355, 0.00187531917, 0.0371458665, 0.0, "f924c744e38d34de"], + "simple-icons/bandrautomation": [0.0720250458, 0.0186334227, 1.81818182, 0.00384703069, 0.0787827628, 0.000517173498, "b3a27dc050577fee"], + "simple-icons/bim": [0.0479623266, 0.0205732472, 2.4822695, 0.00303094578, 0.0401860237, 9.96553594e-05, "a12d5791168ba1ad"], + "simple-icons/boosty": [0.0544629842, 0.0120227141, 5.27272727, 0.00232534087, 0.0647951413, 0.0, "750a1e4ea019e282"], + "simple-icons/changedetection": [0.103335284, 0.0163907908, 1.11702128, 0.00461557508, 0.0552812379, 0.0, "4bb85dad5b687144"], + "simple-icons/cocos": [0.176916838, 0.0310445334, 0.798501873, 0.00640609348, 0.0859074532, 0.0, "c35d76b7d881ef88"], + "simple-icons/contentstack": [0.0777403489, 0.018542352, 1.36764706, 0.00421185978, 0.0560197395, 0.0, "6b1cc902f1352425"], + "simple-icons/debridlink": [0.0468046814, 0.0137784193, 2.23030303, 0.00162539457, 0.0558966413, 0.0, "2b89217a9595c75f"], + "simple-icons/elixir": [0.0458581261, 0.00950558563, 3.09433962, 0.0013331495, 0.0973286892, 0.0, "2f875a75829af86b"], + "simple-icons/fampay": [0.0606591254, 0.0138753882, 2.34224599, 0.00235024211, 0.0619134446, 0.0, "d3b2358ce4cee123"], + "simple-icons/fluxer": [0.0842201263, 0.017107906, 1.96491228, 0.00314538414, 0.0816636407, 0.0, "574131cfbaacfd0b"], + "simple-icons/googlechrome": [0.0755012408, 0.014791626, 4.49450549, 0.00317031448, 0.0585682473, 0.0, "3c4f0059af182c70"], + "simple-icons/h2database": [0.107266061, 0.0151095975, 1.86387435, 0.00387457316, 0.056208196, 0.0, "9adb1a9634896beb"], + "simple-icons/hitachi": [0.0406416878, 0.0390771569, 1.08163265, 0.0014356965, 0.027757637, 0.0, "375cb7659e5297ef"], + "simple-icons/infinityfree": [0.0786835626, 0.0382515253, 1.62227603, 0.00300742593, 0.0678999129, 0.000120518127, "2452888027921583"], + "simple-icons/jdoodle": [0.101044752, 0.0189020777, 1.13065327, 0.00280884653, 0.0657180086, 0.0, "500f8d3569347cee"], + "simple-icons/kleinanzeigen": [0.0898813382, 0.0142757134, 2.74666667, 0.0033103684, 0.059814814, 0.0, "e1a171bae4a6026d"], + "simple-icons/leetcode": [0.053386353, 0.0119448089, 2.29885057, 0.00238980632, 0.0535631901, 0.0, "c3f9dad72f0df406"], + "simple-icons/looker": [0.0722717792, 0.0208432405, 2.05524862, 0.00258136145, 0.0710774448, 0.0, "b9ee761f5e97e3e7"], + "simple-icons/mamp": [0.0724146888, 0.018440245, 4.43333333, 0.00248469017, 0.0809028315, 0.0, "8af0ce14db86d345"], + "simple-icons/microeditor": [0.0802110285, 0.0182565865, 0.865306122, 0.00289419689, 0.0759981646, 0.0, "72e8ae569fb51670"], + "simple-icons/mysql": [0.119989097, 0.0351998513, 0.844282238, 0.00351303699, 0.0803849904, 0.0, "5749cb176c7b27be"], + "simple-icons/notion": [0.0606551021, 0.0123855682, 2.39325843, 0.00380639755, 0.0299747215, 0.0, "5b78806999f6e35e"], + "simple-icons/osano": [0.0439631827, 0.0142982328, 8.25, 0.00216484233, 0.0582958402, 0.0, "d486b9e65f7de0b4"], + "simple-icons/phpstorm": [0.0392084308, 0.0171886909, 1.36111111, 0.00183286774, 0.0561692358, 0.0, "4d7d9243b44f0ce1"], + "simple-icons/playerfm": [0.113627791, 0.0158766454, 1.33888889, 0.00393031584, 0.07913155, 0.0, "af32a7708418ac8a"], + "simple-icons/premierleague": [0.12844263, 0.041626806, 2.76303318, 0.00371681713, 0.0803612815, 0.0, "5d7646d8240d1e3f"], + "simple-icons/pronounsdotpage": [0.0559303761, 0.0143998071, 2.90697674, 0.00256912643, 0.0570035775, 0.0, "7b6fa0ee37e62d66"], + "simple-icons/purescript": [0.0393888988, 0.0159598053, 3.77777778, 0.00200430467, 0.0713363665, 0.0, "892e0fa53258f3ef"], + "simple-icons/redsys": [0.0606819764, 0.0171708751, 2.5915493, 0.00208891602, 0.0879744785, 0.0, "3df253f22d00a012"], + "simple-icons/sagemath": [0.106724553, 0.0370478324, 1.27298444, 0.00647124136, 0.0372268627, 0.0, "b0a76010a8c55f2b"], + "simple-icons/slackware": [0.0952856094, 0.0100220324, 1.21327014, 0.00318128406, 0.0842165209, 0.0, "583964c7f6e893a9"], + "simple-icons/sparkar": [0.0194915086, 0.010760686, 5.16666667, 0.00195532339, 0.0198466774, 0.0, "92c6c20eb113c3c8"], + "simple-icons/stmicroelectronics": [0.0648256615, 0.0121122832, 1.83116883, 0.00174507569, 0.0384634988, 0.0, "f36450162131ea00"], + "simple-icons/ubiquiti": [0.0409612954, 0.0134584046, 1.23893805, 0.00187430542, 0.0458960724, 0.0, "387e588b33376664"], + "simple-icons/visa": [0.0512364954, 0.0207865341, 2.64705882, 0.00209142454, 0.0597387992, 0.0, "467552baa7fc220e"], + "simple-icons/wxt": [0.0883568525, 0.0208288574, 2.67010309, 0.00312663568, 0.0725664457, 0.0, "e83a7cde0859945a"], + "synthetic/gradient_linear": [0.209117934, 0.00440660037, 4.66666667, 0.00320711592, 0.535462699, 0.108039332, "6d73f4b6037edde1"], + "synthetic/mosaic_grid6": [0.311248183, 0.0868793001, 10.0630631, 0.00506695639, 0.387880511, 0.0384075477, "e7417be6cfb66076"], + "synthetic/prim_ellipse": [0.0184495263, 0.00606455425, 6.0, 0.00135403592, 0.0734216219, 0.0, "d2b89a9509bea63f"], + "synthetic/prim_star5": [0.0967477858, 0.00917288447, 3.5, 0.00243733684, 0.0373914951, 0.0, "b2f8f141d3de6122"], + "synthetic/symmetry_rot3": [0.0548891537, 0.0193646865, 5.72222222, 0.00226636417, 0.0910148838, 5.70984215e-05, "006f35062bb18b69"], + "twemoji/1f17e": [0.367678255, 0.0248630595, 3.85, 0.00341189373, 0.0991968649, 0.0, "b03c18b6acc29a42"], + "twemoji/1f1f8": [0.148831964, 0.0245723964, 3.13461538, 0.00258799992, 0.109526336, 0.0, "6418208a4209fd12"], + "twemoji/1f1fa": [0.144460589, 0.0168751717, 2.70454545, 0.00265097199, 0.0905003141, 4.45814355e-05, "3c471a073f747ea5"], + "twemoji/1f325": [0.245495781, 0.0186502131, 2.57923497, 0.00290593738, 0.102986378, 3.21029855e-05, "98859219bf6a1732"], + "twemoji/1f369": [0.277937829, 0.031464391, 1.68164794, 0.00649027759, 0.106074217, 1.97384102e-05, "1a307d814484b3ee"], + "twemoji/1f3ca-1f3fe-200d-2640-fe0f": [0.224051058, 0.0383007994, 3.47169811, 0.00419453438, 0.123081703, 0.0, "2564f62ca82ffb8d"], + "twemoji/1f3cc-1f3fb-200d-2640-fe0f": [0.200602278, 0.0770662456, 3.93877551, 0.00365195167, 0.147705501, 0.00233338445, "5a8241806e05c3be"], + "twemoji/1f42b": [0.270778924, 0.033727004, 4.35606061, 0.0038654895, 0.11556632, 0.0, "0aab3ac7b8e71b31"], + "twemoji/1f468-1f3fb-200d-1f91d-200d-1f468-1f3fd": [0.399825513, 0.137905681, 3.63829787, 0.00664377026, 0.278375511, 0.08571588, "1470f45caa96243d"], + "twemoji/1f468-1f3fc-200d-1f9b0": [0.27850756, 0.151456733, 6.36363636, 0.00372477109, 0.164202939, 0.00621246803, "b552f5c9fd4a08be"], + "twemoji/1f468-1f3fe-200d-2764-fe0f-200d-1f48b-200d-1f468-1f3ff": [0.381992817, 0.0481017576, 2.04347826, 0.00386888813, 0.117299782, 0.00131151189, "b9a1209cf7b9b6fb"], + "twemoji/1f469-1f3fb-200d-1f37c": [0.378795296, 0.101953054, 2.42666667, 0.00567013025, 0.284911528, 0.0620647753, "356f2813ee616842"], + "twemoji/1f469-1f3fc-200d-2764-fe0f-200d-1f468-1f3fc": [0.296293676, 0.131690174, 7.07065217, 0.0055978843, 0.144309949, 0.000950072504, "0cd7187652c2e34a"], + "twemoji/1f469-1f3fe": [0.400315225, 0.0200120796, 2.01515152, 0.0034853674, 0.0952427323, 0.0, "dafc5746d965a139"], + "twemoji/1f469-1f3ff-200d-1f91d-200d-1f468-1f3fc": [0.389351457, 0.0980537882, 3.73383621, 0.00731339538, 0.346789528, 0.115027921, "04f4d495237f33fd"], + "twemoji/1f469-200d-1f467-200d-1f467": [0.152343869, 0.0267305268, 1.03125, 0.00350016449, 0.102659921, 0.0, "21e8e4be082e9911"], + "twemoji/1f470-1f3fc-200d-2640-fe0f": [0.337491423, 0.0686942825, 5.41621622, 0.00542594912, 0.154513032, 6.28357187e-05, "a288864439ce38a9"], + "twemoji/1f481-1f3fc-200d-2640-fe0f": [0.216231033, 0.106250168, 6.97972973, 0.00487833843, 0.188254919, 0.0040391698, "b7c0af1dc3a33d68"], + "twemoji/1f486-1f3ff": [0.495419532, 0.134237145, 5.76639344, 0.00507146865, 0.705932864, 0.340398179, "a2e79b202cb95699"], + "twemoji/1f4e6": [0.277736902, 0.07846539, 5.99180328, 0.0037739086, 0.125482245, 0.0014262093, "3db81116d08b29e8"], + "twemoji/1f53a": [0.0460913107, 0.0052841517, 2.33333333, 0.0014846077, 0.0269135166, 0.0, "e5cc473301263b12"], + "twemoji/1f57a-1f3fb": [0.25103122, 0.0692026548, 1.12598425, 0.00382995885, 0.149085422, 0.000464309073, "1892904f298acbc3"], + "twemoji/1f635": [0.0652815178, 0.0182543787, 1.61363636, 0.00494483626, 0.10929382, 0.0, "d4a39aa782888390"], + "twemoji/1f646-1f3fb-200d-2640-fe0f": [0.419980466, 0.0254722911, 2.8757764, 0.00608450128, 0.184299722, 0.0780485049, "bf29cc0fb1a140cc"], + "twemoji/1f648": [0.214301214, 0.0391292184, 1.44932079, 0.006052237, 0.0843427161, 0.00016547771, "6971cd7d58da2e15"], + "twemoji/1f64d-1f3fd": [0.260160834, 0.0781130603, 5.7421875, 0.00373775745, 0.126022587, 0.00166229298, "31f64ac799c83d6c"], + "twemoji/1f6a3-1f3ff-200d-2642-fe0f": [0.21654278, 0.0419233582, 2.72277228, 0.00463984441, 0.106399902, 0.000464966796, "79f5bca29d263ed4"], + "twemoji/1f6d6": [0.312692344, 0.0887420057, 2.58476658, 0.00484717591, 0.452167933, 0.10656977, "7b47728f21b53b5d"], + "twemoji/1f7eb": [0.43475467, 0.0194460322, 3.75, 0.000576384249, 0.183459237, 0.0, "b2156928af3a7384"], + "twemoji/1f91c-1f3fe": [0.179795906, 0.0178689925, 2.89622642, 0.00202573719, 0.0977278807, 0.0, "371edb0d29969cd9"], + "twemoji/1f938-1f3fe": [0.185539126, 0.179759995, 1.80782918, 0.00450910954, 0.222164276, 0.00670754916, "00eb6dd2e1cd022c"], + "twemoji/1f977-1f3fb": [0.342599928, 0.0450170374, 2.62711864, 0.00375799066, 0.0853629155, 0.00153117337, "2162f1a616fa93c7"], + "twemoji/1f9a8": [0.462667048, 0.0457508396, 3.85436893, 0.00555948494, 0.110157955, 0.0020866289, "c5d3baa0d20b712d"], + "twemoji/1f9c9": [0.180749997, 0.0332923904, 2.7266436, 0.00330178114, 0.111819645, 0.000190201812, "7305cdd62f6c161a"], + "twemoji/1f9d1-1f3fd-200d-1f9af-200d-27a1-fe0f": [0.27276805, 0.132352657, 2.795, 0.00524960132, 0.377494062, 0.183167668, "8ad715b9524819ae"], + "twemoji/1f9d1-1f3ff-200d-2764-fe0f-200d-1f9d1-1f3fb": [0.50996995, 0.0638848043, 3.85849057, 0.00483066542, 0.105986697, 0.0009684457, "04ab1f25616a5388"], + "twemoji/1f9d4-1f3fd": [0.26535517, 0.0352767587, 2.94814815, 0.00465101842, 0.114543021, 0.0, "819df618b3e1339b"], + "twemoji/1f9d8-1f3fe": [0.233248204, 0.0641474919, 2.5144357, 0.00482381228, 0.150798534, 0.00255557416, "c955b299c5a8a2ba"], + "twemoji/1f9e9": [0.132934779, 0.0132993164, 1.18333333, 0.00331634772, 0.0828090848, 0.0, "ca2d6ec20332f7be"], + "twemoji/1faa3": [0.20017606, 0.0802901674, 17.2037037, 0.00455895392, 0.125281297, 0.00115939857, "ac2eb6b6df2d7422"], + "twemoji/1fae5": [0.346506178, 0.0600176253, 5.84920635, 0.00411303714, 0.30761768, 0.0494449841, "16b5cdd34b8b1994"], + "twemoji/2196": [0.134856567, 0.0220693896, 4.28571429, 0.00204727263, 0.0828277495, 0.0, "b7b7285460a0a3fe"], + "twemoji/271d": [0.241734013, 0.0194743971, 2.59615385, 0.00160882412, 0.064088575, 0.000452745035, "6001f8748f627908"] } } } diff --git a/bench/human_stats.py b/bench/human_stats.py new file mode 100644 index 00000000..9951e2f8 --- /dev/null +++ b/bench/human_stats.py @@ -0,0 +1,487 @@ +"""How far the traces are from the artists' files in how they are *drawn*: the design +battery (`inkvec_bench/design.py`) over the screen set, per family, with the oddities, the +statistics' correlations, and a paired before/after comparison to tune a build or a flag. + + python bench/human_stats.py --exe target/release/inkvec # quality-512ssop, quality-web + python bench/human_stats.py --exe target/release/inkvec --extra-args "--editability" \\ + --base-args "" # does the flag help? + python bench/human_stats.py --exe new/inkvec --base-exe old/inkvec # a change, paired + python bench/human_stats.py --exe ... --conditions quality-512ssop --sample 0.25 --oddities 5 + python bench/human_stats.py --from-report gate/report.json --correlate # a gate run's numbers + +What it prints +-------------- +Per condition and family: each statistic's mean on the artist's files and on the traces, and +the mean **divergence** (the per-icon distance between the two; `design.STATS` says how each +is taken). Then the **oddities**: per statistic, the icons farthest from their artist. With +`--base-exe` / `--base-args`, a second arm is traced and every statistic is compared icon by +icon: the family-macro mean divergence before and after, its relative change with a paired, +family-stratified bootstrap interval (`gate_stats.compare`, as the gate does), and how many +icons moved closer to or further from the artist; the last line is the geometric mean of the +after/before ratios over the statistics, one number to tune against (below 1: closer). +`--correlate` prints the Spearman matrix of the per-icon divergences, pooled over the +conditions, with the gate's own axes when they are known (`--from-report`, or `--gate-axes`, +which scores them), and the redundancy pruning that chose `design.KEPT`. + +Tracing only: no renders, so a full condition costs the tracer's time plus about 10 ms of +statistics per icon. Traces are kept under the cache (`/traces/-//`), +keyed by the executable's bytes and the arguments, so a re-run of the same build is free; +`--fresh` retraces. + +The gate (`bench/ci_gate.py`) computes the same battery on every icon it traces and puts it in +its `--report-json` and `--artifact-dir` (`human-.json`); it is reported there, not +gated. +""" +from __future__ import annotations + +import argparse +import functools +import hashlib +import json +import math +import os +import sys +from collections import defaultdict +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "bench")) + +import gate_stats +import svgeval +from inkvec_bench import design + +DEFAULT_CONDITIONS = ("quality-512ssop", "quality-web") +#: The gate's axes that join the correlation matrix when known. +GATE_AXES = ("de00", "geom", "turning_gap", "ratio_gap") +#: Two statistics whose per-icon divergences correlate beyond this (|Spearman rho|) carry +#: one signal: the later one in `design.STATS` order is dropped (`prune`). +REDUNDANT_RHO = 0.7 + + +# --------------------------------------------------------------------------- aggregation +def finite(x) -> bool: + return x is not None and isinstance(x, (int, float)) and math.isfinite(x) + + +def family_mean(per_icon: dict, stat: str, field: str) -> dict[str, float]: + """{family: mean of `field` ("div", "trace" or "artist") of `stat`} over the icons where + it is defined, and "macro": the mean of those family means.""" + fam: dict[str, list] = defaultdict(list) + for k, h in per_icon.items(): + v = h.get(field, {}).get(stat) + if finite(v): + fam[k.split("/", 1)[0]].append(v) + out = {f: float(np.mean(v)) for f, v in sorted(fam.items())} + out["macro"] = float(np.mean(list(out.values()))) if out else float("nan") + return out + + +def document(results: dict[str, dict], stats=None) -> dict: + """The battery of a run as JSON: per condition the family and macro means of each + statistic (divergence, trace, artist) and per icon [trace value, divergence]; the + artist's values once. `results` is {condition: {family/stem: {"human": ...}}}.""" + stats = list(stats or design.KEPT) + out: dict = {"stats": stats, "version": design.VERSION, "conditions": {}, "artist": {}} + for cond, rows in results.items(): + per = {k: r["human"] for k, r in rows.items() if r.get("human")} + out["conditions"][cond] = { + "summary": {s: {f: family_mean(per, s, f) for f in ("div", "trace", "artist")} + for s in stats}, + "per_icon": {k: {s: [h["trace"].get(s), h["div"].get(s)] for s in stats} + for k, h in sorted(per.items())}, + } + for k, h in per.items(): + out["artist"].setdefault(k, {s: h["artist"].get(s) for s in stats}) + out["artist"] = dict(sorted(out["artist"].items())) + return clean(out) + + +def clean(obj): + """`obj` with every non-finite float as None, so it is strict JSON.""" + if isinstance(obj, dict): + return {k: clean(v) for k, v in obj.items()} + if isinstance(obj, (list, tuple)): + return [clean(v) for v in obj] + if isinstance(obj, float) and not math.isfinite(obj): + return None + return obj + + +SHORT = {"quality": "q", "fast": "f"} + + +def print_summary(doc: dict, file=None) -> None: + """The gate's compact console summary: each statistic's family-macro mean divergence, + one column per condition (nothing when no icon has the battery).""" + file = file or sys.stdout + conds = [c for c in doc["conditions"] if doc["conditions"][c]["per_icon"]] + if not conds: + return + heads = ["-".join([SHORT.get(c.split("-", 1)[0], c), c.split("-", 1)[-1]]) for c in conds] + print("\nhuman statistics: distance from the artist's file, family-macro mean (reported, " + "not gated; definitions in bench/inkvec_bench/design.py, detail in " + "bench/human_stats.py)", file=file) + print(f" {'statistic':18s}" + "".join(f"{h:>11s}" for h in heads), file=file) + for s in doc["stats"]: + vals = [doc["conditions"][c]["summary"][s]["div"].get("macro") for c in conds] + print(f" {s:18s}" + "".join(f"{v:11.3f}" if finite(v) else f"{'-':>11s}" for v in vals), + file=file) + + +# --------------------------------------------------------------------------- correlation +def spearman(x: np.ndarray, y: np.ndarray) -> float: + """Spearman's rho over the pairs where both are finite (average ranks for ties).""" + from scipy.stats import rankdata + m = np.isfinite(x) & np.isfinite(y) + if m.sum() < 10: + return float("nan") + rx, ry = rankdata(x[m]), rankdata(y[m]) + if rx.std() == 0 or ry.std() == 0: + return float("nan") + return float(np.corrcoef(rx, ry)[0, 1]) + + +def matrix(columns: dict[str, np.ndarray]) -> tuple[list[str], np.ndarray]: + names = list(columns) + r = np.full((len(names), len(names)), np.nan) + for i, a in enumerate(names): + for j, b in enumerate(names): + r[i, j] = 1.0 if i == j else spearman(columns[a], columns[b]) + return names, r + + +def prune(names: list[str], rho: np.ndarray, fixed: tuple[str, ...] = ()) -> tuple[list[str], dict]: + """Greedy redundancy pruning: walk `names` in order (the gate's axes in `fixed` first, + always kept) and keep a statistic unless its |rho| with one already kept exceeds + `REDUNDANT_RHO`. Returns (kept, {dropped: (the kept statistic it duplicates, rho)}).""" + order = [n for n in fixed if n in names] + [n for n in names if n not in fixed] + kept: list[str] = [] + dropped: dict = {} + for n in order: + i = names.index(n) + worst = max(((abs(rho[i, names.index(k)]), k) for k in kept + if np.isfinite(rho[i, names.index(k)])), default=(0.0, None)) + if n not in fixed and worst[0] > REDUNDANT_RHO: + dropped[n] = (worst[1], float(rho[i, names.index(worst[1])])) + else: + kept.append(n) + return kept, dropped + + +def print_matrix(names: list[str], rho: np.ndarray, file=None) -> None: + file = file or sys.stdout + w = 6 + print(" " * 19 + "".join(f"{i:>{w}d}" for i in range(len(names))), file=file) + for i, n in enumerate(names): + cells = "".join(f"{rho[i, j]:{w}.2f}" if np.isfinite(rho[i, j]) else f"{'':>{w}s}" + for j in range(len(names))) + print(f"{i:2d} {n:16s}" + cells, file=file) + + +# --------------------------------------------------------------------------- tracing +@functools.lru_cache(maxsize=8) +def _exe_key(path: str, mtime_ns: int, size: int) -> str: + return svgeval.exe_key(Path(path)) + + +def trace_dir(exe: Path, args: tuple[str, ...], tier: str) -> Path: + """Where the traces of build `exe` with tracer flags `args` at `tier` are kept.""" + st = exe.stat() + tag = hashlib.sha1(" ".join(args).encode()).hexdigest()[:8] + return svgeval.CACHE / "traces" / f"{_exe_key(str(exe), st.st_mtime_ns, st.st_size)}-{tag}" / tier + + +def one(job: tuple) -> tuple[str, dict]: + """Trace one icon (or read its kept trace) and take the battery; with `gate`, also the + gate's own signals. Top-level for the process pool.""" + exe, it, args, cond_name, fresh, gate = job + import ci_gate + cond = ci_gate.BY_NAME[cond_name] + tier = cond.tier + svgeval.set_tier(tier) + key = f"{it['corpus']}/{it['stem']}" + png, gt = svgeval.item_paths(it) + out = trace_dir(exe, args, tier) / f"{it['corpus']}__{it['stem']}.svg" + if fresh or not out.exists(): + out.parent.mkdir(parents=True, exist_ok=True) + fail, _, _, _ = svgeval._trace(svgeval.Job(exe, it, out.parent, args)) + if fail: + return key, {"fail": fail["fail"]} + svg = out.read_text(encoding="utf-8") + from PIL import Image + with Image.open(png) as im: + px = im.size[0] + row = {"human": svgeval.human_stats(svg, gt, px)} + if gate: + sig = svgeval.score_svg(svg, it, png, gt) + if "fail" not in sig: + row.update(sig) + ci_gate.with_gaps({key: row}, cond) + return key, row + + +def run_arm(exe: Path, args: tuple[str, ...], conds: list[str], items: list[dict], + workers: int, fresh: bool, gate: bool) -> dict[str, dict]: + import ci_gate + out: dict[str, dict] = {} + with svgeval.scoring_pool(workers) as pool: + for c in conds: + full_args = tuple(ci_gate.BY_NAME[c].args) + args + jobs = [(exe, it, full_args, c, fresh, gate) for it in items] + rows = dict(pool.map(one, jobs, chunksize=2)) + bad = [f"{k}: {r['fail']}" for k, r in rows.items() if "fail" in r] + for b in bad[:5]: + print(f" {c}: {b}", file=sys.stderr) + out[c] = {k: r for k, r in rows.items() if "fail" not in r} + return out + + +# --------------------------------------------------------------------------- reports +def print_families(doc: dict, stats: list[str]) -> None: + for cond, d in doc["conditions"].items(): + fams = [f for f in d["summary"][stats[0]]["div"] if f != "macro"] + print(f"\n== {cond}: artist / trace (divergence), mean per family; a mix reads its " + "share of cubics, a distribution its median, a palette its size") + print(f" {'statistic':18s}" + "".join(f"{f[:14]:>24s}" for f in fams + ["macro"])) + for s in stats: + cells = [] + for f in fams + ["macro"]: + a = d["summary"][s]["artist"].get(f) + t = d["summary"][s]["trace"].get(f) + v = d["summary"][s]["div"].get(f) + cells.append(f"{a:7.2f}/{t:7.2f} ({v:5.2f})" if all(finite(x) for x in (a, t, v)) + else f"{'-':>24s}") + print(f" {s:18s}" + "".join(f"{c:>24s}" for c in cells)) + + +def print_oddities(doc: dict, stats: list[str], n: int) -> None: + """Per statistic, the `n` icons farthest from their artist; then overall, the icons with + the highest mean divergence rank over the statistics (ties share their rank; artefact + signals left out).""" + from scipy.stats import rankdata + for cond, d in doc["conditions"].items(): + per = d["per_icon"] + print(f"\n== {cond}: oddities, the {n} icons farthest from their artist per statistic " + "(divergence; trace value vs artist value)") + ranks: dict[str, list] = defaultdict(list) + for s in stats: + rows = [(v[s][1], k, v[s][0], doc["artist"].get(k, {}).get(s)) + for k, v in per.items() if s in v and finite(v[s][1])] + if not rows: + continue + rows.sort(key=lambda r: (-r[0], r[1])) + print(f" {s:18s} " + "; ".join(f"{k} {dv:.2f} ({t:.2f} vs {a:.2f})" + if finite(t) and finite(a) else f"{k} {dv:.2f}" + for dv, k, t, a in rows[:n])) + if s in design.ARTEFACTS: + continue + r = rankdata([x[0] for x in rows]) - 1 + for (_, k, _, _), rk in zip(rows, r): + ranks[k].append(rk / max(1, len(rows) - 1)) + overall = sorted(((float(np.mean(v)), k) for k, v in ranks.items()), reverse=True) + print(" overall, mean divergence rank over the statistics (1 = farthest on all): " + + "; ".join(f"{k} {m:.2f}" for m, k in overall[:n])) + + +def print_ab(after: dict, before: dict, stats: list[str]) -> dict: + """Paired comparison of two arms, per condition and statistic; returns the numbers.""" + res: dict = {} + for cond, a_rows in after.items(): + b_rows = before.get(cond, {}) + print(f"\n== {cond}: before -> after, family-macro mean divergence from the artist " + "(lower is closer)") + print(f" {'statistic':18s} {'before':>9s} {'after':>9s} {'change':>8s} " + f"{'95% CI':>17s} closer further") + ratios = [] + res[cond] = {} + for s in stats: + base, cur, fam = {}, {}, {} + for k in a_rows.keys() & b_rows.keys(): + x = b_rows[k].get("human", {}).get("div", {}).get(s) + y = a_rows[k].get("human", {}).get("div", {}).get(s) + if finite(x) and finite(y): + base[k], cur[k], fam[k] = x, y, k.split("/", 1)[0] + if len(base) < 4: + continue + c = gate_stats.compare(base, cur, fam, "macro") + if c.base > 0 and c.cur > 0 and s not in design.ARTEFACTS: + ratios.append(c.cur / c.base) + res[cond][s] = {"before": c.base, "after": c.cur, "rel": c.rel, "p025": c.p025, + "p975": c.p975, "closer": c.better, "further": c.worse} + sig = "*" if c.p975 < 0 or c.p025 > 0 else " " + print(f" {s:18s} {c.base:9.4f} {c.cur:9.4f} {c.rel * 100:+7.1f}% " + f"[{c.p025 * 100:+6.1f}, {c.p975 * 100:+6.1f}]{sig} {c.better:6d} {c.worse:7d}") + if ratios: + g = float(np.exp(np.mean(np.log(ratios)))) + res[cond]["composite"] = g + print(f" composite (geometric mean of after/before over {len(ratios)} statistics, " + "artefact signals left out): " + f"{g:.4f} ({(g - 1) * 100:+.1f}%; below 1 is closer to the artist)") + print(" (* the 95 % interval excludes zero)") + return res + + +def correlate(results: dict[str, dict], stats: list[str], with_gate: bool) -> None: + keys = [(c, k) for c, rows in results.items() for k in rows] + cols: dict[str, np.ndarray] = {} + if with_gate: + for ax in GATE_AXES: + v = np.array([results[c][k].get(ax, np.nan) for c, k in keys], dtype=float) + if np.isfinite(v).sum() >= 10: + cols[ax] = v + for s in stats: + cols[s] = np.array([results[c][k].get("human", {}).get("div", {}).get(s, np.nan) + for c, k in keys], dtype=float) + cols[s][~np.isfinite(cols[s])] = np.nan + names, rho = matrix(cols) + fixed = tuple(ax for ax in GATE_AXES if ax in cols) + print(f"\n== Spearman correlation of the per-icon divergences, pooled over " + f"{', '.join(results)} ({len(keys)} icon-conditions; pairwise complete)") + print_matrix(names, rho) + kept, dropped = prune(names, rho, fixed) + print(f"\nredundancy pruning at |rho| > {REDUNDANT_RHO} (gate axes kept first, then " + "design.STATS order):") + for n, (k, r) in dropped.items(): + print(f" drop {n:18s} rho {r:+.2f} with {k}") + print(" keep " + ", ".join(n for n in kept if n not in fixed)) + big = [(abs(rho[i, j]), names[i], names[j]) for i in range(len(names)) for j in range(i) + if np.isfinite(rho[i, j]) and names[i] in kept and names[j] in kept] + big.sort(reverse=True) + print(" largest |rho| among the kept: " + ", ".join(f"{a}~{b} {r:.2f}" for r, a, b in big[:6])) + # The same within families: each column replaced by its rank within the icon's family + # and condition, so a family's style (lucide on its grid, noto-emoji off it) cannot + # make two statistics look alike. + groups = np.array([f"{c}|{k.split('/', 1)[0]}" for c, k in keys]) + within = {n: _within_ranks(v, groups) for n, v in cols.items()} + _, rho_w = matrix(within) + print(" within families (ranks within family and condition): " + + ", ".join(f"{n}~{k} {rho_w[names.index(n), names.index(k)]:+.2f}" + for n, (k, _) in dropped.items())) + big_w = [(abs(rho_w[i, j]), names[i], names[j]) for i in range(len(names)) for j in range(i) + if np.isfinite(rho_w[i, j]) and names[i] in kept and names[j] in kept] + big_w.sort(reverse=True) + print(" largest within-family |rho| among the kept: " + + ", ".join(f"{a}~{b} {r:.2f}" for r, a, b in big_w[:6])) + + +def _within_ranks(v: np.ndarray, groups: np.ndarray) -> np.ndarray: + """Each finite value's rank within its group, scaled to [0, 1] (NaN stays NaN).""" + from scipy.stats import rankdata + out = np.full(v.shape, np.nan) + for g in np.unique(groups): + m = (groups == g) & np.isfinite(v) + if m.sum() > 1: + out[m] = (rankdata(v[m]) - 1) / (m.sum() - 1) + return out + + +# --------------------------------------------------------------------------- main +#: Options whose value is itself a list of tracer flags, so starts with "-". +FLAG_OPTIONS = ("--extra-args", "--base-args") + + +def flag_values(argv: list[str]) -> list[str]: + """`argv` with `--extra-args --editability` written `--extra-args=--editability`: argparse + would read a value that starts with "-" as an option of its own.""" + out, i = [], 0 + while i < len(argv): + if argv[i] in FLAG_OPTIONS and i + 1 < len(argv): + out.append(f"{argv[i]}={argv[i + 1]}") + i += 2 + else: + out.append(argv[i]) + i += 1 + return out + + +def load_report(path: Path) -> dict[str, dict]: + """A gate report's per-icon rows: {condition: {key: {axes..., "human": {...}}}}.""" + rep = json.loads(path.read_text(encoding="utf-8")) + hum = rep.get("human") or {} + out: dict[str, dict] = {} + for cond, d in hum.get("conditions", {}).items(): + rows = {} + for k, v in d["per_icon"].items(): + rows[k] = {"human": {"trace": {s: x[0] for s, x in v.items()}, + "div": {s: x[1] for s, x in v.items()}, + "artist": hum.get("artist", {}).get(k, {})}} + rows[k].update(rep.get("per_icon", {}).get(cond, {}).get(k, {})) + out[cond] = rows + return out + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--exe", type=Path, help="the build to read (the 'after' arm)") + ap.add_argument("--extra-args", default="", help="tracer flags for --exe, e.g. \"--editability\"") + ap.add_argument("--base-exe", type=Path, default=None, + help="a second build to compare with (the 'before' arm; default: --exe)") + ap.add_argument("--base-args", default=None, + help="tracer flags for the 'before' arm (\"\" for none); with --base-exe or " + "this, the two arms are compared icon by icon") + ap.add_argument("--conditions", default=",".join(DEFAULT_CONDITIONS), + help="gate conditions to trace (bench/ci_gate.py CONDITIONS)") + ap.add_argument("--sample", type=float, default=None, metavar="FRACTION") + ap.add_argument("--workers", type=int, default=2) + ap.add_argument("--fresh", action="store_true", help="retrace even when a kept trace exists") + ap.add_argument("--from-report", type=Path, nargs="+", default=None, + help="read gate --report-json files instead of tracing") + ap.add_argument("--all-stats", action="store_true", + help="every candidate statistic (design.STATS), not only design.KEPT") + ap.add_argument("--families", action="store_true", help="the per-family table") + ap.add_argument("--oddities", type=int, default=3, metavar="N") + ap.add_argument("--correlate", action="store_true", help="the Spearman matrix and pruning") + ap.add_argument("--gate-axes", action="store_true", + help="also score the gate's axes (renders; slower) for --correlate") + ap.add_argument("--json", type=Path, default=None, help="write the numbers here") + a = ap.parse_args(flag_values(sys.argv[1:])) + os.environ.setdefault("INKVEC_SKIP_DISTS", "1") + stats = list(design.STATS) if a.all_stats or a.correlate else list(design.KEPT) + + import shlex + if a.from_report: + after = {} + for path in a.from_report: + after.update(load_report(path)) + before = None + else: + if a.exe is None: + ap.error("--exe or --from-report is required") + conds = [c.strip() for c in a.conditions.split(",") if c.strip()] + items = svgeval.load_sets()["screen"] + if a.sample is not None: + items = svgeval.sample(items, a.sample) + exe = a.exe.resolve() + args = tuple(shlex.split(a.extra_args)) + print(f"human_stats: {len(items)} icons x {len(conds)} conditions, {exe.name} " + f"{' '.join(args)}", flush=True) + after = run_arm(exe, args, conds, items, a.workers, a.fresh, a.gate_axes) + before = None + if a.base_exe is not None or a.base_args is not None: + bexe = (a.base_exe or a.exe).resolve() + bargs = tuple(shlex.split(a.base_args or "")) + print(f"before: {bexe.name} {' '.join(bargs)}", flush=True) + before = run_arm(bexe, bargs, conds, items, a.workers, a.fresh, a.gate_axes) + + doc = document(after, stats) + if a.families or not before: + print_families(doc, stats) + if a.oddities: + print_oddities(doc, stats, a.oddities) + out = {"after": doc} + if before: + out["before"] = document(before, stats) + out["paired"] = print_ab(after, before, stats) + if a.correlate: + correlate(after, stats, with_gate=a.gate_axes or a.from_report is not None) + if a.json: + a.json.parent.mkdir(parents=True, exist_ok=True) + a.json.write_text(json.dumps(out, indent=1), encoding="utf-8") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bench/inkvec_bench/design.py b/bench/inkvec_bench/design.py new file mode 100644 index 00000000..3e94ad72 --- /dev/null +++ b/bench/inkvec_bench/design.py @@ -0,0 +1,1169 @@ +"""How a file is drawn: a battery of statistics of an SVG's construction, each read on the +trace and on the artist's own file, and the distance between the two. + +The gate's axes ask whether a trace looks like the artist's drawing (dE00, geom) and whether +it is about as long and turns about as much (ratio_gap, turning_gap). None asks whether it is +*built* like it: lines along the axes, nodes at the extrema with level handles, smooth joins +where the artist drew a curve and clean corners where they drew a corner, numbers on the +design grid, values shared, circles written as circles, shapes stacked rather than cut out. +These are what a designer sees on opening the file, and what `--editability` aims at. Each +statistic below is a number per file; its **divergence** is how far the trace's number is +from the artist's, per icon, so that zero is "drawn as the artist drew it" whatever the +family's style. They are reported, not gated. + +Reading a file +-------------- +One pass over the XML (`parse`): `` (every command, relative ones resolved, `S`/`T` +reflected, arcs in endpoint form), and ``, ``, ``, ``, +``, `` and `` as the outlines they stand for (a rectangle four lines, +rounded corners quarter arcs, a circle or an ellipse four quarter arcs starting at its +rightmost point, as an editor shows them). Transforms are applied; paint (fill, stroke, +stroke-width, fill-rule, colour) is inherited down the tree, from attributes and `style`. +Coordinates are mapped to the canvas the gate renders (`render.fit_viewbox`: the viewBox +centred in a square of its longer side), in units of that side, so a 24-unit icon and its +512 px trace read on one scale. A **node** is an on-curve point (each segment's start, and +an open subpath's last end); a **join** is a node between two segments of one subpath, +including where a closed subpath closes; its **turn** is the angle between the incoming and +the outgoing tangent. A segment shorter than `DOT` (1/1000 of the canvas: lucide's `h.01` +round-cap dots) is a dot, not a segment. + +The statistics (`STATS`; divergence in brackets) +------------------------------------------------ +Pieces +* `kinds` segment-kind mix: shares of lines, cubics, quadratics, arcs [total variation + distance between the two mixes, 0-1] +* `primitives` share of drawn elements written as `rect`, `circle`, `ellipse` or `line` + [|difference|] +* `stroked` share of drawn elements with a visible stroke [|difference|] +* `stroke_width_ties` of the stroked elements (two at least), the share whose stroke width + another repeats exactly: one pen for the drawing [|difference|] +* `elements` drawn elements [|ln ratio|] +* `subpaths` subpaths [|ln ratio|] +* `nodes_per_subpath` mean nodes per subpath [|ln ratio|] +* `closed` share of subpaths that are closed [|difference|] +Directions +* `line_axis` share of lines within `AXIS_DEG` of horizontal or vertical [|difference|] +* `line_diag` share of lines within `AXIS_DEG` of a 45 degree diagonal [|difference|] +* `handle_axis` share of cubic handles (node to its control point) within `AXIS_DEG` of an + axis [|difference|] +Joins +* `smooth` of joins with a curve on at least one side, the share turning at most + `SMOOTH_DEG` (G1) [|difference|] +* `extremum` of those smooth joins, the share whose tangent is within `EXTREMUM_DEG` of an + axis: a node at an x or y extremum [|difference|] +* `kinked` of joins between two curves, the share turning more than `SMOOTH_DEG` and at + most `CORNER_DEG`: neither smooth nor a corner [|difference|] +* `collinear` of joins between two lines, the share turning at most `AXIS_DEG`: a node in + the middle of a straight run [|difference|] +* `corner_share` share of all joins turning more than `CORNER_DEG` [|difference|] +* `right_angle` of those corners, the share within `RIGHT_DEG` of 90 degrees [|difference|] +* `corner_angles` the corners' turn angles as a distribution [Wasserstein-1, degrees / 180] +Curves +* `sweep` each curve's own turning (an arc's angle; a cubic's or quadratic's + control-polygon turning) as a distribution [Wasserstein-1, degrees / 180] +* `wide_curves` share of curves turning more than 100 degrees (an extremum skipped) + [|difference|] +* `handle_length` each cubic handle's length over its segment's chord, as a distribution + (a quarter circle's is 0.55) [Wasserstein-1] +* `symmetric_handles` of smooth joins between two cubics, the share whose two handles are + within 5 % of one length [|difference|] +* `segment_lengths` segment lengths, log10 of the canvas fraction, as a distribution + [Wasserstein-1, decades] +* `length_gini` the Gini coefficient of segment lengths [|difference|] +Numbers +* `grid_half` share of node coordinates (x and y) on the artist's half-unit grid, in the + artist's own units (the trace's mapped there), within `GRID_TOL_PX` raster px + for a trace and exactly for the artist [|difference|] +* `grid_int` the same on the whole-unit grid [|difference|] +* `grid_level` the coarsest of the grids 1, 1/2, 1/4, 1/8, 1/16 unit that holds 75 % of the + node coordinates, as 0-4, 5 for none [|difference|] +* `decimals` mean decimals a node coordinate needs in the artist's units (0-3, 4 for more) + at the same tolerance [|difference|] +* `ties` share of node coordinates (x among x, y among y) another node repeats + exactly as written (1e-6 of the canvas) [|difference|] +* `mirror` share of nodes whose mirror image across the drawing's vertical (or, if + more, horizontal) centre line is within `MIRROR_TOL` of another node + [|difference|] +Paint and layers +* `colours` distinct paint colours (flat fills and strokes, gradient stops) [|ln ratio|] +* `palette` the two palettes' symmetric mean nearest-colour distance, CIELAB delta E 1976 + [the distance itself; the artist's own file reads 0] +* `nested` share of closed subpaths that lie inside another subpath of the same element + (holes and islands of a compound path) [|difference|] +* `stacked` share of filled elements painted over an earlier filled element (an interior + point of theirs lies inside it) [|difference|] +* `evenodd` share of filled elements with `fill-rule="evenodd"` [|difference|] +Artefact signal (reported, left out of `bench/human_stats.py`'s composite) +* `halfpx` share of node coordinates on the raster's half-pixel grid (pixel edges and + centres) within `GRID_TOL_PX`: numbers snapped to the pixels the file was + traced from, which no artist's grid explains [|difference|] + +A share whose denominator is empty in either file (no lines, no corners) has no divergence for +that icon. `KEPT` is the non-redundant subset the battery reports: `bench/human_stats.py +--correlate` computes the Spearman correlation of the per-icon divergences and drops a +statistic correlated beyond |rho| 0.7 with one kept before it (see `KEPT` for the result). + +Not from the literature as a battery. The node conventions (nodes at extrema, level handles, +smooth or corner but not in between) are the type-design and icon-design canon (e.g. the +Apple and Material icon grids; Adobe's "Illustrator: nodes at extrema" practice); the +divergences are standard: total variation for a categorical mix, Wasserstein-1 for a +distribution of reals (Villani 2009, Optimal Transport, ch. 6). +""" +from __future__ import annotations + +import math +import re +import xml.etree.ElementTree as ET +from dataclasses import dataclass, field +from functools import lru_cache +from itertools import pairwise + +import numpy as np + +#: Bumped whenever a statistic's definition changes, so cached artist profiles +#: (`svgeval.artist_design`) are never read for a different battery. +VERSION = 1 + +#: Tolerances, in degrees. +AXIS_DEG = 0.5 +SMOOTH_DEG = 3.0 +CORNER_DEG = 30.0 +EXTREMUM_DEG = 1.0 +RIGHT_DEG = 1.0 +WIDE_DEG = 100.0 +#: A segment shorter than this (canvas fraction) is a dot, not a segment. +DOT = 1e-3 +#: A trace's node coordinate is on the artist's grid within this many raster px (the tracer +#: writes two decimals). +GRID_TOL_PX = 0.02 +#: An artist's own coordinate is on its grid within this many of its units (exact numbers). +EXACT_TOL = 1e-6 +#: Two node coordinates are one value within this canvas fraction (as written). +TIE_TOL = 1e-6 +#: A node's mirror image matches another node within this canvas fraction (2 px at 512 px). +MIRROR_TOL = 1 / 256 +#: Grids tried for `grid_level`, as subdivisions of the artist's unit. +GRID_LADDER = (1, 2, 4, 8, 16) +GRID_LEVEL_SHARE = 0.75 + +NONPAINT = {"defs", "clipPath", "mask", "symbol", "linearGradient", "radialGradient", + "filter", "pattern", "marker", "title", "desc", "metadata", "style", "script", + "text", "image", "foreignObject"} +INHERITED = ("fill", "stroke", "stroke-width", "fill-rule", "fill-opacity", "stroke-opacity", + "color", "visibility") +PRIMITIVE_TAGS = ("rect", "circle", "ellipse", "line") +NUM = re.compile(r"[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?") +TOKEN = re.compile(r"[MmLlHhVvCcSsQqTtAaZz]|[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?") +ARGS = {"M": 2, "L": 2, "T": 2, "H": 1, "V": 1, "C": 6, "S": 4, "Q": 4, "A": 7, "Z": 0} +TRANSFORM = re.compile(r"(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)") + + +# --------------------------------------------------------------------------- geometry +@dataclass +class Seg: + """One drawn segment, in canvas units. `kind` is L, C, Q or A; `pts` are its points in + order (start, controls, end); an arc carries its centre form in `arc`.""" + + kind: str + pts: list + arc: tuple | None = None # (cx, cy, rx, ry, phi, theta1, dtheta) + + @property + def p0(self): + return self.pts[0] + + @property + def p1(self): + return self.pts[-1] + + +@dataclass +class Sub: + segs: list[Seg] + closed: bool + + +@dataclass +class Elem: + tag: str + subs: list[Sub] + filled: bool + stroked: bool + evenodd: bool + colours: list = field(default_factory=list) + stroke_width: float = 0.0 # canvas units, when stroked + + +def _affine_mul(m, n): + a, b, c, d, e, f = m + a2, b2, c2, d2, e2, f2 = n + return (a * a2 + c * b2, b * a2 + d * b2, a * c2 + c * d2, b * c2 + d * d2, + a * e2 + c * f2 + e, b * e2 + d * f2 + f) + + +IDENTITY = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0) + + +def _parse_transform(text: str | None): + m = IDENTITY + if not text: + return m + for name, args in TRANSFORM.findall(text): + v = [float(x) for x in NUM.findall(args)] + if name == "matrix" and len(v) == 6: + t = tuple(v) + elif name == "translate" and v: + t = (1.0, 0.0, 0.0, 1.0, v[0], v[1] if len(v) > 1 else 0.0) + elif name == "scale" and v: + t = (v[0], 0.0, 0.0, v[1] if len(v) > 1 else v[0], 0.0, 0.0) + elif name == "rotate" and v: + r = math.radians(v[0]) + cs, sn = math.cos(r), math.sin(r) + t = (cs, sn, -sn, cs, 0.0, 0.0) + if len(v) == 3: + t = _affine_mul(_affine_mul((1.0, 0.0, 0.0, 1.0, v[1], v[2]), t), + (1.0, 0.0, 0.0, 1.0, -v[1], -v[2])) + elif name == "skewX" and v: + t = (1.0, 0.0, math.tan(math.radians(v[0])), 1.0, 0.0, 0.0) + elif name == "skewY" and v: + t = (1.0, math.tan(math.radians(v[0])), 0.0, 1.0, 0.0, 0.0) + else: + continue + m = _affine_mul(m, t) + return m + + +def _arc_centre(p0, rx, ry, phi, fa, fs, p1): + """SVG arc endpoint form to centre form (SVG 1.1 F.6.5): (cx, cy, rx, ry, phi, th1, dth), + or None for a degenerate arc (drawn as a line).""" + x1, y1 = p0 + x2, y2 = p1 + rx, ry = abs(rx), abs(ry) + if rx < 1e-12 or ry < 1e-12 or (abs(x1 - x2) < 1e-12 and abs(y1 - y2) < 1e-12): + return None + c, s = math.cos(phi), math.sin(phi) + dx2, dy2 = (x1 - x2) / 2, (y1 - y2) / 2 + x1p, y1p = c * dx2 + s * dy2, -s * dx2 + c * dy2 + lam = x1p * x1p / (rx * rx) + y1p * y1p / (ry * ry) + if lam > 1: + k = math.sqrt(lam) + rx, ry = rx * k, ry * k + num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p + den = rx * rx * y1p * y1p + ry * ry * x1p * x1p + co = math.sqrt(max(0.0, num / den)) if den > 0 else 0.0 + if fa == fs: + co = -co + cxp, cyp = co * rx * y1p / ry, -co * ry * x1p / rx + cx = c * cxp - s * cyp + (x1 + x2) / 2 + cy = s * cxp + c * cyp + (y1 + y2) / 2 + + def ang(ux, uy, vx, vy): + return math.atan2(ux * vy - uy * vx, ux * vx + uy * vy) + + th1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry) + dth = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry) + if not fs and dth > 0: + dth -= 2 * math.pi + elif fs and dth < 0: + dth += 2 * math.pi + return (cx, cy, rx, ry, phi, th1, dth) + + +def _arc_point(a, th): + cx, cy, rx, ry, phi, _, _ = a + c, s = math.cos(phi), math.sin(phi) + x, y = rx * math.cos(th), ry * math.sin(th) + return (cx + c * x - s * y, cy + s * x + c * y) + + +def _arc_tangent(a, th): + _, _, rx, ry, phi, _, dth = a + c, s = math.cos(phi), math.sin(phi) + dx, dy = -rx * math.sin(th), ry * math.cos(th) + sg = 1.0 if dth >= 0 else -1.0 + return (sg * (c * dx - s * dy), sg * (s * dx + c * dy)) + + +def _scan(d: str): + """Path data as (command, [numbers]); arc flags read one character each, so the compact + `a2 2 0 012-2` reads as SVG says it does.""" + toks = TOKEN.findall(d) + out, i, n, cmd = [], 0, len(toks), None + while i < n: + t = toks[i] + if t.isalpha(): + cmd = t + i += 1 + if cmd in "Zz": + out.append((cmd, [])) + continue + elif cmd is None or cmd in "Zz": + return out + k = ARGS[cmd.upper()] + args: list[float] = [] + while len(args) < k: + if i >= n or toks[i].isalpha(): + return out + t = toks[i] + if cmd in "Aa" and len(args) in (3, 4) and len(t) > 1 and t[0] in "01": + args.append(float(t[0])) + toks[i] = t[1:] + continue + args.append(float(t)) + i += 1 + out.append((cmd, args)) + if cmd == "M": + cmd = "L" + elif cmd == "m": + cmd = "l" + return out + + +class _Builder: + """Collects one element's subpaths in canvas units through a fixed transform.""" + + def __init__(self, ctm): + self.ctm = ctm + a, b, c, d, _, _ = ctm + self.scale = math.sqrt(abs(a * d - b * c)) + self.rot = math.atan2(b, a) + self.flip = a * d - b * c < 0 + self.subs: list[Sub] = [] + self.cur: list[Seg] | None = None + + def tp(self, p): + a, b, c, d, e, f = self.ctm + return (a * p[0] + c * p[1] + e, b * p[0] + d * p[1] + f) + + def start(self): + self.end_sub(False) + self.cur = [] + + def end_sub(self, closed: bool): + if self.cur: + self.subs.append(Sub(self.cur, closed)) + self.cur = None + + def add(self, kind, pts, arc=None): + if self.cur is None: + self.cur = [] + self.cur.append(Seg(kind, [self.tp(p) for p in pts], arc)) + + def add_arc(self, p0, rx, ry, phi_deg, fa, fs, p1): + q0, q1 = self.tp(p0), self.tp(p1) + a = _arc_centre(q0, rx * self.scale, ry * self.scale, + math.radians(phi_deg) + self.rot, fa, (not fs) if self.flip else fs, q1) + if self.cur is None: + self.cur = [] + self.cur.append(Seg("L", [q0, q1]) if a is None else Seg("A", [q0, q1], a)) + + +def _path(b: _Builder, d: str): + cur = start = (0.0, 0.0) + last = None # (kind, control) for S/T reflection + for cmd, a in _scan(d): + U, rel = cmd.upper(), cmd.islower() + ox, oy = cur if rel else (0.0, 0.0) + if U == "M": + cur = start = (ox + a[0], oy + a[1]) + b.start() + last = None + continue + if U == "Z": + if b.cur is not None: + if cur != start: + b.add("L", [cur, start]) + b.end_sub(True) + cur, last = start, None + continue + if b.cur is None: + b.cur = [] + start = cur + if U == "L": + p = (ox + a[0], oy + a[1]) + b.add("L", [cur, p]) + cur, last = p, None + elif U == "H": + p = (ox + a[0] if rel else a[0], cur[1]) + b.add("L", [cur, p]) + cur, last = p, None + elif U == "V": + p = (cur[0], oy + a[0] if rel else a[0]) + b.add("L", [cur, p]) + cur, last = p, None + elif U in "CS": + if U == "C": + c1, c2, p = (ox + a[0], oy + a[1]), (ox + a[2], oy + a[3]), (ox + a[4], oy + a[5]) + else: + c1 = (2 * cur[0] - last[1][0], 2 * cur[1] - last[1][1]) if last and last[0] == "C" else cur + c2, p = (ox + a[0], oy + a[1]), (ox + a[2], oy + a[3]) + b.add("C", [cur, c1, c2, p]) + cur, last = p, ("C", c2) + elif U in "QT": + if U == "Q": + c, p = (ox + a[0], oy + a[1]), (ox + a[2], oy + a[3]) + else: + c = (2 * cur[0] - last[1][0], 2 * cur[1] - last[1][1]) if last and last[0] == "Q" else cur + p = (ox + a[0], oy + a[1]) + b.add("Q", [cur, c, p]) + cur, last = p, ("Q", c) + elif U == "A": + p = (ox + a[5], oy + a[6]) + b.add_arc(cur, a[0], a[1], a[2], int(a[3]), int(a[4]), p) + cur, last = p, None + b.end_sub(False) + + +def _num(el, name, default=0.0) -> float: + v = el.get(name) + if v is None: + return default + m = NUM.match(v.strip()) + return float(m.group(0)) if m else default + + +def _ellipse(b: _Builder, cx, cy, rx, ry): + if rx <= 0 or ry <= 0: + return + pts = [(cx + rx, cy), (cx, cy + ry), (cx - rx, cy), (cx, cy - ry), (cx + rx, cy)] + b.start() + for p, q in pairwise(pts): + b.add_arc(p, rx, ry, 0.0, 0, 1, q) + b.end_sub(True) + + +def _rect(b: _Builder, x, y, w, h, rx, ry): + if w <= 0 or h <= 0: + return + rx, ry = min(rx, w / 2), min(ry, h / 2) + b.start() + if rx <= 0 or ry <= 0: + pts = [(x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y)] + for p, q in pairwise(pts): + b.add("L", [p, q]) + else: + corners = [((x + w - rx, y), (x + w, y + ry)), ((x + w, y + h - ry), (x + w - rx, y + h)), + ((x + rx, y + h), (x, y + h - ry)), ((x, y + ry), (x + rx, y))] + prev = (x + rx, y) + for p, q in corners: + if abs(p[0] - prev[0]) + abs(p[1] - prev[1]) > 1e-12: + b.add("L", [prev, p]) + b.add_arc(p, rx, ry, 0.0, 0, 1, q) + prev = q + b.end_sub(True) + + +# --------------------------------------------------------------------------- paint +@lru_cache(maxsize=4096) +def _rgb(text: str): + """An sRGB triple in [0, 1] for a CSS colour, or None for none / a reference.""" + t = text.strip().lower() + if not t or t in ("none", "transparent") or t.startswith("url("): + return None + if t.startswith("#"): + h = t[1:] + if len(h) in (3, 4): + h = "".join(ch * 2 for ch in h[:3]) + if len(h) >= 6: + try: + return tuple(int(h[i:i + 2], 16) / 255 for i in (0, 2, 4)) + except ValueError: + return None + return None + if t.startswith("rgb"): + v = NUM.findall(t) + if len(v) >= 3: + scale = 100.0 if "%" in t else 255.0 + return tuple(min(1.0, max(0.0, float(x) / scale)) for x in v[:3]) + return None + try: + from svgelements import Color + c = Color(t) + if c.value is None: + return None + return (c.red / 255, c.green / 255, c.blue / 255) + except Exception: # noqa: BLE001 - an unknown name is no colour + return None + + +def _style(el) -> dict: + st = {} + for k in INHERITED + ("opacity", "display"): + v = el.get(k) + if v is not None: + st[k] = v.strip() + for part in (el.get("style") or "").split(";"): + if ":" in part: + k, v = part.split(":", 1) + st[k.strip()] = v.strip() + return st + + +def _local(tag: str) -> str: + return tag.rsplit("}", 1)[-1] + + +@dataclass +class Doc: + """A parsed file: its drawn elements in paint order, in canvas units.""" + + elements: list[Elem] + frame: tuple[float, float, float] # origin x, origin y, side, in the file's units + + +def frame_of(root) -> tuple[float, float, float]: + """The square the gate renders, in the file's own units: the viewBox centred in a square + of its longer side (`render.fit_viewbox`), else the root's width and height.""" + vb = root.get("viewBox") + x = y = 0.0 + w = h = None + if vb: + v = [float(t) for t in NUM.findall(vb)] + if len(v) == 4 and v[2] > 0 and v[3] > 0: + x, y, w, h = v + if w is None: + w, h = _num(root, "width", 0.0), _num(root, "height", 0.0) + if w <= 0 or h <= 0: + w = h = 24.0 + s = max(w, h) + return (x - (s - w) / 2, y - (s - h) / 2, s) + + +def parse(svg: str) -> Doc: + """Every drawn element of `svg` (module documentation), in paint order.""" + root = ET.fromstring(svg) + fx, fy, fs = frame_of(root) + base = (1 / fs, 0.0, 0.0, 1 / fs, -fx / fs, -fy / fs) # file units -> canvas units + ids = {el.get("id"): el for el in root.iter() if el.get("id")} + stops: dict[str, list] = {} + + def gradient_stops(gid: str, depth: int = 0) -> list: + if gid in stops: + return stops[gid] + g = ids.get(gid) + out = [] + if g is not None and depth < 8: + for s in g: + if _local(s.tag) == "stop": + st = _style(s) + c = _rgb(st.get("stop-color", s.get("stop-color", "black"))) + if c is not None: + out.append(c) + if not out: + href = g.get("{http://www.w3.org/1999/xlink}href") or g.get("href") or "" + if href.startswith("#"): + out = gradient_stops(href[1:], depth + 1) + stops[gid] = out + return out + + def paint(value: str | None, st: dict) -> tuple[bool, list]: + if value is None: + return False, [] + v = value.strip() + if v.startswith("url("): + m = re.match(r"url\(\s*#([^)\s]+)\s*\)", v) + return True, gradient_stops(m.group(1)) if m else [] + if v.lower() == "currentcolor": + v = st.get("color", "black") + c = _rgb(v) + return c is not None, [c] if c is not None else [] + + out: list[Elem] = [] + + def walk(node, inherited: dict, ctm, depth: int): + for ch in node: + tag = _local(ch.tag) if isinstance(ch.tag, str) else "" + if not tag or tag in NONPAINT: + continue + own = _style(ch) + if own.get("display") == "none": + continue + st = {k: v for k, v in inherited.items() if k in INHERITED} + st.update(own) + m = _affine_mul(ctm, _parse_transform(ch.get("transform"))) + if tag in ("g", "svg", "a", "switch"): + walk(ch, st, m, depth) + elif tag == "use" and depth < 4: + href = ch.get("{http://www.w3.org/1999/xlink}href") or ch.get("href") or "" + ref = ids.get(href[1:]) if href.startswith("#") else None + if ref is not None: + mu = _affine_mul(m, (1.0, 0.0, 0.0, 1.0, _num(ch, "x"), _num(ch, "y"))) + holder = ET.Element("g") + holder.append(ref) + walk(holder, st, mu, depth + 1) + elif tag in ("path", "rect", "circle", "ellipse", "line", "polyline", "polygon"): + element(tag, ch, st, m) + + def element(tag, el, st, ctm): + b = _Builder(ctm) + if tag == "path": + _path(b, el.get("d") or "") + elif tag == "rect": + rxa, rya = el.get("rx"), el.get("ry") + rx = _num(el, "rx") if rxa is not None else (_num(el, "ry") if rya is not None else 0.0) + ry = _num(el, "ry") if rya is not None else rx + _rect(b, _num(el, "x"), _num(el, "y"), _num(el, "width"), _num(el, "height"), rx, ry) + elif tag == "circle": + r = _num(el, "r") + _ellipse(b, _num(el, "cx"), _num(el, "cy"), r, r) + elif tag == "ellipse": + _ellipse(b, _num(el, "cx"), _num(el, "cy"), _num(el, "rx"), _num(el, "ry")) + elif tag == "line": + b.start() + b.add("L", [(_num(el, "x1"), _num(el, "y1")), (_num(el, "x2"), _num(el, "y2"))]) + b.end_sub(False) + else: + v = [float(t) for t in NUM.findall(el.get("points") or "")] + pts = list(zip(v[0::2], v[1::2])) + if len(pts) >= 2: + b.start() + for p, q in pairwise(pts): + b.add("L", [p, q]) + if tag == "polygon" and pts[-1] != pts[0]: + b.add("L", [pts[-1], pts[0]]) + b.end_sub(tag == "polygon") + if not b.subs: + return + filled, fc = paint(st.get("fill", "black"), st) + stroke_w = st.get("stroke-width", "1") + m = NUM.match(stroke_w or "") + sw = float(m.group(0)) if m else 1.0 + stroked, sc = paint(st.get("stroke"), st) + stroked = stroked and sw > 0 + if not filled and not stroked: + return + out.append(Elem(tag, b.subs, filled, stroked, st.get("fill-rule", "") == "evenodd", + (fc if filled else []) + (sc if stroked else []), + sw * b.scale if stroked else 0.0)) + + walk(root, _style(root), base, 0) + return Doc(out, (fx, fy, fs)) + + +# --------------------------------------------------------------------------- per-segment +def _unit(v): + n = math.hypot(v[0], v[1]) + return (v[0] / n, v[1] / n) if n > 1e-15 else None + + +def _sub(p, q): + return (q[0] - p[0], q[1] - p[1]) + + +def _tangents(s: Seg): + """Unit tangents at the segment's start and end (None when it has no direction).""" + if s.kind == "A": + a = s.arc + return _unit(_arc_tangent(a, a[5])), _unit(_arc_tangent(a, a[5] + a[6])) + pts = s.pts + p0, p1 = pts[0], pts[-1] + t0 = next((u for u in (_unit(_sub(p0, q)) for q in pts[1:]) if u), None) + t1 = next((u for u in (_unit(_sub(q, p1)) for q in reversed(pts[:-1])) if u), None) + return t0, t1 + + +def _turn(u, v) -> float: + """Unsigned angle between two unit directions, degrees.""" + return abs(math.degrees(math.atan2(u[0] * v[1] - u[1] * v[0], u[0] * v[0] + u[1] * v[1]))) + + +def _axis_dev(u) -> float: + a = math.degrees(math.atan2(u[1], u[0])) % 90.0 + return min(a, 90.0 - a) + + +def _length(s: Seg) -> float: + pts = s.pts + if s.kind == "L": + return math.dist(pts[0], pts[1]) + if s.kind == "A": + a = s.arc + n = max(2, int(abs(a[6]) / (math.pi / 8)) + 1) + q = [_arc_point(a, a[5] + a[6] * i / n) for i in range(n + 1)] + return sum(math.dist(u, v) for u, v in pairwise(q)) + chord = math.dist(pts[0], pts[-1]) + poly = sum(math.dist(u, v) for u, v in pairwise(pts)) + return (chord + poly) / 2 + + +def _sweep(s: Seg) -> float: + """A curve's own turning, degrees: an arc's angle, a cubic's or quadratic's + control-polygon turning.""" + if s.kind == "A": + return abs(math.degrees(s.arc[6])) + q = [s.pts[0]] + for p in s.pts[1:]: + if math.dist(p, q[-1]) > 1e-15: + q.append(p) + dirs = [_unit(_sub(u, v)) for u, v in pairwise(q)] + return sum(_turn(u, v) for u, v in pairwise(dirs)) + + +def _flatten(sub: Sub) -> np.ndarray: + pts = [sub.segs[0].p0] + for s in sub.segs: + if s.kind == "L": + pts.append(s.p1) + elif s.kind == "A": + a = s.arc + pts += [_arc_point(a, a[5] + a[6] * i / 6) for i in range(1, 7)] + else: + p = np.asarray(s.pts) + t = np.linspace(1 / 6, 1, 6)[:, None] + if s.kind == "C": + b = ((1 - t) ** 3) * p[0] + 3 * ((1 - t) ** 2) * t * p[1] + 3 * (1 - t) * t * t * p[2] + t ** 3 * p[3] + else: + b = ((1 - t) ** 2) * p[0] + 2 * (1 - t) * t * p[1] + t * t * p[2] + pts += [tuple(r) for r in b] + return np.asarray(pts, dtype=np.float64) + + +def _inside(pts: np.ndarray, ring: np.ndarray) -> np.ndarray: + """Even-odd point-in-polygon of each row of `pts` against the closed `ring`.""" + x, y = pts[:, 0:1], pts[:, 1:2] + x0, y0 = ring[:, 0][None, :], ring[:, 1][None, :] + x1, y1 = np.roll(ring[:, 0], -1)[None, :], np.roll(ring[:, 1], -1)[None, :] + cond = (y0 > y) != (y1 > y) + with np.errstate(divide="ignore", invalid="ignore"): + xc = x0 + (y - y0) * (x1 - x0) / (y1 - y0) + return (np.count_nonzero(cond & (x < xc), axis=1) % 2) == 1 + + +def _ties(values: list[float]) -> float: + """Share of `values` another one repeats (within `TIE_TOL`); NaN for fewer than two.""" + if len(values) < 2: + return float("nan") + v = np.sort(np.asarray(values, dtype=np.float64)) + close = np.diff(v) <= TIE_TOL + tied = np.zeros(v.size, dtype=bool) + tied[1:] |= close + tied[:-1] |= close + return float(tied.mean()) + + +def _gini(x: np.ndarray) -> float: + if x.size == 0 or x.sum() <= 0: + return float("nan") + s = np.sort(x) + n = s.size + return float((2 * np.arange(1, n + 1) - n - 1) @ s / (n * s.sum())) + + +def _lab(rgbs: list) -> np.ndarray: + if not rgbs: + return np.zeros((0, 3)) + from skimage.color import rgb2lab + return rgb2lab(np.asarray(rgbs, dtype=np.float64).reshape(-1, 1, 3)).reshape(-1, 3) + + +# --------------------------------------------------------------------------- profile +def _share(num: int, den: int) -> float: + return num / den if den else float("nan") + + +def profile(svg: str, grid: tuple[float, float, float] | None = None, + tol: float | None = None, raster_px: int | None = None) -> dict: + """Every statistic of `svg`, as a dict: scalars, and for the distribution statistics + the sample (a list). `grid` is the artist's frame (origin x, origin y, side, in the + artist's units) that the grid statistics are read in; None reads the file in its own + units, exactly (the artist's file). `tol` is the grid tolerance in artist units. + `raster_px` is the side of the raster the canvas is drawn on, for `halfpx` (NaN + without it).""" + doc = parse(svg) + grid = doc.frame if grid is None else grid + tol = EXACT_TOL if tol is None else tol + els = doc.elements + page = bool(els) and _is_page(els[0]) + if page: + els = els[1:] + n_seg = {"L": 0, "C": 0, "Q": 0, "A": 0} + lines = l_axis = l_diag = 0 + handles = h_axis = 0 + curved_joins = smooth = smooth_ext = 0 + cc_joins = cc_kink = 0 + ll_joins = ll_coll = 0 + joins = corners = right = 0 + corner_angles: list[float] = [] + sweeps: list[float] = [] + wide = 0 + handle_len: list[float] = [] + sym_joins = sym_ok = 0 + lengths: list[float] = [] + nodes: list[tuple[float, float]] = [] + n_sub = closed = 0 + for e in els: + for sub in e.subs: + segs = [(s, _length(s)) for s in sub.segs] + segs = [(s, L) for s, L in segs if L >= DOT] + if not segs: + continue + n_sub += 1 + closed += sub.closed + info = [] + for s, L in segs: + n_seg[s.kind] += 1 + lengths.append(L) + t0, t1 = _tangents(s) + info.append((s, t0, t1)) + nodes.append(s.p0) + if s.kind == "L": + lines += 1 + if t0 is not None: + dev = _axis_dev(t0) + l_axis += dev <= AXIS_DEG + l_diag += abs(dev - 45.0) <= AXIS_DEG + else: + sw = _sweep(s) + sweeps.append(sw) + wide += sw > WIDE_DEG + if s.kind == "C": + chord = math.dist(s.p0, s.p1) + for p, q in ((s.pts[0], s.pts[1]), (s.pts[3], s.pts[2])): + v = _sub(p, q) + hl = math.hypot(*v) + if hl > 1e-12: + handles += 1 + h_axis += _axis_dev((v[0] / hl, v[1] / hl)) <= AXIS_DEG + if chord > 1e-12: + handle_len.append(hl / chord) + if not sub.closed: + nodes.append(segs[-1][0].p1) + pairs = list(pairwise(info)) + if sub.closed and len(info) > 1: + pairs.append((info[-1], info[0])) + for (sa, _, ta), (sb, tb, _) in pairs: + if ta is None or tb is None: + continue + joins += 1 + t = _turn(ta, tb) + ca, cb = sa.kind != "L", sb.kind != "L" + if t > CORNER_DEG: + corners += 1 + corner_angles.append(t) + right += abs(t - 90.0) <= RIGHT_DEG + if ca or cb: + curved_joins += 1 + if t <= SMOOTH_DEG: + smooth += 1 + smooth_ext += _axis_dev(tb) <= EXTREMUM_DEG + if ca and cb: + cc_joins += 1 + cc_kink += SMOOTH_DEG < t <= CORNER_DEG + if sa.kind == "C" and sb.kind == "C" and t <= SMOOTH_DEG: + h_in = math.dist(sa.pts[2], sa.pts[3]) + h_out = math.dist(sb.pts[0], sb.pts[1]) + if h_in > 1e-12 and h_out > 1e-12: + sym_joins += 1 + sym_ok += abs(math.log(h_in / h_out)) <= math.log(1.05) + if not ca and not cb: + ll_joins += 1 + ll_coll += t <= AXIS_DEG + n_all = sum(n_seg.values()) + p: dict = { + "kinds": [n_seg[k] / n_all for k in "LCQA"] if n_all else None, + "primitives": _share(sum(e.tag in PRIMITIVE_TAGS for e in els), len(els)), + "stroked": _share(sum(e.stroked for e in els), len(els)), + "stroke_width_ties": _ties([e.stroke_width for e in els if e.stroked]), + "elements": len(els), + "subpaths": n_sub, + "nodes_per_subpath": len(nodes) / n_sub if n_sub else float("nan"), + "closed": _share(closed, n_sub), + "line_axis": _share(l_axis, lines), + "line_diag": _share(l_diag, lines), + "handle_axis": _share(h_axis, handles), + "smooth": _share(smooth, curved_joins), + "extremum": _share(smooth_ext, smooth), + "kinked": _share(cc_kink, cc_joins), + "collinear": _share(ll_coll, ll_joins), + "corner_share": _share(corners, joins), + "right_angle": _share(right, corners), + "corner_angles": corner_angles, + "sweep": sweeps, + "wide_curves": _share(wide, len(sweeps)), + "handle_length": handle_len, + "symmetric_handles": _share(sym_ok, sym_joins), + "segment_lengths": [math.log10(x) for x in lengths if x > 0], + "length_gini": _gini(np.asarray(lengths)), + } + p.update(_numbers(nodes, grid, tol)) + p["halfpx"] = _halfpx(nodes, raster_px) + p.update(_paint_and_layers(els)) + p["page"] = page + return p + + +#: A first element filled in white (every channel at least this) and spanning this share of +#: the canvas both ways is the page an opaque input was traced on, not part of the drawing. +PAGE_WHITE = 0.94 +PAGE_SPAN = 0.98 + + +def _is_page(e: Elem) -> bool: + if not e.filled or e.stroked or not e.colours: + return False + if any(min(c) < PAGE_WHITE for c in e.colours): + return False + pts = np.asarray([p for s in e.subs for seg in s.segs for p in seg.pts]) + if pts.size == 0: + return False + span = pts.max(0) - pts.min(0) + return bool(np.all(span >= PAGE_SPAN)) + + +def _halfpx(nodes, raster_px: int | None) -> float: + """Share of node coordinates on the raster's half-pixel grid (pixel edges and centres), + within `GRID_TOL_PX`, the canvas drawn on a `raster_px` raster.""" + if not nodes or not raster_px: + return float("nan") + v = np.asarray(nodes, dtype=np.float64).reshape(-1) * raster_px * 2 + return float((np.abs(v - np.round(v)) / 2 <= GRID_TOL_PX).mean()) + + +def _numbers(nodes, grid, tol) -> dict: + """The grid, decimals, ties and mirror statistics of the nodes (canvas units); `grid` is + the frame the grid is read in, `tol` its tolerance in that frame's units.""" + if not nodes: + return {"grid_half": float("nan"), "grid_int": float("nan"), "grid_level": float("nan"), + "decimals": float("nan"), "ties": float("nan"), "mirror": float("nan")} + xy = np.asarray(nodes, dtype=np.float64) + gx, gy, gs = grid + units = np.concatenate([gx + xy[:, 0] * gs, gy + xy[:, 1] * gs]) + + def on(k: float) -> np.ndarray: + v = units * k + return np.abs(v - np.round(v)) <= tol * k + + level = len(GRID_LADDER) + for i, k in enumerate(GRID_LADDER): + if on(k).mean() >= GRID_LEVEL_SHARE: + level = i + break + dec = np.full(units.shape, 4.0) + for d in (3, 2, 1, 0): + dec[on(10.0 ** d)] = d + ties = 0 + for col in (xy[:, 0], xy[:, 1]): + s = np.sort(col) + close = np.diff(s) <= TIE_TOL + tied = np.zeros(s.size, dtype=bool) + tied[1:] |= close + tied[:-1] |= close + ties += int(tied.sum()) + from scipy.spatial import cKDTree + tree = cKDTree(xy) + lo, hi = xy.min(0), xy.max(0) + best = 0.0 + for axis in (0, 1): + m = xy.copy() + m[:, axis] = lo[axis] + hi[axis] - m[:, axis] + d, _ = tree.query(m, k=1) + best = max(best, float((d <= MIRROR_TOL).mean())) + return {"grid_half": float(on(2).mean()), "grid_int": float(on(1).mean()), + "grid_level": float(level), "decimals": float(dec.mean()), + "ties": ties / (2 * len(xy)), "mirror": best} + + +def _paint_and_layers(els: list[Elem]) -> dict: + cols = {tuple(round(c * 255) for c in rgb) for e in els for rgb in e.colours} + filled = [e for e in els if e.filled] + rings_of: list[list[tuple[np.ndarray, bool]]] = [] + for e in filled: + rings = [] + for s in e.subs: + r = _flatten(s) + if len(r) >= 3: + rings.append((r, s.closed)) + rings_of.append(rings) + # nested: a closed subpath inside another subpath of the same element (its first point + # inside the other's outline, and its box inside the other's box) + n_closed = n_nested = 0 + for rings in rings_of: + n_closed += sum(c for _, c in rings) + if len(rings) < 2: + continue + firsts = np.asarray([r[0] for r, _ in rings]) + lo = np.asarray([r.min(0) for r, _ in rings]) + hi = np.asarray([r.max(0) for r, _ in rings]) + nested = np.zeros(len(rings), dtype=bool) + for i, (ri, _) in enumerate(rings): + inside = _inside(firsts, ri) & np.all(lo >= lo[i], axis=1) & np.all(hi <= hi[i], axis=1) + inside[i] = False + nested |= inside + n_nested += int(sum(n and c for n, (_, c) in zip(nested, rings))) + # stacked: an interior point of the element (its largest outline's vertex mean, when that + # is inside the element) lies inside an earlier filled element (even-odd) + probes = np.full((len(rings_of), 2), np.nan) + for j, rings in enumerate(rings_of): + if rings: + big = max((r for r, _ in rings), key=lambda r: float(np.ptp(r[:, 0]) * np.ptp(r[:, 1]))) + c = big.mean(0, keepdims=True) + if sum(bool(_inside(c, r)[0]) for r, _ in rings) % 2 == 1: + probes[j] = c[0] + has = np.isfinite(probes[:, 0]) + over = np.zeros(len(rings_of), dtype=bool) + for i, rings in enumerate(rings_of[:-1]): + later = np.flatnonzero(has[i + 1:]) + i + 1 + if not rings or later.size == 0: + continue + parity = np.zeros(later.size, dtype=bool) + for r, _ in rings: + parity ^= _inside(probes[later], r) + over[later[parity]] = True + stacked, counted = int(over[has].sum()), int(has.sum()) + return {"colours": len(cols), "palette": [list(c) for c in sorted(cols)], + "nested": _share(n_nested, n_closed), + "stacked": _share(stacked, counted), + "evenodd": _share(sum(e.evenodd for e in filled), len(filled))} + + +# --------------------------------------------------------------------------- divergence +#: How each statistic's divergence is taken (module documentation). +SHARE = "share" +COUNT = "count" +DIST = "dist" +MIX = "mix" +PALETTE = "palette" +STATS: dict[str, tuple[str, float]] = { + # name: (kind, scale). The order is the pruning's priority (`KEPT`): where two carry one + # signal the earlier stays, so the node conventions `--editability` works on come first, + # then the numbers, the pieces and the paint. + "kinds": (MIX, 1.0), + "smooth": (SHARE, 1.0), + "extremum": (SHARE, 1.0), + "handle_axis": (SHARE, 1.0), + "kinked": (SHARE, 1.0), + "corner_share": (SHARE, 1.0), + "right_angle": (SHARE, 1.0), + "corner_angles": (DIST, 180.0), + "line_axis": (SHARE, 1.0), + "line_diag": (SHARE, 1.0), + "collinear": (SHARE, 1.0), + "sweep": (DIST, 180.0), + "wide_curves": (SHARE, 1.0), + "handle_length": (DIST, 1.0), + "symmetric_handles": (SHARE, 1.0), + "grid_half": (SHARE, 1.0), + "grid_int": (SHARE, 1.0), + "grid_level": (SHARE, 5.0), + "decimals": (SHARE, 4.0), + "ties": (SHARE, 1.0), + "mirror": (SHARE, 1.0), + "primitives": (SHARE, 1.0), + "stroked": (SHARE, 1.0), + "stroke_width_ties": (SHARE, 1.0), + "elements": (COUNT, 1.0), + "subpaths": (COUNT, 1.0), + "nodes_per_subpath": (COUNT, 1.0), + "closed": (SHARE, 1.0), + "segment_lengths": (DIST, 1.0), + "length_gini": (SHARE, 1.0), + "colours": (COUNT, 1.0), + "palette": (PALETTE, 1.0), + "nested": (SHARE, 1.0), + "stacked": (SHARE, 1.0), + "evenodd": (SHARE, 1.0), + "halfpx": (SHARE, 1.0), +} +#: Statistics that flag a tracer's artefact rather than a way of drawing: reported with the +#: others, left out of the human-closeness composite (`bench/human_stats.py`). +ARTEFACTS = ("halfpx",) + + +def _w1(a, b) -> float: + """Wasserstein-1 distance between two empirical distributions on the line.""" + a, b = np.sort(np.asarray(a, dtype=np.float64)), np.sort(np.asarray(b, dtype=np.float64)) + if a.size == 0 or b.size == 0: + return float("nan") + allv = np.concatenate([a, b]) + allv.sort(kind="mergesort") + d = np.diff(allv) + fa = np.searchsorted(a, allv[:-1], side="right") / a.size + fb = np.searchsorted(b, allv[:-1], side="right") / b.size + return float(np.sum(np.abs(fa - fb) * d)) + + +def _palette_distance(a: list, b: list) -> float: + if not a or not b: + return float("nan") + la, lb = _lab([[c / 255 for c in x] for x in a]), _lab([[c / 255 for c in x] for x in b]) + d = np.sqrt(((la[:, None, :] - lb[None, :, :]) ** 2).sum(-1)) + return float((d.min(1).mean() + d.min(0).mean()) / 2) + + +def _nan(x) -> bool: + return x is None or (isinstance(x, float) and math.isnan(x)) + + +def divergence(trace: dict, artist: dict) -> dict[str, float]: + """Per statistic, how far `trace`'s value is from `artist`'s (module documentation); + NaN where either has no value.""" + out = {} + for name, (kind, scale) in STATS.items(): + t, a = trace.get(name), artist.get(name) + if kind == PALETTE: + out[name] = _palette_distance(t or [], a or []) + elif kind == MIX: + out[name] = float("nan") if t is None or a is None else \ + 0.5 * sum(abs(x - y) for x, y in zip(t, a)) + elif kind == DIST: + out[name] = _w1(t or [], a or []) / scale + elif _nan(t) or _nan(a): + out[name] = float("nan") + elif kind == COUNT: + out[name] = abs(math.log((t + 0.5) / (a + 0.5)) if min(t, a) <= 0 else math.log(t / a)) + else: + out[name] = abs(t - a) / scale + return out + + +def summary_value(name: str, value) -> float: + """One number for a statistic's value in a file, for tables: the value itself, a + distribution's median, the mix's share of lines, a palette's size.""" + kind = STATS[name][0] + if value is None: + return float("nan") + if kind == DIST: + return float(np.median(value)) if len(value) else float("nan") + if kind == MIX: + return float(value[1]) # the share of cubics + if kind == PALETTE: + return float(len(value)) + return float(value) + + +def artist_grid(artist_svg: str) -> tuple[float, float, float]: + """The artist's frame, read once: where its grid is.""" + return frame_of(ET.fromstring(artist_svg)) + + +def trace_tolerance(artist_svg: str, raster_px: int) -> float: + """`GRID_TOL_PX` raster px in the artist's units.""" + return GRID_TOL_PX * artist_grid(artist_svg)[2] / max(1, raster_px) + + +def compare(trace_svg: str, artist_svg: str, raster_px: int, artist: dict | None = None) -> dict: + """{"trace": profile, "artist": profile, "div": divergences} of one icon; pass the + artist's profile when it is already known.""" + if artist is None: + artist = profile(artist_svg, raster_px=raster_px) + t = profile(trace_svg, artist_grid(artist_svg), trace_tolerance(artist_svg, raster_px), + raster_px) + return {"trace": t, "artist": artist, "div": divergence(t, artist)} + + +#: Candidates the battery does not report, and why. Pruned on the Spearman correlation of the +#: per-icon divergences over the 246 screen icons, quality-512ssop and quality-web pooled +#: (`bench/human_stats.py --correlate`, 2026-10-10): a candidate correlated beyond |rho| 0.7 +#: with one kept before it in `STATS` order carries no signal of its own. +DROPPED = { + "wide_curves": "rho +0.72 with sweep (a curve turning over 100 degrees is the sweep's tail)", + "grid_int": "rho +0.98 with grid_half (the whole-unit grid is inside the half-unit one)", + "grid_level": "rho +0.72 with grid_half", + "decimals": "rho +0.74 with grid_half", + "length_gini": "rho +0.79 with segment_lengths (the spread is part of the distribution)", + "palette": "rho +0.84 with colours", + "evenodd": "nonzero on 6 of 616 icon-conditions: neither the tracer nor the artists use it", +} +#: The statistics the battery reports: `STATS` less `DROPPED`. Every gate axis stays below +#: |rho| 0.57 with each of them (largest: colours with de00, 0.56; smooth with geom, 0.54). +KEPT: tuple[str, ...] = tuple(s for s in STATS if s not in DROPPED) diff --git a/bench/inkvec_bench/geomatch.py b/bench/inkvec_bench/geomatch.py new file mode 100644 index 00000000..58430742 --- /dev/null +++ b/bench/inkvec_bench/geomatch.py @@ -0,0 +1,269 @@ +"""Geometric match to the artist's file: how far the trace's edges are from the artist's. + +dE00 asks whether two renders *look* alike, pixel by pixel; a boundary 0.1 px off along a +black-on-white edge and a slightly wrong fill colour can cost it the same. This asks the +geometric question directly: paint both files flat (no anti-aliasing), give every pixel the +artist's colour it shows, and measure the area where the two disagree. Divided by the length +of the artist's own boundaries, that area is the **mean edge displacement**: the average +distance, in pixels of the traced raster, between where the trace puts an edge and where +the artist did. A trace whose every edge is moved out by `δ` reads `δ` (the area between two +curves `δ` apart is `δ` times their length), whatever the colours, which is what makes it a +calibrated measure of "the same design" rather than of "a similar picture". + +* `geom` the mean edge displacement, source px: the mismatched area over the artist's + boundary length. +* `geom_far` the part of it farther than one source pixel (city-block) from any artist + edge, in the same units: missing or extra features, wrong colours over whole + regions, rather than edges a little off. + +Both read 0 for the artist's own file. Each pixel takes the nearest of the artist's colours +(in CIELAB, with alpha as a fourth coordinate, so a transparent hole is its own colour); +shaded art with more than `MAX_COLOURS` colours has them clustered first, so a gradient is +compared as a few bands rather than as noise. Both files are drawn by the +gate's own renderer and viewBox fitting, at `RES` times the input's size, so they share +one frame. + +The boundary length is the four-direction Cauchy-Crofton estimate from the artist's label +map: a curve of length `L` crosses the rows, columns and two diagonals `∫(|sin θ| + |cos θ| ++ |sin(θ − 45°)| + |cos(θ − 45°)|) ds` times in all (diagonals counted at their spacing +`1/√2`), which averages `8/π` per unit length; within 5 % for any direction. + +Method from: the symmetric difference of two regions as their distance (the area +difference metric of shape matching; e.g. Veltkamp, Hagedoorn (2001), State of the art in +shape matching, Principles of Visual Information Retrieval, Springer, doi:10.1007/978-1-4471-3702-3_4); +the length estimate from Cauchy-Crofton (Santaló 1976, Integral Geometry and Geometric +Probability). Not from the literature: area over length as a calibrated mean displacement +between a vector truth and a vector trace. +""" + +from __future__ import annotations + +import hashlib +import os +import re +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +#: Render pixels per pixel of the input raster: the flat renders are `RES` times the input's +#: size (2048 px for a 512 px input). The area is point-sampled, so it is unbiased at any +#: size and this sets only its noise. +RES = 4 +#: More distinct artist colours than this are clustered (shaded emoji). +MAX_COLOURS = 48 +#: Alpha's weight beside CIELAB (0-100) when matching colours. +ALPHA_WEIGHT = 100.0 + + +def _crisp(svg: str) -> str: + """`svg` drawn without anti-aliasing: `shape-rendering="crispEdges"` on its root.""" + return re.sub(r" np.ndarray: + """`svg` drawn without anti-aliasing at `size` px, as 8-bit RGBA, in the gate's frame + (`render.fit_viewbox`).""" + import io + from PIL import Image + from inkvec_bench import render + png = render.render_to_png(_crisp(svg), size, size) + img = Image.open(io.BytesIO(png)).convert("RGBA") + if img.size != (size, size): + img = img.resize((size, size), Image.NEAREST) + return np.asarray(img, dtype=np.uint8) + + +def _codes(rgba: np.ndarray, opaque: bool) -> np.ndarray: + """Per pixel, its 8-bit RGBA packed in one integer (over white, opaque, when the + input was flattened onto a white page). + + Over white, each channel is `(c a + 255 (255 - a) + 127) // 255`. That is `c` itself + where `a` is 255 and 255 where `a` is 0, so only the partly covered pixels (few, in a + render without anti-aliasing) are computed; the packing reads the four bytes as one + big-endian word. Both give the same integers as the arithmetic on every pixel.""" + u = np.ascontiguousarray(rgba, dtype=np.uint8) + if opaque: + a = u[..., 3] + part = (a != 0) & (a != 255) + u = u.copy() + u[a == 0] = 255 + if part.any(): + p = u[part].astype(np.uint32) + pa = p[:, 3:4] + p[:, :3] = (p[:, :3] * pa + 255 * (255 - pa) + 127) // 255 + u[part] = p.astype(np.uint8) + u[..., 3] = 255 + return u.view(">u4")[..., 0].astype(np.uint32) + + +def _features(codes: np.ndarray) -> np.ndarray: + """CIELAB of each packed colour over white, and its alpha scaled to match.""" + from skimage.color import rgb2lab + c = codes.astype(np.uint64) + rgba = np.stack([(c >> 24) & 255, (c >> 16) & 255, (c >> 8) & 255, c & 255], -1) / 255.0 + a = rgba[:, 3:4] + rgb = rgba[:, :3] * a + (1.0 - a) + lab = rgb2lab(np.clip(rgb, 0, 1)[:, None, :])[:, 0, :] + return np.concatenate([lab, ALPHA_WEIGHT * a], axis=-1) + + +def _palette(feat: np.ndarray, counts: np.ndarray) -> np.ndarray: + """The artist's colours (`feat`, one row per distinct colour, `counts` pixels each): + all of them, or `MAX_COLOURS` clusters (weighted k-means, seeded with the most + frequent colours, fixed iterations).""" + if len(feat) <= MAX_COLOURS: + return feat + order = np.argsort(-counts, kind="stable") + centres = feat[order[:MAX_COLOURS]].copy() + w = counts.astype(np.float64) + for _ in range(12): + lab = ((feat[:, None, :] - centres[None, :, :]) ** 2).sum(-1).argmin(1) + for k in range(len(centres)): + m = lab == k + if m.any(): + centres[k] = (feat[m] * w[m, None]).sum(0) / w[m].sum() + return centres + + +def _labels(codes: np.ndarray, palette: np.ndarray) -> np.ndarray: + """Index of the nearest palette colour per pixel. + + Read run by run along the rows: a flat render is long runs of one colour, so the + distinct colours and their nearest palette entries are found from the runs' values + (a few thousand, not millions) and spread back over the runs. The same distinct colours + in the same sorted order as `np.unique` of every pixel, so the same labels.""" + flat = codes.reshape(-1) + if flat.size == 0: + return np.zeros(codes.shape, dtype=np.intp) + starts = np.flatnonzero(flat[1:] != flat[:-1]) + 1 + starts = np.concatenate(([0], starts)) + uniq, inv = np.unique(flat[starts], return_inverse=True) + d = ((_features(uniq)[:, None, :] - palette[None, :, :]) ** 2).sum(-1) + per_run = d.argmin(1)[inv.reshape(-1)] + runs = np.diff(np.append(starts, flat.size)) + return np.repeat(per_run, runs).reshape(codes.shape) + + +def boundary_length(lab: np.ndarray) -> float: + """Four-direction Cauchy-Crofton length of the label map's boundaries, render px.""" + n_h = np.count_nonzero(lab[:, 1:] != lab[:, :-1]) + n_v = np.count_nonzero(lab[1:, :] != lab[:-1, :]) + n_d = np.count_nonzero(lab[1:, 1:] != lab[:-1, :-1]) + n_a = np.count_nonzero(lab[1:, :-1] != lab[:-1, 1:]) + return float(np.pi / 8.0 * (n_h + n_v + (n_d + n_a) / np.sqrt(2.0))) + + +@dataclass(frozen=True) +class ArtistSide: + """Everything `geomatch` reads from the artist's file at one size: a function of the + file's bytes, the size and the page (over white or not), so kept between runs.""" + + labels: np.ndarray # nearest-palette index per render pixel + palette: np.ndarray # the artist's colours (`_palette`), one row each + length: float # boundary length of `labels`, render px (`boundary_length`) + near: np.ndarray # within one source pixel (city-block, RES render px) of an edge + + +#: Where `artist_side` keeps its results between runs (None: recomputed every time). +#: `svgeval` points it at its cache. Entries are keyed by everything that changes them. +CACHE_DIR: Path | None = None +#: Bumped whenever an entry's meaning changes. +CACHE_FORMAT = 1 + + +def _cache_key(artist: str, size: int, opaque: bool) -> str: + """Hash of the artist's bytes and everything else an `ArtistSide` depends on: the size, + the page, this module's constants, the renderer and the libraries that do the + arithmetic.""" + import importlib.metadata as md + + import skimage + try: + resvg = md.version("resvg_py") + except md.PackageNotFoundError: + resvg = "?" + h = hashlib.sha256(artist.encode("utf-8")) + h.update(f"|{size}|{int(opaque)}|{RES}|{MAX_COLOURS}|{ALPHA_WEIGHT}|{CACHE_FORMAT}" + f"|resvg {resvg}|numpy {np.__version__}|skimage {skimage.__version__}".encode()) + return h.hexdigest()[:32] + + +def _compute_artist_side(artist: str, size: int, opaque: bool) -> ArtistSide: + from scipy import ndimage + ca = _codes(_flat(artist, size), opaque) + uniq, counts = np.unique(ca.reshape(-1), return_counts=True) + pal = _palette(_features(uniq), counts) + la = _labels(ca, pal) + edges = np.zeros(la.shape, dtype=bool) + edges[:, 1:] |= la[:, 1:] != la[:, :-1] + edges[1:, :] |= la[1:, :] != la[:-1, :] + # Within one source pixel of an artist edge (city-block distance): RES steps. + near = ndimage.binary_dilation(edges, iterations=RES) + return ArtistSide(la.astype(np.uint8), pal, boundary_length(la), near) + + +def artist_side(artist: str, size: int, opaque: bool) -> ArtistSide: + """The artist's side of `geomatch` at `size` px, from `CACHE_DIR` when it holds it. + + An entry stores the labels and the near-edge mask losslessly (the labels fit a byte: + `MAX_COLOURS` < 256) and the palette as float64, so a hit gives the same numbers as + computing it. The write is atomic: pool workers may miss on the same file at once.""" + path = CACHE_DIR / f"{_cache_key(artist, size, opaque)}.npz" if CACHE_DIR else None + if path is not None and path.exists(): + try: + with np.load(path) as z: + near = np.unpackbits(z["near"], count=size * size).reshape(size, size) + return ArtistSide(z["labels"], z["palette"], float(z["length"]), near.astype(bool)) + except Exception: # noqa: BLE001 - a damaged entry is recomputed and replaced + path.unlink(missing_ok=True) + side = _compute_artist_side(artist, size, opaque) + if path is not None: + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(f"{path.stem}.{os.getpid()}.tmp.npz") + np.savez_compressed(tmp, labels=side.labels, palette=side.palette, + length=np.float64(side.length), near=np.packbits(side.near)) + try: + os.replace(tmp, path) + except OSError: + tmp.unlink(missing_ok=True) + return side + + +def geomatch(ours: str, artist: str, src_px: int, opaque: bool = False) -> dict: + """`geom` and `geom_far` (module documentation) of the trace `ours` against `artist`, + both SVG text, for an input raster `src_px` pixels across.""" + size = RES * src_px + art = artist_side(artist, size, opaque) + if art.length <= 0: + return {"geom": 0.0, "geom_far": 0.0} + lb = _labels(_codes(_flat(ours, size), opaque), art.palette) + scale = src_px / size # source px per render px + miss = art.labels != lb + area = float(np.count_nonzero(miss)) + far = float(np.count_nonzero(miss & ~art.near)) + # Area in source px² over length in source px: source px. + return {"geom": area * scale * scale / (art.length * scale), + "geom_far": far * scale * scale / (art.length * scale)} + + +def _self_check() -> None: + """A disc against itself reads 0; against the disc `δ` larger, `δ` (to the estimate's + few per cent).""" + disc = ('' + '' + '') + base = disc.format(r=7.0) + assert geomatch(base, base, 512)["geom"] == 0.0 + for delta in (0.05, 0.25, 1.0): + r = 7.0 + delta * 24 / 512 # delta source px at 512 px + g = geomatch(disc.format(r=r), base, 512)["geom"] + # The disc's share of the boundary, against the rectangle's unmoved edges. + disc_len, rect_len = 2 * np.pi * 7.0, 20.0 + want = delta * disc_len / (disc_len + rect_len) + assert abs(g - want) < 0.06 * want + 0.004, (delta, g, want) + + +if __name__ == "__main__": + _self_check() + print("geomatch self-check passed") diff --git a/bench/inkvec_bench/metrics/color.py b/bench/inkvec_bench/metrics/color.py index 3aae5759..a454c98e 100644 --- a/bench/inkvec_bench/metrics/color.py +++ b/bench/inkvec_bench/metrics/color.py @@ -11,6 +11,8 @@ """ from __future__ import annotations +from functools import lru_cache + import numpy as np from skimage.color import deltaE_ciede2000, rgb2lab @@ -21,8 +23,21 @@ MAX_DELTA_E_SAMPLES = 250_000 +@lru_cache(maxsize=4) +def _sample(n: int, k: int) -> np.ndarray: + """The `k` of `n` pixels `delta_e00` reads: always the same ones for the same `n`.""" + idx = np.random.default_rng(0).choice(n, k, replace=False) + idx.flags.writeable = False + return idx + + def delta_e00(a_rgb: np.ndarray, b_rgb: np.ndarray, mask: np.ndarray | None = None) -> dict[str, float]: - """CIEDE2000 between two RGB images in [0, 1], optionally restricted to a mask.""" + """CIEDE2000 between two RGB images in [0, 1], optionally restricted to a mask. + + Only the sampled pixels whose colours differ are converted and compared: a pixel the + same in both images has a CIEDE2000 of exactly 0 (the formula's every term is a + difference of equal numbers), and the conversion is per pixel, so the array of + differences, and every statistic of it, is the one the whole sample would give.""" a = np.clip(a_rgb, 0, 1).reshape(-1, 3) b = np.clip(b_rgb, 0, 1).reshape(-1, 3) if mask is not None: @@ -31,12 +46,17 @@ def delta_e00(a_rgb: np.ndarray, b_rgb: np.ndarray, mask: np.ndarray | None = No if a.shape[0] == 0: return {"de00_mean": float("nan"), "de00_p95": float("nan"), "de00_max": float("nan")} if a.shape[0] > MAX_DELTA_E_SAMPLES: - idx = np.random.default_rng(0).choice(a.shape[0], MAX_DELTA_E_SAMPLES, replace=False) + idx = _sample(a.shape[0], MAX_DELTA_E_SAMPLES) a, b = a[idx], b[idx] - lab_a = rgb2lab(a.reshape(-1, 1, 3)) - lab_b = rgb2lab(b.reshape(-1, 1, 3)) - de = deltaE_ciede2000(lab_a, lab_b).reshape(-1) + diff = np.flatnonzero((a != b).any(axis=1)) + # The dtype the whole sample's differences would have (skimage keeps float32 as float32). + probe = deltaE_ciede2000(rgb2lab(a[:1].reshape(-1, 1, 3)), rgb2lab(b[:1].reshape(-1, 1, 3))) + de = np.zeros(a.shape[0], dtype=probe.dtype) + if diff.size: + lab_a = rgb2lab(a[diff].reshape(-1, 1, 3)) + lab_b = rgb2lab(b[diff].reshape(-1, 1, 3)) + de[diff] = deltaE_ciede2000(lab_a, lab_b).reshape(-1) de = de[np.isfinite(de)] if de.size == 0: return {"de00_mean": float("nan"), "de00_p95": float("nan"), "de00_max": float("nan")} diff --git a/bench/quality_budget.json b/bench/quality_budget.json index 4bfe4ab3..bb56f30a 100644 --- a/bench/quality_budget.json +++ b/bench/quality_budget.json @@ -11,6 +11,7 @@ "circle_roundness", "disc_r3", "disc_r5", + "edge_axis", "edge_diag30", "junction_quad", "junction_tri", @@ -84,6 +85,7 @@ "coverage:inkvec-sr": 95, "coverage:inkvec-svgmin": 91, "coverage:inkvec-trace": 92, + "coverage:inkvec-verified": 97, "coverage:inkvec-wasm": 94, "debt_markers": 0, "env_reads": 12, @@ -102,7 +104,7 @@ "mutation:inkvec-trace/gradient": 67, "mutation:inkvec-trace/native": 68, "rustfmt_hunks": 0, - "test_functions": 1096, + "test_functions": 1214, "untested_modules": [ "crates/inkvec-cli/src/alpha.rs", "crates/inkvec-cli/src/rings.rs", diff --git a/bench/svgeval.py b/bench/svgeval.py index 354ba5fc..664bc8b6 100644 --- a/bench/svgeval.py +++ b/bench/svgeval.py @@ -262,11 +262,14 @@ def flatten_onto_white(src: Path, dst: Path) -> None: def item_paths(it: dict) -> tuple[Path, Path]: """The input raster at the current tier and the artist's SVG for one icon. - A committed raster wins. For an opaque tier (`op`) with no committed raster, the - base tier's raster is flattened onto white into the cache (`CACHE/raster//`) once, - and that file is the input.""" + A committed raster wins, PNG or (a tier stored as JPEG files: `web`) JPEG. For an opaque + tier (`op`) with no committed raster, the base tier's raster is flattened onto white + into the cache (`CACHE/raster//`) once, and that file is the input.""" t = tier() png = ROOT / "bench" / "data" / "corpus_raster" / it["corpus"] / t / f"{it['stem']}.png" + jpg = png.with_suffix(".jpg") + if not png.exists() and jpg.exists(): + png = jpg # a tier committed as JPEG files (`web`), traced as the tracer reads them gt = ROOT / "bench" / "data" / "corpus_svg" / it["corpus"] / f"{it['stem']}.svg" if not png.exists() and base_tier(t) != t: src = ROOT / "bench" / "data" / "corpus_raster" / it["corpus"] / base_tier(t) / f"{it['stem']}.png" @@ -422,10 +425,24 @@ class ImageScore: self_res: float = 0.0 turning: float = 0.0 mirror: float = 0.0 + # Geometric match to the artist's file (`inkvec_bench/geomatch.py`): the mean distance, + # in input pixels, between the trace's edges and the artist's, by the area between + # them; and the part of it more than a pixel from any artist edge. + geom: float = 0.0 + geom_far: float = 0.0 svg: str = "" # SHA-256 of the emitted SVG's bytes. Two builds that emit the same bytes for an icon # score it identically, so the gate can tell "unchanged" from "changed by a tie". sha256: str = "" + # True when the SVG's bytes matched the ones a baseline scored (`Job.known`), so the + # scores above are the baseline's, not recomputed; `mirror` and `dists` are then NaN. + reused: bool = False + # The design battery (`inkvec_bench/design.py`) when asked for (`Job.human`): + # {"trace": {statistic: value}, "div": {statistic: distance from the artist's file}}. + human: dict = field(default_factory=dict) + # CPU seconds this icon cost in its worker: the tracer ("trace"), the gate's signals + # ("score", 0 when reused) and the design battery ("human"). + cpu: dict = field(default_factory=dict) @dataclass @@ -540,7 +557,10 @@ def _init_worker(): #: points (215 of 246 screen-set traces carry arcs) and one polyline ran through every #: subpath; primitives (``, ``, ...) were not read at all. dE00, ratio and #: self_res are unchanged. -SCORER_VERSION = 3 +#: +#: 4 (2026-10-10): `geom` and `geom_far`, the geometric match to the artist's file +#: (`inkvec_bench/geomatch.py`), are scored. Every earlier signal is unchanged. +SCORER_VERSION = 4 def _rgb8(img: np.ndarray) -> np.ndarray: @@ -663,7 +683,7 @@ def cache_save(exe: Path, extra_args, entries: dict) -> None: CACHE_FIELDS = ("de00", "dists", "ratio", "seconds", "corpus", "stem", - "self_res", "turning", "mirror", "sha256") + "self_res", "turning", "mirror", "geom", "geom_far", "sha256") def structure_signals(svg: str, src_png: Path) -> dict: @@ -710,52 +730,189 @@ def structure_signals(svg: str, src_png: Path) -> dict: return out -def score_one(args: tuple) -> dict: - """Trace + render + colour error for one icon. Top-level so a process pool can - pickle it. DISTS is *not* computed here: it needs torch and a VGG, which would put - ~1 GB and a slice of the GPU into every worker; the parent scores it from the saved - render instead (`score_set`).""" - exe, it, out_dir, extra_args, keep_svg = args +def is_opaque(src_png: Path) -> bool: + """Whether an icon is compared over white: an opaque tier (flattened onto white) or a + file with no alpha at all (a JPEG), as it was made. A transparent tier's icon stays + transparent even where its pixels happen to be all opaque, so its numbers stay + comparable with its baseline.""" from PIL import Image - from inkvec_bench import render, svgmodel - from inkvec_bench.metrics import color as mcolor - png, gt = item_paths(it) - if not png.exists() or not gt.exists(): - return {"fail": f"{it['stem']}: missing input"} - out = Path(out_dir) / f"{it['corpus']}__{it['stem']}.svg" + with Image.open(src_png) as im: + return base_tier(tier()) != tier() or "A" not in im.getbands() + + +def geometric_match(svg: str, gt: Path, src_png: Path) -> dict: + """`geom` and `geom_far` of our SVG against the artist's file (`inkvec_bench/geomatch.py`), + at the input raster's size; over white when the input is opaque. The artist's side is + kept in the cache (`geomatch.artist_side`): it depends on the artist's bytes, the size + and the page only.""" + from PIL import Image + from inkvec_bench import geomatch as gm + gm.CACHE_DIR = CACHE / "geomatch" + with Image.open(src_png) as im: + w = im.size[0] + return gm.geomatch(svg, gt.read_text(encoding="utf-8"), w, is_opaque(src_png)) + + +def artist_design(gt: Path, raster_px: int) -> dict: + """The design battery's profile of the artist's file (`inkvec_bench/design.py`) for a + `raster_px` raster, kept in the cache by the file's hash, the raster size and the + battery's version: it is the same in every run.""" + from inkvec_bench import design + text = gt.read_text(encoding="utf-8") + key = hashlib.sha256(f"{design.VERSION}|{raster_px}|{text}".encode()).hexdigest()[:32] + cp = CACHE / "design" / f"{key}.json" + if cp.exists(): + try: + return json.loads(cp.read_text(encoding="utf-8")) + except (OSError, ValueError): + pass + prof = design.profile(text, raster_px=raster_px) + cp.parent.mkdir(parents=True, exist_ok=True) + tmp = cp.with_name(f"{cp.stem}.{os.getpid()}.tmp") + tmp.write_text(json.dumps(prof), encoding="utf-8") + try: + os.replace(tmp, cp) + except OSError: + tmp.unlink(missing_ok=True) + return prof + + +def human_stats(svg: str, gt: Path, raster_px: int) -> dict: + """{"trace": {statistic: one number}, "artist": {statistic: one number}, "div": + {statistic: distance from the artist's file}} of one trace (`inkvec_bench/design.py`); + empty if the trace cannot be read.""" + from inkvec_bench import design + try: + art_text = gt.read_text(encoding="utf-8") + c = design.compare(svg, art_text, raster_px, artist_design(gt, raster_px)) + except Exception: # noqa: BLE001 - a statistic must never fail a score + return {} + return {side: {k: design.summary_value(k, c[side][k]) for k in design.STATS} + for side in ("trace", "artist")} | {"div": c["div"]} + + +@dataclass(frozen=True) +class Job: + """One icon to trace and score; picklable, so it is what the pool's workers receive. + + `tier` is set in the worker, so one pool serves every condition. `known` is a + baseline's (SHA-256 prefix, {axis: value}) for the icon: when the new SVG's bytes have + that hash, the icon is not scored again and takes those values (`ImageScore.reused`). + `human` asks for the design battery.""" + + exe: Path + it: dict + out_dir: Path + extra_args: tuple = () + keep_svg: bool = False + tier: str = "" + known: tuple | None = None + human: bool = False + + +def _trace(job: Job) -> tuple[dict | None, Path, float, subprocess.CompletedProcess | None]: + """Run the tracer on one icon: (failure or None, output path, seconds, result).""" + it = job.it + out = Path(job.out_dir) / f"{it['corpus']}__{it['stem']}.svg" t0 = time.time() try: - r = subprocess.run([str(exe), str(png), "-o", str(out), "--quiet", *extra_args], - capture_output=True, timeout=TRACE_TIMEOUT) + r = subprocess.run([str(job.exe), str(item_paths(it)[0]), "-o", str(out), "--quiet", + *job.extra_args], capture_output=True, timeout=TRACE_TIMEOUT) except subprocess.TimeoutExpired: - return {"fail": f"{it['stem']}: timeout after {TRACE_TIMEOUT}s"} + return {"fail": f"{it['stem']}: timeout after {TRACE_TIMEOUT}s"}, out, 0.0, None dt = time.time() - t0 if r.returncode != 0: - return {"fail": f"{it['stem']}: exit {r.returncode}: " - f"{r.stderr.decode('utf-8', 'replace')[-300:]}"} - raw = out.read_bytes() # hashed as written ... - svg = out.read_text(encoding="utf-8") # ... and scored as before (newline-translated) + return ({"fail": f"{it['stem']}: exit {r.returncode}: " + f"{r.stderr.decode('utf-8', 'replace')[-300:]}"}, out, dt, r) + return None, out, dt, r + + +def score_svg(svg: str, it: dict, png: Path, gt: Path, render_path: Path | None = None) -> dict: + """Every gate signal of one SVG against the artist's file: the scorer itself, a pure + function of the two files (and the input raster, for `self_res`). Returns the signals, + or {"fail": reason}. `render_path`, when given, receives the 1024 px render as a PNG + (for DISTS, scored in the parent).""" + from PIL import Image + from inkvec_bench import render, svgmodel + from inkvec_bench.metrics import color as mcolor try: b = render.composite(render.render(svg, JUDGE_SIZE, JUDGE_SIZE)) except BaseException as e: # resvg raises odd things on malformed output return {"fail": f"{it['stem']}: render {type(e).__name__}"} ref = gt_render(gt, it["corpus"], it["stem"]) - rp = Path(out_dir) / f"{it['corpus']}__{it['stem']}.render.png" - Image.fromarray((np.clip(b, 0, 1) * 255 + 0.5).astype(np.uint8)).save(rp, optimize=False) + if render_path is not None: + Image.fromarray((np.clip(b, 0, 1) * 255 + 0.5).astype(np.uint8)).save(render_path, optimize=False) sig = structure_signals(svg, png) - res = dict(stem=it["stem"], corpus=it["corpus"], **sig, - de00=float(mcolor.delta_e00(ref, b)["de00_mean"]), - dists=0.0, - ratio=svgmodel.parse(svg).n_params / max(1, it["gt_params"]), - seconds=dt, svg=svg if keep_svg else "", - sha256=hashlib.sha256(raw).hexdigest()) - res["_render"] = str(rp) - res["_gt"] = str(CACHE / f"gt{JUDGE_SIZE}" / it["corpus"] / f"{it['stem']}.png") - if not keep_svg: + try: + sig.update(geometric_match(svg, gt, png)) + except BaseException as e: # resvg raises odd things on malformed output + return {"fail": f"{it['stem']}: geometric match {type(e).__name__}"} + return dict(**sig, de00=float(mcolor.delta_e00(ref, b)["de00_mean"]), + ratio=svgmodel.parse(svg).n_params / max(1, it["gt_params"])) + + +def score_one(job: Job) -> dict: + """Trace + render + colour error for one icon. Top-level so a process pool can + pickle it. DISTS is *not* computed here: it needs torch and a VGG, which would put + ~1 GB and a slice of the GPU into every worker; the parent scores it from the saved + render instead (`score_set`), unless `INKVEC_SKIP_DISTS=1` (the gate), when no render + is saved at all. + + An icon whose SVG bytes match `job.known`'s hash is not scored: its scores are the + known ones, exactly what scoring the same bytes again would give (the scorer is a pure + function of the files), at the cost of the trace alone.""" + if job.tier: + set_tier(job.tier) + it = job.it + png, gt = item_paths(it) + if not png.exists() or not gt.exists(): + return {"fail": f"{it['stem']}: missing input"} + c0 = _children_cpu() + fail, out, dt, _ = _trace(job) + if fail: + return fail + cpu = {"trace": _children_cpu() - c0} + c0 = time.process_time() + raw = out.read_bytes() # hashed as written ... + svg = out.read_text(encoding="utf-8") # ... and scored as before (newline-translated) + sha = hashlib.sha256(raw).hexdigest() + res = {"stem": it["stem"], "corpus": it["corpus"], "seconds": dt, + "svg": svg if job.keep_svg else "", "sha256": sha} + if job.known and job.known[0] and sha.startswith(job.known[0]): + res.update(job.known[1], dists=float("nan"), mirror=float("nan"), reused=True) + else: + want_dists = os.environ.get("INKVEC_SKIP_DISTS") != "1" + rp = Path(job.out_dir) / f"{it['corpus']}__{it['stem']}.render.png" if want_dists else None + sig = score_svg(svg, it, png, gt, rp) + if "fail" in sig: + return sig + res.update(sig, dists=0.0) + if rp is not None: + res["_render"] = str(rp) + res["_gt"] = str(CACHE / f"gt{JUDGE_SIZE}" / it["corpus"] / f"{it['stem']}.png") + cpu["score"] = time.process_time() - c0 + if job.human: + from PIL import Image + c0 = time.process_time() + with Image.open(png) as im: + res["human"] = human_stats(svg, gt, im.size[0]) + cpu["human"] = time.process_time() - c0 + res["cpu"] = cpu + if not job.keep_svg: out.unlink(missing_ok=True) return res +def _children_cpu() -> float: + """CPU seconds of every child process this one has waited for (the tracer).""" + try: + import resource + except ImportError: # Windows: no rusage; the breakdown reads 0 there + return 0.0 + r = resource.getrusage(resource.RUSAGE_CHILDREN) + return r.ru_utime + r.ru_stime + + def _dists_in_parent(results: list[dict]) -> None: """DISTS for every scored icon, in this process only: one VGG, on the GPU when there is one. Reads the renders the workers saved and deletes them.""" @@ -764,7 +921,7 @@ def _dists_in_parent(results: list[dict]) -> None: if not skip: from inkvec_bench.metrics import raster for res in results: - if "fail" in res: + if "fail" in res or "_render" not in res: continue rp, gp = Path(res.pop("_render")), Path(res.pop("_gt")) if not skip: @@ -774,8 +931,38 @@ def _dists_in_parent(results: list[dict]) -> None: rp.unlink(missing_ok=True) +@contextmanager +def scoring_pool(workers: int): + """A process pool of `workers` scoring workers, one core each, for `score_set(pool=...)`: + one pool for every condition of a run, so each worker imports the scorer once. + + BLAS and rayon threads are pinned in the *parent* environment for the pool's life: + children inherit it and numpy reads it at import, which happens before any initializer + runs. Setting it only in the initializer is too late; each worker then starts a + full-width OpenBLAS pool, and 12 workers x 16 threads took a 4-minute scoring pass to + three hours (measured 2026-09-02).""" + saved = {k: os.environ.get(k) for k in PIN_VARS} + for k in PIN_VARS: + os.environ[k] = "1" + pool = ProcessPoolExecutor(max_workers=max(1, workers), initializer=_init_worker) + try: + yield pool + finally: + pool.shutdown() + for k, v in saved.items(): + if v is None: + os.environ.pop(k, None) + else: + os.environ[k] = v + + def score_set(exe: Path, name: str, items: list[dict], out_dir: Path, extra_args=(), - keep_svgs: bool = False, workers: int = 1, use_cache: bool = True) -> SetScore: + keep_svgs: bool = False, workers: int = 1, use_cache: bool = True, + known: dict | None = None, human: bool = False, pool=None) -> SetScore: + """Trace and score `items`. `known` maps `family/stem` to a baseline's (SHA-256 prefix, + {axis: value}): those icons are scored only if their SVG bytes changed (`score_one`). + `human` adds the design battery to every icon. `pool` is a `scoring_pool` to run in + (else one is made for this set when `workers` > 1).""" out_dir.mkdir(parents=True, exist_ok=True) ss = SetScore(name) # Anything already scored for this exact build comes off disk; only the rest is traced. @@ -793,38 +980,25 @@ def score_set(exe: Path, name: str, items: list[dict], out_dir: Path, extra_args if cached: print(f"{name}: {len(cached)} of {len(items)} from cache", flush=True) items = todo - jobs = [(exe, it, out_dir, tuple(extra_args), keep_svgs) for it in items] - if workers <= 1 or len(jobs) < 2: + known = known or {} + jobs = [Job(exe, it, out_dir, tuple(extra_args), keep_svgs, tier(), + known.get(f"{it['corpus']}/{it['stem']}"), human) for it in items] + if pool is not None and jobs: + results = list(pool.map(score_one, jobs, chunksize=1)) + elif workers <= 1 or len(jobs) < 2: # Serial = the tracer runs the way a user runs it, with its own rayon pool on # every core. That is the wall time the sub-5 s rule is about (the canary); # single-threaded times are 5-10x longer and would trip the gate on nothing. results = list(map(score_one, jobs)) else: - # Pin BLAS/rayon threads in the *parent* environment before the pool spawns: - # children inherit it and numpy reads it at import, which happens before any - # initializer runs. Setting it only in the initializer is too late — each - # worker then starts a full-width OpenBLAS pool, and 12 workers x 16 threads - # took a 4-minute scoring pass to three hours (measured 2026-09-02). - saved = {k: os.environ.get(k) for k in PIN_VARS} - for k in PIN_VARS: - os.environ[k] = "1" - try: - pool = ProcessPoolExecutor(max_workers=min(workers, len(jobs)), - initializer=_init_worker) - results = list(pool.map(score_one, jobs, chunksize=1)) - pool.shutdown() - finally: - for k, v in saved.items(): - if v is None: - os.environ.pop(k, None) - else: - os.environ[k] = v + with scoring_pool(min(workers, len(jobs))) as p: + results = list(p.map(score_one, jobs, chunksize=1)) _dists_in_parent(results) if cached or (use_cache and not keep_svgs and os.environ.get("INKVEC_NO_SCORE_CACHE") != "1"): fresh = { f"{r['corpus']}/{r['stem']}": {k: r[k] for k in CACHE_FIELDS} - for r in results if "fail" not in r + for r in results if "fail" not in r and not r.get("reused") } if fresh: cache_save(exe, tuple(extra_args), fresh) diff --git a/bench/tests/test_ci_gate.py b/bench/tests/test_ci_gate.py index 35a56fbf..b6739bb0 100644 --- a/bench/tests/test_ci_gate.py +++ b/bench/tests/test_ci_gate.py @@ -31,7 +31,8 @@ def rows(scale: float = 1.0, changed: tuple[str, ...] | None = None) -> dict: s = scale if hit else 1.0 digest = hashlib.sha256(f"{k}-{s if hit else 1.0}".encode()).hexdigest() out[k] = {"corpus": it["corpus"], "de00": 0.1 * (1 + n % 5) * s, "turning": 0.04 * s, - "ratio": 1.2 * s, "self_res": 0.003, "sha256": digest} + "ratio": 1.2 * s, "self_res": 0.003, "geom": 0.02 * s, "geom_far": 0.001 * s, + "sha256": digest} return out @@ -45,7 +46,7 @@ def __init__(self, tmp: Path, scores: dict): def __call__(self, *args: str) -> tuple[int, str]: buf = io.StringIO() - fake = lambda exe, cond, items, workers: (self.scores[cond.name], []) # noqa: E731 + fake = lambda exe, cond, items, workers, *a, **k: (self.scores[cond.name], []) # noqa: E731 with patch.object(ci_gate, "score_condition", side_effect=fake), \ patch.object(ci_gate.svgeval, "load_sets", return_value={"screen": ITEMS}), \ patch.object(ci_gate, "BASELINE", self.tmp / "legacy.json"), \ @@ -81,9 +82,50 @@ def test_pack_round_trip(self): for k in r: self.assertEqual(back[k]["corpus"], r[k]["corpus"]) self.assertEqual(back[k]["sha256"], r[k]["sha256"][:ci_gate.SHA_CHARS]) - for ax in ci_gate.REPORTED_AXES: + for ax in ci_gate.ROW_AXES: self.assertAlmostEqual(back[k][ax], r[k][ax], delta=abs(r[k][ax]) * 1e-8) + def test_gaps_measure_distance_from_the_artist(self): + cond = ci_gate.BY_NAME["quality-512ssop"] + with patch.object(ci_gate, "artist_turning", return_value=10.0): + near = ci_gate.with_gaps({"f/a": {"turning": 9.0 / 512, "ratio": 0.5}}, cond)["f/a"] + far = ci_gate.with_gaps({"f/a": {"turning": 4.0 / 512, "ratio": 2.0}}, cond)["f/a"] + self.assertAlmostEqual(near["turning_gap"], 1.0) + self.assertAlmostEqual(far["turning_gap"], 6.0) + # Half and twice the artist's parameters are equally far. + self.assertAlmostEqual(near["ratio_gap"], far["ratio_gap"]) + + def test_turning_toward_the_artist_is_not_a_regression(self): + # A build whose traces turn MORE, but toward an artist who turns more still, passes; + # the raw `turning` axis would have failed it. + base = rows() + cur = rows(1.0) + for r in cur.values(): + r["turning"] *= 1.3 + r["sha256"] = "f" * 64 + with patch.object(ci_gate, "artist_turning", return_value=0.08 * 512): + v = ci_gate.compare_condition( + ci_gate.with_gaps(base, ci_gate.BY_NAME["quality-512ss"]), + ci_gate.with_gaps(cur, ci_gate.BY_NAME["quality-512ss"]), ci_gate.MARGINS) + self.assertTrue(v["turning_gap"][1].passed) + self.assertGreater(v["turning"][0].rel, 0.25) # raw turning rose 30 % + self.assertNotIn("turning", ci_gate.GATED_AXES) + + def test_tier_sides_match_the_committed_rasters(self): + from PIL import Image + data = ci_gate.ROOT / "bench" / "data" / "corpus_raster" + for tier, side in ci_gate.TIER_PX.items(): + ext = "jpg" if tier == "web" else "png" + some = next(data.glob(f"lucide/{tier}/*.{ext}"), None) + if some is None: + self.skipTest("screen rasters not present") + self.assertEqual(Image.open(some).size, (side, side), tier) + + def test_canvas_side_reads_the_longer_viewbox_side(self): + self.assertEqual(ci_gate.canvas_side(''), 36.0) + self.assertEqual(ci_gate.canvas_side(''), 128.0) + self.assertIsNone(ci_gate.canvas_side("")) + def test_write_then_identical_build_passes(self): run = Run(self.tmp, {c.name: rows() for c in ci_gate.CONDITIONS}) code, out = run("--write-baseline") @@ -93,8 +135,9 @@ def test_write_then_identical_build_passes(self): self.assertEqual(doc["scorer_version"], ci_gate.svgeval.SCORER_VERSION) code, out = run() self.assertEqual(code, 0, out) - # Three gated axes per condition read "identical"; self_res reads "reported". - self.assertEqual(len(re.findall(r"\bidentical\b", out)), 3 * len(ci_gate.CONDITIONS)) + # Every gated axis of every condition reads "identical"; the others "reported". + self.assertEqual(len(re.findall(r"\bidentical\b", out)), + len(ci_gate.GATED_AXES) * len(ci_gate.CONDITIONS)) def test_regression_fails_and_bypass_needs_a_reason(self): run = Run(self.tmp, {c.name: rows() for c in ci_gate.CONDITIONS}) diff --git a/bench/tests/test_design.py b/bench/tests/test_design.py new file mode 100644 index 00000000..c8b735b2 --- /dev/null +++ b/bench/tests/test_design.py @@ -0,0 +1,176 @@ +"""The design battery (`inkvec_bench/design.py`): each statistic on files whose answer is +known by construction, and the divergence's zero on a file against itself or against the same +drawing written in another frame. numpy, scipy and scikit-image; no renders, no tracer.""" +from __future__ import annotations + +import math +import sys +import unittest +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from inkvec_bench import design + +HEAD = '' + + +def svg(body: str, vb: str = "0 0 24 24") -> str: + return HEAD.format(vb=vb) + body + "" + + +SQUARE = svg('') +CIRCLE = svg('') + + +class ParseTests(unittest.TestCase): + def test_rect_is_four_right_angled_axis_lines(self): + p = design.profile(SQUARE) + self.assertEqual(p["kinds"], [1.0, 0.0, 0.0, 0.0]) + self.assertEqual(p["line_axis"], 1.0) + self.assertEqual(p["corner_share"], 1.0) + self.assertEqual(p["right_angle"], 1.0) + self.assertEqual(p["closed"], 1.0) + self.assertEqual(p["primitives"], 1.0) + self.assertEqual(p["nodes_per_subpath"], 4.0) + self.assertEqual(p["grid_int"], 1.0) + self.assertEqual(p["grid_level"], 0.0) + self.assertEqual(p["decimals"], 0.0) + self.assertEqual(p["mirror"], 1.0) + + def test_circle_is_four_smooth_quarter_arcs_at_the_extrema(self): + p = design.profile(CIRCLE) + self.assertEqual(p["kinds"], [0.0, 0.0, 0.0, 1.0]) + self.assertEqual(p["smooth"], 1.0) + self.assertEqual(p["extremum"], 1.0) + self.assertEqual(p["wide_curves"], 0.0) + for s in p["sweep"]: + self.assertAlmostEqual(s, 90.0, places=6) + + def test_relative_commands_reflections_and_compact_arc_flags(self): + # The same square as SQUARE, written relative; a compact arc `a4 4 0 014 4`. + rel = design.profile(svg('')) + self.assertEqual(rel["kinds"], [1.0, 0.0, 0.0, 0.0]) + self.assertEqual(rel["nodes_per_subpath"], 4.0) + arc = design.parse(svg('')).elements[0].subs[0].segs[0] + self.assertEqual(arc.kind, "A") + self.assertAlmostEqual(arc.p1[0] * 24, 8.0) + self.assertAlmostEqual(arc.p1[1] * 24, 4.0) + # S reflects the previous control point: a symmetric S-curve has two cubics. + s = design.parse(svg('')).elements[0].subs[0].segs + self.assertEqual([x.kind for x in s], ["C", "C"]) + self.assertAlmostEqual(s[1].pts[1][0] * 24, 8.0) + self.assertAlmostEqual(s[1].pts[1][1] * 24, 18.0) + + def test_transforms_are_applied(self): + diamond = design.profile(svg('')) + self.assertEqual(diamond["line_diag"], 1.0) + self.assertEqual(diamond["line_axis"], 0.0) + + def test_paint_is_inherited_and_strokes_counted(self): + p = design.profile(svg('' + '')) + self.assertEqual(p["stroked"], 1.0) + self.assertEqual(p["elements"], 2) + self.assertEqual(p["palette"], [[0, 0, 0]]) + self.assertEqual(p["closed"], 0.0) + + def test_a_white_page_is_not_part_of_the_drawing(self): + page = svg('' + '', + vb="-0.5 -0.5 512 512") + p = design.profile(page) + self.assertTrue(p["page"]) + self.assertEqual(p["elements"], 1) + self.assertFalse(design.profile(SQUARE)["page"]) + + def test_half_pixel_grid(self): + # 4 and 20 units of 24 on a 48 px raster are 8 and 40 px: on the grid. On a 50 px + # raster, 8.33 and 41.67 px: off it. + self.assertEqual(design.profile(SQUARE, raster_px=48)["halfpx"], 1.0) + self.assertEqual(design.profile(SQUARE, raster_px=50)["halfpx"], 0.0) + self.assertTrue(math.isnan(design.profile(SQUARE)["halfpx"])) + self.assertIn("halfpx", design.ARTEFACTS) + + def test_nested_and_stacked(self): + ring = design.profile(svg('')) + self.assertEqual(ring["nested"], 0.5) + self.assertEqual(ring["evenodd"], 1.0) + stack = design.profile(svg('' + '')) + self.assertEqual(stack["stacked"], 0.5) + + +class DivergenceTests(unittest.TestCase): + def test_a_file_against_itself_is_zero(self): + for f in (SQUARE, CIRCLE): + p = design.profile(f) + for k, v in design.divergence(p, p).items(): + self.assertTrue(math.isnan(v) or v == 0.0, (k, v)) + + def test_the_same_drawing_in_the_trace_frame_is_zero(self): + # The square drawn as a 512 px trace writes it: pixel centres at integers, two + # decimals. Every statistic reads the same, the grid ones within the tolerance. + k = 512 / 24 + trace = svg(f'', + vb="-0.5 -0.5 512 512") + c = design.compare(trace, SQUARE, 512) + for name, v in c["div"].items(): + if name == "primitives": # a path, where the artist wrote a + self.assertEqual(v, 1.0) + continue + self.assertTrue(math.isnan(v) or v < 1e-4, (name, v)) # two decimals + + def test_divergence_kinds(self): + a = {"kinds": [1.0, 0.0, 0.0, 0.0], "elements": 4, "line_axis": 0.75, + "sweep": [90.0, 90.0], "palette": [[0, 0, 0]]} + t = {"kinds": [0.5, 0.5, 0.0, 0.0], "elements": 8, "line_axis": 0.25, + "sweep": [45.0, 45.0], "palette": [[0, 0, 0], [255, 255, 255]]} + d = design.divergence(t, a) + self.assertAlmostEqual(d["kinds"], 0.5) + self.assertAlmostEqual(d["elements"], math.log(2)) + self.assertAlmostEqual(d["line_axis"], 0.5) + self.assertAlmostEqual(d["sweep"], 45.0 / 180.0) + self.assertAlmostEqual(d["palette"], 25.0, places=3) # white is 100 from black, half the set + self.assertTrue(math.isnan(d["smooth"])) + + def test_w1_matches_scipy(self): + from scipy.stats import wasserstein_distance + rng = np.random.default_rng(1) + for _ in range(20): + a, b = rng.normal(size=rng.integers(1, 40)), rng.gamma(2.0, size=rng.integers(1, 40)) + self.assertAlmostEqual(design._w1(a, b), wasserstein_distance(a, b), places=12) + + def test_report_aggregates_and_pruning(self): + import human_stats + per = {"a/1": {"div": {"x": 1.0}}, "a/2": {"div": {"x": 3.0}}, + "b/1": {"div": {"x": 10.0}}, "b/2": {"div": {"x": float("nan")}}} + m = human_stats.family_mean(per, "x", "div") + self.assertEqual(m, {"a": 2.0, "b": 10.0, "macro": 6.0}) + rng = np.random.default_rng(2) + base = rng.normal(size=200) + cols = {"g": rng.normal(size=200), "s1": base, "s2": base * 3 + 0.01 * rng.normal(size=200), + "s3": rng.normal(size=200)} + names, rho = human_stats.matrix(cols) + self.assertAlmostEqual(rho[1, 1], 1.0) + kept, dropped = human_stats.prune(names, rho, fixed=("g",)) + self.assertEqual(kept, ["g", "s1", "s3"]) + self.assertEqual(dropped["s2"][0], "s1") + + def test_tracer_flags_are_taken_as_values(self): + import human_stats + self.assertEqual(human_stats.flag_values(["--exe", "x", "--extra-args", "--editability", + "--base-args", ""]), + ["--exe", "x", "--extra-args=--editability", "--base-args="]) + + def test_kept_statistics_are_defined(self): + self.assertTrue(set(design.KEPT) <= set(design.STATS)) + self.assertEqual(len(set(design.KEPT)), len(design.KEPT)) + + +if __name__ == "__main__": + unittest.main() diff --git a/bench/tests/test_gate_scoring.py b/bench/tests/test_gate_scoring.py index 2dfa0c64..22f89823 100644 --- a/bench/tests/test_gate_scoring.py +++ b/bench/tests/test_gate_scoring.py @@ -112,5 +112,122 @@ def test_item_paths_derives_the_opaque_raster_once(self): svgeval.os.environ["INKVEC_TIER"] = saved[2] +class FastPathTests(unittest.TestCase): + """The scorer's shortcuts give the numbers of the plain computations they replace.""" + + def test_codes_match_the_arithmetic(self): + from inkvec_bench import geomatch as gm + rng = np.random.default_rng(3) + rgba = rng.integers(0, 256, (37, 41, 4), dtype=np.uint8) + rgba[::3, :, 3] = 255 + rgba[1::3, :, 3] = 0 + for opaque in (False, True): + u = rgba.astype(np.uint32) + if opaque: + a = u[..., 3:4] + u[..., :3] = (u[..., :3] * a + 255 * (255 - a) + 127) // 255 + u[..., 3] = 255 + want = (u[..., 0] << 24) | (u[..., 1] << 16) | (u[..., 2] << 8) | u[..., 3] + got = gm._codes(rgba, opaque) + self.assertEqual(got.dtype, want.dtype) + self.assertTrue(np.array_equal(got, want), opaque) + + def test_labels_by_runs_match_unique(self): + from inkvec_bench import geomatch as gm + rng = np.random.default_rng(4) + codes = rng.choice(np.array([0xFF0000FF, 0x00FF00FF, 0x123456FF, 0xFFFFFF00], np.uint32), + size=(64, 50)).astype(np.uint32) + codes[10:30, :] = 0x00FF00FF # long runs, as a flat render has + uniq, counts = np.unique(codes.reshape(-1), return_counts=True) + pal = gm._palette(gm._features(uniq), counts)[:3] + _, inv = np.unique(codes.reshape(-1), return_inverse=True) + d = ((gm._features(uniq)[:, None, :] - pal[None, :, :]) ** 2).sum(-1) + want = d.argmin(1)[inv.reshape(-1)].reshape(codes.shape) + self.assertTrue(np.array_equal(gm._labels(codes, pal), want)) + + def test_artist_side_cache_hit_equals_miss(self): + from inkvec_bench import geomatch as gm + art = ('' + '' + '') + ours = art.replace('r="7"', 'r="7.3"') + saved = gm.CACHE_DIR + try: + gm.CACHE_DIR = None + plain = gm.geomatch(ours, art, 64, True) + with tempfile.TemporaryDirectory() as d: + gm.CACHE_DIR = Path(d) + miss = gm.geomatch(ours, art, 64, True) + self.assertEqual(len(list(Path(d).glob("*.npz"))), 1) + hit = gm.geomatch(ours, art, 64, True) + other = gm.geomatch(ours, art, 64, False) # another page: another entry + self.assertEqual(len(list(Path(d).glob("*.npz"))), 2) + finally: + gm.CACHE_DIR = saved + self.assertEqual(plain, miss) + self.assertEqual(plain, hit) + self.assertGreater(plain["geom"], 0.0) + self.assertNotEqual(other, {}) + + def test_delta_e00_matches_the_whole_sample(self): + from inkvec_bench.metrics import color + from skimage.color import deltaE_ciede2000, rgb2lab + rng = np.random.default_rng(5) + a = (rng.integers(0, 256, (600, 700, 3)) / 255).astype(np.float32) + b = a.copy() + b[:40] = (rng.integers(0, 256, (40, 700, 3)) / 255).astype(np.float32) + for x, y in ((a, b), (a, a), (a.astype(np.float64), b.astype(np.float64))): + xs, ys = np.clip(x, 0, 1).reshape(-1, 3), np.clip(y, 0, 1).reshape(-1, 3) + idx = np.random.default_rng(0).choice(xs.shape[0], color.MAX_DELTA_E_SAMPLES, replace=False) + de = deltaE_ciede2000(rgb2lab(xs[idx].reshape(-1, 1, 3)), + rgb2lab(ys[idx].reshape(-1, 1, 3))).reshape(-1) + got = color.delta_e00(x, y) + self.assertEqual(got["de00_mean"], float(de.mean())) + self.assertEqual(got["de00_p95"], float(np.percentile(de, 95))) + self.assertEqual(got["de00_max"], float(de.max())) + + +@unittest.skipIf(sys.platform == "win32", "the stand-in tracer is a shell script") +class ReuseTests(unittest.TestCase): + """An icon whose SVG bytes match the baseline's is traced but not scored again.""" + + def test_byte_identical_svg_takes_the_known_numbers(self): + import hashlib + import os + it = svgeval.load_sets()["screen"][0] + saved = (svgeval.TIER, svgeval._TIER_RESOLVED, os.environ.get("INKVEC_TIER")) + self.addCleanup(self._restore_tier, saved) + with tempfile.TemporaryDirectory() as d: + out = Path(d) / "out.svg" + out.write_text(GT_SVG, encoding="utf-8") + exe = Path(d) / "tracer.sh" + # A stand-in tracer: copies the fixed SVG to the `-o` path. + exe.write_text(f'#!/bin/sh\ncp "{out}" "$3"\n', encoding="utf-8") + os.chmod(exe, 0o755) + sha = hashlib.sha256(out.read_bytes()).hexdigest() + known = {ax: 0.5 for ax in ("de00", "turning", "ratio", "self_res", "geom", "geom_far")} + job = svgeval.Job(exe, it, Path(d), (), False, "128ss", (sha[:16], known), True) + res = svgeval.score_one(job) + self.assertTrue(res.get("reused"), res) + self.assertEqual(res["de00"], 0.5) + self.assertEqual(res["sha256"], sha) + self.assertIn("div", res["human"]) # the battery still runs + self.assertEqual(res["cpu"]["score"] < 0.5, True) + stale = svgeval.Job(exe, it, Path(d), (), False, "128ss", ("0" * 16, known), False) + with patch.dict(os.environ, {"INKVEC_SKIP_DISTS": "1"}): + fresh = svgeval.score_one(stale) + self.assertFalse(fresh.get("reused", False)) + self.assertNotEqual(fresh["de00"], 0.5) + + @staticmethod + def _restore_tier(saved): + import os + svgeval.TIER, svgeval._TIER_RESOLVED = saved[0], saved[1] + if saved[2] is None: + os.environ.pop("INKVEC_TIER", None) + else: + os.environ["INKVEC_TIER"] = saved[2] + + if __name__ == "__main__": unittest.main() diff --git a/bench/theory/README.md b/bench/theory/README.md new file mode 100644 index 00000000..3cbeccf1 --- /dev/null +++ b/bench/theory/README.md @@ -0,0 +1,55 @@ +# bench/theory + +Experiments behind [`docs/theory/README.md`](../../docs/theory/README.md): boundary-point +readings scored against exactly known geometry. + +| file | what it does | +|---|---| +| `exact_raster.py` | exact box-filter (area-coverage) rasteriser for polygons in float64, a port of font-rs's signed-area accumulation; `python3 exact_raster.py` runs its self-check against hand-computed areas | +| `strip_eval.py` | the ½-crossing, the column-sum mean and the column sum with the cubic correction, on exact renders of circles, ellipses and straight edges, noiseless, 8-bit and with added noise | +| `inkvec_compare.py` | runs the inkvec binary with `INKVEC_DUMP_CONTOUR` and scores the points stage 07 (`planar::measure_subpixel`) measured beside the estimators above | +| `attribution.py` | each icon's dE00 against the artist's render at 1024 px, split by where it lies: within a source pixel of an edge (smooth, corner, junction), 1-3 px from one, flat or shaded interior, and blobs of missing or extra features | +| `params_diag.py` | the gate's parameter count of the trace and the artist's file, by element and segment kind, per family and for stroked against filled artwork | +| `naturality_diag.py` | parameters an artist would not write: collinear vertices, straight cubics, co-circular arcs, open strokes that continue each other | +| `evidence_eval.py` | the boundary chain's variance model and precision formulas (`docs/theory/chain-boundary.md`): window sums against exact areas under 8-bit and `n × n` point supersampling, the information column sums keep, a wedge's vertex from its arms, and the smallest fillet the pixels can tell from a sharp corner | +| `renderer_floor.py` | the corpus intake (resvg at 8×, 8-bit) against the artists' own geometry drawn exactly, per family and tier, by window: quantisation, true arcs against usvg's cubics, per-element compositing, the per-edge share of the floor, and with `--fresh` a render made now (is the tier stale?) and tiny-skia's 4 × 4 sample lattice replicated, split into straight fills, curves and strokes | +| `oracle_cost.py` | the trace against the artist's own file on the input's pixels and the tracer's price per parameter: which icons the objective would rather have the artist's description for (a search error) and which it prefers the trace for (a question for the prior), `docs/theory/optimal.md` §6 | +| `geom_calibration.py` | the gate's geometric match (`geom`) against dE00 on a disc grown by known amounts in two colour contrasts: `geom` reads the displacement in either colour, dE00 reads the contrast | +| `noise_profile.py` | where a real input's noise sits: the gate's `web` tier (resized, quality-80 JPEG) against the exact raster it stands for, split into the resampling's deterministic blur and the codec's error, by distance to the nearest edge, on luma and chroma, next to the engine's own noise estimate; and the window identity under that blur and noise (the sums stay unbiased, their variance grows) | +| `floor_selfcal.py` | the engine's own windows against the truth, per input: an exact render, 8 × 8 point samples, tiny-skia's lattice, resvg now, the committed tier and the `web` JPEG, each traced by the Quality front end and its evidence built (`examples/evidence_calibrate.rs`); `χ²` per independent measurement under rounding alone and under the image's self-calibrated noise model, scored with the evaluator's own `score` (replicas, per-edge offset, Huber), by class and family, with each image's measured noise, tail and window scale | +| `design_prior.py` | the human prior of `docs/theory/chain-representation.md` (R3), counted from the artists' own files with exact rational arithmetic: segment kinds, axis-aligned and 45° lines, smooth and sharp joins, numbers on the design grid by the role of their point, ties, repeated radii, stroke widths, layers, symmetry and repetition; and two simulations of the chain's decisions on the artists' numbers with added noise (empirical-Bayes grid inference with snapping, `--part grid_sim`; coordinate ties by exact one-dimensional clustering, `--part ties_sim`). Needs no binary | +| `amodal_eval.py` | completion against the artists' hidden geometry on the emoji families: each artist element rendered alone (its full shape, including what later elements hide), every face the completion stage tried matched to the element of its colour it shows most of, and the IoU of the face before and after completion against that element's full shape; win rates per candidate kind (primitive, corner, corner cut, chord, offset, bulge, bridge) and the share refused | +| `human_gap.py` | a change read as distance to the artist's file rather than as raw values: per icon the turning gap (the gate's `turning` times the canvas width, trace against artist) and the parameter gap (`|ln ratio|`), before and after, per family, with how many icons moved closer or further; with `--faces`, whether the fills a change adds are the artist's (nearest artist fill within 2 dE00, IoU of the two colour regions). `--before`/`--after` take a binary or a directory of SVGs (`--save` keeps both sides) | + +```bash +cargo build --release -p inkvec-cli +python3 bench/theory/exact_raster.py +python3 bench/theory/strip_eval.py +python3 bench/theory/evidence_eval.py all +python3 bench/theory/inkvec_compare.py --exe target/release/inkvec [--mode fast] +python3 bench/theory/attribution.py --exe target/release/inkvec --tier 512ss +python3 bench/theory/params_diag.py --exe target/release/inkvec --tier 512ss +python3 bench/theory/naturality_diag.py --exe target/release/inkvec --tier 512ss +python3 bench/theory/oracle_cost.py --exe target/release/inkvec --tier 512ss +python3 bench/theory/design_prior.py [--set screen] [--part counts|geometry|grid_sim|ties_sim|all] +python3 bench/theory/amodal_eval.py --exe target/release/inkvec [--tier 512ss] +python3 bench/theory/human_gap.py --before old/inkvec --after target/release/inkvec --tier web [--faces] +python3 bench/theory/geom_calibration.py +python3 bench/theory/renderer_floor.py --fresh [--per-family 6] [--tiers 128ss,512ss] +python3 bench/theory/noise_profile.py [--per-family 6] +cargo build --release -p inkvec-trace --example evidence_calibrate +python3 bench/theory/floor_selfcal.py [--sizes 128,512] [--conditions exact,ss8,lat32,fresh,committed] +python3 bench/theory/floor_selfcal.py --sizes 400 --conditions web +``` + +Coordinates: these scripts put pixel `(i, j)` on `[i, i+1] × [j, j+1]`; inkvec puts pixel +centres on integers, so `inkvec_compare.py` shifts inkvec's points by `+½` before scoring. +Distances are to the true polygon (circles and ellipses are 8192-gons whose radius is +area-matched to the curve, within 1e-7 px). Points within 2 px of the frame are not scored: +the frame is not a boundary of the drawing. + +Needs numpy and Pillow only, except `design_prior.py`, which also needs svgelements and, +for `--part geometry`, shapely and resvg-py (the harness's renderer); +`renderer_floor.py`, which needs svgelements, shapely, scipy and resvg-py; and +`noise_profile.py`, which needs scipy and resvg-py; and `human_gap.py`, which needs +svgelements, scikit-image and resvg-py. diff --git a/bench/theory/amodal_eval.py b/bench/theory/amodal_eval.py new file mode 100644 index 00000000..c62a4024 --- /dev/null +++ b/bench/theory/amodal_eval.py @@ -0,0 +1,241 @@ +"""Amodal completion against the artists' hidden geometry. + +The emoji corpora are stacked layers: an artist draws a whole disc and paints a shading +crescent over it, so every element has a full shape, part of it hidden under later ones. +That hidden part is the ground truth the completion stage (`crates/inkvec-cli/src/layers.rs`, +chain R's painter's interval) guesses at. For every screen icon of the emoji families this +script: + +1. renders each of the artist's elements alone (every other drawing element hidden), to get + its full shape as a mask and its colour, and the part of it that shows (its mask minus + the masks of the elements painted after it); +2. traces the icon in quality mode with `INKVEC_COMPLETION_DEBUG=3`, which reports for every + face the stage tried whether it was completed or refused, the winning candidate, the + face's ink, and its element before and after the completion; +3. matches each tried face to the artist's element of the closest colour whose visible part + it overlaps most; +4. scores the face's element before the completion (the visible crescent the trace would + write without the stage) and after it against the artist's full shape, by IoU. + +It reports the share of tried faces refused, and per candidate kind (primitive, corner, +corner cut, chord, offset, bulge, bridge) how often the completed shape is closer to the +artist's element than the crescent was, with the IoU distributions. + + python3 bench/theory/amodal_eval.py --exe target/release/inkvec [--tier 512ss] + [--families noto-emoji,twemoji,openmoji] [--workers 2] [--json out.json] +""" + +from __future__ import annotations + +import argparse +import copy +import json +import os +import re +import subprocess +import sys +import xml.etree.ElementTree as ET +from collections import defaultdict +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "bench")) + +SVG_NS = "http://www.w3.org/2000/svg" +DRAWING = {"path", "rect", "circle", "ellipse", "polygon", "polyline", "line"} +NONPAINT = {"defs", "clipPath", "mask", "symbol", "linearGradient", "radialGradient", "filter", + "pattern", "marker", "title", "desc", "metadata", "style"} +#: Colour distance (sRGB, 0-255, Euclidean) within which an artist's element can be the one +#: a face stands for. +COLOUR_TOL = 40.0 +#: A win: the completed shape's IoU beats the crescent's by more than this. +WIN = 1e-3 +#: Kinds as the stage reports them, grouped as the review names them. +GROUP = {"circle": "primitive", "ellipse": "primitive", "rect": "primitive", "corner": "corner", + "corner-cut": "corner cut", "chord": "chord", "offset": "offset", "bulge": "bulge", + "bridge": "bridge"} + + +def tag(el) -> str: + return el.tag.split("}")[-1] + + +def drawing_leaves(root) -> list: + """The drawing elements in paint order, skipping definitions.""" + out = [] + + def walk(node): + for ch in node: + t = tag(ch) + if t in NONPAINT: + continue + if t in DRAWING: + out.append(ch) + walk(ch) + + walk(root) + return out + + +def artist_layers(svg_text: str, size: int): + """Per drawing element in paint order: (full mask, mean colour, visible mask).""" + from inkvec_bench import render + ET.register_namespace("", SVG_NS) + root = ET.fromstring(svg_text) + n = len(drawing_leaves(root)) + masks, colours = [], [] + for i in range(n): + r = copy.deepcopy(root) + leaves = drawing_leaves(r) + for j, el in enumerate(leaves): + if j != i: + el.set("display", "none") + else: + # Alone and opaque: the shape is the mask, whatever its opacity. + for k in ("opacity", "fill-opacity"): + if k in el.attrib: + del el.attrib[k] + img = render.render(ET.tostring(r, encoding="unicode"), size, size) + m = img[..., 3] > 0.5 + masks.append(m) + colours.append(img[..., :3][m].mean(axis=0) * 255 if m.any() else np.array([-999.0] * 3)) + visible = [] + above = np.zeros((size, size), bool) + for i in range(n - 1, -1, -1): + visible.append(masks[i] & ~above) + above |= masks[i] + visible.reverse() + return masks, colours, visible + + +def element_mask(el: str, size: int) -> np.ndarray | None: + """One of our elements (as the stage printed it) drawn alone in the trace's frame.""" + from inkvec_bench import render + if not el: + return None + el = re.sub(r'\sfill="[^"]*"', "", el) + el = el.replace("/>", ' fill="#000000"/>', 1) + svg = (f'{el}') + return render.render(svg, size, size)[..., 3] > 0.5 + + +def iou(a: np.ndarray, b: np.ndarray) -> float: + u = (a | b).sum() + return float((a & b).sum() / u) if u else 0.0 + + +def hex_rgb(h: str) -> np.ndarray: + h = h.lstrip("#") + return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], float) + + +def one_icon(arg): + exe, fam, stem, tier = arg + import svgeval + svgeval.set_tier(tier) + png, gt = svgeval.item_paths({"corpus": fam, "stem": stem}) + if not png.exists(): + return [] + from PIL import Image + size = Image.open(png).size[0] + env = dict(os.environ, INKVEC_COMPLETION_DEBUG="3") + out = Path(os.environ.get("TMPDIR", "/tmp")) / f"amodal_{os.getpid()}.svg" + r = subprocess.run([str(exe), str(png), "-o", str(out), "--quiet", "--mode", "quality"], + env=env, capture_output=True, text=True, timeout=900) + rows = [ln.split("\t") for ln in r.stderr.splitlines() if ln.startswith("completion\t")] + if not rows: + return [] + masks, colours, visible = artist_layers(gt.read_text(encoding="utf-8"), size) + res = [] + for _, face, status, kind, fill, before, after in (x + [""] * (7 - len(x)) for x in rows): + b = element_mask(before, size) + if b is None or not b.any(): + continue + a = element_mask(after, size) if status == "completed" else b + if a is None: + continue + try: + c = hex_rgb(fill) + except ValueError: + continue + best, best_ov = None, 0 + for i, (m, col, vis) in enumerate(zip(masks, colours, visible)): + if np.linalg.norm(col - c) > COLOUR_TOL: + continue + ov = int((b & vis).sum()) + if ov > best_ov: + best, best_ov = i, ov + if best is None or best_ov < 0.5 * b.sum(): + res.append({"icon": f"{fam}/{stem}", "face": int(face), "status": status, "kind": kind, + "matched": False}) + continue + m = masks[best] + res.append({"icon": f"{fam}/{stem}", "face": int(face), "status": status, "kind": kind, + "matched": True, "iou_off": iou(b, m), "iou_on": iou(a, m), + "hidden_share": float(1 - visible[best].sum() / max(1, m.sum()))}) + return res + + +def quartiles(xs): + if not xs: + return "-" + q = np.percentile(xs, [25, 50, 75]) + return f"{q[0]:.3f} / {q[1]:.3f} / {q[2]:.3f}" + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--exe", type=Path, required=True) + ap.add_argument("--tier", default="512ss") + ap.add_argument("--families", default="noto-emoji,twemoji,openmoji") + ap.add_argument("--workers", type=int, default=2) + ap.add_argument("--json", type=Path) + a = ap.parse_args() + import svgeval + fams = set(a.families.split(",")) + items = [it for it in svgeval.load_sets()["screen"] if it["corpus"] in fams] + jobs = [(a.exe.resolve(), it["corpus"], it["stem"], a.tier) for it in items] + rows = [] + with ProcessPoolExecutor(a.workers) as ex: + for r in ex.map(one_icon, jobs): + rows.extend(r) + tried = len(rows) + done = [r for r in rows if r["status"] == "completed"] + matched = [r for r in done if r["matched"]] + print(f"{len(items)} icons, {tried} faces tried, {len(done)} completed, " + f"{tried - len(done)} refused ({(tried - len(done)) / max(1, tried):.1%}); " + f"{len(matched)} completed faces matched to an artist element") + by = defaultdict(list) + for r in matched: + for k in r["kind"].split("+"): + by[GROUP.get(k, k)].append(r) + print(f"{'candidate':12s} {'faces':>6s} {'win':>6s} {'loss':>6s} {'mean dIoU':>10s} " + f"{'IoU off q1/med/q3':>24s} {'IoU on q1/med/q3':>24s}") + for k in sorted(by): + rs = by[k] + d = [r["iou_on"] - r["iou_off"] for r in rs] + win = sum(x > WIN for x in d) / len(d) + loss = sum(x < -WIN for x in d) / len(d) + print(f"{k:12s} {len(rs):6d} {win:6.1%} {loss:6.1%} {np.mean(d):+10.4f} " + f"{quartiles([r['iou_off'] for r in rs]):>24s} {quartiles([r['iou_on'] for r in rs]):>24s}") + if matched: + d = [r["iou_on"] - r["iou_off"] for r in matched] + print(f"{'all':12s} {len(matched):6d} {sum(x > WIN for x in d) / len(d):6.1%} " + f"{sum(x < -WIN for x in d) / len(d):6.1%} {np.mean(d):+10.4f} " + f"{quartiles([r['iou_off'] for r in matched]):>24s} " + f"{quartiles([r['iou_on'] for r in matched]):>24s}") + refused = [r for r in rows if r["status"] == "refused" and r["matched"]] + if refused: + print(f"refused faces matched: {len(refused)}, their crescent's IoU q1/med/q3 " + f"{quartiles([r['iou_off'] for r in refused])}, hidden share of the artist's " + f"element {quartiles([r['hidden_share'] for r in refused])}") + if a.json: + a.json.write_text(json.dumps(rows, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/bench/theory/attribution.py b/bench/theory/attribution.py new file mode 100644 index 00000000..900466d2 --- /dev/null +++ b/bench/theory/attribution.py @@ -0,0 +1,206 @@ +"""Where does the colour error come from? Attribute each icon's dE00 to its sources. + +The gate's dE00 is the mean CIEDE2000 over every pixel of the trace and the artist's file, +both rendered at 1024 px. Every pixel's error is assigned to one bin by where it lies in the +artist's render: + +* `edge` within 1 source pixel of an edge of the artist's render: boundary placement +* `near` 1-3 source pixels from an edge: boundary shape (rounded corners, bulges), + slivers, and the anti-aliasing a fitted curve paints differently +* `flat` further from any edge, where the artist's render is flat: fill colour, and + features the trace added or lost +* `shaded` further from any edge, where the artist's render varies smoothly: gradients + +The bins' contributions sum to the icon's dE00. A large connected patch of interior error +(at least `BLOB_PX` source pixels above `BLOB_DE`) is counted separately as `blob`: a missing +or extra feature, not a colour that is slightly off. + + python3 bench/theory/attribution.py --exe target/release/inkvec --tier 512ss [--mode fast] +""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +import tempfile +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "bench")) + +EDGE_DE = 2.0 # neighbour difference that marks an edge of the artist's render +SHADE_DE = 0.25 # neighbour difference above which an interior pixel is "shaded" +BLOB_DE = 3.0 +BLOB_PX = 2.0 # source pixels (area) + + +def de_map(a: np.ndarray, b: np.ndarray) -> np.ndarray: + from skimage.color import deltaE_ciede2000, rgb2lab + return deltaE_ciede2000(rgb2lab(np.clip(a, 0, 1)), rgb2lab(np.clip(b, 0, 1))) + + +def neighbour_de(lab: np.ndarray) -> np.ndarray: + """Largest CIEDE2000 between each pixel and its four neighbours.""" + from skimage.color import deltaE_ciede2000 + out = np.zeros(lab.shape[:2]) + for dy, dx in ((0, 1), (1, 0)): + a = lab[: lab.shape[0] - dy, : lab.shape[1] - dx] + b = lab[dy:, dx:] + d = deltaE_ciede2000(a, b) + out[: lab.shape[0] - dy, : lab.shape[1] - dx] = np.maximum( + out[: lab.shape[0] - dy, : lab.shape[1] - dx], d) + out[dy:, dx:] = np.maximum(out[dy:, dx:], d) + return out + + +def edge_structure(lab: np.ndarray, nde: np.ndarray, scale: float) -> np.ndarray: + """Per pixel: 'j' (junction), 'c' (corner), 's' (smooth edge) or ' ' (no edge in reach).""" + from scipy import ndimage + flat = nde < 0.5 + regions, _ = ndimage.label(flat) + r = max(1, int(round(1.5 * scale))) + near_edge = ndimage.distance_transform_edt(~(nde > EDGE_DE)) <= scale + ys, xs = np.nonzero(near_edge) + h, w = nde.shape + offs = [(dy, dx) for dy in range(-r, r + 1, max(1, r // 3)) for dx in range(-r, r + 1, max(1, r // 3)) + if dy * dy + dx * dx <= r * r] + lab_at = np.stack([regions[np.clip(ys + dy, 0, h - 1), np.clip(xs + dx, 0, w - 1)] + for dy, dx in offs], axis=1) + lab_at.sort(axis=1) + distinct = ((np.diff(lab_at, axis=1) != 0) & (lab_at[:, 1:] != 0)).sum(1) + (lab_at[:, 0] != 0) + # structure tensor on the three Lab channels, at the scale of a source pixel + sig = max(1.0, scale) + jxx = jyy = jxy = 0 + for ch in range(3): + gy, gx = np.gradient(lab[..., ch]) + jxx = jxx + ndimage.gaussian_filter(gx * gx, sig) + jyy = jyy + ndimage.gaussian_filter(gy * gy, sig) + jxy = jxy + ndimage.gaussian_filter(gx * gy, sig) + tr = jxx + jyy + det = jxx * jyy - jxy * jxy + disc = np.sqrt(np.maximum(tr * tr / 4 - det, 0)) + lmax, lmin = tr / 2 + disc, tr / 2 - disc + ratio = np.where(lmax > 1e-9, lmin / np.maximum(lmax, 1e-9), 0) + out = np.full(nde.shape, " ", dtype="= 3, "j", np.where(ratio[ys, xs] > 0.15, "c", "s")) + out[ys, xs] = kind + return out + + +def score(args: tuple) -> dict: + exe, it, tier, mode, td, extra = args + import svgeval + from inkvec_bench import render + from scipy import ndimage + from skimage.color import rgb2lab + svgeval.set_tier(tier) + png, gt = svgeval.item_paths(it) + out = Path(td) / f"{it['corpus']}__{it['stem']}__{mode}.svg" + subprocess.run([exe, str(png), "-o", str(out), "--quiet", "--mode", mode, *extra], + check=True, capture_output=True) + b = render.composite(render.render(out.read_text(encoding="utf-8"), 1024, 1024)) + b = svgeval._from_rgb8(svgeval._rgb8(b)) + ref = svgeval.gt_render(gt, it["corpus"], it["stem"]) + de = de_map(ref, b) + from PIL import Image + src_w = Image.open(png).size[0] + scale = 1024 / src_w # judge pixels per source pixel + lab = rgb2lab(ref) + nde = neighbour_de(lab) + edges = nde > EDGE_DE + if edges.any(): + dist = ndimage.distance_transform_edt(~edges) / scale + else: + dist = np.full(de.shape, np.inf) + shaded = nde > SHADE_DE + n = de.size + bins = { + "edge": dist <= 1.0, + "near": (dist > 1.0) & (dist <= 3.0), + } + interior = dist > 3.0 + # Blobs: connected interior error above BLOB_DE of at least BLOB_PX source pixels. + hot = interior & (de > BLOB_DE) + lab_ids, k = ndimage.label(hot) + blob = np.zeros_like(hot) + if k: + sizes = ndimage.sum(hot, lab_ids, index=np.arange(1, k + 1)) + big = np.flatnonzero(sizes / scale**2 >= BLOB_PX) + 1 + blob = np.isin(lab_ids, big) + bins["blob"] = blob + bins["flat"] = interior & ~blob & ~shaded + bins["shaded"] = interior & ~blob & shaded + # Split the edge band by local structure of the artist's render: a junction has three or + # more flat regions within reach, a corner two regions and a structure tensor with two + # strong directions, a smooth edge the rest. + struct = edge_structure(lab, nde, scale) + for kname in ("junction", "corner", "smooth"): + m = bins["edge"] & (struct == kname[0]) + bins["edge_" + kname] = m + res = {"icon": f"{it['corpus']}/{it['stem']}", "family": it["corpus"], + "de00": float(de.mean())} + for kname, m in bins.items(): + res[kname] = float(de[m].sum() / n) + res[kname + "_area"] = float(m.mean()) + # Fill colour: the flat interior's own mean error per pixel (not weighted by area). + flat = bins["flat"] + res["flat_de_per_px"] = float(de[flat].mean()) if flat.any() else 0.0 + out.unlink(missing_ok=True) + return res + + +def main() -> None: + import svgeval + ap = argparse.ArgumentParser() + ap.add_argument("--exe", default=str(ROOT / "target/release/inkvec")) + ap.add_argument("--tier", default="512ss") + ap.add_argument("--mode", default="quality") + ap.add_argument("--set", default="screen") + ap.add_argument("--workers", type=int, default=4) + ap.add_argument("--json", default=None) + ap.add_argument("--extra", default="", help="further tracer arguments, space-separated") + a = ap.parse_args() + items = svgeval.load_sets()[a.set] + with tempfile.TemporaryDirectory() as td: + with ProcessPoolExecutor(a.workers) as pool: + rows = list(pool.map(score, [(a.exe, it, a.tier, a.mode, td, a.extra.split()) for it in items], + chunksize=2)) + keys = ["edge", "near", "flat", "shaded", "blob"] + sub = ["edge_smooth", "edge_corner", "edge_junction"] + fams = sorted({r["family"] for r in rows}) + print(f"{a.mode} {a.tier}: {len(rows)} icons; contribution to mean dE00 (share)") + print(f"{'family':15s} {'dE00':>7s} " + " ".join(f"{k:>14s}" for k in keys)) + for f in fams + ["ALL (macro)"]: + rs = rows if f.startswith("ALL") else [r for r in rows if r["family"] == f] + if f.startswith("ALL"): + per = {k: np.mean([np.mean([r[k] for r in rows if r["family"] == g]) for g in fams]) + for k in keys + ["de00"]} + else: + per = {k: np.mean([r[k] for r in rs]) for k in keys + ["de00"]} + tot = per["de00"] + print(f"{f:15s} {tot:7.4f} " + " ".join( + f"{per[k]:7.4f} ({100 * per[k] / max(tot, 1e-12):3.0f}%)" for k in keys)) + print("\nedge band by structure: share of the edge band's error / share of its area") + for f in fams + ["ALL"]: + rs = rows if f == "ALL" else [r for r in rows if r["family"] == f] + e = sum(r["edge"] for r in rs) + ea = sum(r["edge_area"] for r in rs) + print(f"{f:15s} " + " ".join( + f"{k[5:]:>9s} {100 * sum(r[k] for r in rs) / max(e, 1e-12):4.0f}% / {100 * sum(r[k + '_area'] for r in rs) / max(ea, 1e-12):4.0f}%" + for k in sub)) + print("\nworst icons by bin:") + for k in keys: + top = sorted(rows, key=lambda r: -r[k])[:5] + print(f" {k:7s} " + ", ".join(f"{r['icon']} {r[k]:.3f}" for r in top)) + if a.json: + Path(a.json).write_text(json.dumps(rows, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/bench/theory/design_prior.py b/bench/theory/design_prior.py new file mode 100644 index 00000000..00319b14 --- /dev/null +++ b/bench/theory/design_prior.py @@ -0,0 +1,1387 @@ +"""The human prior, counted: how the artists of the corpus draw. + +Chain R of `docs/theory/chain-representation.md` needs numbers: how often a line is +axis-aligned, a coordinate sits on a design grid, a join is smooth, a radius repeats, a +drawing is mirror-symmetric, a shape repeats, a shape continues under the shapes painted +over it. This script counts them from the artists' own files (`bench/data/corpus_svg`). The +numbers are read as written and kept as exact rationals, so no float tolerance decides +whether a line is horizontal or a coordinate is on the grid; relative commands are resolved +exactly. It then runs two simulations of the chain's decision rules on those coordinates, +with a stated noise model standing in for the boundary chain's precision: + +* `grid_sim`: empirical-Bayes inference of the design grid (pitch from the raster size and a + list of viewBox sizes and subdivisions, with an Occam prior that halves per subdivision), + then snapping each coordinate whose posterior puts it on the grid. Twice: per coordinate + with one on-grid weight, and hierarchically (tie classes first, the grid on their means, + the on-grid weight conditioned on the point's role: construction or derived). Scored by + how many of the artist's exact numbers come back, and how many snaps are wrong. +* `ties_sim`: coordinate ties (a vertical edge shares its x; two shapes share a baseline) by + the exact one-dimensional clustering under a Chinese-restaurant prior (an O(n^2) dynamic + program over the sorted values; contiguity of the optimal clusters is lemma R2.5 of the + chain), scored by pairwise precision and recall of "these two numbers are equal" and by + the error against the artist's numbers before and after. + + python3 bench/theory/design_prior.py # counts, every gate family + python3 bench/theory/design_prior.py --set screen # the 246-icon screen set + python3 bench/theory/design_prior.py --part geometry # symmetry, repetition, layers + python3 bench/theory/design_prior.py --part grid_sim + python3 bench/theory/design_prior.py --part ties_sim + python3 bench/theory/design_prior.py --part all --json out/design_prior.json + +Coordinates in the simulations are in raster pixels with pixel *edges* at integers (the +design's 0 maps to 0); inkvec's own convention puts pixel centres at integers, a fixed +offset of one half that the grid hypothesis carries. +""" + +from __future__ import annotations + +import argparse +import io +import json +import math +import re +import sys +import xml.etree.ElementTree as ET +from collections import Counter, defaultdict +from concurrent.futures import ProcessPoolExecutor +from fractions import Fraction +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "bench")) + +CORPUS = ROOT / "bench" / "data" / "corpus_svg" +GATE_FAMILIES = ["lucide", "material-icons", "simple-icons", "openmoji", "twemoji", + "noto-emoji", "synthetic"] + +# --------------------------------------------------------------------------- parsing + +PAINT_ATTRS = ("fill", "stroke", "stroke-width", "opacity", "fill-opacity", + "stroke-opacity", "stroke-linecap", "stroke-linejoin", "display") +NONPAINT = {"defs", "clipPath", "mask", "symbol", "linearGradient", "radialGradient", + "filter", "pattern", "marker", "title", "desc", "metadata", "style"} +NUM_RE = re.compile(r"[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?") +ARGS = {"M": 2, "L": 2, "T": 2, "H": 1, "V": 1, "C": 6, "S": 4, "Q": 4, "A": 7, "Z": 0} +GATE = {"L": 2, "Q": 4, "C": 6, "A": 7} +TURN_BINS = [(0, 0.5), (0.5, 2), (2, 5), (5, 10), (10, 30), (30, 60), (60, 90.01), (90.01, 181)] + + +def frac(text: str) -> Fraction: + t = text.strip().removesuffix("px") + if t.endswith("."): + t = t[:-1] + return Fraction(t) + + +def scan_path(d: str) -> list[tuple[str, list[Fraction]]]: + """Path data as (command, arguments), arguments exact; arc flags read one character each, + so the compact form `a2 2 0 012-2` reads as SVG says it does.""" + out: list[tuple[str, list[Fraction]]] = [] + i, n, cmd = 0, len(d), None + + def skip(i: int) -> int: + while i < n and d[i] in " \t\r\n,": + i += 1 + return i + + while True: + i = skip(i) + if i >= n: + break + if d[i].isalpha(): + cmd = d[i] + i += 1 + if cmd in "Zz": + out.append((cmd, [])) + continue + elif cmd is None or cmd in "Zz": + raise ValueError(f"bad path data at {i}") + k = ARGS[cmd.upper()] + args: list[Fraction] = [] + for a in range(k): + i = skip(i) + if cmd in "Aa" and a in (3, 4): + args.append(Fraction(int(d[i]))) + i += 1 + else: + m = NUM_RE.match(d, i) + if not m: + raise ValueError(f"bad number at {i}") + args.append(frac(m.group(0))) + i = m.end() + out.append((cmd, args)) + if cmd == "M": + cmd = "L" + elif cmd == "m": + cmd = "l" + return out + + +def to_subpaths(cmds) -> list[dict]: + """Absolute, exact segments per subpath. A segment is (kind, letter, p0, ..., p1) with + kind L, Q, C or A; a closing `Z` with a gap writes ('L', 'Z', cur, start).""" + subs: list[dict] = [] + cur = start = (Fraction(0), Fraction(0)) + sp = None + last = None # (kind, control) for S and T reflection + + def ensure(): + nonlocal sp + if sp is None: + sp = {"start": cur, "segs": [], "closed": False} + subs.append(sp) + return sp + + for cmd, a in cmds: + U, rel = cmd.upper(), cmd.islower() + ox, oy = cur if rel else (Fraction(0), Fraction(0)) + if U == "M": + cur = start = (ox + a[0], oy + a[1]) + sp = {"start": cur, "segs": [], "closed": False} + subs.append(sp) + last = None + continue + if U == "Z": + s = ensure() + s["closed"] = True + if cur != start: + s["segs"].append(("L", "Z", cur, start)) + cur = start + sp = None + last = None + continue + s = ensure() + if U == "L": + p = (ox + a[0], oy + a[1]) + s["segs"].append(("L", cmd, cur, p)) + cur, last = p, None + elif U == "H": + p = (ox + a[0] if rel else a[0], cur[1]) + s["segs"].append(("L", cmd, cur, p)) + cur, last = p, None + elif U == "V": + p = (cur[0], oy + a[0] if rel else a[0]) + s["segs"].append(("L", cmd, cur, p)) + cur, last = p, None + elif U in "CS": + if U == "C": + c1 = (ox + a[0], oy + a[1]) + c2, p = (ox + a[2], oy + a[3]), (ox + a[4], oy + a[5]) + else: + c1 = (2 * cur[0] - last[1][0], 2 * cur[1] - last[1][1]) if last and last[0] == "C" else cur + c2, p = (ox + a[0], oy + a[1]), (ox + a[2], oy + a[3]) + s["segs"].append(("C", cmd, cur, c1, c2, p)) + cur, last = p, ("C", c2) + elif U in "QT": + if U == "Q": + c, p = (ox + a[0], oy + a[1]), (ox + a[2], oy + a[3]) + else: + c = (2 * cur[0] - last[1][0], 2 * cur[1] - last[1][1]) if last and last[0] == "Q" else cur + p = (ox + a[0], oy + a[1]) + s["segs"].append(("Q", cmd, cur, c, p)) + cur, last = p, ("Q", c) + elif U == "A": + p = (ox + a[5], oy + a[6]) + s["segs"].append(("A", cmd, cur, abs(a[0]), abs(a[1]), a[2], int(a[3]), int(a[4]), p)) + cur, last = p, None + return subs + + +def style_of(el) -> dict: + st = {k: el.get(k).strip() for k in PAINT_ATTRS if el.get(k) is not None} + for part in (el.get("style") or "").split(";"): + if ":" in part: + k, v = part.split(":", 1) + if k.strip() in PAINT_ATTRS: + st[k.strip()] = v.strip() + return st + + +def num_attr(el, name, default="0") -> Fraction: + v = el.get(name) + try: + return frac(v) if v is not None else frac(default) + except (ValueError, ZeroDivisionError): + return frac(default) + + +class Element: + __slots__ = ("tag", "el", "st", "tf", "subs", "prim", "typed", "gate") + + def __init__(self, tag, el, st, tf): + self.tag, self.el, self.st, self.tf = tag, el, st, tf + self.subs: list[dict] = [] + self.prim: dict = {} + self.typed = 0 # numbers the artist typed for the geometry + self.gate = 0 # the gate's parameter count (bench/inkvec_bench/svgmodel.py rules) + + @property + def fill(self) -> str: + return self.st.get("fill", "#000").lower() + + @property + def stroke(self) -> str: + return self.st.get("stroke", "none").lower() + + @property + def stroke_width(self) -> Fraction: + try: + return frac(self.st.get("stroke-width", "1")) + except (ValueError, ZeroDivisionError): + return Fraction(1) + + @property + def filled(self) -> bool: + return self.fill not in ("none", "transparent") + + @property + def stroked(self) -> bool: + return self.stroke not in ("none", "transparent") and self.stroke_width > 0 + + @property + def opaque(self) -> bool: + for k in ("opacity", "fill-opacity"): + try: + if float(self.st.get(k, "1")) < 0.999: + return False + except ValueError: + pass + return True + + +def parse_doc(text: str) -> tuple[list[Element], Fraction]: + root = ET.fromstring(text) + vb = (root.get("viewBox") or "0 0 24 24").replace(",", " ").split() + V = max(frac(vb[2]), frac(vb[3])) + out: list[Element] = [] + + def walk(node, inherited: dict, tf: bool): + for ch in node: + tag = ch.tag.split("}")[-1] + if tag in NONPAINT: + continue + st = dict(inherited) + st.update(style_of(ch)) + if st.get("display") == "none": + continue + t = tf or ch.get("transform") is not None + if tag in ("g", "svg", "a", "switch"): + walk(ch, st, t) + elif tag in ("path", "rect", "circle", "ellipse", "line", "polyline", "polygon", "use"): + out.append(Element(tag, ch, st, t)) + + walk(root, style_of(root), False) + for e in out: + el = e.el + if e.tag == "path": + cmds = scan_path(el.get("d") or "") + e.subs = to_subpaths(cmds) + e.typed = sum(len(a) for _, a in cmds) + e.gate = sum(GATE[s[0]] for sp in e.subs for s in sp["segs"] if s[1] not in "Zz") + elif e.tag in ("polyline", "polygon"): + nums = [frac(x) for x in NUM_RE.findall(el.get("points") or "")] + pts = list(zip(nums[0::2], nums[1::2])) + if pts: + segs = [("L", "L", p, q) for p, q in zip(pts, pts[1:])] + closed = e.tag == "polygon" + if closed and pts[-1] != pts[0]: + segs.append(("L", "Z", pts[-1], pts[0])) + e.subs = [{"start": pts[0], "segs": segs, "closed": closed}] + e.typed = len(nums) + e.gate = max(4, 2 * (len(pts) - 1)) if e.tag == "polygon" else 2 * len(pts) + elif e.tag == "line": + p = (num_attr(el, "x1"), num_attr(el, "y1")) + q = (num_attr(el, "x2"), num_attr(el, "y2")) + e.subs = [{"start": p, "segs": [("L", "L", p, q)], "closed": False}] + e.typed, e.gate = 4, 4 + elif e.tag == "rect": + rx, ry = el.get("rx"), el.get("ry") + rxv = num_attr(el, "rx") if rx is not None else (num_attr(el, "ry") if ry is not None else Fraction(0)) + ryv = num_attr(el, "ry") if ry is not None else rxv + e.prim = dict(x=num_attr(el, "x"), y=num_attr(el, "y"), w=num_attr(el, "width"), + h=num_attr(el, "height"), rx=rxv, ry=ryv) + e.typed = sum(el.get(k) is not None for k in ("x", "y", "width", "height", "rx", "ry")) + e.gate = 6 + elif e.tag == "circle": + e.prim = dict(cx=num_attr(el, "cx"), cy=num_attr(el, "cy"), r=num_attr(el, "r")) + e.typed = sum(el.get(k) is not None for k in ("cx", "cy", "r")) + e.gate = 3 + elif e.tag == "ellipse": + e.prim = dict(cx=num_attr(el, "cx"), cy=num_attr(el, "cy"), rx=num_attr(el, "rx"), + ry=num_attr(el, "ry")) + e.typed = sum(el.get(k) is not None for k in ("cx", "cy", "rx", "ry")) + e.gate = 4 + elif e.tag == "use": + e.gate = 6 + return out, V + + +# --------------------------------------------------------------------------- geometry helpers + + +def vec(p, q): + return (q[0] - p[0], q[1] - p[1]) + + +def nonzero(v) -> bool: + return v[0] != 0 or v[1] != 0 + + +def arc_center(p0, rx, ry, phi_deg, fa, fs, p1): + """SVG arc endpoint form to centre form (SVG 1.1 F.6.5), floats.""" + x1, y1 = float(p0[0]), float(p0[1]) + x2, y2 = float(p1[0]), float(p1[1]) + rx, ry = float(rx), float(ry) + phi = math.radians(float(phi_deg)) + c, s = math.cos(phi), math.sin(phi) + dx2, dy2 = (x1 - x2) / 2, (y1 - y2) / 2 + x1p, y1p = c * dx2 + s * dy2, -s * dx2 + c * dy2 + if rx == 0 or ry == 0: + return None + lam = x1p ** 2 / rx ** 2 + y1p ** 2 / ry ** 2 + if lam > 1: + rx, ry = rx * math.sqrt(lam), ry * math.sqrt(lam) + num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p + den = rx * rx * y1p * y1p + ry * ry * x1p * x1p + co = math.sqrt(max(0.0, num / den)) if den > 0 else 0.0 + if fa == fs: + co = -co + cxp, cyp = co * rx * y1p / ry, -co * ry * x1p / rx + + def ang(ux, uy, vx, vy): + return math.atan2(ux * vy - uy * vx, ux * vx + uy * vy) + + th1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry) + dth = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry) + if not fs and dth > 0: + dth -= 2 * math.pi + elif fs and dth < 0: + dth += 2 * math.pi + return rx, ry, phi, th1, dth + + +def arc_tangent(rx, ry, phi, th, sgn): + c, s = math.cos(phi), math.sin(phi) + tx = -rx * math.sin(th) * c - ry * math.cos(th) * s + ty = -rx * math.sin(th) * s + ry * math.cos(th) * c + return (sgn * tx, sgn * ty) + + +def tangents(seg): + """(start tangent, end tangent) of a segment; exact for L, Q, C; float for A.""" + k = seg[0] + if k == "L": + v = vec(seg[2], seg[3]) + return v, v + if k == "C": + p0, c1, c2, p3 = seg[2:6] + t0 = next((vec(p0, q) for q in (c1, c2, p3) if nonzero(vec(p0, q))), (0, 0)) + t1 = next((vec(q, p3) for q in (c2, c1, p0) if nonzero(vec(q, p3))), (0, 0)) + return t0, t1 + if k == "Q": + p0, c, p1 = seg[2:5] + t0 = vec(p0, c) if nonzero(vec(p0, c)) else vec(p0, p1) + t1 = vec(c, p1) if nonzero(vec(c, p1)) else vec(p0, p1) + return t0, t1 + ac = arc_center(seg[2], seg[3], seg[4], seg[5], seg[6], seg[7], seg[8]) + if ac is None: + v = vec(seg[2], seg[8]) + return v, v + rx, ry, phi, th1, dth = ac + sg = 1.0 if dth >= 0 else -1.0 + return arc_tangent(rx, ry, phi, th1, sg), arc_tangent(rx, ry, phi, th1 + dth, sg) + + +def seg_length_nonzero(seg) -> bool: + pts = seg[2:6] if seg[0] == "C" else (seg[2:5] if seg[0] == "Q" else (seg[2], seg[-1])) + return any(p != pts[0] for p in pts[1:]) + + +def turn_deg(t_in, t_out) -> float: + a = (float(t_in[0]), float(t_in[1])) + b = (float(t_out[0]), float(t_out[1])) + cr = a[0] * b[1] - a[1] * b[0] + dt = a[0] * b[0] + a[1] * b[1] + return abs(math.degrees(math.atan2(cr, dt))) + + +def exact_g1(t_in, t_out) -> bool: + if any(isinstance(x, float) for x in (*t_in, *t_out)): + return turn_deg(t_in, t_out) < 1e-6 + return t_in[0] * t_out[1] - t_in[1] * t_out[0] == 0 and t_in[0] * t_out[0] + t_in[1] * t_out[1] > 0 + + +def cubic_is_arc(seg) -> bool: + """A cubic written as a circular arc: equal handles, symmetric, of the length + `(4/3)·tan(θ/4)·r` for its turn θ (the standard arc approximation), within 10 %.""" + p0, c1, c2, p3 = [(float(p[0]), float(p[1])) for p in seg[2:6]] + h0, h1 = (c1[0] - p0[0], c1[1] - p0[1]), (p3[0] - c2[0], p3[1] - c2[1]) + l0, l1 = math.hypot(*h0), math.hypot(*h1) + if l0 < 1e-9 or l1 < 1e-9 or abs(l0 - l1) > 0.1 * max(l0, l1): + return False + th = math.radians(turn_deg(h0, h1)) + if th < math.radians(5) or th > math.radians(179): + return False + chord = math.hypot(p3[0] - p0[0], p3[1] - p0[1]) + r = chord / (2 * math.sin(th / 2)) + want = 4 / 3 * math.tan(th / 4) * r + # the chord must make equal angles with both handles (symmetric arc) + cx, cy = p3[0] - p0[0], p3[1] - p0[1] + a0 = turn_deg(h0, (cx, cy)) + a1 = turn_deg((cx, cy), h1) + return abs(a0 - a1) < 2.0 and abs((l0 + l1) / 2 - want) < 0.1 * want + + +def cubic_is_straight(seg) -> bool: + p0, c1, c2, p3 = [(float(p[0]), float(p[1])) for p in seg[2:6]] + dx, dy = p3[0] - p0[0], p3[1] - p0[1] + L = math.hypot(dx, dy) + if L < 1e-9: + return False + for c in (c1, c2): + if abs((c[0] - p0[0]) * dy - (c[1] - p0[1]) * dx) / L > 0.01 * L: + return False + return True + + +def denominator_class(v: Fraction) -> tuple[int, int]: + """(dyadic exponent or 99, decimal digits or 99) of an exact number.""" + d = v.denominator + a2 = 0 + while d % 2 == 0: + d //= 2 + a2 += 1 + a5 = 0 + while d % 5 == 0: + d //= 5 + a5 += 1 + if d != 1: + return 99, 99 + return (a2 if a5 == 0 else 99), max(a2, a5) + + +def on_curve_points(sp) -> list: + """The subpath's on-curve points, each once: the start and every segment end, except a + final end that returns to the start.""" + pts = [sp["start"]] + for s in sp["segs"]: + pts.append(s[-1]) + if len(pts) > 1 and pts[-1] == pts[0]: + pts.pop() + return pts + + +def control_points(sp) -> list: + out = [] + for s in sp["segs"]: + if s[0] == "C": + out += [s[3], s[4]] + elif s[0] == "Q": + out.append(s[3]) + return out + + +# --------------------------------------------------------------------------- counting + + +def count_icon(path: Path) -> dict: + """Every per-icon count the prior needs, from one artist file.""" + text = path.read_text(encoding="utf-8") + try: + els, V = parse_doc(text) + except Exception as ex: # noqa: BLE001 + return {"error": f"{type(ex).__name__}: {ex}"} + c: Counter = Counter() + dot = Fraction(V) / 480 # a stroke "dot" (lucide's `h.01`), not a drawn line + xs, ys, radii, widths = [], [], [], [] + ends, ctrls = [], [] + classed: list[tuple[str, Fraction]] = [] + + def is_dot(s) -> bool: + return s[0] == "L" and abs(s[3][0] - s[2][0]) + abs(s[3][1] - s[2][1]) < dot + + coords: list[tuple[str, str, Fraction]] = [] # (axis, role, value) of every position + + def record(p, cls: str) -> None: + xs.append(p[0]) + ys.append(p[1]) + ends.extend((p[0], p[1])) + classed.extend(((cls, p[0]), (cls, p[1]))) + coords.extend((("x", cls, p[0]), ("y", cls, p[1]))) + + for e in els: + c["el:" + e.tag] += 1 + c["gate"] += e.gate + c["typed"] += e.typed + if e.stroked: + c["el_stroked"] += 1 + widths.append(e.stroke_width) + if e.filled: + c["el_filled"] += 1 + if e.tf: + c["el_transformed"] += 1 + if e.tag == "rect": + c["rect_rounded"] += int(e.prim["rx"] > 0) + if e.prim["rx"] > 0: + radii.append(e.prim["rx"]) + for k in ("x", "w"): + xs.append(e.prim["x"] if k == "x" else e.prim["x"] + e.prim["w"]) + ys += [e.prim["y"], e.prim["y"] + e.prim["h"]] + ends += [e.prim["x"], e.prim["y"], e.prim["w"], e.prim["h"]] + classed += [("prim", e.prim[k]) for k in ("x", "y", "w", "h")] + coords += [("x", "prim", e.prim["x"]), ("x", "prim", e.prim["x"] + e.prim["w"]), + ("y", "prim", e.prim["y"]), ("y", "prim", e.prim["y"] + e.prim["h"])] + elif e.tag in ("circle", "ellipse"): + radii += [e.prim["r"]] if e.tag == "circle" else [e.prim["rx"], e.prim["ry"]] + xs.append(e.prim["cx"]) + ys.append(e.prim["cy"]) + ends += [e.prim["cx"], e.prim["cy"]] + classed += [("prim", e.prim[k]) for k in e.prim] + coords += [("x", "prim", e.prim["cx"]), ("y", "prim", e.prim["cy"])] + for sp in e.subs: + for p in control_points(sp): + ctrls += [p[0], p[1]] + segs = [s for s in sp["segs"] if seg_length_nonzero(s) and not is_dot(s)] + c["line_dot"] += sum(1 for s in sp["segs"] if seg_length_nonzero(s) and is_dot(s)) + if not segs: # a dot (lucide's `M6 8h.01`) or a lone move: one free point + record(sp["start"], "end") + continue + for s in segs: + k, letter = s[0], s[1] + if letter in "Zz": + c["seg:Z-line"] += 1 + else: + c["seg:" + k] += 1 + c["cmd:" + letter.upper()] += 1 + if k == "L": + dx, dy = vec(s[2], s[3]) + c["line"] += 1 + if dx == 0 or dy == 0: + c["line_axis"] += 1 + c["line_axis_hv"] += int(letter.upper() in "HV") + elif abs(dx) == abs(dy): + c["line_45"] += 1 + else: + ang = math.degrees(math.atan2(abs(float(dy)), abs(float(dx)))) + if min(ang, 90 - ang) <= 0.5: + c["line_near_axis"] += 1 + elif abs(ang - 45) <= 0.5: + c["line_near_45"] += 1 + else: + c["line_other"] += 1 + elif k == "C": + c["cubic"] += 1 + c["cubic_arc"] += int(cubic_is_arc(s)) + c["cubic_straight"] += int(cubic_is_straight(s)) + elif k == "Q": + c["quad"] += 1 + elif k == "A": + c["arc"] += 1 + c["arc_circular"] += int(s[3] == s[4]) + if s[3] == s[4]: + radii.append(s[3]) + else: + radii += [s[3], s[4]] + ac = arc_center(s[2], s[3], s[4], s[5], s[6], s[7], s[8]) + if ac: + sw = abs(math.degrees(ac[4])) + c["arc_sweep_le90"] += int(sw <= 90.5) + c["arc_sweep_le120"] += int(sw <= 120.5) + c["arc_sweep_le180"] += int(sw <= 180.5) + # joins: consecutive segments, and the wrap-around of a closed subpath; each + # on-curve point is classed by the join it sits at + pairs = list(zip(segs, segs[1:])) + if sp["closed"] and len(segs) >= 2: + pairs.append((segs[-1], segs[0])) + else: + record(segs[0][2], "end") + record(segs[-1][-1], "end") + for a, b in pairs: + key = "-".join(sorted((a[0], b[0]))) + t_in, t_out = tangents(a)[1], tangents(b)[0] + c["join:" + key] += 1 + t = turn_deg(t_in, t_out) + curved = key != "L-L" + for lo, hi in TURN_BINS: + if lo <= t < hi: + c[f"turn{'_curve' if curved else '_line'}:{lo}"] += 1 + if exact_g1(t_in, t_out): + c["join_g1:" + key] += 1 + elif t < 2.0: + c["join_near:" + key] += 1 + elif t > 178.0: + c["join_cusp:" + key] += 1 + record(a[-1], "smooth" if t < 2.0 else ("corner" if key == "L-L" else "corner_curve")) + + # coordinates on a grid, as written + for name, vals in (("end", ends), ("ctrl", ctrls)): + for v in vals: + dy2, dec = denominator_class(v) + c[f"{name}_n"] += 1 + for kexp in range(5): + c[f"{name}_dy{kexp}"] += int(dy2 <= kexp) + for d in range(4): + c[f"{name}_dec{d}"] += int(dec <= d) + # the icon's own grid: the coarsest dyadic unit covering 95 % of its on-curve numbers + grid = None + construction = [v for cls, v in classed if cls in ("corner", "end", "prim")] or ends + if construction: + for kexp in range(5): + share = sum(denominator_class(v)[0] <= kexp for v in construction) / len(construction) + if share >= 0.8: + grid = kexp + break + for cls, v in classed: + c[f"cls_{cls}_n"] += 1 + c[f"cls_{cls}_half"] += int(denominator_class(v)[0] <= 1) + c[f"cls_{cls}_icongrid"] += int(grid is not None and denominator_class(v)[0] <= grid) + c[f"cls_{cls}_dec2"] += int(denominator_class(v)[1] <= 2) + # repeated radii and widths + rc = Counter(radii) + c["radius_n"] = len(radii) + c["radius_repeat"] = sum(n for n in rc.values() if n >= 2) + c["radius_distinct"] = len(rc) + c["width_distinct"] = len(set(widths)) + c["stroked_icon"] = int(bool(widths)) + xk, yk = len(set(xs)), len(set(ys)) + return { + "counts": dict(c), + "V": float(V), + "grid": grid, + "xs": [str(v) for v in xs], + "ys": [str(v) for v in ys], + "nx": len(xs), "kx": xk, "ny": len(ys), "ky": yk, + "radii": [str(v) for v in radii], + "coords": [(a, r, str(v)) for a, r, v in coords], + } + + +def icons_for(set_name: str) -> list[tuple[str, Path]]: + if set_name == "corpus": + return [(f, p) for f in GATE_FAMILIES for p in sorted((CORPUS / f).glob("*.svg"))] + import svgeval + items = svgeval.load_sets()[set_name] + return [(it["corpus"], CORPUS / it["corpus"] / f"{it['stem']}.svg") for it in items] + + +def _count_one(arg): + fam, p = arg + r = count_icon(p) + r["family"], r["icon"] = fam, p.stem + return r + + +def crp_alpha(rows: list[tuple[int, int]]) -> float: + """Maximum-likelihood concentration of a Chinese-restaurant process from (n, K) pairs: + the Ewens likelihood K·ln α + lnΓ(α) − lnΓ(α + n), summed over icons.""" + rows = [(n, k) for n, k in rows if n > 0] + if not rows: + return float("nan") + + def ll(la): + a = math.exp(la) + return sum(k * la + math.lgamma(a) - math.lgamma(a + n) for n, k in rows) + + lo, hi = -6.0, 10.0 + g = (math.sqrt(5) - 1) / 2 + for _ in range(80): + m1, m2 = hi - g * (hi - lo), lo + g * (hi - lo) + if ll(m1) < ll(m2): + lo = m1 + else: + hi = m2 + return math.exp((lo + hi) / 2) + + +def prior_code_nats(vals: list[Fraction], V: float, grid: int | None, alpha: float, + pi_on: float, n_px: int = 512, prec_px: float = 0.1) -> list[float]: + """Nats per value under a Chinese-restaurant prior whose base measure is the icon's grid + (weight `pi_on`) mixed with a uniform at inkvec's flat precision; values in order.""" + flat = math.log(n_px / prec_px) + seen: Counter = Counter() + out = [] + for i, v in enumerate(vals): + if seen[v]: + out.append(-math.log(seen[v] / (i + alpha))) + else: + if grid is not None and denominator_class(v)[0] <= grid and pi_on > 0: + base = -math.log(pi_on) + math.log(V * 2 ** grid) + else: + base = -math.log(max(1e-9, 1 - pi_on if grid is not None else 1.0)) + flat + out.append(-math.log(alpha / (i + alpha)) + base) + seen[v] += 1 + return out + + +def summarize_counts(rows: list[dict]) -> dict: + fams = [f for f in GATE_FAMILIES if any(r["family"] == f for r in rows)] + res = {} + for fam in fams + ["ALL"]: + rs = [r for r in rows if "counts" in r and (fam == "ALL" or r["family"] == fam)] + C: Counter = Counter() + for r in rs: + C.update(r["counts"]) + n_icons = len(rs) + + def ratio(a, b): + return C[a] / C[b] if C[b] else float("nan") + + joins = {} + for key in ("L-L", "C-L", "C-C", "A-L", "A-C", "A-A"): + nj = C["join:" + key] + if nj: + joins[key] = dict(n=nj, g1=C["join_g1:" + key] / nj, + near=C["join_near:" + key] / nj, + cusp=C["join_cusp:" + key] / nj) + nseg = sum(C["seg:" + k] for k in ("L", "Q", "C", "A")) + grid_icons = Counter(r["grid"] for r in rs) + xs_rows = [(r["nx"], r["kx"]) for r in rs] + ys_rows = [(r["ny"], r["ky"]) for r in rs] + ax, ay = crp_alpha(xs_rows), crp_alpha(ys_rows) + # the share of an on-grid icon's numbers that are on its grid + on_share = [] + for r in rs: + if r["grid"] is not None and r["xs"]: + vals = [Fraction(v) for v in r["xs"] + r["ys"]] + on_share.append(np.mean([denominator_class(v)[0] <= r["grid"] for v in vals])) + pi_on = float(np.mean(on_share)) if on_share else 0.0 + code = [] + for r in rs: + for key, a in (("xs", ax), ("ys", ay)): + vals = [Fraction(v) for v in r[key]] + code += prior_code_nats(vals, r["V"], r["grid"], a, pi_on) + res[fam] = dict( + icons=n_icons, + gate_per_icon=C["gate"] / max(1, n_icons), + typed_over_gate=ratio("typed", "gate"), + elements=C["el:path"] + C["el:rect"] + C["el:circle"] + C["el:ellipse"] + + C["el:line"] + C["el:polyline"] + C["el:polygon"] + C["el:use"], + el_kinds={k[3:]: C[k] for k in C if k.startswith("el:")}, + stroked_elements=ratio("el_stroked", "el:path") if C["el:path"] else float("nan"), + stroked_icons=C["stroked_icon"] / max(1, n_icons), + rect_rounded=ratio("rect_rounded", "el:rect"), + seg_share={k: C["seg:" + k] / nseg for k in ("L", "Q", "C", "A")} if nseg else {}, + hv_of_axis_lines=ratio("line_axis_hv", "line_axis"), + cmd_S=C["cmd:S"], cmd_T=C["cmd:T"], + lines=C["line"], + line_axis=ratio("line_axis", "line"), + line_45=ratio("line_45", "line"), + line_near_axis=ratio("line_near_axis", "line"), + line_near_45=ratio("line_near_45", "line"), + line_other=ratio("line_other", "line"), + line_dots=C["line_dot"], + cubics=C["cubic"], + cubic_arc=ratio("cubic_arc", "cubic"), + cubic_straight=ratio("cubic_straight", "cubic"), + arcs=C["arc"], + arc_circular=ratio("arc_circular", "arc"), + arc_le90=ratio("arc_sweep_le90", "arc"), + arc_le120=ratio("arc_sweep_le120", "arc"), + arc_le180=ratio("arc_sweep_le180", "arc"), + joins=joins, + end_on_grid={u: ratio(f"end_dy{k}", "end_n") for k, u in + enumerate(("1", "1/2", "1/4", "1/8", "1/16"))}, + end_decimals={d: ratio(f"end_dec{d}", "end_n") for d in range(4)}, + ctrl_on_grid={u: ratio(f"ctrl_dy{k}", "ctrl_n") for k, u in + enumerate(("1", "1/2", "1/4", "1/8", "1/16"))}, + ctrl_decimals={d: ratio(f"ctrl_dec{d}", "ctrl_n") for d in range(4)}, + icon_grid={("none" if g is None else f"1/{2 ** g}"): n / max(1, n_icons) + for g, n in sorted(grid_icons.items(), key=lambda t: (t[0] is None, t[0] or 0))}, + pi_on_grid=pi_on, + radius_repeat=ratio("radius_repeat", "radius_n"), + radii=C["radius_n"], + widths_per_stroked_icon=C["width_distinct"] / max(1, C["stroked_icon"]), + x_reuse=1 - sum(k for _, k in xs_rows) / max(1, sum(n for n, _ in xs_rows)), + y_reuse=1 - sum(k for _, k in ys_rows) / max(1, sum(n for n, _ in ys_rows)), + crp_alpha_x=ax, crp_alpha_y=ay, + point_classes={cls: dict(n=C[f"cls_{cls}_n"], half=ratio(f"cls_{cls}_half", f"cls_{cls}_n"), + icon_grid=ratio(f"cls_{cls}_icongrid", f"cls_{cls}_n"), + dec2=ratio(f"cls_{cls}_dec2", f"cls_{cls}_n")) + for cls in ("corner", "end", "prim", "corner_curve", "smooth")}, + turn_curve={f"{lo}": C[f"turn_curve:{lo}"] / max(1, sum(C[f"turn_curve:{b[0]}"] for b in TURN_BINS)) + for lo, _ in TURN_BINS}, + turn_line={f"{lo}": C[f"turn_line:{lo}"] / max(1, sum(C[f"turn_line:{b[0]}"] for b in TURN_BINS)) + for lo, _ in TURN_BINS}, + prior_nats_per_coord=float(np.mean(code)) if code else float("nan"), + flat_nats_per_coord=math.log(512 / 0.1), + ) + return res + + +# --------------------------------------------------------------------------- geometry (shapely) + + +def shapes_of(text: str): + """Painted elements in paint order as shapely geometries (fill ∪ stroke), with the gate + parameter count of each; svgelements resolves transforms and inheritance.""" + import shapely + import svgelements as se + from shapely.geometry import LineString, Polygon + from shapely.ops import unary_union + doc = se.SVG.parse(io.StringIO(text)) + out = [] + for el in doc.elements(): + if not isinstance(el, se.Shape) or isinstance(el, (se.SVG, se.Group)): + continue + try: + segs = list(se.Path(el).segments()) + except Exception: # noqa: BLE001 + continue + rings, cur, params = [], [], 0 + opened = [] + for s in segs: + nm = type(s).__name__ + if nm == "Move": + if len(cur) >= 2: + opened.append(cur) + cur = [(s.end.x, s.end.y)] + continue + if nm == "Close": + if len(cur) >= 3: + rings.append(cur) + cur = [] + continue + params += {"Line": 2, "QuadraticBezier": 4, "CubicBezier": 6, "Arc": 7}.get(nm, 0) + n = 1 if nm == "Line" else 12 + for i in range(1, n + 1): + p = s.point(i / n) + cur.append((p.x, p.y)) + if len(cur) >= 2: + opened.append(cur) + kind = type(el).__name__ + prim = {"Circle": 3, "Ellipse": 4, "Rect": 6, "SimpleLine": 4}.get(kind) + if prim is not None: + params = prim + fill = el.fill if el.fill is not None and el.fill.value is not None else None + geo = [] + if fill is not None and fill.alpha != 0: + polys = [] + for r in rings + [o for o in opened if len(o) >= 3]: + pg = Polygon(r).buffer(0) + if not pg.is_empty: + polys.append(pg) + if polys: + g = polys[0] + for pg in polys[1:]: + g = g.symmetric_difference(pg) + geo.append(g) + sw = float(el.stroke_width or 0) if el.stroke is not None and el.stroke.value is not None else 0.0 + if sw > 0 and el.stroke.alpha != 0: + cap = {"round": 1, "square": 3}.get(str(el.values.get("stroke-linecap", "butt")), 2) + join = {"round": 1, "bevel": 3}.get(str(el.values.get("stroke-linejoin", "miter")), 2) + for r in rings: + geo.append(LineString(r + [r[0]]).buffer(sw / 2, cap_style=cap, join_style=join)) + for o in opened: + geo.append(LineString(o).buffer(sw / 2, cap_style=cap, join_style=join)) + if not geo: + continue + try: + g = shapely.set_precision(unary_union(geo).buffer(0), 1e-5) + except Exception: # noqa: BLE001 + continue + if g.is_empty or g.area <= 0: + continue + op = 1.0 + for k in ("opacity", "fill-opacity"): + try: + op *= float(el.values.get(k, 1)) + except (TypeError, ValueError): + pass + opaque = op > 0.999 and (fill is None or fill.alpha == 255) + paint = (str(fill) if fill is not None and fill.alpha != 0 else None, + str(el.stroke) if sw > 0 else None) + out.append(dict(geo=g, params=params, opaque=opaque, kind=kind, paint=paint)) + return out + + +def iou(a, b) -> float: + try: + i = a.intersection(b).area + except Exception: # noqa: BLE001 + return 0.0 + u = a.area + b.area - i + return i / u if u > 0 else 0.0 + + +def geometry_icon(arg) -> dict: + fam, path = arg + from shapely import affinity + from shapely.ops import unary_union + text = path.read_text(encoding="utf-8") + try: + sh = shapes_of(text) + except Exception as ex: # noqa: BLE001 + return {"family": fam, "icon": path.stem, "error": str(ex)} + res = {"family": fam, "icon": path.stem, "n": len(sh)} + total = sum(s["params"] for s in sh) or 1 + # layers: how much of each element the elements painted after it, in another paint, cover + later = [] + occ = [] + for s in reversed(sh): + g = s["geo"] + f, borrowed = 0.0, 0.0 + cands = [h["geo"] for h in later if h["opaque"] and h["paint"] != s["paint"] + and h["geo"].intersects(g)] + if cands: + try: + union = unary_union(cands) + f = g.intersection(union).area / g.area + if 0.02 < f < 0.98: + vis = g.difference(union) + blen = vis.boundary.length + shared = vis.boundary.intersection( + union.boundary.buffer(1e-3 * math.sqrt(g.area))).length + borrowed = shared / blen if blen > 0 else 0.0 + except Exception: # noqa: BLE001 + pass + occ.append((f, s["params"], borrowed)) + later.append(s) + occ.reverse() + res["partial"] = sum(1 for f, _, _ in occ if 0.02 < f < 0.98) + res["hidden"] = sum(1 for f, _, _ in occ if f >= 0.98) + res["partial_params"] = sum(p for f, p, _ in occ if 0.02 < f < 0.98) / total + res["hidden_params"] = sum(p for f, p, _ in occ if f >= 0.98) / total + res["borrowed"] = [b for f, _, b in occ if 0.02 < f < 0.98] + # symmetry, repetition: elements against their own mirror and against each other + self_sym = mirror_pair = repeat = 0 + save_use = 0 + cents = [s["geo"].centroid for s in sh] + used = set() + for i, s in enumerate(sh): + g = s["geo"] + c = cents[i] + if iou(g, affinity.scale(g, -1, 1, origin=c)) > 0.97 or iou(g, affinity.scale(g, 1, -1, origin=c)) > 0.97: + self_sym += 1 + for j in range(i + 1, len(sh)): + h = sh[j]["geo"] + if abs(g.area - h.area) > 0.03 * max(g.area, h.area): + continue + cj = cents[j] + if math.hypot(c.x - cj.x, c.y - cj.y) < 1e-6 * math.sqrt(g.area): + continue + if iou(affinity.translate(g, cj.x - c.x, cj.y - c.y), h) > 0.97: + if j not in used: + repeat += 1 + used.add(j) + save_use += max(0, sh[j]["params"] - 6) + continue + if abs(c.y - cj.y) < 0.02 * math.sqrt(g.area) and \ + iou(affinity.scale(g, -1, 1, origin=((c.x + cj.x) / 2, c.y)), h) > 0.97: + mirror_pair += 1 + res.update(self_sym=self_sym, mirror_pair=mirror_pair, repeat=repeat, + use_saving=save_use / total) + # whole-drawing symmetry, on a render + try: + from inkvec_bench import render + img = render.render(text, 128, 128).astype(np.float64) + pm = np.concatenate([img[..., :3] * img[..., 3:], img[..., 3:]], axis=-1) + den = np.abs(pm).sum() or 1.0 + res["sym_v"] = float(np.abs(pm - pm[:, ::-1]).sum() / den) + res["sym_h"] = float(np.abs(pm - pm[::-1, :]).sum() / den) + res["sym_r"] = float(np.abs(pm - pm[::-1, ::-1]).sum() / den) + except Exception: # noqa: BLE001 + pass + return res + + +def summarize_geometry(rows: list[dict]) -> dict: + out = {} + fams = [f for f in GATE_FAMILIES if any(r["family"] == f for r in rows)] + for fam in fams + ["ALL"]: + rs = [r for r in rows if "n" in r and (fam == "ALL" or r["family"] == fam)] + if not rs: + continue + nel = sum(r["n"] for r in rs) or 1 + b = [x for r in rs for x in r["borrowed"]] + d = dict( + icons=len(rs), + el_partially_covered=sum(r["partial"] for r in rs) / nel, + el_hidden=sum(r["hidden"] for r in rs) / nel, + icons_with_partial=np.mean([r["partial"] > 0 for r in rs]), + params_in_partial=float(np.mean([r["partial_params"] for r in rs])), + params_in_hidden=float(np.mean([r["hidden_params"] for r in rs])), + borrowed_boundary_median=float(np.median(b)) if b else float("nan"), + el_self_symmetric=sum(r["self_sym"] for r in rs) / nel, + el_mirror_pairs=sum(r["mirror_pair"] for r in rs) / nel, + el_repeats=sum(r["repeat"] for r in rs) / nel, + icons_with_repeat=np.mean([r["repeat"] > 0 for r in rs]), + use_saving=float(np.mean([r["use_saving"] for r in rs])), + ) + for k in ("sym_v", "sym_h", "sym_r"): + v = [r[k] for r in rs if k in r] + if v: + d[k + "_lt_0.01"] = float(np.mean([x < 0.01 for x in v])) + d[k + "_lt_0.03"] = float(np.mean([x < 0.03 for x in v])) + d["any_mirror_lt_0.01"] = float(np.mean([min(r.get("sym_v", 1), r.get("sym_h", 1)) < 0.01 for r in rs])) + out[fam] = d + return out + + +# --------------------------------------------------------------------------- simulations + +VIEWBOXES = [16, 20, 24, 32, 36, 48, 64, 72, 96, 100, 128] +SUBDIV = [0, 1, 2, 3] # unit 1, 1/2, 1/4, 1/8 + + +def wrapped_density(r: np.ndarray, g: float, sigma: float) -> np.ndarray: + """Density at offset `r` (|r| <= g/2) of a Gaussian wrapped on a circle of length g.""" + k = np.arange(-2, 3)[:, None] + return np.exp(-0.5 * ((r[None, :] + k * g) / sigma) ** 2).sum(0) / (math.sqrt(2 * math.pi) * sigma) + + +def infer_grid(x: np.ndarray, n_px: int, sigma: float): + """Empirical-Bayes design grid. Hypotheses: pitch g = n_px/V·2^-k for V in VIEWBOXES and k + in SUBDIV, prior uniform over V and halving per subdivision, and 'no grid' at prior ½. Per + pitch the mixture weight π of on-grid coordinates is fitted (Laplace, ½·ln n for it). The + likelihood ratio of one coordinate against a uniform background is π·g·φ(r) + 1 − π, with + φ the wrapped Gaussian at its offset r from the nearest grid point.""" + hyps: dict[float, float] = {} + for V in VIEWBOXES: + for k in SUBDIV: + g = round(n_px / V / 2 ** k, 12) + hyps[g] = hyps.get(g, 0.0) + (1 / len(VIEWBOXES)) * 2.0 ** -(k + 1) * 0.5 / (1 - 2 ** -len(SUBDIV)) + best = (math.log(0.5), None, 0.0) + n = len(x) + pis = np.linspace(0.02, 0.995, 60) + for g, pr in hyps.items(): + if g < 3 * sigma: + continue # the pitch is below the measurement's resolution: no evidence either way + r = x - g * np.round(x / g) + dens = g * wrapped_density(r, g, sigma) + ll = np.log(pis[:, None] * dens[None, :] + (1 - pis[:, None])).sum(1) + j = int(np.argmax(ll)) + score = math.log(pr) + ll[j] - 0.5 * math.log(max(n, 1)) + if score > best[0]: + best = (score, g, pis[j]) + return best + + +def grid_sim_icon(arg) -> list[dict]: + fam, icon, xs, ys, V, n_pxs, sigmas, seed = arg + rng = np.random.default_rng(seed) + vals = [Fraction(v) for v in xs + ys] + if len(vals) < 4: + return [] + out = [] + for n_px in n_pxs: + s = Fraction(n_px) / Fraction(V).limit_denominator(10 ** 6) + true_px = np.array([float(v * s) for v in vals]) + for sigma in sigmas: + obs = true_px + rng.normal(0, sigma, len(true_px)) + _, g, pi = infer_grid(obs, n_px, sigma) + snapped = np.zeros(len(obs), bool) + final = obs.copy() + if g is not None: + r = obs - g * np.round(obs / g) + d = g * wrapped_density(r, g, sigma) + resp = pi * d / (pi * d + 1 - pi) + snapped = resp > 0.5 + final[snapped] = g * np.round(obs[snapped] / g) + exact = np.abs(final - true_px) < 1e-7 + out.append(dict(family=fam, icon=icon, n_px=n_px, sigma=sigma, n=len(obs), + grid=g, exact=int((snapped & exact).sum()), + wrong=int((snapped & ~exact).sum()), + err_before=float(np.abs(obs - true_px).mean()), + err_after=float(np.abs(final - true_px).mean()))) + return out + + +CONSTRUCTION = {"corner", "end", "prim"} + + +def grid_hypotheses(n_px: int) -> dict[float, float]: + """Pitch (px) -> prior mass: uniform over VIEWBOXES, halving per subdivision, total 1/2.""" + hyps: dict[float, float] = {} + for Vh in VIEWBOXES: + for k in SUBDIV: + g = round(n_px / Vh / 2 ** k, 12) + hyps[g] = hyps.get(g, 0.0) + (1 / len(VIEWBOXES)) * 2.0 ** -(k + 1) * 0.5 / (1 - 2 ** -len(SUBDIV)) + return hyps + + +def grid_sim_hier_icon(arg) -> list[dict]: + """The hierarchical model: ties first (exact 1-D clustering per axis under the CRP), then + the grid on the cluster means (each with noise sigma/sqrt(size)), with the on-grid weight + fitted separately for construction points (line-line corners, open ends, primitive + centres and sides) and for derived points (curve corners, tangent points).""" + fam, icon, coords, V, alpha, n_pxs, sigmas, seed = arg + rng = np.random.default_rng(seed) + if len(coords) < 4: + return [] + out = [] + pis = np.linspace(0.02, 0.995, 60) + kk = np.arange(-2, 3)[:, None] + for n_px in n_pxs: + s = Fraction(n_px) / Fraction(V).limit_denominator(10 ** 6) + for sigma in sigmas: + clusters = [] # (mean, sd, construction?, member indices) + true_all, obs_all = [], [] + for axis in ("x", "y"): + idx = [i for i, c in enumerate(coords) if c[0] == axis] + if not idx: + continue + true = np.array([float(Fraction(coords[i][2]) * s) for i in idx]) + obs = true + rng.normal(0, sigma, len(true)) + lab = ties_dp(obs, sigma, alpha, float(n_px)) if len(idx) <= 1500 else np.arange(len(idx)) + base = len(true_all) + true_all += true.tolist() + obs_all += obs.tolist() + for c in np.unique(lab): + mem = np.where(lab == c)[0] + con = any(coords[idx[m]][1] in CONSTRUCTION for m in mem) + clusters.append((float(obs[mem].mean()), sigma / math.sqrt(len(mem)), con, + [base + int(m) for m in mem])) + true_all, obs_all = np.array(true_all), np.array(obs_all) + mu = np.array([c[0] for c in clusters]) + sd = np.array([c[1] for c in clusters]) + con = np.array([c[2] for c in clusters]) + best = (math.log(0.5), None, 0.0, 0.0) + for g, pr in grid_hypotheses(n_px).items(): + if g < 3 * sigma: + continue + r = mu - g * np.round(mu / g) + dens = g * np.exp(-0.5 * ((r[None, :] + kk * g) / sd[None, :]) ** 2).sum(0) / (math.sqrt(2 * math.pi) * sd) + score = math.log(pr) + pick = [] + for mask in (con, ~con): + if mask.sum() == 0: + pick.append(0.0) + continue + ll = np.log(pis[:, None] * dens[mask][None, :] + (1 - pis[:, None])).sum(1) + j = int(np.argmax(ll)) + score += ll[j] - 0.5 * math.log(mask.sum()) + pick.append(pis[j]) + if score > best[0]: + best = (score, g, pick[0], pick[1]) + _, g, pc, pd = best + final = np.zeros(len(true_all)) + snapped = np.zeros(len(true_all), bool) + for (m, sdc, cflag, mem) in clusters: + val = m + if g is not None: + pi = pc if cflag else pd + r = m - g * round(m / g) + d = g * sum(math.exp(-0.5 * ((r + k * g) / sdc) ** 2) for k in range(-2, 3)) / (math.sqrt(2 * math.pi) * sdc) + if pi * d / (pi * d + 1 - pi) > 0.5: + val = g * round(m / g) + snapped[mem] = True + final[mem] = val + exact = np.abs(final - true_all) < 1e-7 + out.append(dict(family=fam, icon=icon, n_px=n_px, sigma=sigma, n=len(true_all), + grid=g, exact=int((snapped & exact).sum()), + wrong=int((snapped & ~exact).sum()), + err_before=float(np.abs(obs_all - true_all).mean()), + err_after=float(np.abs(final - true_all).mean()))) + return out + + +def ties_dp(x: np.ndarray, sigma: float, alpha: float, W: float) -> np.ndarray: + """MAP partition of the values into equal-value clusters under a Chinese-restaurant prior + (concentration alpha), a uniform base measure on [0, W] and Gaussian noise of known sigma. + Equal noise makes the optimal clusters contiguous in sorted order, so this O(n²) dynamic + program is exact. Returns a cluster label per input value (input order).""" + order = np.argsort(x) + v = x[order] + n = len(v) + s1 = np.concatenate([[0.0], np.cumsum(v)]) + s2 = np.concatenate([[0.0], np.cumsum(v * v)]) + best = np.full(n + 1, np.inf) + best[0] = 0.0 + arg = np.zeros(n + 1, int) + lg = np.array([math.lgamma(m) if m > 0 else 0.0 for m in range(n + 1)]) + l2ps = math.log(2 * math.pi * sigma * sigma) + for b in range(1, n + 1): + a = np.arange(0, b) + m = b - a + sse = (s2[b] - s2[a]) - (s1[b] - s1[a]) ** 2 / m + cost = (-math.log(alpha) - lg[m] + math.log(W) + 0.5 * (m - 1) * l2ps + + np.maximum(sse, 0) / (2 * sigma * sigma) + 0.5 * np.log(m)) + tot = best[a] + cost + j = int(np.argmin(tot)) + best[b], arg[b] = tot[j], a[j] + labels = np.zeros(n, int) + b, lab = n, 0 + while b > 0: + a = arg[b] + labels[order[a:b]] = lab + lab += 1 + b = a + return labels + + +def ties_sim_icon_exact(arg) -> list[dict]: + """Pairwise precision/recall of recovered equalities, and error before/after.""" + fam, icon, xs, ys, V, alpha, n_pxs, sigmas, seed = arg + rng = np.random.default_rng(seed) + out = [] + for n_px in n_pxs: + s = n_px / V + for sigma in sigmas: + row = dict(family=fam, icon=icon, n_px=n_px, sigma=sigma, tp=0, fp=0, fn=0, + n=0, err_before=0.0, err_after=0.0) + for coords in (xs, ys): + if len(coords) < 2 or len(coords) > 1500: + continue + vals = [Fraction(v) for v in coords] + true = np.array([float(v) * s for v in vals]) + obs = true + rng.normal(0, sigma, len(true)) + lab = ties_dp(obs, sigma, alpha, float(n_px)) + est = obs.copy() + for c in np.unique(lab): + est[lab == c] = obs[lab == c].mean() + t_lab = {} + tl = np.array([t_lab.setdefault(str(v), len(t_lab)) for v in vals]) + # pairs predicted equal, truly equal, both + joint = Counter(zip(lab.tolist(), tl.tolist())) + pred = Counter(lab.tolist()) + tru = Counter(tl.tolist()) + both = sum(k * (k - 1) // 2 for k in joint.values()) + p_pairs = sum(k * (k - 1) // 2 for k in pred.values()) + t_pairs = sum(k * (k - 1) // 2 for k in tru.values()) + row["tp"] += both + row["fp"] += p_pairs - both + row["fn"] += t_pairs - both + row["n"] += len(true) + row["err_before"] += float(np.abs(obs - true).sum()) + row["err_after"] += float(np.abs(est - true).sum()) + out.append(row) + return out + + +# --------------------------------------------------------------------------- main + + +def report_grid(sims, title, set_name) -> dict: + agg = {} + print(f"\n== grid inference and snapping, {title} ({set_name})") + for fam in [f for f in GATE_FAMILIES if any(s["family"] == f for s in sims)] + ["ALL"]: + for n_px in (128, 512): + for sigma in (0.005, 0.02, 0.05, 0.1): + ss = [s for s in sims if (fam == "ALL" or s["family"] == fam) + and s["n_px"] == n_px and s["sigma"] == sigma] + n = sum(s["n"] for s in ss) or 1 + d = dict(exact=sum(s["exact"] for s in ss) / n, wrong=sum(s["wrong"] for s in ss) / n, + grid_found=float(np.mean([s["grid"] is not None for s in ss])), + err_ratio=sum(s["err_after"] for s in ss) / max(1e-12, sum(s["err_before"] for s in ss))) + agg[f"{fam}/{n_px}/{sigma}"] = d + print(f"[{fam}] {n_px}px σ={sigma}: grid found {fmt(d['grid_found'], 2)}, " + f"exact {fmt(d['exact'])}, wrong {fmt(d['wrong'], 4)}, " + f"error after/before {fmt(d['err_ratio'])}") + return agg + + +def fmt(x, nd=3): + if isinstance(x, float): + return "nan" if math.isnan(x) else f"{x:.{nd}f}" + return str(x) + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--set", default="corpus", help="corpus (every gate-family file), screen, all, ...") + ap.add_argument("--part", default="counts", choices=["counts", "geometry", "grid_sim", "ties_sim", "all"]) + ap.add_argument("--workers", type=int, default=3) + ap.add_argument("--json", default="") + a = ap.parse_args() + icons = icons_for(a.set) + report: dict = {"set": a.set, "icons": len(icons)} + parts = ["counts", "geometry", "grid_sim", "ties_sim"] if a.part == "all" else [a.part] + + with ProcessPoolExecutor(a.workers) as pool: + rows = [r for r in pool.map(_count_one, icons, chunksize=8) if "counts" in r] + cs = summarize_counts(rows) + report["counts"] = cs + if "counts" in parts: + print(f"== counts over {len(rows)} artist files ({a.set})") + for fam, d in cs.items(): + print(f"\n[{fam}] icons {d['icons']}, gate params/icon {fmt(d['gate_per_icon'], 1)}, " + f"typed/gate {fmt(d['typed_over_gate'], 2)}") + print(" elements", d["el_kinds"], "rounded rects", fmt(d["rect_rounded"], 2), + "stroked icons", fmt(d["stroked_icons"], 2)) + print(" segments", {k: fmt(v, 3) for k, v in d["seg_share"].items()}, + "S", d["cmd_S"], "T", d["cmd_T"]) + print(f" lines {d['lines']}: axis {fmt(d['line_axis'])} (H/V {fmt(d['hv_of_axis_lines'], 2)}), " + f"45° {fmt(d['line_45'])}, near-axis {fmt(d['line_near_axis'])}, near-45 " + f"{fmt(d['line_near_45'])}, other {fmt(d['line_other'])}; dots {d['line_dots']}") + print(f" cubics {d['cubics']}: arc-like {fmt(d['cubic_arc'])}, straight {fmt(d['cubic_straight'])}; " + f"arcs {d['arcs']}: circular {fmt(d['arc_circular'])}, ≤90° {fmt(d['arc_le90'])}, " + f"≤120° {fmt(d['arc_le120'])}, ≤180° {fmt(d['arc_le180'])}") + print(" joins", {k: {kk: fmt(vv) for kk, vv in v.items()} for k, v in d["joins"].items()}) + print(" on-curve numbers on grid", {k: fmt(v) for k, v in d["end_on_grid"].items()}, + "decimals≤", {k: fmt(v) for k, v in d["end_decimals"].items()}) + print(" control numbers on grid", {k: fmt(v) for k, v in d["ctrl_on_grid"].items()}, + "decimals≤", {k: fmt(v) for k, v in d["ctrl_decimals"].items()}) + print(" point classes", {k: {kk: fmt(vv) for kk, vv in v.items()} for k, v in d["point_classes"].items()}) + print(" turn at curve joins (deg bins)", {k: fmt(v) for k, v in d["turn_curve"].items()}) + print(" turn at line-line joins", {k: fmt(v) for k, v in d["turn_line"].items()}) + print(" icon grid", {k: fmt(v) for k, v in d["icon_grid"].items()}, + "π_on", fmt(d["pi_on_grid"])) + print(f" radii {d['radii']}: repeated {fmt(d['radius_repeat'])}; widths per stroked icon " + f"{fmt(d['widths_per_stroked_icon'], 2)}") + print(f" reuse x {fmt(d['x_reuse'])} y {fmt(d['y_reuse'])}; CRP α x {fmt(d['crp_alpha_x'], 2)} " + f"y {fmt(d['crp_alpha_y'], 2)}; nats/coord prior {fmt(d['prior_nats_per_coord'], 2)} " + f"vs flat {fmt(d['flat_nats_per_coord'], 2)}") + + if "geometry" in parts: + g_rows = list(pool.map(geometry_icon, icons, chunksize=4)) + gs = summarize_geometry([r for r in g_rows if "n" in r]) + report["geometry"] = gs + print(f"\n== geometry ({a.set})") + for fam, d in gs.items(): + print(f"[{fam}] " + ", ".join(f"{k} {fmt(v)}" for k, v in d.items())) + + if "grid_sim" in parts: + args = [(r["family"], r["icon"], r["xs"], r["ys"], r["V"], [128, 512], [0.005, 0.02, 0.05, 0.1], + i) for i, r in enumerate(rows)] + sims = [x for lst in pool.map(grid_sim_icon, args, chunksize=4) for x in lst] + alphas = {f: (d["crp_alpha_x"] + d["crp_alpha_y"]) / 2 for f, d in cs.items()} + hargs = [(r["family"], r["icon"], r["coords"], r["V"], alphas[r["family"]], [128, 512], + [0.005, 0.02, 0.05, 0.1], i) for i, r in enumerate(rows)] + hsims = [x for lst in pool.map(grid_sim_hier_icon, hargs, chunksize=4) for x in lst] + report["grid_sim_hier"] = report_grid(hsims, "hierarchical: ties, then grid by role", a.set) + agg = {} + print(f"\n== grid inference and snapping, per coordinate, one weight ({a.set})") + for fam in [f for f in GATE_FAMILIES if any(s["family"] == f for s in sims)] + ["ALL"]: + for n_px in (128, 512): + for sigma in (0.005, 0.02, 0.05, 0.1): + ss = [s for s in sims if (fam == "ALL" or s["family"] == fam) + and s["n_px"] == n_px and s["sigma"] == sigma] + n = sum(s["n"] for s in ss) or 1 + d = dict(exact=sum(s["exact"] for s in ss) / n, wrong=sum(s["wrong"] for s in ss) / n, + grid_found=float(np.mean([s["grid"] is not None for s in ss])), + err_ratio=sum(s["err_after"] for s in ss) / max(1e-12, sum(s["err_before"] for s in ss))) + agg[f"{fam}/{n_px}/{sigma}"] = d + print(f"[{fam}] {n_px}px σ={sigma}: grid found {fmt(d['grid_found'], 2)}, " + f"exact {fmt(d['exact'])}, wrong {fmt(d['wrong'], 4)}, " + f"error after/before {fmt(d['err_ratio'])}") + report["grid_sim"] = agg + + if "ties_sim" in parts: + alphas = {f: (d["crp_alpha_x"] + d["crp_alpha_y"]) / 2 for f, d in cs.items()} + args = [(r["family"], r["icon"], r["xs"], r["ys"], r["V"], alphas[r["family"]], [128, 512], + [0.005, 0.02, 0.05, 0.1], 7 + i) for i, r in enumerate(rows)] + sims = [x for lst in pool.map(ties_sim_icon_exact, args, chunksize=4) for x in lst] + agg = {} + print(f"\n== coordinate ties by exact 1-D clustering under a CRP prior ({a.set})") + for fam in [f for f in GATE_FAMILIES if any(s["family"] == f for s in sims)] + ["ALL"]: + for n_px in (128, 512): + for sigma in (0.005, 0.02, 0.05, 0.1): + ss = [s for s in sims if (fam == "ALL" or s["family"] == fam) + and s["n_px"] == n_px and s["sigma"] == sigma] + tp, fp, fn = (sum(s[k] for s in ss) for k in ("tp", "fp", "fn")) + d = dict(precision=tp / max(1, tp + fp), recall=tp / max(1, tp + fn), + err_ratio=sum(s["err_after"] for s in ss) / max(1e-12, sum(s["err_before"] for s in ss))) + agg[f"{fam}/{n_px}/{sigma}"] = d + print(f"[{fam}] {n_px}px σ={sigma}: pairs precision {fmt(d['precision'])}, " + f"recall {fmt(d['recall'])}, error after/before {fmt(d['err_ratio'])}") + report["ties_sim"] = agg + + if a.json: + Path(a.json).parent.mkdir(parents=True, exist_ok=True) + Path(a.json).write_text(json.dumps(report, indent=1, default=str), encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/bench/theory/evidence_eval.py b/bench/theory/evidence_eval.py new file mode 100644 index 00000000..f6f4e600 --- /dev/null +++ b/bench/theory/evidence_eval.py @@ -0,0 +1,286 @@ +"""Checks of the boundary chain's variance model and precision formulas on exact renders. + +`docs/theory/chain-boundary.md` states, informally, what the pixels' area measurements are +worth: how much a window sum varies under 8-bit quantisation and under n x n point +supersampling, how much information column sums keep against per-pixel terms, how precisely +two arms place a corner's vertex, and how small a fillet the pixels can tell from a sharp +corner. Each subcommand measures one of those claims against exactly known geometry. + +* `calib` column- and row-window sums of discs against the exact areas in the same windows: + residual spread against `n_partial / (255^2 * 12)` (8-bit) and `1 / (12 n^3)` + (point supersampling), by angle to the scan axis, and its lag-1 correlation. +* `info` Fisher information about a straight edge's normal offset, per-pixel terms against + column sums, with equal noise on every partial pixel: predicted ratio + `(1 - t/2) / (1 - t/3)`, `t = |tan|`, never below 3/4. +* `vertex` a wedge's vertex as the intersection of two arms fitted by column-sum least + squares: RMS error against `sqrt(2 V_eff (1 + 12 s_m^2 / L^2) / L) / sin(alpha)`. +* `fillet` per-pixel chi^2 between a sharp corner and a fillet of radius r, against the + one-pixel bound `r = sqrt(3 sigma / (tan(tau/2) - tau/2))` for chi^2 = 9. + + python3 bench/theory/evidence_eval.py calib|info|vertex|fillet|all + +Coordinates as in `exact_raster.py`: pixel (i, j) is [i, i+1] x [j, j+1], y down. +""" + +from __future__ import annotations + +import math +import sys + +import numpy as np + +import exact_raster as er + +SIGMA_Q = 1.0 / (255.0 * math.sqrt(12.0)) # 8-bit quantisation, one channel (or a grey axis) + + +def q8(a: np.ndarray) -> np.ndarray: + return np.round(a * 255.0) / 255.0 + + +# ---------------------------------------------------------------------------------- calib + +def _ss_disc(size: int, cx: float, cy: float, r: float, n: int) -> np.ndarray: + s = (np.arange(size * n) + 0.5) / n + x, y = np.meshgrid(s, s) + inside = ((x - cx) ** 2 + (y - cy) ** 2 < r * r).astype(np.float64) + return inside.reshape(size, n, size, n).mean(axis=(1, 3)) + + +def _windows(obs: np.ndarray, exact: np.ndarray, cx: float, cy: float) -> list[tuple]: + """Column windows where the boundary is within 45 degrees of horizontal, row windows + elsewhere, each from a pure pixel to a pure pixel of the other kind. Returns + (observed sum - exact sum, partial pixels, angle to the scan axis, polar angle).""" + eps = 1e-9 + out = [] + for transpose in (False, True): + a = obs.T if transpose else obs + e = exact.T if transpose else exact + h, w = a.shape + for i in range(w): + col = a[:, i] + sat = np.where(col >= 1 - eps, 1, np.where(col <= eps, 0, -1)) + j = 0 + while j < h: + if sat[j] == -1: + j += 1 + continue + k = j + 1 + while k < h and sat[k] == -1: + k += 1 + if k >= h: + break + if sat[k] != sat[j] and k - j >= 2: + xm, ym = i + 0.5, 0.5 * (j + k) + 0.5 + px, py = (ym, xm) if transpose else (xm, ym) + nx, ny = px - cx, py - cy + a_n, b_n = (nx, ny) if not transpose else (ny, nx) + if abs(b_n) >= abs(a_n): + seg = e[j:k + 1, i] + npart = int(((seg > eps) & (seg < 1 - eps)).sum()) + out.append((col[j:k + 1].sum() - seg.sum(), npart, + math.atan2(abs(a_n), abs(b_n)), + math.atan2(py - cy, px - cx))) + j = k + return out + + +def calib(trials: int = 16, size: int = 64) -> None: + rng = np.random.default_rng(7) + print(f"8-bit sigma_q = 1/(255 sqrt 12) = {SIGMA_Q:.5f}") + conds = [("exact float", None, False), ("exact + 8-bit", None, True)] + conds += [(f"ss{n} + 8-bit", n, True) for n in (8, 16, 32)] + for name, n, quant in conds: + res = [] + for _ in range(trials): + r = rng.uniform(6, 26) + cx, cy = rng.uniform(r + 3, size - r - 3, 2) + exact = er.rasterize([er.circle(cx, cy, r)], size, size) + obs = exact if n is None else _ss_disc(size, cx, cy, r, n) + if quant: + obs = q8(obs) + res.append(_windows(obs, exact, cx, cy)) + rr = np.array([w[0] for ws in res for w in ws]) + npart = np.array([w[1] for ws in res for w in ws]) + ang = np.array([w[2] for ws in res for w in ws]) + cors = [] + for ws in res: + seq = np.array([w[0] for w in sorted(ws, key=lambda w: w[3])]) + if len(seq) > 10 and seq.std() > 0: + cors.append(np.corrcoef(seq[:-1], seq[1:])[0, 1]) + pred = math.sqrt(npart.mean() * SIGMA_Q ** 2 * quant + (1 / (12 * n ** 3) if n else 0.0)) + lag = f"{np.mean(cors):+.3f}" if cors else "n/a" + print(f"{name:14s} windows {len(rr):5d} std {rr.std():.5f} predicted {pred:.5f} " + f"rms/sqrt(partial) {np.sqrt((rr ** 2 / np.maximum(npart, 1)).mean()):.5f} " + f"lag-1 corr {lag}") + if n: + for lo, hi in [(0, 0.02), (0.02, 0.13), (0.13, 0.4), (0.4, 0.8)]: + m = (ang >= lo) & (ang < hi) + if m.sum() > 10: + print(f" angle {lo:.2f}-{hi:.2f} rad: n {m.sum():4d} mean {rr[m].mean():+.5f}" + f" std {rr[m].std():.5f} (near-axis bound 1/(2n) = {1 / (2 * n):.4f})") + + +# ----------------------------------------------------------------------------------- info + +def info(trials: int = 24, size: int = 48) -> None: + rng = np.random.default_rng(11) + h = 1e-5 + + def cov(theta: float, off: float) -> np.ndarray: + nrm = np.array([-math.sin(theta), math.cos(theta)]) + p = np.array([size / 2, size / 2]) + off * nrm + return er.rasterize([er.half_plane(size, size, p[0], p[1], theta)], size, size) + + print("information about the normal offset kept by column sums (equal noise per partial pixel)") + for deg in (0, 10, 20, 30, 40): + th = math.radians(deg) + 1e-3 + pix = col = 0.0 + for _ in range(trials): + off = rng.uniform(0, 1) + a0 = cov(th, off)[8:-8, 8:-8] + g = (cov(th, off + h)[8:-8, 8:-8] - a0) / h + part = (a0 > 1e-9) & (a0 < 1 - 1e-9) + pix += (g[part] ** 2).sum() + for i in range(g.shape[1]): + m = part[:, i] + if m.any(): + col += g[m, i].sum() ** 2 / m.sum() + t = math.tan(th) + print(f" {deg:2d} deg: measured {col / pix:.3f} predicted {(1 - t / 2) / (1 - t / 3):.3f}") + + +# --------------------------------------------------------------------------------- vertex + +def _wedge(size: int, v, u1, u2) -> np.ndarray: + """The wedge {v + s u1 + t u2 : s, t >= 0} clipped to the frame (Sutherland-Hodgman).""" + poly = [np.array(p, dtype=float) for p in [(0, 0), (size, 0), (size, size), (0, size)]] + tests = (lambda p: u1[0] * (p[1] - v[1]) - u1[1] * (p[0] - v[0]), + lambda p: (p[0] - v[0]) * u2[1] - (p[1] - v[1]) * u2[0]) + for f in tests: + out = [] + for k in range(len(poly)): + a, b = poly[k], poly[(k + 1) % len(poly)] + fa, fb = f(a), f(b) + if fa >= 0: + out.append(a) + if (fa >= 0) != (fb >= 0): + out.append(a + fa / (fa - fb) * (b - a)) + poly = out + return np.array(poly) + + +def _ss_convex(size: int, poly: np.ndarray, n: int) -> np.ndarray: + s = (np.arange(size * n) + 0.5) / n + x, y = np.meshgrid(s, s) + p = np.vstack([poly, poly[:1]]) + sgn = np.sign(sum(p[k, 0] * p[k + 1, 1] - p[k + 1, 0] * p[k, 1] for k in range(len(poly)))) + inside = np.ones_like(x, dtype=bool) + for k in range(len(poly)): + (ax, ay), (bx, by) = p[k], p[k + 1] + inside &= sgn * ((bx - ax) * (y - ay) - (by - ay) * (x - ax)) > 0 + return inside.reshape(size, n, size, n).mean(axis=(1, 3)) + + +def _arm_line(a: np.ndarray, v, u, gap: float, length: float, size: int): + """The arm's line from column-sum least squares over the windows at arclength + [gap, gap + length] (rows when the arm is steeper than 45 degrees); n . p = d.""" + transpose = abs(u[1]) > abs(u[0]) + img = a.T if transpose else a + uu, vv = (u[::-1], v[::-1]) if transpose else (u, v) + x_lo, x_hi = sorted((vv[0] + gap * uu[0], vv[0] + (gap + length) * uu[0])) + rows, rhs = [], [] + for i in range(int(math.floor(x_lo)), int(math.ceil(x_hi))): + xc = i + 0.5 + sc = (xc - vv[0]) / uu[0] + if not gap <= sc <= gap + length: + continue + jc = int(math.floor(vv[1] + sc * uu[1])) + j0, j1 = jc - 1, jc + 1 + while j0 > 0 and 1e-9 < img[j0, i] < 1 - 1e-9: + j0 -= 1 + while j1 < size - 1 and 1e-9 < img[j1, i] < 1 - 1e-9: + j1 += 1 + w = img[j0:j1 + 1, i] + pure = [q <= 1e-9 or q >= 1 - 1e-9 for q in (w[0], w[-1])] + if not all(pure) or (w[0] > 0.5) == (w[-1] > 0.5): + continue + # the top face's area in the window is the boundary's column mean below j0 + top = w if w[0] > 0.5 else 1.0 - w + rows.append([1.0, xc]) + rhs.append(j0 + top.sum()) + c, b = np.linalg.lstsq(np.array(rows), np.array(rhs), rcond=None)[0] + return (np.array([1.0, -b]), c) if transpose else (np.array([-b, 1.0]), c) + + +def vertex(trials: int = 30, size: int = 48) -> None: + rng = np.random.default_rng(5) + cos_mean = 0.90 # mean cos of the angle to the scan axis over random orientations + cases = (("exact + 8-bit", lambda p: q8(er.rasterize([p], size, size)), 1.42 * SIGMA_Q ** 2), + ("ss8 + 8-bit", lambda p: q8(_ss_convex(size, p, 8)), 1 / (12 * 8 ** 3) + 1.42 * SIGMA_Q ** 2)) + print("vertex of a wedge from two arms of length L (column-sum least squares)") + for name, render, v_col in cases: + for deg in (30, 60, 90, 120, 150): + al = math.radians(deg) + gap = (2.0 / math.sin(al) if al < math.pi / 2 else 2.0) + 1.0 + for length in (6.0, 12.0): + err = [] + for _ in range(trials): + rot = rng.uniform(0, 2 * math.pi) + v = np.array([size / 2, size / 2]) + rng.uniform(-0.5, 0.5, 2) + u1 = np.array([math.cos(rot), math.sin(rot)]) + u2 = np.array([math.cos(rot + al), math.sin(rot + al)]) + a = render(_wedge(size, v, u1, u2)) + (n1, d1), (n2, d2) = (_arm_line(a, v, u, gap, length, size) for u in (u1, u2)) + est = np.linalg.solve(np.array([n1, n2]), np.array([d1, d2])) + err.append(float(np.linalg.norm(est - v))) + s_m = gap + length / 2 + pred = math.sqrt(2 * v_col * cos_mean * (1 + 12 * s_m ** 2 / length ** 2) / length) / math.sin(al) + print(f" {name:13s} alpha {deg:3d} L {length:4.1f}: rms {math.sqrt(np.mean(np.square(err))):.4f} px" + f" predicted {pred:.4f} px") + + +# --------------------------------------------------------------------------------- fillet + +def _corner(v, rot: float, tau: float, r: float, n_arc: int = 400) -> np.ndarray: + d_in = np.array([math.cos(rot), math.sin(rot)]) + d_out = np.array([math.cos(rot + tau), math.sin(rot + tau)]) + reach = 14.0 + if r == 0: + path = [v - reach * d_in, v, v + reach * d_out] + else: + p0 = v - r * math.tan(tau / 2) * d_in + c = p0 + r * np.array([-d_in[1], d_in[0]]) + a0 = math.atan2(p0[1] - c[1], p0[0] - c[0]) + arc = [c + r * np.array([math.cos(a0 + k * tau / n_arc), math.sin(a0 + k * tau / n_arc)]) + for k in range(n_arc + 1)] + path = [v - reach * d_in] + arc + [v + reach * d_out] + far = v + 0.5 * reach * (np.array([-d_in[1], d_in[0]]) + np.array([-d_out[1], d_out[0]])) + return np.array(path + [far]) + + +def fillet(trials: int = 8, size: int = 40) -> None: + rng = np.random.default_rng(3) + print("chi^2 between a sharp corner and a fillet of radius r (per-pixel, equal noise)") + for deg in (90, 60, 30): + tau = math.radians(deg) + k = math.tan(tau / 2) - tau / 2 + for name, sg in (("8-bit", SIGMA_Q), ("8x8 ss", 1 / math.sqrt(12 * 8 ** 3))): + cells = [] + for r in (0.1, 0.2, 0.4, 0.8, 1.6, 3.2): + tot = 0.0 + for _ in range(trials): + v = np.array([size / 2, size / 2]) + rng.uniform(-0.5, 0.5, 2) + rot = rng.uniform(0, 2 * math.pi) + a0 = er.rasterize([_corner(v, rot, tau, 0.0)], size, size) + a1 = er.rasterize([_corner(v, rot, tau, r)], size, size) + tot += ((a1 - a0) ** 2).sum() / sg ** 2 + cells.append(f"r={r}: {tot / trials:9.1f}") + print(f" turn {deg:2d} {name:7s} bound r = {math.sqrt(3 * sg / k):.2f} " + " ".join(cells)) + + +if __name__ == "__main__": + what = sys.argv[1] if len(sys.argv) > 1 else "all" + for name, fn in (("calib", calib), ("info", info), ("vertex", vertex), ("fillet", fillet)): + if what in (name, "all"): + fn() diff --git a/bench/theory/exact_raster.py b/bench/theory/exact_raster.py new file mode 100644 index 00000000..0c834084 --- /dev/null +++ b/bench/theory/exact_raster.py @@ -0,0 +1,171 @@ +"""Exact box-filter (area-coverage) rasteriser for polygons, in float64. + +A port of the signed-area accumulation rasteriser of R. Levien's font-rs +(https://github.com/raphlinus/font-rs, `accumulate`/`draw_line`), the same family as +FreeType's smooth rasteriser and inkvec's own `boundary_opt/band.rs`: each line segment +deposits, into every cell it crosses, the signed area between itself and the cell's right +side, plus a carried cover; a prefix sum along each row yields the exact area of the polygon +inside every pixel. Pixel (i, j) is the square [i, i+1] x [j, j+1] (x right, y down). + +Used by `strip_eval.py` to render shapes whose geometry is known exactly, so estimator +errors are the estimators' own and not the renderer's. +""" + +from __future__ import annotations + +import math + +import numpy as np + + +def _draw_line(acc: np.ndarray, x0: float, y0: float, x1: float, y1: float) -> None: + h, wp = acc.shape + if y0 == y1: + return + if y0 < y1: + d_sign = 1.0 + else: + d_sign = -1.0 + x0, y0, x1, y1 = x1, y1, x0, y0 + dxdy = (x1 - x0) / (y1 - y0) + x = x0 + ystart = max(int(math.floor(y0)), 0) + if y0 < 0.0: + x -= y0 * dxdy + yend = min(h, int(math.ceil(y1))) + for y in range(ystart, yend): + dy = min(y + 1.0, y1) - max(float(y), y0) + xnext = x + dxdy * dy + d = dy * d_sign + xa, xb = (x, xnext) if x < xnext else (xnext, x) + xa_floor = math.floor(xa) + xai = int(xa_floor) + xb_ceil = math.ceil(xb) + xbi = int(xb_ceil) + row = acc[y] + if xbi <= xai + 1: + xmf = 0.5 * (x + xnext) - xa_floor + row[xai] += d - d * xmf + row[xai + 1] += d * xmf + else: + s = 1.0 / (xb - xa) + xaf = xa - xa_floor + a0 = 0.5 * s * (1.0 - xaf) * (1.0 - xaf) + xbf = xb - xb_ceil + 1.0 + am = 0.5 * s * xbf * xbf + row[xai] += d * a0 + if xbi == xai + 2: + row[xai + 1] += d * (1.0 - a0 - am) + else: + a1 = s * (1.5 - xaf) + row[xai + 1] += d * (a1 - a0) + for xi in range(xai + 2, xbi - 1): + row[xi] += d * s + a2 = a1 + (xbi - xai - 3) * s + row[xbi - 1] += d * (1.0 - a2 - am) + row[xbi] += d * am + x = xnext + + +def rasterize(polygons: list[np.ndarray], width: int, height: int) -> np.ndarray: + """Exact area coverage in [0, 1] of the union of closed polygons (non-zero winding, the + polygons must not overlap), as a (height, width) float64 array. Each polygon is an (n, 2) + array of (x, y) vertices; it is closed implicitly. Geometry must lie inside + [0, width] x [0, height].""" + acc = np.zeros((height, width + 2), dtype=np.float64) + for poly in polygons: + n = len(poly) + for k in range(n): + xa, ya = poly[k] + xb, yb = poly[(k + 1) % n] + _draw_line(acc, float(xa), float(ya), float(xb), float(yb)) + cov = np.abs(np.cumsum(acc, axis=1))[:, :width] + return np.clip(cov, 0.0, 1.0) + + +def circle(cx: float, cy: float, r: float, n: int = 8192) -> np.ndarray: + t = np.linspace(0.0, 2.0 * math.pi, n, endpoint=False) + # Vertices on a circle of radius r / cos(pi/n) would bound the same area as the disc; + # the area-matched radius keeps the polygon's coverage within 1e-7 of the disc's. + rr = r * math.sqrt((2.0 * math.pi / n) / math.sin(2.0 * math.pi / n)) + return np.stack([cx + rr * np.cos(t), cy + rr * np.sin(t)], axis=1) + + +def ellipse(cx: float, cy: float, a: float, b: float, phi: float, n: int = 8192) -> np.ndarray: + t = np.linspace(0.0, 2.0 * math.pi, n, endpoint=False) + k = math.sqrt((2.0 * math.pi / n) / math.sin(2.0 * math.pi / n)) + x = a * k * np.cos(t) + y = b * k * np.sin(t) + c, s = math.cos(phi), math.sin(phi) + return np.stack([cx + c * x - s * y, cy + s * x + c * y], axis=1) + + +def half_plane(width: int, height: int, px: float, py: float, theta: float) -> np.ndarray: + """The part of the frame on the left of the directed line through (px, py) at angle + theta, as a polygon (clipped to the frame).""" + d = np.array([math.cos(theta), math.sin(theta)]) + nrm = np.array([-d[1], d[0]]) + frame = [np.array(v, dtype=float) for v in + [(0, 0), (width, 0), (width, height), (0, height)]] + out = [] + p = np.array([px, py]) + m = len(frame) + for k in range(m): + a, b = frame[k], frame[(k + 1) % m] + sa, sb = np.dot(a - p, nrm), np.dot(b - p, nrm) + if sa >= 0: + out.append(a) + if (sa >= 0) != (sb >= 0): + t = sa / (sa - sb) + out.append(a + t * (b - a)) + return np.array(out) + + +def ribbon(width: int, height: int, px: float, py: float, theta: float, w: float) -> np.ndarray: + """A straight stroke of width w centred on the line through (px, py) at angle theta, + clipped to the frame.""" + d = np.array([math.cos(theta), math.sin(theta)]) + nrm = np.array([-d[1], d[0]]) + poly = [np.array(v, dtype=float) for v in + [(0, 0), (width, 0), (width, height), (0, height)]] + p = np.array([px, py]) + for sign, off in ((1.0, -0.5 * w), (-1.0, -0.5 * w)): + q = p + sign * (-off) * nrm + out = [] + m = len(poly) + for k in range(m): + a, b = poly[k], poly[(k + 1) % m] + sa = sign * np.dot(a - q, nrm) + sb = sign * np.dot(b - q, nrm) + if sa <= 0: + out.append(a) + if (sa <= 0) != (sb <= 0): + t = sa / (sa - sb) + out.append(a + t * (b - a)) + poly = out + return np.array(poly) + + +def _self_check() -> None: + # An axis-aligned rectangle: every pixel's area is a product of overlaps. + x0, x1, y0, y1 = 2.3, 7.1, 3.7, 9.25 + cov = rasterize([np.array([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])], 12, 12) + for j in range(12): + for i in range(12): + ox = max(0.0, min(i + 1, x1) - max(i, x0)) + oy = max(0.0, min(j + 1, y1) - max(j, y0)) + assert abs(cov[j, i] - ox * oy) < 1e-12, (i, j, cov[j, i], ox * oy) + # A triangle: total area, and one pixel against a hand computation. + tri = np.array([(1.0, 1.0), (9.0, 1.0), (1.0, 9.0)]) + cov = rasterize([tri], 12, 12) + assert abs(cov.sum() - 32.0) < 1e-12 + # Pixel [4,5] x [5,6] is cut corner to corner by x + y = 10; [4,5]^2 is inside. + assert abs(cov[5, 4] - 0.5) < 1e-12 and abs(cov[4, 4] - 1.0) < 1e-12 + # A disc: the area-matched polygon has the disc's area. + cov = rasterize([circle(16.3, 15.7, 9.4)], 32, 32) + assert abs(cov.sum() - math.pi * 9.4 ** 2) < 1e-6, cov.sum() - math.pi * 9.4 ** 2 + + +if __name__ == "__main__": + _self_check() + print("exact_raster: self-check passed") diff --git a/bench/theory/floor_selfcal.py b/bench/theory/floor_selfcal.py new file mode 100644 index 00000000..9cb5a70d --- /dev/null +++ b/bench/theory/floor_selfcal.py @@ -0,0 +1,283 @@ +"""The renderer floor estimated per image, checked against the artists' own geometry. + +`docs/theory/chain-boundary.md` (Phase 2, milestone 2): the engine's forward model is the +exact geometry, and what the renderer added beyond 8-bit rounding is a floor the evidence +estimates from the image itself, so that `chi2/M` at the truth stays near 1 whatever made +the input. This script makes the inputs, runs the engine's evidence on them +(`crates/inkvec-trace/examples/evidence_calibrate.rs`), and scores every run window against +the truth. + +Inputs, per icon and size, all drawn from the artist's file: + +* `exact` per-element compositing with exact coverage at 8x, box-filtered, 8-bit; +* `ss8` per-element compositing with 8 x 8 point samples per pixel, 8-bit; +* `lat32` tiny-skia's sample lattice (4 x 4 per 8x pixel: 32 per pixel), exact + flattening, 8-bit; +* `fresh` resvg 0.48.1 now (`build_corpus_v2.render_supersampled`, the harness's code); +* `committed` the gate's committed intake (`bench/data/corpus_raster//ss`); +* `web` the gate's noisy tier (size 400 only): the committed 512 px intake flattened + onto white, bicubic-resized to 400 px and saved as a quality-80 JPEG with 4:2:0 + chroma (`bench/build_web_tier.py`). + +The truth for all of them is the first before rounding, with the true geometry (arcs as +arcs): what the engine's exact forward model should read. Inputs, truths and the harness's +rows are cached under `bench/data/theory_floor_cache/` (ignored by git, regenerable). + +Reported per input: `χ²/M` of the truth under rounding alone and under the image's +self-calibrated window variances, by class (straight, curved) and with each run's offset +profiled out; the engine's own score of the truth (`χ²_floor` and Huber's cost per +independent measurement, replicas counted once, by family); and each image's window scale +and tail. + + cargo build --release -p inkvec-trace --example evidence_calibrate + python3 bench/theory/floor_selfcal.py [--per-family 6] [--sizes 128,512] +""" + +from __future__ import annotations + +import argparse +import io +import math +import subprocess +import sys +from collections import defaultdict +from pathlib import Path + +import numpy as np +from PIL import Image + +import renderer_floor as rf + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "bench")) +CACHE = ROOT / "bench/data/theory_floor_cache" +CONDITIONS = ("exact", "ss8", "lat32", "fresh", "committed") +ALL_CONDITIONS = CONDITIONS + ("web",) +EXE = ROOT / "target/release/examples/evidence_calibrate" +W4 = np.array([1.0, -4.0, 6.0, -4.0, 1.0]) +COLS = ["name", "edge", "index", "axis", "line", "lo", "hi", "s", "sum", "qvar", "truth", + "left_low", "pos", "closed", "lattice", "z", "var"] +FLOOR_COLS = ["lattice", "window_var", "edge_var", "sigma", "ramp_width", "soft", "ringing", + "extra_straight", "extra_curved", "n_straight", "n_curved", "nu", "window_scale", + "sigma_edge0"] + + +# ---------------------------------------------------------------------------------- inputs + +def render_points(layers, size, sub): + """Per-element compositing at 1x with `sub x sub` point samples per pixel.""" + acc = np.zeros((size, size, 4)) + for reg, col, _, _ in layers: + c = rf.lattice_coverage(reg, size, ss=1, sub=sub) + acc = c[..., None] * np.array([*col, 1.0]) + (1 - c[..., None]) * acc + return acc + + +def encode_png(pm, path): + """Premultiplied RGBA -> straight 8-bit PNG, rounded as the corpus builder rounds.""" + a = pm[..., 3:4] + rgb = np.where(a > 1e-6, pm[..., :3] / np.maximum(a, 1e-6), 0.0) + out = np.concatenate([rgb, a], -1) + Image.fromarray((np.clip(out, 0, 1) * 255 + 0.5).astype(np.uint8), "RGBA").save(path) + + +def inputs_for(item, size, conditions): + """{condition: PNG path} and the truth file (sRGB over white, f32), cached; None when the + file uses what `renderer_floor.layers_of` does not draw.""" + import build_corpus_v2 as B + d = CACHE / f"{size}" / item["corpus"] + d.mkdir(parents=True, exist_ok=True) + stem = item["stem"] + truth_path = d / f"{stem}.truth.rgbf32" + svg = (ROOT / "bench/data/corpus_svg" / item["corpus"] / f"{stem}.svg").read_text() + layers, truth = None, None + if not truth_path.exists(): + layers = rf.layers_of(svg, size, "true") + if not layers: + return None, None + truth = rf.render_layered(layers, size, rf.SS) + over_white = truth[..., :3] + (1.0 - truth[..., 3:4]) + over_white.astype("= 0.01 + kappa = np.array([min(3.0, math.sqrt(floors[n]["nu"])) if math.isfinite(floors[n]["nu"]) else 3.0 + for n in t["name"]]) + # Each run's offset, profiled out under the calibrated variances. + prof = np.zeros(len(r)) + for run in rr: + w = 1 / t["var"][run] + prof[run] = r[run] - (r[run] * w).sum() / w.sum() + m_prof = len(r) - len(rr) + print(f"-- {size} px {cond}: {len(r)} windows in {len(rr)} runs, {len(floors) - 1} images") + for name, m in (("all", np.ones(len(r), bool)), ("straight", straight), ("curved", curved)): + zq = r[m] / np.sqrt(t["qvar"][m]) + zc = r[m] / np.sqrt(t["var"][m]) + hub = huber(zc, kappa[m]) + print(f" {name:9s} n {m.sum():6d} rounding {np.mean(zq ** 2):9.2f} calibrated {np.mean(zc ** 2):7.2f}" + f" median {np.median(zc ** 2) / 0.4549:5.2f} huber {np.mean(hub):6.2f}" + f" |z|>3 {np.mean(np.abs(zc) > 3):.3f}") + zp = prof / np.sqrt(t["var"]) + print(f" profiled chi2/M {np.sum(zp ** 2) / m_prof:7.2f} huber {np.sum(huber(zp, kappa)) / m_prof:6.2f}") + ed = floors.get("__edges__", []) + if ed: + a = np.array([e[2:] for e in ed]) # m, dof, chi2, chi2_floor, cost + fam = np.array([e[0].split("/")[0] for e in ed]) + print(f" engine score of the truth: chi2_floor/dof {a[:, 3].sum() / a[:, 1].sum():6.2f} " + f"huber/dof {a[:, 4].sum() / a[:, 1].sum():6.2f} chi2/dof {a[:, 2].sum() / a[:, 1].sum():7.2f} " + f"dof/m {a[:, 1].sum() / a[:, 0].sum():.2f}") + print(" by family (chi2_floor/dof, huber/dof): " + " ".join( + f"{f} {a[fam == f, 3].sum() / a[fam == f, 1].sum():.2f}/{a[fam == f, 4].sum() / a[fam == f, 1].sum():.2f}" + for f in sorted(set(fam)))) + imgs = {k: v for k, v in floors.items() if k != "__edges__"} + ws = [f["window_scale"] for f in imgs.values()] + nus = [f["nu"] for f in imgs.values()] + print(f" window_scale median {np.median(ws):.2f} [{min(ws):.2f}, {max(ws):.2f}] nu median {np.median(nus):.1f}" + f" finite {sum(math.isfinite(v) for v in nus)}/{len(nus)}") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--per-family", type=int, default=3) + ap.add_argument("--sizes", default="128") + ap.add_argument("--conditions", default=",".join(CONDITIONS)) + ap.add_argument("--exe", default=str(EXE)) + ap.add_argument("--refresh", action="store_true", help="rerun the harness") + a = ap.parse_args() + items = pick_items(a.per_family) + for size in [int(s) for s in a.sizes.split(",")]: + for cond in a.conditions.split(","): + t, floors = rows_for(items, size, cond, a.exe, a.refresh) + if t is not None: + report(size, cond, t, floors) + + +if __name__ == "__main__": + main() diff --git a/bench/theory/geom_calibration.py b/bench/theory/geom_calibration.py new file mode 100644 index 00000000..8f0f266d --- /dev/null +++ b/bench/theory/geom_calibration.py @@ -0,0 +1,42 @@ +"""Which metric measures "the same design"? `geom` against dE00 on known displacements. + +Each case is an artist file and a trace of it whose every edge is moved by a known `δ` +(source pixels at a 512 px input): a disc grown by `δ`, in two colour contrasts (dark red on +transparent, and a pale grey close to white). A metric of geometric match should read the +displacement, the same for both contrasts, and in proportion to `δ`. `geom` +(`inkvec_bench/geomatch.py`) does by construction; dE00, the gate's colour error, reads the +contrast as much as the displacement. + + python3 bench/theory/geom_calibration.py +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "bench")) + +DISC = ('' + '') + + +def main() -> None: + from inkvec_bench import render + from inkvec_bench.geomatch import geomatch + from inkvec_bench.metrics import color as mcolor + print(f"{'colour':10s} {'delta px':>9s} {'geom px':>9s} {'dE00':>9s}") + for colour in ("#d22f27", "#e8e8e8"): + art = DISC.format(r=7.0, c=colour) + ref = render.composite(render.render(art, 1024, 1024)) + for delta in (0.0, 0.05, 0.1, 0.25, 0.5): + ours = DISC.format(r=7.0 + delta * 24 / 512, c=colour) + g = geomatch(ours, art, 512)["geom"] + b = render.composite(render.render(ours, 1024, 1024)) + de = float(mcolor.delta_e00(ref, b)["de00_mean"]) + print(f"{colour:10s} {delta:9.3f} {g:9.4f} {de:9.4f}") + + +if __name__ == "__main__": + main() diff --git a/bench/theory/human_gap.py b/bench/theory/human_gap.py new file mode 100644 index 00000000..7329e9a5 --- /dev/null +++ b/bench/theory/human_gap.py @@ -0,0 +1,284 @@ +"""How far a trace sits from the artist's own file, before and after a change. + +The gate reads `turning` and the parameter ratio as "lower is better". Against the artist +that is only half true: a trace can be smoother or sparser than the file it stands for (on +`quality-web`, lucide, material and simple-icons turn less than their artists do), and then a +rise moves it closer. This script reads both as a distance to the artist, per icon: + +* **turning gap** `|T_trace - T_artist|`, where `T` is the gate's `turning` (absolute turning + of the outlines' control polygons per unit of their length, `inkvec_bench/turning.py`) + times the canvas width: the trace's viewBox width (the raster's, 400 px on `web`) and the + artist's viewBox width (128 on noto-emoji). `T` is then in radians per canvas width, and a + file drawn on a 128-unit grid compares with its trace at 400 px; +* **parameter gap** `|ln ratio|`, where `ratio` is the gate's parameter count of the trace + (`svgmodel`) over the artist's: 0 when they spend the same, symmetric in "twice as many" + and "half as many". + +For each family it prints the mean of both gaps before and after, and how many icons moved +closer, further, or not at all (an icon whose SVG is byte-identical counts as unchanged). + +With `--faces`, also: every fill colour the after-trace has and the before-trace lacks +(farther than 1 dE00 from each of its fills) -- a face the change brought back -- is matched +to the artist's nearest fill colour (CIEDE2000): within 2 dE00 counts as a match, and the +intersection over union of the two colour regions (pixels within 1 dE00 of the colour, on +renders over white at the raster's size) says whether it is the artist's region. + +`--before` and `--after` each take an inkvec binary (traced now, at the tier's raster, with +`--mode` and `--extra` passed through) or a directory of SVGs named `__.svg` +(as `--save DIR` keeps them, in `DIR/before` and `DIR/after`; the gate does not keep its SVGs). + + python3 bench/theory/human_gap.py --before old/inkvec --after target/release/inkvec \\ + --tier web [--mode fast] [--faces] [--jobs 2] [--json out.json] [--save DIR] [--verbose] + +Needs numpy, Pillow, svgelements, scikit-image and resvg-py (the harness's renderer). +Not from the literature: a reading of the gate's own axes as distances. +""" + +from __future__ import annotations + +import argparse +import json +import math +import os +import re +import subprocess +import sys +import tempfile +from collections import defaultdict +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "bench")) +os.environ.setdefault("INKVEC_SKIP_DISTS", "1") + +#: A fill farther than this from every fill of the before-trace is a face the change added. +NEW_FILL_DE00 = 1.0 +#: A recovered face whose colour is within this of an artist fill matches that fill. +MATCH_DE00 = 2.0 +#: A pixel belongs to a colour's region when it renders within this of the colour. +REGION_DE00 = 1.0 + +VIEWBOX = re.compile(r']*?\bviewBox="\s*([-\d.eE+]+)[\s,]+([-\d.eE+]+)[\s,]+([-\d.eE+]+)') +WIDTH = re.compile(r']*?\bwidth="\s*([\d.eE+]+)') +FILL = re.compile(r'\bfill="(#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3})"') + + +def canvas_width(svg: str) -> float: + """The root viewBox width, else the root `width`, else 0.""" + m = VIEWBOX.search(svg) + if m: + return float(m.group(3)) + m = WIDTH.search(svg) + return float(m.group(1)) if m else 0.0 + + +def norm_turning(svg: str) -> float: + """The gate's `turning` times the canvas width: radians per canvas width.""" + from inkvec_bench.turning import turning + return turning(svg) * canvas_width(svg) + + +def hex_rgb(h: str) -> tuple[float, float, float]: + h = h.lstrip("#") + if len(h) == 3: + h = "".join(c * 2 for c in h) + return tuple(int(h[i:i + 2], 16) / 255 for i in (0, 2, 4)) + + +def lab(rgb) -> np.ndarray: + from skimage.color import rgb2lab + a = np.asarray(rgb, dtype=np.float64) + return rgb2lab(a.reshape(-1, 1, 3)).reshape(a.shape) + + +def de00(lab_a: np.ndarray, lab_b: np.ndarray) -> np.ndarray: + from skimage.color import deltaE_ciede2000 + a, b = np.broadcast_arrays(lab_a, lab_b) + return deltaE_ciede2000(a.reshape(-1, 1, 3), b.reshape(-1, 1, 3)).reshape(a.shape[:-1]) + + +def artist_fills(gt: Path) -> list[str]: + """The solid fill colours of the artist's shapes, styles and inheritance resolved.""" + from svgelements import SVG, Color, Shape + out = set() + for e in SVG.parse(str(gt)).elements(): + if isinstance(e, Shape) and isinstance(e.fill, Color) and e.fill.value is not None \ + and e.fill.alpha > 0: + out.add(f"#{e.fill.red:02x}{e.fill.green:02x}{e.fill.blue:02x}") + return sorted(out) + + +def trace_fills(svg: str) -> list[str]: + return sorted({f.lower() for f in FILL.findall(svg)}) + + +def get_svg(source: str, it: dict, png: Path, td: str, mode: str, extra: list[str]) -> str | None: + """The SVG `source` gives for one icon: read from a directory, or traced by a binary.""" + p = Path(source) + name = f"{it['corpus']}__{it['stem']}.svg" + if p.is_dir(): + f = p / name + return f.read_text(encoding="utf-8") if f.exists() else None + out = Path(td) / name + args = [str(p), str(png), "-o", str(out), "--quiet", *extra] + if mode == "fast": + args += ["--mode", "fast"] + r = subprocess.run(args, capture_output=True) + return out.read_text(encoding="utf-8") if r.returncode == 0 else None + + +def faces(before: str, after: str, gt: Path, size: tuple[int, int]) -> list[dict]: + """The fills `after` adds over `before`, each matched to the artist's nearest fill.""" + from inkvec_bench import render + b_fills = trace_fills(before) + added = [] + b_lab = lab([hex_rgb(h) for h in b_fills]) if b_fills else None + for h in trace_fills(after): + c = lab([hex_rgb(h)])[0] + if b_lab is None or de00(b_lab, c[None]).min() > NEW_FILL_DE00: + added.append((h, c)) + if not added: + return [] + w, hgt = size + img_t = lab(render.composite(render.render(after, w, hgt))) + gsvg = gt.read_text(encoding="utf-8") + img_a = lab(render.composite(render.render(gsvg, w, hgt))) + a_fills = artist_fills(gt) + a_lab = lab([hex_rgb(x) for x in a_fills]) if a_fills else None + out = [] + for h, c in added: + rec = {"fill": h, "pixels": int((de00(img_t, c) <= REGION_DE00).sum())} + if a_lab is not None: + d = de00(a_lab, c[None]) + k = int(np.argmin(d)) + rec.update(artist=a_fills[k], de00=float(d[k]), match=bool(d[k] <= MATCH_DE00)) + mt = de00(img_t, c) <= REGION_DE00 + ma = de00(img_a, a_lab[k]) <= REGION_DE00 + union = int((mt | ma).sum()) + rec["iou"] = float((mt & ma).sum() / union) if union else 0.0 + out.append(rec) + return out + + +def one(args) -> dict: + tier, it, before, after, mode, extra, want_faces, save = args + import svgeval + from inkvec_bench import svgmodel + from PIL import Image + svgeval.set_tier(tier) + png, gt = svgeval.item_paths(it) + key = f"{it['corpus']}/{it['stem']}" + if not png.exists() or not gt.exists(): + return {"key": key, "fail": "missing input"} + with tempfile.TemporaryDirectory() as td: + Path(td, "b").mkdir() + Path(td, "a").mkdir() + sb = get_svg(before, it, png, td + "/b", mode, extra) + sa = get_svg(after, it, png, td + "/a", mode, extra) + if sb is None or sa is None: + return {"key": key, "fail": "no trace"} + if save: + for tag, svg in (("before", sb), ("after", sa)): + d = Path(save) / tag + d.mkdir(parents=True, exist_ok=True) + (d / f"{it['corpus']}__{it['stem']}.svg").write_text(svg, encoding="utf-8") + gsvg = gt.read_text(encoding="utf-8") + gt_params = max(1, it["gt_params"]) + rec = {"key": key, "family": it["corpus"], "changed": sb != sa, + "artist_T": norm_turning(gsvg)} + for tag, svg in (("before", sb), ("after", sa)): + n = svgmodel.parse(svg).n_params + rec[tag] = {"T": norm_turning(svg), "ratio": n / gt_params} + rec[tag]["turning_gap"] = abs(rec[tag]["T"] - rec["artist_T"]) + rec[tag]["param_gap"] = abs(math.log(max(rec[tag]["ratio"], 1e-9))) + if want_faces and rec["changed"]: + with Image.open(png) as im: + size = im.size + rec["faces"] = faces(sb, sa, gt, size) + return rec + + +def report(rows: list[dict]) -> None: + fam = defaultdict(list) + for r in rows: + fam[r["family"]].append(r) + print("turning normalised to canvas width (radians per canvas width), mean over icons:") + print(f" artist {np.mean([r['artist_T'] for r in rows]):.2f} " + f"before {np.mean([r['before']['T'] for r in rows]):.2f} " + f"after {np.mean([r['after']['T'] for r in rows]):.2f}") + for gap in ("turning_gap", "param_gap"): + print(f"\n{gap}: mean before -> after (all icons | changed icons), " + f"changed icons closer / further / level") + for f in sorted(fam) + ["ALL"]: + rs = rows if f == "ALL" else fam[f] + ch = [r for r in rs if r["changed"]] + b = np.mean([r["before"][gap] for r in rs]) + a = np.mean([r["after"][gap] for r in rs]) + d = [r["after"][gap] - r["before"][gap] for r in ch] + closer = sum(x < -1e-9 for x in d) + further = sum(x > 1e-9 for x in d) + cb = np.mean([r["before"][gap] for r in ch]) if ch else float("nan") + ca = np.mean([r["after"][gap] for r in ch]) if ch else float("nan") + print(f" {f:14s} n={len(rs):3d} {b:7.3f} -> {a:7.3f} | changed {len(ch):3d}: " + f"{cb:7.3f} -> {ca:7.3f} closer {closer:3d} further {further:3d} " + f"level {len(ch) - closer - further:3d}") + fr = [(r["key"], x) for r in rows for x in r.get("faces", [])] + if fr: + print(f"\nfaces the change added: {len(fr)}") + by = defaultdict(list) + for k, x in fr: + by[k.split("/")[0]].append(x) + for f in sorted(by): + xs = by[f] + m = [x for x in xs if x.get("match")] + iou = np.mean([x["iou"] for x in m]) if m else float("nan") + print(f" {f:14s} added {len(xs):3d} within {MATCH_DE00} dE00 of an artist fill " + f"{len(m):3d} mean IoU of those {iou:.2f}") + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--before", required=True, help="inkvec binary or directory of SVGs") + ap.add_argument("--after", required=True, help="inkvec binary or directory of SVGs") + ap.add_argument("--tier", default="web") + ap.add_argument("--mode", default="quality", choices=("quality", "fast")) + ap.add_argument("--extra", default="", help="more arguments for a traced binary, comma-separated") + ap.add_argument("--icons", default="", help="family/stem,... (default: the gate's screen set)") + ap.add_argument("--faces", action="store_true") + ap.add_argument("--jobs", type=int, default=2) + ap.add_argument("--json", type=Path) + ap.add_argument("--save", default="", help="keep both sides' SVGs in DIR/before and DIR/after") + ap.add_argument("--verbose", action="store_true", help="one line per changed icon") + a = ap.parse_args() + import svgeval + svgeval.set_tier(a.tier) + items = svgeval.load_sets()["screen"] + if a.icons: + want = set(a.icons.split(",")) + items = [i for i in items if f"{i['corpus']}/{i['stem']}" in want] + extra = [x for x in a.extra.split(",") if x] + jobs = [(a.tier, it, a.before, a.after, a.mode, extra, a.faces, a.save) for it in items] + with ProcessPoolExecutor(a.jobs) as ex: + rows = list(ex.map(one, jobs)) + bad = [r for r in rows if "fail" in r] + for r in bad: + print("FAIL", r["key"], r["fail"]) + rows = [r for r in rows if "fail" not in r] + if a.verbose: + for r in rows: + if r["changed"]: + b, f = r["before"], r["after"] + print(f"{r['key']:52s} T artist {r['artist_T']:6.2f} {b['T']:6.2f} -> {f['T']:6.2f} " + f"ratio {b['ratio']:5.2f} -> {f['ratio']:5.2f}" + + "".join(f" +{x['fill']}~{x.get('artist')} {x.get('de00', 0):.1f}dE " + f"IoU {x.get('iou', 0):.2f}" for x in r.get("faces", []))) + report(rows) + if a.json: + a.json.write_text(json.dumps(rows, indent=1), encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/bench/theory/inkvec_compare.py b/bench/theory/inkvec_compare.py new file mode 100644 index 00000000..eafce0e8 --- /dev/null +++ b/bench/theory/inkvec_compare.py @@ -0,0 +1,93 @@ +"""inkvec's own sub-pixel stage against the strip estimator, on exactly rendered shapes. + +Renders each shape of `strip_eval.shapes` with the exact area rasteriser, writes it as an +8-bit black-on-white PNG, runs the inkvec binary with `INKVEC_DUMP_CONTOUR` (the boundary +points `planar::measure_subpixel` measured, stage 07, before the boundary solve), and scores +those points and the strip estimator's against the true geometry. + + python3 bench/theory/inkvec_compare.py --exe target/release/inkvec [--mode quality] + +inkvec puts pixel centres on integers; this file's pixels are [i, i+1], so inkvec's points +are shifted by +1/2 before scoring. +""" + +from __future__ import annotations + +import argparse +import os +import subprocess +import tempfile + +import numpy as np +from PIL import Image + +import exact_raster as er +import strip_eval as se + + +def read_dump(path: str) -> np.ndarray: + pts = [] + with open(path) as f: + for line in f: + if line.startswith("#") or not line.strip(): + continue + x, y, _ = (float(t) for t in line.split()) + pts.append((x + 0.5, y + 0.5)) + return np.array(pts) + + +def run(exe: str, png: str, mode: str, workdir: str, extra_env: dict | None = None) -> np.ndarray: + dump = os.path.join(workdir, "contour.txt") + if os.path.exists(dump): + os.remove(dump) + env = dict(os.environ, INKVEC_DUMP_CONTOUR=dump, **(extra_env or {})) + subprocess.run([exe, png, "-o", os.path.join(workdir, "out.svg"), "--mode", mode], + env=env, check=True, capture_output=True) + return read_dump(dump) + + +def interior(p: np.ndarray, size: int, margin: float = 2.0) -> np.ndarray: + return (p[:, 0] > margin) & (p[:, 0] < size - margin) & (p[:, 1] > margin) & (p[:, 1] < size - margin) + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--exe", default="target/release/inkvec") + ap.add_argument("--mode", default="quality") + ap.add_argument("--size", type=int, default=64) + args = ap.parse_args() + rng = np.random.default_rng(20261009) + size = args.size + acc: dict[str, list[np.ndarray]] = {"inkvec stage 07": [], "levelset": [], "strip": []} + per_kind: dict[str, dict[str, list[np.ndarray]]] = {} + with tempfile.TemporaryDirectory() as td: + for name, poly in se.shapes(rng, size): + a = er.rasterize([poly], size, size) + img = np.round((1.0 - a) * 255.0).astype(np.uint8) + png = os.path.join(td, "in.png") + Image.fromarray(np.stack([img] * 3, axis=2)).save(png) + got = {"inkvec stage 07": run(args.exe, png, args.mode, td)} + est = se.estimate(img_to_cov(img), 0.02) + got["levelset"] = est["levelset"] + got["strip"] = est["strip"] + kind = name.split()[0] + for k, p in got.items(): + p = p[interior(p, size)] + d = se.dist_to_polygon(p, poly) + acc[k].append(d) + per_kind.setdefault(kind, {}).setdefault(k, []).append(d) + print(f"mode={args.mode} size={size}, 8-bit input, distance to the true boundary (px)") + for k, v in acc.items(): + print(f" {k:16s} {se.summarize(np.concatenate(v))}") + for kind, dd in per_kind.items(): + print(f" {kind}") + for k, v in dd.items(): + print(f" {k:16s} {se.summarize(np.concatenate(v))}") + + +def img_to_cov(img: np.ndarray) -> np.ndarray: + return 1.0 - img.astype(np.float64) / 255.0 + + +if __name__ == "__main__": + main() diff --git a/bench/theory/naturality_diag.py b/bench/theory/naturality_diag.py new file mode 100644 index 00000000..14bd55c5 --- /dev/null +++ b/bench/theory/naturality_diag.py @@ -0,0 +1,175 @@ +"""How much of a trace's parameter count is "unnatural": descriptions an artist would not write. + +Counts, in the SVGs inkvec writes, the patterns a shorter description would replace at no +cost in fit (each a merge the MDL objective itself prefers once the fit is unchanged): + +* `collinear` a vertex between two line segments that turns by less than `TURN_DEG` + (one line would do: -2 parameters) +* `straight` a cubic whose control points lie within `STRAIGHT_PX` of its chord + (a line would do: -4 parameters) +* `cocircular` two consecutive arcs with the same radius (within `RADIUS_REL`) and centre + (one arc would do: -7 parameters) +* `continue` two open stroke paths meeting end to end with tangents continuing within + `TURN_DEG` (one path would do; their shared segment pair is then often + `collinear` too) + + python3 bench/theory/naturality_diag.py --exe target/release/inkvec --tier 512ss \\ + --families lucide,openmoji +""" + +from __future__ import annotations + +import argparse +import math +import re +import subprocess +import sys +import tempfile +from collections import Counter +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "bench")) + +TURN_DEG = 3.0 +STRAIGHT_PX = 0.25 +RADIUS_REL = 0.02 + + +def subpaths(svg: str): + """(stroked, list of segments) per subpath; a segment is ('L', p0, p1), ('C', p0, c1, c2, + p1) or ('A', p0, r, p1, large, sweep).""" + import svgelements as se + doc = se.SVG.parse(__import__("io").StringIO(svg)) + out = [] + for el in doc.elements(): + if not isinstance(el, se.Shape) or isinstance(el, (se.Circle, se.Ellipse, se.Rect)): + continue + stroked = el.stroke is not None and el.stroke.value is not None and ( + el.fill is None or el.fill.value is None) + cur = [] + for seg in se.Path(el).segments(): + if isinstance(seg, se.Move): + if cur: + out.append((stroked, cur)) + cur = [] + elif isinstance(seg, se.Line): + cur.append(("L", complex(*seg.start), complex(*seg.end))) + elif isinstance(seg, se.CubicBezier): + cur.append(("C", complex(*seg.start), complex(*seg.control1), + complex(*seg.control2), complex(*seg.end))) + elif isinstance(seg, se.Arc): + cur.append(("A", complex(*seg.start), (seg.rx + seg.ry) / 2, complex(*seg.end), + complex(*seg.center))) + elif isinstance(seg, se.Close): + if cur and abs(complex(*seg.start) - complex(*seg.end)) > 1e-6: + cur.append(("L", complex(*seg.start), complex(*seg.end))) + if cur: + out.append((stroked, cur)) + return out + + +def tangent(seg, at_end: bool) -> complex: + k = seg[0] + if k == "L": + d = seg[2] - seg[1] + elif k == "C": + d = (seg[4] - seg[3]) if at_end else (seg[2] - seg[1]) + if abs(d) < 1e-9: + d = seg[4] - seg[1] + else: + c = seg[4] + p = seg[3] if at_end else seg[1] + r = p - c + d = complex(-r.imag, r.real) + # orientation: follow the chord direction + if ((seg[3] - seg[1]) * d.conjugate()).real < 0: + d = -d + return d / abs(d) if abs(d) > 1e-12 else 0j + + +def turn_deg(a: complex, b: complex) -> float: + if a == 0 or b == 0: + return 180.0 + return abs(math.degrees(math.atan2((b * a.conjugate()).imag, (b * a.conjugate()).real))) + + +def count(svg: str, units: float) -> Counter: + c: Counter = Counter() + paths = subpaths(svg) + for stroked, segs in paths: + for i, s in enumerate(segs): + if s[0] == "C": + p0, p1 = s[1], s[4] + ch = p1 - p0 + if abs(ch) > 1e-9: + dist = max(abs(((q - p0) * ch.conjugate()).imag) / abs(ch) for q in (s[2], s[3])) + if dist < STRAIGHT_PX * units: + c["straight"] += 1 + if i + 1 < len(segs): + t = segs[i + 1] + if s[0] == "L" and t[0] == "L" and turn_deg(tangent(s, True), tangent(t, False)) < TURN_DEG: + c["collinear"] += 1 + if s[0] == "A" and t[0] == "A" and abs(s[2] - t[2]) < RADIUS_REL * s[2] \ + and abs(s[4] - t[4]) < RADIUS_REL * s[2]: + c["cocircular"] += 1 + ends = [(segs[0][1], tangent(segs[0], False), segs[-1][-2] if segs[-1][0] == "A" else segs[-1][-1], + tangent(segs[-1], True)) for st, segs in paths if st and segs] + # open stroked paths meeting end to end with a continuing tangent + used = set() + for i, (a0, ta0, a1, ta1) in enumerate(ends): + for j, (b0, tb0, b1, tb1) in enumerate(ends): + if i >= j or i in used or j in used: + continue + for p, tp, q, tq in ((a1, ta1, b0, tb0), (b1, tb1, a0, ta0), (a1, ta1, b1, -tb1), + (a0, -ta0, b0, tb0)): + if abs(p - q) < 0.6 * units and turn_deg(tp, tq) < 25.0: + c["continue"] += 1 + used.update((i, j)) + break + return c + + +def one(args): + exe, it, tier, mode, td, extra = args + import svgeval + from PIL import Image + svgeval.set_tier(tier) + png, gt = svgeval.item_paths(it) + out = Path(td) / f"{it['corpus']}__{it['stem']}.svg" + subprocess.run([exe, str(png), "-o", str(out), "--quiet", "--mode", mode, *extra], + check=True, capture_output=True) + units = 1.0 # trace coordinates are source pixels + return dict(icon=f"{it['corpus']}/{it['stem']}", family=it["corpus"], + c=count(out.read_text(encoding="utf-8"), units)) + + +def main() -> None: + import svgeval + ap = argparse.ArgumentParser() + ap.add_argument("--exe", default=str(ROOT / "target/release/inkvec")) + ap.add_argument("--tier", default="512ss") + ap.add_argument("--mode", default="quality") + ap.add_argument("--extra", default="") + ap.add_argument("--families", default="") + a = ap.parse_args() + items = svgeval.load_sets()["screen"] + if a.families: + items = [it for it in items if it["corpus"] in a.families.split(",")] + with tempfile.TemporaryDirectory() as td, ProcessPoolExecutor(4) as pool: + rows = list(pool.map(one, [(a.exe, it, a.tier, a.mode, td, a.extra.split()) for it in items])) + save = {"collinear": 2, "straight": 4, "cocircular": 7, "continue": 0} + for f in sorted({r["family"] for r in rows}): + tot = Counter() + for r in rows: + if r["family"] == f: + tot.update(r["c"]) + n = sum(1 for r in rows if r["family"] == f) + print(f"{f:15s} icons {n:3d} " + " ".join(f"{k} {tot[k]:4d} (-{tot[k] * save[k]} params)" for k in save)) + + +if __name__ == "__main__": + main() diff --git a/bench/theory/noise_profile.py b/bench/theory/noise_profile.py new file mode 100644 index 00000000..bff6f0c7 --- /dev/null +++ b/bench/theory/noise_profile.py @@ -0,0 +1,236 @@ +"""Where the noise of a real input sits: the `web` tier against the exact raster it stands for. + +The gate's `web` tier (`bench/build_web_tier.py`) is each screen icon as logos usually reach a +tracer: the 512 px raster on white, resized to 400 px (bicubic) and saved as a quality-80 +JPEG with 4:2:0 chroma. Its ideal is the exact box-filtered raster at 400 px: the artist's +file rendered at 8x and averaged, on white, unrounded. Against it, the error splits in two: + +* `resample` bicubic(512) - exact(400): deterministic, the resampling kernel's blur and + overshoot (not noise: a forward model can reproduce it); +* `jpeg` jpeg - bicubic(512): the codec's quantisation (block steps, ringing, chroma at + half resolution); +* `total` jpeg - exact(400). + +Each is reported as an RMS in 8-bit levels, by distance to the nearest edge of the exact +raster (a pixel that differs from a 4-neighbour by more than two levels), on luma (Y) and on +chroma (the Cb/Cr pair, as one RMS); next to `est`, the engine's own noise estimate +(`coverage::estimate_noise`: the tenth percentile of |Laplacian| of luma, read as a +Gaussian sigma). The question it answers: is one sigma read from flat regions the noise the +boundary windows see? + +A second table checks the window identity under the effective blur: for each edge of the +exact raster, the coverage of one side summed over a column window grown by `r` pixels each +side, in the exact raster and in three observed ones (unmixed on luma between their own +plateau colours): the exact raster rounded to 8 bits, the bicubic one before the JPEG step, +and the `web` one. A column window's sum is the column-area profile convolved with the +kernel's horizontal marginal, plus the plateau step times the kernel's vertical first moment +(Fubini), when every input pixel's weights over the outputs sum to one. Measured +(2026-10-10, 41 icons): every mean is within 0.0004 px of zero, so the sums stay unbiased +under resampling and JPEG and growing the window only adds noise; the spread is what grows, +from 0.005 px of area (8-bit) to 0.039 (bicubic: Pillow normalises weights per output pixel, +so at a non-integer factor an edge's sum ripples with its phase against the output grid; +the same 0.041 from an exact 512 px render, about 0.004 px of it a translation) and 0.066 +(`web`; the codec's part about 0.047). + + python3 bench/theory/noise_profile.py [--per-family 6] + +Needs scipy and resvg-py (about a minute for six icons per family). +""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "bench")) + +SIZE = 400 +SS = 8 +#: Distance-to-edge bins, in pixels of the 400 px raster: [lo, hi). +BINS = ((0, 1), (1, 2), (2, 3), (3, 5), (5, 8), (8, 10_000)) +#: A pixel is on an edge when it differs from a 4-neighbour by more than this (8-bit levels). +EDGE_LEVELS = 2.0 +#: Window growth tested by the identity table, in pixels each side. +GROWTH = (0, 1, 2, 3, 4) +#: Plateau length an edge needs on both sides to enter the identity table. +PLATEAU = 10 + + +def exact_on_white(svg: str) -> np.ndarray: + """The artist's file at 400 px, box-filtered from 8x, composited on white, in [0, 1].""" + from inkvec_bench import render + rgba = render.render(svg, SIZE * SS, SIZE * SS) + a = rgba[..., 3:4] + pre = np.concatenate([rgba[..., :3] * a, a], axis=-1) + blk = pre.reshape(SIZE, SS, SIZE, SS, 4).mean(axis=(1, 3)) + return blk[..., :3] + (1.0 - blk[..., 3:4]) + + +def bicubic_on_white(png: Path) -> np.ndarray: + """`build_web_tier`'s pipeline without the JPEG step, unrounded where Pillow allows.""" + from PIL import Image + im = Image.open(png).convert("RGBA") + page = Image.new("RGBA", im.size, (255, 255, 255, 255)) + page.alpha_composite(im) + out = page.convert("RGB").resize((SIZE, SIZE), Image.BICUBIC) + return np.asarray(out, dtype=np.float64) / 255.0 + + +def ycc(rgb: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """JPEG's (BT.601 full-range) luma and the chroma pair, in the same units as `rgb`.""" + r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2] + y = 0.299 * r + 0.587 * g + 0.114 * b + cb = -0.168736 * r - 0.331264 * g + 0.5 * b + cr = 0.5 * r - 0.418688 * g - 0.081312 * b + return y, np.stack([cb, cr], axis=-1) + + +def engine_sigma(y: np.ndarray) -> float: + """`coverage::estimate_noise` on luma: the tenth percentile of |4c - neighbours|, read + through the half-normal's tenth percentile and the kernel's gain, floored at 0.5/255.""" + lap = np.abs(4 * y[1:-1, 1:-1] - y[1:-1, :-2] - y[1:-1, 2:] - y[:-2, 1:-1] - y[2:, 1:-1]) + flat = np.sort(lap.ravel()) + q = flat[int(len(flat) * 0.10)] + return max(q / 0.12566 / np.sqrt(20.0), 0.5 / 255.0) + + +def edge_distance(ref: np.ndarray) -> np.ndarray: + from scipy.ndimage import distance_transform_edt + d = np.zeros(ref.shape[:2], dtype=bool) + step = EDGE_LEVELS / 255.0 + dx = np.abs(ref[:, 1:] - ref[:, :-1]).max(axis=-1) > step + dy = np.abs(ref[1:, :] - ref[:-1, :]).max(axis=-1) > step + d[:, 1:] |= dx + d[:, :-1] |= dx + d[1:, :] |= dy + d[:-1, :] |= dy + return distance_transform_edt(~d) + + +def column_windows(ref_y: np.ndarray) -> list[tuple[int, int, int, float, float]]: + """Column runs where luma ramps between two plateaus that differ by at least 0.25: each as + (column, first, last, the plateau above, the plateau below). Only isolated edges with + plateaus at least `PLATEAU` px long on both sides are kept, so a grown window holds one + edge and the outer part of each plateau is beyond any window's reach.""" + out = [] + h, w = ref_y.shape + for x in range(w): + col = ref_y[:, x] + flat = np.abs(np.diff(col)) < 1e-4 + y = 0 + while y < h - 1: + if flat[y]: + y += 1 + continue + a = y + while y < h - 1 and not flat[y]: + y += 1 + b = y # col[a] .. col[b] ramps; flat before a, after b + lo, hi = a - PLATEAU, b + PLATEAU + if lo < 0 or hi >= h: + continue + if not (flat[lo:a].all() and flat[b:hi].all()): + continue + top, bot = col[a], col[b] + if abs(top - bot) < 0.25: + continue + out.append((x, a, b, top, bot)) + return out + + +def window_bias(ref_y: np.ndarray, obs: dict[str, np.ndarray]) -> dict[str, dict[int, list]]: + """Per observed raster and growth `r`: its window sum minus the exact one, in pixels of + area, over every column window of `column_windows` (the coverage of the `top` plateau's + ink). An observed column is unmixed between its own plateaus, read as medians of the + outer `PLATEAU - 6` pixels each side (robust ink colours: JPEG shifts a plateau by a + level or two).""" + out = {name: {r: [] for r in GROWTH} for name in obs} + k = PLATEAU - 6 + for x, a, b, top, bot in column_windows(ref_y): + for name, o in obs.items(): + top_o = float(np.median(o[a - PLATEAU:a - PLATEAU + k, x])) + bot_o = float(np.median(o[b + PLATEAU - k + 1:b + PLATEAU + 1, x])) + if abs(top_o - bot_o) < 0.2: + break + for r in GROWTH: + s = slice(a - r, b + 1 + r) + cov_ref = (ref_y[s, x] - bot) / (top - bot) + cov_o = (o[s, x] - bot_o) / (top_o - bot_o) + out[name][r].append(float(cov_o.sum() - cov_ref.sum())) + return out + + +def main() -> int: + import svgeval + ap = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--per-family", type=int, default=6) + a = ap.parse_args() + from PIL import Image + items = svgeval.load_sets()["screen"] + by_fam: dict[str, list] = {} + for it in items: + by_fam.setdefault(it["corpus"], []).append(it) + base = ROOT / "bench" / "data" + acc = {k: {b: [] for b in BINS} for k in ("resample_y", "jpeg_y", "total_y", "jpeg_c")} + sig = [] + bias = {name: {r: [] for r in GROWTH} for name in ("8-bit", "bicubic", "web")} + n = 0 + for fam, its in sorted(by_fam.items()): + for it in its[: a.per_family]: + svg = (base / "corpus_svg" / fam / f"{it['stem']}.svg").read_text(encoding="utf-8") + ref = exact_on_white(svg) + bic = bicubic_on_white(base / "corpus_raster" / fam / "512ss" / f"{it['stem']}.png") + web = np.asarray(Image.open(base / "corpus_raster" / fam / "web" / f"{it['stem']}.jpg") + .convert("RGB"), dtype=np.float64) / 255.0 + dist = edge_distance(ref) + (ry, _), (by, _), (wy, wc) = ycc(ref), ycc(bic), ycc(web) + _, bc = ycc(bic) + for lo, hi in BINS: + m = (dist >= lo) & (dist < hi) + if not m.any(): + continue + acc["resample_y"][(lo, hi)].append((by - ry)[m]) + acc["jpeg_y"][(lo, hi)].append((wy - by)[m]) + acc["total_y"][(lo, hi)].append((wy - ry)[m]) + acc["jpeg_c"][(lo, hi)].append(np.linalg.norm(wc - bc, axis=-1)[m] / np.sqrt(2)) + sig.append(engine_sigma(wy)) + obs = {"8-bit": np.round(ry * 255) / 255, "bicubic": by, "web": wy} + for name, per_r in window_bias(ry, obs).items(): + for r, v in per_r.items(): + bias[name][r].extend(v) + n += 1 + lv = 255.0 + print(f"{n} icons, {SIZE} px; RMS in 8-bit levels by distance to the nearest exact edge\n") + print(f"{'distance':>10} {'share':>6} {'resample Y':>11} {'jpeg Y':>8} {'total Y':>8} " + f"{'jpeg CbCr':>10}") + total_px = sum(np.concatenate(acc["total_y"][b]).size for b in BINS if acc["total_y"][b]) + for b in BINS: + if not acc["total_y"][b]: + continue + cols = {k: np.concatenate(acc[k][b]) for k in acc} + rms = {k: float(np.sqrt(np.mean(v ** 2))) * lv for k, v in cols.items()} + label = f"{b[0]}-{b[1]}" if b[1] < 1000 else f">={b[0]}" + print(f"{label:>10} {cols['total_y'].size / total_px:6.1%} {rms['resample_y']:11.2f} " + f"{rms['jpeg_y']:8.2f} {rms['total_y']:8.2f} {rms['jpeg_c']:10.2f}") + s = np.array(sig) * lv + print(f"\nengine estimate (one sigma per image, luma): median {np.median(s):.2f}, " + f"p10 {np.percentile(s, 10):.2f}, p90 {np.percentile(s, 90):.2f} levels") + print("\ncolumn windows grown by r px each side: observed sum - exact sum (px of area);" + "\n8-bit = the exact raster rounded, bicubic = before the JPEG step, web = the tier") + print(f"{'':>9} {'r':>3} {'windows':>8} {'mean':>8} {'rms':>8} {'p95 |.|':>8}") + for name, per_r in bias.items(): + for r in GROWTH: + v = np.array(per_r[r]) + if v.size: + print(f"{name:>9} {r:>3} {v.size:>8} {v.mean():8.4f} " + f"{np.sqrt(np.mean(v ** 2)):8.4f} {np.percentile(np.abs(v), 95):8.4f}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/bench/theory/oracle_cost.py b/bench/theory/oracle_cost.py new file mode 100644 index 00000000..a3a50f86 --- /dev/null +++ b/bench/theory/oracle_cost.py @@ -0,0 +1,138 @@ +"""Search error or model error? Each trace against the artist's own file, on the input's pixels. + +The optimal tracer (`docs/theory/optimal.md` §2) writes the description that best trades +its fit to the input's pixels against its size. The artist's file is one description of +those pixels, so it bounds what the search could have found: + +* `search` the artist's file is no larger *and* fits the pixels no worse: a better + description exists, and the tracer missed it. More moves, wider search. +* `ahead` the trace is no larger and fits no worse: the tracer is at least as good as + the artist's file on its own objective. +* `bigger` the trace is larger and fits better: it spends parameters on the pixels. Is + that fit the picture or the renderer's anti-aliasing? The description-length + verdict (`mdl`) says which at the tracer's price per parameter. +* `smaller` the trace is smaller and fits worse: it simplified. If the gate's dE00 against + the artist's file is also worse, the objective preferred the wrong description: + a model error (the prior or the loss), not a search error. + +The fit is the sum of squared differences between the input raster and each SVG rendered at +the input's size, composited over white and over black (so transparency counts). The +description-length verdict prices a parameter at the tracer's `λ = ln(extent / 0.1)` nats +and measures the squared differences in units of the artist file's own residual per +boundary pixel, the renderer floor: what two renderers of the same file disagree by. + + python3 bench/theory/oracle_cost.py --exe target/release/inkvec --tier 512ss +""" + +from __future__ import annotations + +import argparse +import json +import math +import subprocess +import sys +import tempfile +from collections import Counter +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "bench")) + +PRECISION = 0.1 # px: inkvec's default --precision +TIE = 0.02 # relative difference in fit treated as equal + + +def sse(src: np.ndarray, svg: str) -> tuple[float, np.ndarray]: + """Squared difference of `svg` rendered at the input's size against the input, over + white and over black, and the per-pixel map. An opaque input (a logo flattened onto a + white page, the gate's `512ssop`) is compared over white only, as it was made.""" + from inkvec_bench import render + h, w = src.shape[:2] + r = render.render(svg, w, h) + m = np.zeros((h, w)) + opaque = float(src[..., 3].min()) >= 0.999 + grounds = ((1.0, 1.0, 1.0),) if opaque else ((1.0, 1.0, 1.0), (0.0, 0.0, 0.0)) + for bg in grounds: + d = render.composite(r, bg) - render.composite(src, bg) + m += (d * d).sum(-1) + return float(m.sum()), m + + +def one(args): + exe, it, tier, mode, td, extra = args + import svgeval + from inkvec_bench import render, svgmodel + svgeval.set_tier(tier) + png, gt = svgeval.item_paths(it) + out = Path(td) / f"{it['corpus']}__{it['stem']}.svg" + subprocess.run([exe, str(png), "-o", str(out), "--quiet", "--mode", mode, *extra], + check=True, capture_output=True) + src = render.load_rgba(png) + ours_svg = out.read_text(encoding="utf-8") + art_svg = gt.read_text(encoding="utf-8") + s_ours, _ = sse(src, ours_svg) + s_art, m_art = sse(src, art_svg) + k_ours = svgmodel.parse(ours_svg).n_params + k_art = svgmodel.parse(art_svg).n_params + h, w = src.shape[:2] + lam = math.log(max(max(w, h) / PRECISION, math.e)) + # The renderer floor: the artist file's own residual per pixel where it has any. + hot = m_art > 1e-6 + sigma2 = float(m_art[hot].mean()) if hot.any() else 1e-6 + d_cost = 0.5 * (s_ours - s_art) / sigma2 + lam * (k_ours - k_art) + tie = TIE * max(s_art, 1e-9) + fit = "same" if abs(s_ours - s_art) <= tie else ("better" if s_ours < s_art else "worse") + if k_ours <= k_art and fit != "worse": + cls = "ahead" + elif k_ours >= k_art and fit != "better": + cls = "search" + elif k_ours > k_art: + cls = "bigger" + else: + cls = "smaller" + out.unlink(missing_ok=True) + return dict(icon=f"{it['corpus']}/{it['stem']}", family=it["corpus"], cls=cls, + k_ours=k_ours, k_art=k_art, sse_ours=s_ours, sse_art=s_art, + d_cost=d_cost, mdl="ours" if d_cost < 0 else "artist") + + +def main() -> None: + import svgeval + ap = argparse.ArgumentParser() + ap.add_argument("--exe", default=str(ROOT / "target/release/inkvec")) + ap.add_argument("--tier", default="512ss") + ap.add_argument("--mode", default="quality") + ap.add_argument("--set", default="screen") + ap.add_argument("--workers", type=int, default=4) + ap.add_argument("--extra", default="", help="further tracer arguments, space-separated") + ap.add_argument("--json", default=None) + a = ap.parse_args() + items = svgeval.load_sets()[a.set] + with tempfile.TemporaryDirectory() as td, ProcessPoolExecutor(a.workers) as pool: + rows = list(pool.map(one, [(a.exe, it, a.tier, a.mode, td, a.extra.split()) + for it in items], chunksize=2)) + fams = sorted({r["family"] for r in rows}) + classes = ["ahead", "search", "bigger", "smaller"] + print(f"{a.mode} {a.tier}: {len(rows)} icons; the trace against the artist's file on the " + f"input's pixels") + print(f"{'family':15s} " + " ".join(f"{c:>8s}" for c in classes) + " MDL prefers ours") + for f in fams + ["ALL"]: + rs = rows if f == "ALL" else [r for r in rows if r["family"] == f] + c = Counter(r["cls"] for r in rs) + prefer = sum(r["mdl"] == "ours" for r in rs) + print(f"{f:15s} " + " ".join(f"{c[k]:8d}" for k in classes) + f" {prefer:3d}/{len(rs)}") + print("\nclearest search errors (the artist's file smaller and fitting no worse), by " + "parameters the trace spends over it:") + se = sorted((r for r in rows if r["cls"] == "search"), key=lambda r: r["k_art"] - r["k_ours"]) + for r in se[:12]: + print(f" {r['icon']:45s} {r['k_ours']:5d} vs {r['k_art']:5d} " + f"fit {r['sse_ours']:.3g} vs {r['sse_art']:.3g}") + if a.json: + Path(a.json).write_text(json.dumps(rows, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/bench/theory/params_diag.py b/bench/theory/params_diag.py new file mode 100644 index 00000000..c28baad8 --- /dev/null +++ b/bench/theory/params_diag.py @@ -0,0 +1,93 @@ +"""Where do the parameters go? Inkvec's SVG against the artist's, by element and segment type. + +For every icon of a set: the gate's parameter count (`svgmodel`: 2 per line, 6 per cubic, +7 per arc, a fixed count per primitive) of the trace and of the artist's file, split by what +spends them, and whether the artist drew with strokes (a stroked centre line is one path; +traced, it is an outline of two sides and two caps). + + python3 bench/theory/params_diag.py --exe target/release/inkvec --tier 512ss +""" + +from __future__ import annotations + +import argparse +import re +import subprocess +import sys +import tempfile +from collections import Counter, defaultdict +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "bench")) + + +def breakdown(svg: str) -> Counter: + from inkvec_bench import svgmodel + doc = svgmodel.parse(svg) + c: Counter = Counter() + for e in doc.elements: + if e.is_primitive: + c["prim:" + e.kind] += e.params + else: + for name, n in e.seg_types.items(): + c["seg:" + name] += {"Line": 2, "QuadraticBezier": 4, "CubicBezier": 6, + "Arc": 7}.get(name, 0) * n + return c + + +def one(args): + exe, it, tier, mode, td, extra = args + import svgeval + svgeval.set_tier(tier) + png, gt = svgeval.item_paths(it) + out = Path(td) / f"{it['corpus']}__{it['stem']}.svg" + subprocess.run([exe, str(png), "-o", str(out), "--quiet", "--mode", mode, *extra], + check=True, capture_output=True) + gsvg = gt.read_text(encoding="utf-8") + stroked = bool(re.search(r'stroke-width|stroke="(?!none)', gsvg)) + return dict(icon=f"{it['corpus']}/{it['stem']}", family=it["corpus"], + ours=breakdown(out.read_text(encoding="utf-8")), human=breakdown(gsvg), + stroked=stroked) + + +def main() -> None: + import svgeval + ap = argparse.ArgumentParser() + ap.add_argument("--exe", default=str(ROOT / "target/release/inkvec")) + ap.add_argument("--tier", default="512ss") + ap.add_argument("--mode", default="quality") + ap.add_argument("--set", default="screen") + ap.add_argument("--extra", default="") + a = ap.parse_args() + items = svgeval.load_sets()[a.set] + with tempfile.TemporaryDirectory() as td, ProcessPoolExecutor(4) as pool: + rows = list(pool.map(one, [(a.exe, it, a.tier, a.mode, td, a.extra.split()) for it in items])) + fams = sorted({r["family"] for r in rows}) + print(f"{a.mode} {a.tier}: parameters, inkvec / artist (family means of per-icon ratios)") + for f in fams + ["ALL"]: + rs = rows if f == "ALL" else [r for r in rows if r["family"] == f] + ratio = np.mean([sum(r["ours"].values()) / max(1, sum(r["human"].values())) for r in rs]) + st = sum(r["stroked"] for r in rs) + ours, hum = Counter(), Counter() + for r in rs: + ours.update(r["ours"]) + hum.update(r["human"]) + to, th = sum(ours.values()), sum(hum.values()) + def fmt(c, t): + return ", ".join(f"{k.split(':')[1]} {100 * v / t:.0f}%" for k, v in c.most_common(5)) + print(f"{f:15s} ratio {ratio:5.2f} stroked {st:3d}/{len(rs):3d} total {to:6d} vs {th:6d}") + print(f"{'':15s} inkvec: {fmt(ours, to)}") + print(f"{'':15s} artist: {fmt(hum, th)}") + for flag in (True, False): + rs = [r for r in rows if r["stroked"] == flag] + if rs: + print(f"artist {'stroked' if flag else 'filled '}: {len(rs)} icons, mean ratio " + f"{np.mean([sum(r['ours'].values()) / max(1, sum(r['human'].values())) for r in rs]):.2f}") + + +if __name__ == "__main__": + main() diff --git a/bench/theory/renderer_floor.py b/bench/theory/renderer_floor.py new file mode 100644 index 00000000..32167a29 --- /dev/null +++ b/bench/theory/renderer_floor.py @@ -0,0 +1,780 @@ +"""The renderer floor of the corpus intake, measured against the artists' own geometry. + +`docs/theory/chain-boundary.md` scores a description by window areas with calibrated +variances. Its calibration (amendment A1 of `chain-representation.md`) asks: when the +artist's own SVG is scored against the intake the gate feeds the tracer (resvg at 8x, +box-filtered, 8-bit; `bench/build_corpus_v2.py`), what is left over, and which part of it +is structure a forward model must reproduce rather than noise it may average? + +Each flat-paint icon of the screen set (no gradients, clips, masks, opacity, ``) is +drawn exactly, with no anti-aliasing approximation: its elements become shapely regions +(fill rules by winding number, strokes by buffering the centreline with the SVG's caps, +joins and miter limit), and each region's exact area per pixel comes from +`exact_raster.py`. Three models: + +* `true` the true geometry (arcs, circles and ellipses as ellipses), the visible partition + (each element minus everything painted above it); +* `usvg` usvg's geometry (every arc, circle, ellipse and rounded corner converted to cubics + by kurbo at 0.1 user units, as `usvg::parser::shapes` does), the visible partition; +* `as8` usvg's geometry composited element by element with exact coverage at 8x, then + box-filtered: resvg's own procedure, except that resvg's coverage of each 8x pixel + is anti-aliased by tiny-skia (4x4 supersampling, curves flattened) where this is exact. + +The intake's residual against each model is projected, at every pixel two inks share, onto +the axis between them (a coverage), and summed over windows: maximal runs of such pixels +along a column (where the boundary is within 45 degrees of horizontal) or a row +(elsewhere), each pixel in exactly one window. Reported per family and tier: + +* `rms_q` window error of the 8-bit quantisation alone (`as8` rounded as the intake is); +* `rms_*` window error of the intake against each model; +* `floor` `sqrt(rms_as8^2 - rms_q^2)`: the renderer floor, what tiny-skia adds; +* `bias` mean signed window error against `as8` (coverage of the ink on the left of the + boundary's direction), and `chain`: the share of the floor's variance that is a + constant per connected run of windows (one edge), A3's correlation; +* `selfcal` the fourth-difference estimate of the window variance from the intake alone, + over the truth-based one; +* `curve`, `line`, `stroke`, `fill-ln`: `rms_as8` restricted to windows on curves, on + straight segments, on stroke outlines, and on straight segments of fills; +* `seam` window error between `as8` and `usvg` (what per-element compositing at 8x adds + along abutting edges), and at junction pixels the size of the compositing term. + +With `--fresh`, the icon is also rendered now by the harness's own code +(`build_corpus_v2.render_supersampled`, resvg-py), and: + +* `fresh` window error of that render against `as8`; `stale` the largest difference, in + 8-bit levels, between it and the committed intake (0: the intake is reproducible); +* `lattice` window error of that render against `as8` drawn with tiny-skia's sample lattice + (4 x 4 points per 8x pixel, `lattice_coverage`), and `lat-ln`, `lat-cv`, `lat-st` + the same on straight fill segments, curves and stroke outlines: what is left is + tiny-skia's curve flattening and its stroker. + + python3 bench/theory/renderer_floor.py [--per-family 6] [--tiers 128ss,512ss] [--fresh] + +Needs svgelements, shapely, scipy and resvg-py (about 25 minutes with `--fresh` for six +icons per family at both tiers). +""" + +from __future__ import annotations + +import argparse +import io +import math +import re +import sys +from collections import defaultdict +from pathlib import Path + +import numpy as np +from PIL import Image + +import exact_raster as er + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "bench")) + +TOL_PX = 2e-4 # flattening tolerance of the exact models, px +ARC_TOL = 0.1 # usvg's arc-to-cubic tolerance, user units +SS = 8 # the intake's supersampling +EPS_COV = 1e-6 # an ink takes part in a pixel above this coverage + + +# ------------------------------------------------------------------- kurbo's arc, in Python + +def svg_arc(p0, p1, rx, ry, xrot, large, sweep): + """kurbo::Arc::from_svg_arc: (center, rx, ry, start, sweep, xrot) or None (a line).""" + if abs(p0[0] - p1[0]) < 1e-12 and abs(p0[1] - p1[1]) < 1e-12: + return None + rx, ry = abs(rx), abs(ry) + if rx < 1e-5 or ry < 1e-5: + return None + sp, cp = math.sin(xrot), math.cos(xrot) + hdx, hdy = (p0[0] - p1[0]) / 2, (p0[1] - p1[1]) / 2 + hsx, hsy = (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 + px, py = cp * hdx + sp * hdy, -sp * hdx + cp * hdy + rf = px * px / (rx * rx) + py * py / (ry * ry) + if rf > 1: + rx, ry = rx * math.sqrt(rf), ry * math.sqrt(rf) + rxry, rxpy, rypx = rx * ry, rx * py, ry * px + s2 = rxpy * rxpy + rypx * rypx + sign = -1.0 if large == sweep else 1.0 + coe = sign * math.sqrt(abs((rxry * rxry - s2) / s2)) + tcx, tcy = coe * rxpy / ry, -coe * rypx / rx + c = (cp * tcx - sp * tcy + hsx, sp * tcx + cp * tcy + hsy) + sa = math.atan2((py - tcy) / ry, (px - tcx) / rx) + ea = math.atan2((-py - tcy) / ry, (-px - tcx) / rx) + sw = math.fmod(ea - sa, 2 * math.pi) + if sweep and sw < 0: + sw += 2 * math.pi + elif not sweep and sw > 0: + sw -= 2 * math.pi + return c, rx, ry, sa, sw, xrot + + +def _ell(rx, ry, xrot, a): + u, v = rx * math.cos(a), ry * math.sin(a) + return (u * math.cos(xrot) - v * math.sin(xrot), u * math.sin(xrot) + v * math.cos(xrot)) + + +def arc_cubics(arc, start): + """kurbo's append_iter(ARC_TOL): the cubics usvg writes for an arc, from `start`.""" + c, rx, ry, a0, sw, xr = arc + n_err = max((1.1163 * max(rx, ry) / ARC_TOL) ** (1 / 6), 3.999999) + n = int(math.ceil(n_err * abs(sw) / (2 * math.pi))) + step = sw / n + arm = (4 / 3) * math.tan(abs(0.25 * step)) * math.copysign(1, sw) + out, prev = [], start + p0 = _ell(rx, ry, xr, a0) + for _ in range(n): + a1 = a0 + step + d0 = _ell(rx, ry, xr, a0 + math.pi / 2) + p3 = _ell(rx, ry, xr, a1) + d3 = _ell(rx, ry, xr, a1 + math.pi / 2) + q1 = (c[0] + p0[0] + arm * d0[0], c[1] + p0[1] + arm * d0[1]) + q2 = (c[0] + p3[0] - arm * d3[0], c[1] + p3[1] - arm * d3[1]) + q3 = (c[0] + p3[0], c[1] + p3[1]) + out.append(("C", prev, q1, q2, q3)) + prev, p0, a0 = q3, p3, a1 + return out + + +def arc_true(arc, start, end): + return [("A", start, arc, end)] + + +# ---------------------------------------------------------------- elements to subpaths + +def _shape_segments(e, se, mode): + """Subpaths of one svgelements shape in its local units, as usvg builds them: + [(segments, closed)], segments ('L', p, q), ('C', p, c1, c2, q), ('A', p, arc, q).""" + def arc_to(prev, to, rx, ry, xrot_deg, large, sweep): + a = svg_arc(prev, to, rx, ry, math.radians(xrot_deg), large, sweep) + if a is None: + return [("L", prev, to)] + return arc_cubics(a, prev) if mode == "usvg" else arc_true(a, prev, to) + + if isinstance(e, (se.Circle, se.Ellipse)): + cx, cy, rx, ry = float(e.cx), float(e.cy), float(e.rx), float(e.ry) + if rx <= 0 or ry <= 0: + return [] + pts = [(cx + rx, cy), (cx, cy + ry), (cx - rx, cy), (cx, cy - ry), (cx + rx, cy)] + segs = [] + for k in range(4): + segs += arc_to(pts[k], pts[k + 1], rx, ry, 0.0, False, True) + return [(segs, True)] + if isinstance(e, se.Rect): + x, y, w, h = float(e.x), float(e.y), float(e.width), float(e.height) + rx, ry = float(e.rx or 0), float(e.ry or 0) + rx, ry = min(rx, w / 2), min(ry, h / 2) + if rx <= 0 or ry <= 0: + p = [(x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y)] + return [([("L", p[k], p[k + 1]) for k in range(4)], True)] + segs, cur = [], (x + rx, y) + + def line(q): + nonlocal cur + segs.append(("L", cur, q)) + cur = q + + def arc(q): + nonlocal cur + segs.extend(arc_to(cur, q, rx, ry, 0.0, False, True)) + cur = q + line((x + w - rx, y)); arc((x + w, y + ry)); line((x + w, y + h - ry)) + arc((x + w - rx, y + h)); line((x + rx, y + h)); arc((x, y + h - ry)) + line((x, y + ry)); arc((x + rx, y)) + return [(segs, True)] + if isinstance(e, (se.SimpleLine,)): + return [([("L", (float(e.x1), float(e.y1)), (float(e.x2), float(e.y2)))], False)] + if isinstance(e, (se.Polyline, se.Polygon)): + pts = [(float(p.x), float(p.y)) for p in e.points] + segs = [("L", pts[k], pts[k + 1]) for k in range(len(pts) - 1)] + return [(segs, isinstance(e, se.Polygon))] + if isinstance(e, se.Path): + out, segs, closed = [], [], False + start = None + for s in e: + if isinstance(s, se.Move): + if segs: + out.append((segs, closed)) + segs, closed, start = [], False, (s.end.x, s.end.y) + elif isinstance(s, se.Close): + if s.start is not None and s.end is not None and (s.start != s.end): + segs.append(("L", (s.start.x, s.start.y), (s.end.x, s.end.y))) + closed = True + out.append((segs, closed)) + segs, closed = [], False + elif isinstance(s, se.Line): + segs.append(("L", (s.start.x, s.start.y), (s.end.x, s.end.y))) + elif isinstance(s, se.CubicBezier): + segs.append(("C", (s.start.x, s.start.y), (s.control1.x, s.control1.y), + (s.control2.x, s.control2.y), (s.end.x, s.end.y))) + elif isinstance(s, se.QuadraticBezier): + p0, q, p1 = (s.start.x, s.start.y), (s.control.x, s.control.y), (s.end.x, s.end.y) + c1 = (p0[0] + 2 / 3 * (q[0] - p0[0]), p0[1] + 2 / 3 * (q[1] - p0[1])) + c2 = (p1[0] + 2 / 3 * (q[0] - p1[0]), p1[1] + 2 / 3 * (q[1] - p1[1])) + segs.append(("C", p0, c1, c2, p1)) + elif isinstance(s, se.Arc): + sw = float(s.sweep) + segs += arc_to((s.start.x, s.start.y), (s.end.x, s.end.y), float(s.rx), float(s.ry), + math.degrees(float(s.get_rotation())), abs(sw) > math.pi, sw > 0) + if segs: + out.append((segs, closed)) + return out + return [] + + +def _flatten(segs, tf, tol): + """Polyline (px) of a subpath under the affine `tf` (a, b, c, d, e, f), and per vertex + whether it came from a curve.""" + a, b, c, d, e, f = tf + scale = math.sqrt(abs(a * d - b * c)) or 1.0 + t_loc = tol / scale + pts, curve = [], [] + + def put(p, cv): + pts.append((a * p[0] + c * p[1] + e, b * p[0] + d * p[1] + f)) + curve.append(cv) + for s in segs: + if not pts: + put(s[1], False) + if s[0] == "L": + put(s[2], False) + elif s[0] == "C": + p0, p1, p2, p3 = (np.array(v) for v in s[1:]) + m = max(np.linalg.norm(p0 - 2 * p1 + p2), np.linalg.norm(p1 - 2 * p2 + p3)) + n = max(1, int(math.ceil(math.sqrt(6 * m / (8 * t_loc))))) + for k in range(1, n + 1): + t = k / n + q = (1 - t) ** 3 * p0 + 3 * (1 - t) ** 2 * t * p1 + 3 * (1 - t) * t * t * p2 + t ** 3 * p3 + put(q, True) + elif s[0] == "A": + (cx, cy), rx, ry, a0, sw, xr = s[2] + r = max(rx, ry) + dth = 2 * math.acos(max(-1.0, 1 - t_loc / r)) if r > t_loc else math.pi / 2 + n = max(2, int(math.ceil(abs(sw) / dth))) + for k in range(1, n + 1): + u, v = _ell(rx, ry, xr, a0 + sw * k / n) + put((cx + u, cy + v), True) + # the arc ends exactly where the path says + return pts, curve + + +def _winding(pt, ring): + x, y = pt + r = np.asarray(ring) + x0, y0, x1, y1 = r[:, 0], r[:, 1], np.roll(r[:, 0], -1), np.roll(r[:, 1], -1) + up = (y0 <= y) & (y1 > y) + dn = (y0 > y) & (y1 <= y) + cross = (x1 - x0) * (y - y0) - (x - x0) * (y1 - y0) + return int(np.sum(up & (cross > 0)) - np.sum(dn & (cross < 0))) + + +def _fill_region(rings, evenodd): + import shapely + from shapely.geometry import LineString, Polygon + from shapely.ops import polygonize, unary_union + rings = [r for r in rings if len(r) >= 3] + if not rings: + return None + if len(rings) == 1: + p = Polygon(rings[0]) + return p if p.is_valid else shapely.make_valid(p) + lines = unary_union([LineString(list(r) + [r[0]]) for r in rings]) + keep = [] + for face in polygonize(lines): + rp = face.representative_point() + w = sum(_winding((rp.x, rp.y), r) for r in rings) + if (w % 2 != 0) if evenodd else (w != 0): + keep.append(face) + return unary_union(keep) if keep else None + + +def _stroke_region(paths, width, cap, join, miter): + from shapely.geometry import LineString, LinearRing + from shapely.ops import unary_union + cap_style = {"butt": "flat", "round": "round", "square": "square"}.get(cap, "flat") + join_style = {"miter": "mitre", "round": "round", "bevel": "bevel"}.get(join, "mitre") + parts = [] + for pts, closed in paths: + q = [p for k, p in enumerate(pts) if k == 0 or p != pts[k - 1]] + if len(q) == 1: + if cap_style == "flat": + continue + q = [q[0], (q[0][0] + 1e-9, q[0][1])] + g = LinearRing(q) if closed and len(q) >= 3 else LineString(q) + parts.append(g.buffer(width / 2, quad_segs=48, cap_style=cap_style, + join_style=join_style, mitre_limit=miter)) + return unary_union(parts) if parts else None + + +def layers_of(svg_text: str, size: int, mode: str): + """[(region, premultiplied rgba, kind, curve_points)] in paint order, in px of a `size` + raster in the gate's frame, or None when the file uses what this does not draw.""" + import svgelements as se + from inkvec_bench import render + if re.search(r"Gradient|]*>", s) + tag = re.sub(r'\s(width|height)="[^"]*"', "", m.group(0)) + tag = tag[:-1] + f' width="{size}" height="{size}">' + s = s[:m.start()] + tag + s[m.end():] + doc = se.SVG.parse(io.StringIO(s), reify=False) + out = [] + for e in doc.elements(): + if not isinstance(e, se.Shape) or isinstance(e, se.Text): + continue + if e.values.get("visibility") == "hidden" or e.values.get("display") == "none": + continue + tf = e.transform + tf = (tf.a, tf.b, tf.c, tf.d, tf.e, tf.f) + sub = _shape_segments(e, se, mode) + if not sub: + continue + flat = [(_flatten(segs, tf, TOL_PX), closed) for segs, closed in sub] + curve_pts = [p for (pts, cv), _ in flat for p, c in zip(pts, cv) if c] + fill = e.fill + if fill is not None and fill.value is not None and fill.alpha > 0: + rings = [pts for (pts, _), _ in flat] + reg = _fill_region(rings, e.values.get("fill-rule") == "evenodd") + if reg is not None and not reg.is_empty: + out.append((reg, (fill.red / 255, fill.green / 255, fill.blue / 255), "fill", curve_pts)) + st = e.stroke + if st is not None and st.value is not None and st.alpha > 0: + scale = math.sqrt(abs(tf[0] * tf[3] - tf[1] * tf[2])) + width = float(e.stroke_width) * scale + if width > 0: + reg = _stroke_region([(pts, closed) for (pts, _), closed in flat], width, + e.values.get("stroke-linecap", "butt"), + e.values.get("stroke-linejoin", "miter"), + float(e.values.get("stroke-miterlimit", 4))) + if reg is not None and not reg.is_empty: + out.append((reg, (st.red / 255, st.green / 255, st.blue / 255), "stroke", curve_pts)) + return out + + +# ------------------------------------------------------------------------- exact rasters + +def coverage(geom, w: int, h: int, scale: float = 1.0, y0: int = 0, y1: int | None = None): + """Exact area coverage of `geom` (shapely, px) on a `w x h` raster at `scale`, rows + `y0..y1` of the scaled raster: (rows, w*scale) float64.""" + import shapely + from shapely import affinity + from shapely.geometry import box + from shapely.geometry.polygon import orient + W, H = int(round(w * scale)), int(round(h * scale)) + y1 = H if y1 is None else y1 + out = np.zeros((y1 - y0, W)) + g = affinity.scale(geom, scale, scale, origin=(0, 0)) if scale != 1 else geom + g = g.intersection(box(0, y0, W, y1)) + if g.is_empty: + return out + polys = [p for p in getattr(g, "geoms", [g]) if p.geom_type == "Polygon" and p.area > 0] + for p in polys: + p = orient(p, 1.0) + minx, miny, maxx, maxy = p.bounds + bx0, by0 = max(0, int(math.floor(minx))), max(y0, int(math.floor(miny))) + bx1, by1 = min(W, int(math.ceil(maxx))), min(y1, int(math.ceil(maxy))) + if bx1 <= bx0 or by1 <= by0: + continue + rings = [np.asarray(p.exterior.coords)[:-1] - (bx0, by0)] + rings += [np.asarray(r.coords)[:-1] - (bx0, by0) for r in p.interiors] + rings = [np.clip(r, 0, None) for r in rings] + c = er.rasterize(rings, bx1 - bx0, by1 - by0) + out[by0 - y0:by1 - y0, bx0:bx1] += c + return np.clip(out, 0, 1) + + +def visible_regions(layers): + from shapely.ops import unary_union + covered, vis = None, [] + for reg, col, kind, cpts in reversed(layers): + v = reg if covered is None else reg.difference(covered) + covered = reg if covered is None else unary_union([covered, reg]) + vis.append((v, col, kind, cpts)) + return list(reversed(vis)) + + +def render_partition(vis, size): + """Premultiplied RGBA of the visible partition, exact area, and per-layer coverages.""" + img = np.zeros((size, size, 4)) + covs = [] + for v, col, _, _ in vis: + c = coverage(v, size, size) if not v.is_empty else np.zeros((size, size)) + covs.append(c) + img += c[..., None] * np.array([*col, 1.0]) + return img, covs + + +def render_layered(layers, size, scale, strip=16): + """Premultiplied RGBA of per-element "over" compositing with exact coverage at `scale`, + box-filtered to `size`: resvg's procedure with exact coverage.""" + img = np.zeros((size, size, 4)) + for r0 in range(0, size, strip): + r1 = min(size, r0 + strip) + acc = np.zeros(((r1 - r0) * scale, size * scale, 4)) + for reg, col, _, _ in layers: + c = coverage(reg, size, size, scale, r0 * scale, r1 * scale) + src = np.array([*col, 1.0]) + acc = c[..., None] * src + (1 - c[..., None]) * acc + img[r0:r1] = acc.reshape(r1 - r0, scale, size, scale, 4).mean(axis=(1, 3)) + return img + + +def _rings(geom): + out = [] + for g in getattr(geom, "geoms", [geom]): + if g.geom_type == "Polygon": + out.append(np.asarray(g.exterior.coords)) + out += [np.asarray(r.coords) for r in g.interiors] + return out + + +def lattice_coverage(geom, size, ss=SS, sub=4): + """tiny-skia's anti-aliasing of `geom` at `ss`: each device pixel's coverage is the share + of its `sub x sub` sample points, at the centres of the supersampled grid, that lie + inside (a span covers supersampled pixels `round(x_left) .. round(x_right)` on each + supersampled scanline, sampled at its centre: `scan/path_aa.rs`, SUPERSAMPLE_SHIFT 2).""" + D, S = size * ss, size * ss * sub + rings = _rings(geom) + if not rings: + return np.zeros((D, D)) + e = np.concatenate([np.stack([r[:-1], r[1:]], 1) for r in rings]) * (ss * sub) + x0, y0, x1, y1 = e[:, 0, 0], e[:, 0, 1], e[:, 1, 0], e[:, 1, 1] + ymin, ymax = np.minimum(y0, y1), np.maximum(y0, y1) + cnt = np.zeros((D, S)) + for k in range(int(max(0, math.floor(ymin.min()))), int(min(S, math.ceil(ymax.max())))): + yc = k + 0.5 + m = (ymin <= yc) & (ymax > yc) + if not m.any(): + continue + t = (yc - y0[m]) / (y1[m] - y0[m]) + xs = np.sort(x0[m] + t * (x1[m] - x0[m])) + lo = np.clip(np.ceil(xs[0::2] - 0.5).astype(int), 0, S) + hi = np.clip(np.ceil(xs[1::2] - 0.5).astype(int), 0, S) + row = np.zeros(S + 1) + np.add.at(row, lo, 1) + np.add.at(row, hi, -1) + cnt[k // sub] += np.cumsum(row)[:S] + return cnt.reshape(D, D, sub).sum(-1) / (sub * sub) + + +def render_lattice(layers, size): + """resvg's procedure with tiny-skia's sample lattice (curves flattened at `TOL_PX`, not + by tiny-skia's own forward differencing; strokes by the exact offset, not its stroker).""" + acc = np.zeros((size * SS, size * SS, 4)) + for reg, col, _, _ in layers: + c = lattice_coverage(reg, size) + acc = c[..., None] * np.array([*col, 1.0]) + (1 - c[..., None]) * acc + return acc.reshape(size, SS, size, SS, 4).mean(axis=(1, 3)) + + +def quantise_like_intake(pm): + """Premultiplied RGBA -> straight 8-bit (as the corpus builder) -> premultiplied.""" + a = pm[..., 3:4] + rgb = np.where(a > 1e-6, pm[..., :3] / np.maximum(a, 1e-6), 0.0) + q = np.round(np.clip(np.concatenate([rgb, a], -1), 0, 1) * 255) / 255 + return np.concatenate([q[..., :3] * q[..., 3:4], q[..., 3:4]], -1) + + +def load_intake(path): + s = np.asarray(Image.open(path).convert("RGBA"), dtype=np.float64) / 255 + return np.concatenate([s[..., :3] * s[..., 3:4], s[..., 3:4]], -1) + + +# -------------------------------------------------------------------------------- windows + +def ink_maps(vis, covs, size): + cols = {} + for (v, col, _, _), c in zip(vis, covs): + cols.setdefault(col, np.zeros((size, size))) + cols[col] += c + inks = [(0.0, 0.0, 0.0, 0.0)] + [(*k, 1.0) for k in cols] + cov = [np.clip(1 - sum(cols.values()), 0, 1)] + list(cols.values()) + return np.array(inks), np.array(cov) + + +def windows(cov_ink, inks): + """Two-ink pixels grouped into column and row windows; each such pixel in one window.""" + k, h, w = cov_ink.shape + present = cov_ink > EPS_COV + two = present.sum(0) == 2 + idx = np.argsort(~present, axis=0, kind="stable")[:2] # the two present inks, ascending + a_ink = np.minimum(idx[0], idx[1]) + b_ink = np.maximum(idx[0], idx[1]) + grads = np.array([np.gradient(cov_ink[i]) for i in range(k)]) # (k, 2, h, w) + g = np.take_along_axis(grads, b_ink[None, None], 0)[0] + gy, gx = g[0], g[1] + colcls = np.abs(gy) >= np.abs(gx) + wins = [] + for cls in (True, False): + mask = two & (colcls == cls) + lines = range(w) if cls else range(h) + for li in lines: + col = mask[:, li] if cls else mask[li, :] + pa = a_ink[:, li] if cls else a_ink[li, :] + pb = b_ink[:, li] if cls else b_ink[li, :] + j = 0 + n = len(col) + while j < n: + if not col[j]: + j += 1 + continue + k0 = j + while j + 1 < n and col[j + 1] and pa[j + 1] == pa[k0] and pb[j + 1] == pb[k0]: + j += 1 + pix = [(k, li) if cls else (li, k) for k in range(k0, j + 1)] + wins.append({"col": cls, "line": li, "lo": k0, "pix": pix, + "pair": (int(pa[k0]), int(pb[k0]))}) + j += 1 + return wins, two + + +def project(res, wins, inks): + """Per window, the residual's coverage of the pair's higher ink, summed.""" + out = np.zeros(len(wins)) + for t, wdw in enumerate(wins): + a, b = wdw["pair"] + d = inks[b] - inks[a] + dd = float(d @ d) + ys = np.array([p[0] for p in wdw["pix"]]) + xs = np.array([p[1] for p in wdw["pix"]]) + out[t] = float((res[ys, xs] @ d).sum()) / dd + return out + + +def chains(wins): + """Connected runs of windows (consecutive lines, same pair and axis, overlapping).""" + key = {} + for t, wdw in enumerate(wins): + key.setdefault((wdw["col"], wdw["line"], wdw["pair"]), []).append(t) + parent = list(range(len(wins))) + + def find(i): + while parent[i] != i: + parent[i] = parent[parent[i]] + i = parent[i] + return i + nxt = {} + for t, wdw in enumerate(wins): + for u in key.get((wdw["col"], wdw["line"] + 1, wdw["pair"]), []): + v = wins[u] + if v["lo"] <= wdw["lo"] + len(wdw["pix"]) + 1 and wdw["lo"] <= v["lo"] + len(v["pix"]) + 1: + parent[find(u)] = find(t) + nxt.setdefault(t, u) + return [find(t) for t in range(len(wins))], nxt + + +def fourth_difference(wins, nxt, obs, inks, cov_ink): + """D over five consecutive windows of one run, from the intake alone: each window's mean + boundary position, `lo + (the weight of the ink on the window's low side)`. The model is + used only to say which ink that is.""" + size = obs.shape[0] + + def pos(t): + wdw = wins[t] + a, b = wdw["pair"] + d = inks[b] - inks[a] + ys = np.array([p[0] for p in wdw["pix"]]) + xs = np.array([p[1] for p in wdw["pix"]]) + wb = float((((obs[ys, xs] - inks[a]) @ d) / float(d @ d)).sum()) + y, x = wdw["pix"][0] + y, x = (y - 1, x) if wdw["col"] else (y, x - 1) + if y < 0 or x < 0 or y >= size or x >= size: + return None + low = int(np.argmax(cov_ink[:, y, x])) + if low == b: + return wdw["lo"] + wb + if low == a: + return wdw["lo"] + len(wdw["pix"]) - wb + return None + ds = [] + for t in range(len(wins)): + seq = [t] + while len(seq) < 5 and seq[-1] in nxt: + seq.append(nxt[seq[-1]]) + if len(seq) < 5: + continue + hs = [pos(u) for u in seq] + if any(v is None for v in hs): + continue + ds.append(hs[0] - 4 * hs[1] + 6 * hs[2] - 4 * hs[3] + hs[4]) + return np.array(ds) + + +# ------------------------------------------------------------------------------- the run + +def measure(item, tier, fresh=False): + from inkvec_bench import render # noqa: F401 + size = int(re.match(r"\d+", tier).group(0)) + svg = (ROOT / "bench/data/corpus_svg" / item["corpus"] / f"{item['stem']}.svg").read_text() + png = ROOT / "bench/data/corpus_raster" / item["corpus"] / tier / f"{item['stem']}.png" + if not png.exists(): + return None + lay_u = layers_of(svg, size, "usvg") + lay_t = layers_of(svg, size, "true") + if not lay_u: + return None + obs = load_intake(png) + vis_u = visible_regions(lay_u) + x_u, covs_u = render_partition(vis_u, size) + x_t, _ = render_partition(visible_regions(lay_t), size) + x_8 = render_layered(lay_u, size, SS) + inks, cov_ink = ink_maps(vis_u, covs_u, size) + wins, two = windows(cov_ink, inks) + if not wins: + return None + r = {} + r["q"] = project(quantise_like_intake(x_8) - x_8, wins, inks) + r["true"] = project(obs - x_t, wins, inks) + r["usvg"] = project(obs - x_u, wins, inks) + r["as8"] = project(obs - x_8, wins, inks) + r["seam"] = project(x_8 - x_u, wins, inks) + if fresh: + sys.path.insert(0, str(ROOT / "bench")) + import build_corpus_v2 as B + f = np.asarray(Image.open(io.BytesIO(B.render_supersampled(svg, size, SS))).convert("RGBA"), + dtype=np.float64) / 255 + fpm = np.concatenate([f[..., :3] * f[..., 3:4], f[..., 3:4]], -1) + r["fresh"] = project(fpm - x_8, wins, inks) + r["stale"] = float(np.abs(fpm - obs).max() * 255) + x_l = render_lattice(lay_u, size) + r["lattice"] = project(fpm - x_l, wins, inks) + # tags + curve = np.zeros((size, size), bool) + stroke = np.zeros((size, size), bool) + for reg, col, kind, cpts in lay_u: + if cpts: + p = np.asarray(cpts) + ix = np.clip(np.floor(p[:, 0]).astype(int), 0, size - 1) + iy = np.clip(np.floor(p[:, 1]).astype(int), 0, size - 1) + curve[iy, ix] = True + if kind == "stroke": + for g in getattr(reg, "geoms", [reg]): + for ring in [g.exterior, *g.interiors] if g.geom_type == "Polygon" else []: + q = np.asarray(ring.coords) + seg = np.linspace(0, 1, 4)[:, None, None] + pts = (q[:-1][None] * (1 - seg) + q[1:][None] * seg).reshape(-1, 2) + ix = np.clip(np.floor(pts[:, 0]).astype(int), 0, size - 1) + iy = np.clip(np.floor(pts[:, 1]).astype(int), 0, size - 1) + stroke[iy, ix] = True + from scipy import ndimage + curve = ndimage.binary_dilation(curve) + r["curve"] = np.array([any(curve[y, x] for y, x in w["pix"]) for w in wins]) + r["stroke"] = np.array([any(stroke[y, x] for y, x in w["pix"]) for w in wins]) + r["n"] = np.array([len(w["pix"]) for w in wins]) + r["col"] = np.array([w["col"] for w in wins]) + ch, nxt = chains(wins) + r["chain"] = np.array(ch) + r["d4"] = fourth_difference(wins, nxt, obs, inks, cov_ink) + # junction pixels: three or more inks; the compositing term there and overall + multi = (cov_ink > EPS_COV).sum(0) >= 3 + dl = np.abs(x_8 - x_u).max(-1) + r["junction_px"] = int(multi.sum()) + r["comp_junction"] = dl[multi] + r["comp_two"] = dl[two] + r["boundary_px"] = int(two.sum()) + return r + + +def chain_share(e, ch): + """Share of the variance of `e` that is a constant per chain (one edge).""" + groups = defaultdict(list) + for v, c in zip(e, ch): + groups[c].append(v) + within = sum(((np.array(g) - np.mean(g)) ** 2).sum() for g in groups.values() if len(g) > 1) + n_within = sum(len(g) - 1 for g in groups.values() if len(g) > 1) + tot = float(((e - e.mean()) ** 2).sum()) / max(1, len(e) - 1) + w = within / max(1, n_within) + return max(0.0, 1 - w / tot) if tot > 0 else 0.0 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--per-family", type=int, default=6) + ap.add_argument("--tiers", default="128ss,512ss") + ap.add_argument("--fresh", action="store_true", help="also score a fresh resvg render") + ap.add_argument("--seed", type=int, default=1) + a = ap.parse_args() + import svgeval + items = svgeval.load_sets()["screen"] + rng = np.random.default_rng(a.seed) + by_fam = defaultdict(list) + for it in items: + by_fam[it["corpus"]].append(it) + pick = [] + for fam, its in sorted(by_fam.items()): + its = [it for it in its if layers_of_ok(it)] + rng.shuffle(its) + pick += its[:a.per_family] + for tier in a.tiers.split(","): + acc = defaultdict(lambda: defaultdict(list)) + for it in pick: + try: + r = measure(it, tier, a.fresh) + except Exception as ex: # a file this cannot draw is skipped, and said so + print(f" skip {it['corpus']}/{it['stem']}: {type(ex).__name__}: {ex}", file=sys.stderr) + continue + if r is None: + continue + for k in ("q", "true", "usvg", "as8", "seam", "curve", "stroke", "n", "col", "d4", + "comp_junction", "comp_two"): + acc[it["corpus"]][k].append(r[k]) + if "fresh" in r: + acc[it["corpus"]]["fresh"].append(r["fresh"]) + acc[it["corpus"]]["lattice"].append(r["lattice"]) + acc[it["corpus"]]["stale"].append(np.array([r["stale"]])) + acc[it["corpus"]]["chain"].append(r["chain"] + 10 ** 6 * len(acc[it["corpus"]]["chain"])) + acc[it["corpus"]]["jpx"].append(np.array([r["junction_px"]])) + acc[it["corpus"]]["bpx"].append(np.array([r["boundary_px"]])) + report(tier, acc) + + +def layers_of_ok(it): + s = (ROOT / "bench/data/corpus_svg" / it["corpus"] / f"{it['stem']}.svg").read_text() + return not re.search(r"Gradient|5s} {'windows':>7s} {'rms_q':>7s} {'true':>7s} {'usvg':>7s} {'as8':>7s} " + f"{'floor':>7s} {'bias':>8s} {'chain':>6s} {'selfcal':>7s} {'curve':>7s} {'line':>7s} " + f"{'stroke':>7s} {'fill-ln':>7s} {'seam':>7s} {'fresh':>7s} {'stale':>6s} {'lattice':>7s} " + f"{'lat-ln':>7s} {'lat-cv':>7s} {'lat-st':>7s}") + for fam, d in sorted(acc.items()): + cat = {k: np.concatenate(v) for k, v in d.items()} + q, t, u, s8, sm = cat["q"], cat["true"], cat["usvg"], cat["as8"], cat["seam"] + floor = math.sqrt(max(0.0, rms(s8) ** 2 - rms(q) ** 2)) + d4 = cat["d4"] + selfcal = ((np.median(np.abs(d4)) / 0.6745) ** 2 / 70) / (rms(s8) ** 2) if len(d4) > 10 else float("nan") + cv, st = cat["curve"].astype(bool), cat["stroke"].astype(bool) + fresh = rms(cat["fresh"]) if "fresh" in cat else float("nan") + stale = float(cat["stale"].max()) if "stale" in cat else float("nan") + fl = (~cv) & (~st) + if "lattice" in cat: + la = cat["lattice"] + lat, lat_ln, lat_cv, lat_st = rms(la), rms(la[fl]), rms(la[cv]), rms(la[st]) + else: + lat = lat_ln = lat_cv = lat_st = float("nan") + print(f"{fam:15s} {len(d['q']):5d} {len(q):7d} {rms(q):7.4f} {rms(t):7.4f} {rms(u):7.4f} {rms(s8):7.4f} " + f"{floor:7.4f} {s8.mean():+8.5f} {chain_share(s8, cat['chain']):6.2f} {selfcal:7.2f} " + f"{rms(s8[cv]):7.4f} {rms(s8[~cv]):7.4f} {rms(s8[st]):7.4f} {rms(s8[fl]):7.4f} " + f"{rms(sm):7.4f} {fresh:7.4f} {stale:6.0f} {lat:7.4f} {lat_ln:7.4f} {lat_cv:7.4f} {lat_st:7.4f}") + print("compositing term (max over channels of |as8 - usvg|, colour units):") + for fam, d in sorted(acc.items()): + cj = np.concatenate(d["comp_junction"]) if d["comp_junction"] else np.zeros(0) + ct = np.concatenate(d["comp_two"]) if d["comp_two"] else np.zeros(0) + jpx = int(np.concatenate(d["jpx"]).sum()) + bpx = int(np.concatenate(d["bpx"]).sum()) + q99 = lambda v: float(np.quantile(v, 0.99)) if len(v) else float("nan") + print(f" {fam:15s} junction px {jpx:6d}: mean {cj.mean() if len(cj) else float('nan'):.4f} " + f"p99 {q99(cj):.4f} max {cj.max() if len(cj) else float('nan'):.4f} " + f"two-ink px {bpx:6d}: mean {ct.mean() if len(ct) else float('nan'):.5f} p99 {q99(ct):.4f} " + f"share > 1/255: {float((ct > 1 / 255).mean()) if len(ct) else float('nan'):.3f}") + + +if __name__ == "__main__": + main() diff --git a/bench/theory/strip_eval.py b/bench/theory/strip_eval.py new file mode 100644 index 00000000..730e808e --- /dev/null +++ b/bench/theory/strip_eval.py @@ -0,0 +1,217 @@ +"""Boundary-point estimators from box-filtered coverage, scored against exact geometry. + +The estimators, each reading a two-tone coverage image `a` (1 = ink) and returning boundary +points: + +* `levelset`: the 1/2 crossing of the linear interpolation between pixel centres, along + columns (and rows), the reading of `contour.rs` and `planar::root_find_half`. +* `strip_mean`: the column-sum theorem (`InkvecTheory.column_sum_eq_average`): the sum of a + column's coverages between saturated pixels is the column mean of the boundary height. +* `strip`: the same with the cell-mean-to-point correction + (`InkvecTheory.boundary_point_from_pixels`), exact for cubic boundaries. + +Columns are scanned for boundaries flatter than 45 degrees, rows for steeper ones (the +axis along which the boundary is a graph with slope at most 1). + +Run `python3 strip_eval.py` for the synthetic comparison; `inkvec_compare.py` adds inkvec's +own sub-pixel stage to it. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass + +import numpy as np + +import exact_raster as er + + +@dataclass +class Crossing: + """One boundary crossing of a scan line (a column, or a row).""" + + line: int # column (or row) index + lo: int # first partial pixel along the line (or the pixel after the border) + hi: int # last partial pixel (lo - 1 when the boundary sits on a pixel border) + ink_first: bool # ink on the low-index side + mean: float # column mean of the boundary position (column-sum theorem) + half: float # the 1/2 crossing of the interpolated coverage + + +def scan(a: np.ndarray, eps: float) -> list[Crossing]: + """Crossings of every column of `a` (rows are the scan direction: a[j, i], j varies). + + A crossing is a run of partial pixels flanked by saturated pixels of opposite kinds. + """ + h, w = a.shape + out: list[Crossing] = [] + for i in range(w): + col = a[:, i] + sat = np.where(col >= 1.0 - eps, 1, np.where(col <= eps, 0, -1)) + j = 0 + while j < h: + if sat[j] == -1: + j += 1 + continue + # saturated pixel j; find the next saturated pixel k > j + k = j + 1 + while k < h and sat[k] == -1: + k += 1 + if k >= h: + break + if sat[k] != sat[j]: + lo, hi = j + 1, k - 1 + ink_first = sat[j] == 1 + # The window runs from flank to flank: the column-sum theorem holds for any + # window that contains the crossing, and the flanks' own (noisy) values keep + # the sum unbiased where a near-saturated pixel was classed as saturated. + part = col[j:k + 1] + if ink_first: + mean = j + float(part.sum()) + else: + mean = j + float((1.0 - part).sum()) + # 1/2 crossing of the linear interpolation between centres j+1/2 .. k+1/2 + seg = col[j:k + 1] + half = math.nan + for t in range(len(seg) - 1): + u, v = seg[t] - 0.5, seg[t + 1] - 0.5 + if u * v <= 0.0 and seg[t] != seg[t + 1]: + half = (j + t + 0.5) + (seg[t] - 0.5) / (seg[t] - seg[t + 1]) + break + out.append(Crossing(i, lo, hi, ink_first, mean, half)) + j = k + return out + + +def _neighbours(cr: list[Crossing]) -> dict[tuple[int, int], Crossing]: + return {(c.line, k): c for k, c in enumerate(cr)} + + +def points_from_scan(cr: list[Crossing], transpose: bool) -> dict[str, list[tuple[float, float]]]: + """Boundary points from one scan direction, by each estimator. A crossing is used only + when its neighbours on both adjacent lines exist, have the same orientation and are + within one pixel (slope at most 1 along this axis).""" + by_line: dict[int, list[Crossing]] = {} + for c in cr: + by_line.setdefault(c.line, []).append(c) + + def match(c: Crossing, line: int) -> Crossing | None: + best = None + for d in by_line.get(line, []): + if d.ink_first == c.ink_first and abs(d.mean - c.mean) <= 1.0: + if best is None or abs(d.mean - c.mean) < abs(best.mean - c.mean): + best = d + return best + + pts: dict[str, list[tuple[float, float]]] = {"levelset": [], "strip_mean": [], "strip": []} + for c in cr: + l, r = match(c, c.line - 1), match(c, c.line + 1) + if l is None or r is None: + continue + x = c.line + 0.5 + y_mean = c.mean + y_pt = c.mean - (r.mean - 2.0 * c.mean + l.mean) / 24.0 + cand = {"levelset": c.half, "strip_mean": y_mean, "strip": y_pt} + for k, y in cand.items(): + if math.isnan(y): + continue + pts[k].append((y, x) if transpose else (x, y)) + return pts + + +def estimate(a: np.ndarray, eps: float = 0.02) -> dict[str, np.ndarray]: + """Boundary points (x, y) by every estimator, from column and row scans.""" + out: dict[str, list] = {"levelset": [], "strip_mean": [], "strip": []} + for transpose in (False, True): + img = a.T if transpose else a + p = points_from_scan(scan(img, eps), transpose) + for k in out: + out[k].extend(p[k]) + return {k: np.array(v) for k, v in out.items()} + + +def dist_to_polygon(pts: np.ndarray, poly: np.ndarray) -> np.ndarray: + """Unsigned distance from each point to the closed polygon's boundary.""" + a = poly + b = np.roll(poly, -1, axis=0) + ab = b - a + ab2 = (ab * ab).sum(1) + d = np.full(len(pts), np.inf) + for s in range(0, len(pts), 256): + p = pts[s:s + 256, None, :] + t = np.clip(((p - a[None]) * ab[None]).sum(2) / ab2[None], 0.0, 1.0) + q = a[None] + t[..., None] * ab[None] + d[s:s + 256] = np.sqrt(((p - q) ** 2).sum(2)).min(1) + return d + + +def add_noise(a: np.ndarray, sigma: float, rng: np.random.Generator, quantize: bool) -> np.ndarray: + b = a + rng.normal(0.0, sigma, a.shape) if sigma > 0 else a.copy() + if quantize: + b = np.round(np.clip(b, 0.0, 1.0) * 255.0) / 255.0 + return np.clip(b, 0.0, 1.0) + + +def summarize(d: np.ndarray) -> str: + if len(d) == 0: + return "n=0" + return (f"n={len(d):5d} mean={d.mean():.4f} rms={math.sqrt((d * d).mean()):.4f} " + f"p99={np.quantile(d, 0.99):.4f} max={d.max():.4f}") + + +def shapes(rng: np.random.Generator, size: int = 64) -> list[tuple[str, np.ndarray]]: + out = [] + for _ in range(12): + r = rng.uniform(4.0, 24.0) + cx, cy = rng.uniform(r + 4, size - r - 4, 2) if r < size / 2 - 4 else (size / 2, size / 2) + out.append((f"circle r={r:.1f}", er.circle(cx, cy, r))) + for _ in range(8): + a = rng.uniform(6.0, 24.0) + b = rng.uniform(4.0, a) + out.append((f"ellipse {a:.1f}x{b:.1f}", + er.ellipse(size / 2 + rng.uniform(-2, 2), size / 2 + rng.uniform(-2, 2), a, b, + rng.uniform(0, math.pi)))) + for _ in range(8): + th = rng.uniform(0, math.pi) + out.append((f"edge th={math.degrees(th):.0f}", + er.half_plane(size, size, size / 2 + rng.uniform(-1, 1), + size / 2 + rng.uniform(-1, 1), th))) + return out + + +def edge_only(poly: np.ndarray, size: int) -> np.ndarray: + """For a half-plane clipped to the frame, the true boundary excludes the frame sides: + keep the polygon (the distance to the frame never wins far from it).""" + return poly + + +def main() -> None: + rng = np.random.default_rng(20261009) + size = 64 + conds = [("noiseless, float", 0.0, False), ("8-bit", 0.0, True), + ("8-bit + noise 1/255", 1.0 / 255, True), ("8-bit + noise 4/255", 4.0 / 255, True)] + sh = shapes(rng, size) + for cname, sigma, quant in conds: + acc: dict[str, list[np.ndarray]] = {} + for name, poly in sh: + a = er.rasterize([poly], size, size) + b = add_noise(a, sigma, rng, quant) + eps = max(0.02, 4.0 * sigma) + pts = estimate(b, eps) + for k, p in pts.items(): + if len(p) == 0: + continue + d = dist_to_polygon(p, poly) + # half-planes: drop points within 2 px of the frame (the frame is not a boundary) + if name.startswith("edge"): + keep = (p[:, 0] > 2) & (p[:, 0] < size - 2) & (p[:, 1] > 2) & (p[:, 1] < size - 2) + d = d[keep] + acc.setdefault(k, []).append(d) + print(f"== {cname}") + for k in ("levelset", "strip_mean", "strip"): + print(f" {k:11s} {summarize(np.concatenate(acc[k]))}") + + +if __name__ == "__main__": + main() diff --git a/bindings/contract/cases.json b/bindings/contract/cases.json index 76c4ff22..0a5ea232 100644 --- a/bindings/contract/cases.json +++ b/bindings/contract/cases.json @@ -13,12 +13,8 @@ }, "svg": { "x86_64-linux-gnu": { - "bytes": 8826, - "sha256": "b605367c0ca15ff23f0be08e4ecc5598b8c5e176429c32e597c65fd2428d5c6f" - }, - "x86_64-windows-msvc": { - "bytes": 8826, - "sha256": "aaac3e48856448edc19c682a6b5c3544ecc5f704fa3c0c7b331a7f959ae1c749" + "bytes": 8349, + "sha256": "ef4e226361037eac0a1763f8610774ff0658d30b58d207473c291ce5470e5c46" } } }, @@ -36,12 +32,8 @@ }, "svg": { "x86_64-linux-gnu": { - "bytes": 8826, - "sha256": "b605367c0ca15ff23f0be08e4ecc5598b8c5e176429c32e597c65fd2428d5c6f" - }, - "x86_64-windows-msvc": { - "bytes": 8826, - "sha256": "aaac3e48856448edc19c682a6b5c3544ecc5f704fa3c0c7b331a7f959ae1c749" + "bytes": 8349, + "sha256": "ef4e226361037eac0a1763f8610774ff0658d30b58d207473c291ce5470e5c46" } } }, @@ -61,12 +53,8 @@ }, "svg": { "x86_64-linux-gnu": { - "bytes": 5790, - "sha256": "b6d5c649cee3b9f0d781bc508e457a560bcf55a2b4706656806f21acb5d760e0" - }, - "x86_64-windows-msvc": { - "bytes": 5782, - "sha256": "ea544ec4bda9f2c0ff71c6711164c9b88e1dcd3617838f79a58872c157ddd9cd" + "bytes": 5647, + "sha256": "972e2f0a364778e775e62c4c87da0669cfecdbabfd227334a92ace53f0bc8800" } } }, @@ -83,12 +71,8 @@ }, "svg": { "x86_64-linux-gnu": { - "bytes": 8846, - "sha256": "6677a9b3711698a52f2cd8d9a892505c595f3f1da32f7a6abb533f6b9470c48b" - }, - "x86_64-windows-msvc": { - "bytes": 8846, - "sha256": "e558048b2aac2f534e296f307b8bc2c8cf48093f40da9f38a04a5eccabd786b6" + "bytes": 8369, + "sha256": "89d5100eb55c47c07c134d19ef241a4bec81a0bdfd6478a15029606388b11032" } } }, @@ -105,12 +89,8 @@ }, "svg": { "x86_64-linux-gnu": { - "bytes": 3303, - "sha256": "61f4dd2b28791294991b26464f896af1ec5a8df0db13adb790833af3b364757f" - }, - "x86_64-windows-msvc": { - "bytes": 3303, - "sha256": "1206b5a7806c272325cdf86d6c7de9c2ba1f7d4a14dac9a5d6dee21fc782943d" + "bytes": 2964, + "sha256": "beb7db2b1ddcd9a068a51715056f526fa31cf4bf7c1d1a621975c4c8779feec2" } } }, @@ -130,12 +110,8 @@ }, "svg": { "x86_64-linux-gnu": { - "bytes": 3303, - "sha256": "61f4dd2b28791294991b26464f896af1ec5a8df0db13adb790833af3b364757f" - }, - "x86_64-windows-msvc": { - "bytes": 3303, - "sha256": "1206b5a7806c272325cdf86d6c7de9c2ba1f7d4a14dac9a5d6dee21fc782943d" + "bytes": 2964, + "sha256": "beb7db2b1ddcd9a068a51715056f526fa31cf4bf7c1d1a621975c4c8779feec2" } } }, @@ -153,12 +129,8 @@ }, "svg": { "x86_64-linux-gnu": { - "bytes": 3319, - "sha256": "1fd4806b93c420c56098142da56f9f8a01fc694964bc30237742ef5b0c330e9c" - }, - "x86_64-windows-msvc": { - "bytes": 3319, - "sha256": "62952a5875fb97291e617fa027dc2ac8f5b37ef8669f8aff3af89244fcfbc222" + "bytes": 2980, + "sha256": "f72515edc7f187930b6d3cc95f03657ed4270959fc32cbcb09cfafbc667d1c06" } } }, @@ -173,12 +145,8 @@ }, "svg": { "x86_64-linux-gnu": { - "bytes": 679, - "sha256": "cbaf89d8dea3b3715e88d954dac5f99b8d52006cbffc236758a7a91a65f9112b" - }, - "x86_64-windows-msvc": { - "bytes": 679, - "sha256": "cbaf89d8dea3b3715e88d954dac5f99b8d52006cbffc236758a7a91a65f9112b" + "bytes": 682, + "sha256": "76fe770f9a7610175a9ecf953c02f918e8d22e75617d8b77674efcefe85d0f58" } } }, @@ -196,12 +164,8 @@ }, "svg": { "x86_64-linux-gnu": { - "bytes": 679, - "sha256": "cbaf89d8dea3b3715e88d954dac5f99b8d52006cbffc236758a7a91a65f9112b" - }, - "x86_64-windows-msvc": { - "bytes": 679, - "sha256": "cbaf89d8dea3b3715e88d954dac5f99b8d52006cbffc236758a7a91a65f9112b" + "bytes": 682, + "sha256": "76fe770f9a7610175a9ecf953c02f918e8d22e75617d8b77674efcefe85d0f58" } } }, @@ -218,12 +182,8 @@ }, "svg": { "x86_64-linux-gnu": { - "bytes": 760, - "sha256": "79f85e2ec9adb8b2ea9ba1ab39d108c8872d76e49bf7e7c8c3416fe493dfeb76" - }, - "x86_64-windows-msvc": { - "bytes": 760, - "sha256": "79f85e2ec9adb8b2ea9ba1ab39d108c8872d76e49bf7e7c8c3416fe493dfeb76" + "bytes": 682, + "sha256": "9fee7810aadc6f32ede16fc0f5c32ceeb1b6ef63cda375d40d9e34673eec713e" } } }, @@ -241,12 +201,8 @@ }, "svg": { "x86_64-linux-gnu": { - "bytes": 760, - "sha256": "79f85e2ec9adb8b2ea9ba1ab39d108c8872d76e49bf7e7c8c3416fe493dfeb76" - }, - "x86_64-windows-msvc": { - "bytes": 760, - "sha256": "79f85e2ec9adb8b2ea9ba1ab39d108c8872d76e49bf7e7c8c3416fe493dfeb76" + "bytes": 682, + "sha256": "9fee7810aadc6f32ede16fc0f5c32ceeb1b6ef63cda375d40d9e34673eec713e" } } }, @@ -267,12 +223,8 @@ }, "svg": { "x86_64-linux-gnu": { - "bytes": 760, - "sha256": "79f85e2ec9adb8b2ea9ba1ab39d108c8872d76e49bf7e7c8c3416fe493dfeb76" - }, - "x86_64-windows-msvc": { - "bytes": 760, - "sha256": "79f85e2ec9adb8b2ea9ba1ab39d108c8872d76e49bf7e7c8c3416fe493dfeb76" + "bytes": 682, + "sha256": "9fee7810aadc6f32ede16fc0f5c32ceeb1b6ef63cda375d40d9e34673eec713e" } } }, diff --git a/bindings/openapi.json b/bindings/openapi.json index f21e6b98..8214d8a0 100644 --- a/bindings/openapi.json +++ b/bindings/openapi.json @@ -210,7 +210,7 @@ "name": "detect_strokes", "in": "query", "required": false, - "description": "Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count. Quality mode only; off by default.", + "description": "Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count, and a ring on a plain page as one stroke over the page rather than two discs. Quality mode only; on by default.", "schema": { "type": "boolean" } @@ -538,9 +538,9 @@ "default": false }, "detect_strokes": { - "description": "Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count. Quality mode only; off by default.", + "description": "Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count, and a ring on a plain page as one stroke over the page rather than two discs. Quality mode only; on by default.", "type": "boolean", - "default": false + "default": true }, "merge_colors": { "description": "Colour groups: fills to draw as one, so the shapes between them join rather than being recoloured. Empty (the default) changes nothing. Groups are separated by ';' and members by ','; a member is a colour '#rrggbb' as it appears in a trace of the same image, or a gradient written as its stop colours joined by '>'. An optional '=' says what the group becomes: '=#rrggbb' a flat colour, '=@n' its n-th member (1-based; a gradient there is refitted over the whole group); without it, the member covering the most of the image. Example: '#c0392b,#e74c3c;#f00>#00f,#0a0=@1'. A group costs one extra trace.", diff --git a/bindings/options.schema.json b/bindings/options.schema.json index 7b74d965..8c545bb1 100644 --- a/bindings/options.schema.json +++ b/bindings/options.schema.json @@ -118,9 +118,9 @@ "default": false }, "detect_strokes": { - "description": "Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count. Quality mode only; off by default.", + "description": "Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count, and a ring on a plain page as one stroke over the page rather than two discs. Quality mode only; on by default.", "type": "boolean", - "default": false + "default": true }, "merge_colors": { "description": "Colour groups: fills to draw as one, so the shapes between them join rather than being recoloured. Empty (the default) changes nothing. Groups are separated by ';' and members by ','; a member is a colour '#rrggbb' as it appears in a trace of the same image, or a gradient written as its stop colours joined by '>'. An optional '=' says what the group becomes: '=#rrggbb' a flat colour, '=@n' its n-th member (1-based; a gradient there is refitted over the whole group); without it, the member covering the most of the image. Example: '#c0392b,#e74c3c;#f00>#00f,#0a0=@1'. A group costs one extra trace.", diff --git a/crates/inkvec-cli/Cargo.toml b/crates/inkvec-cli/Cargo.toml index bd476904..30529f5c 100644 --- a/crates/inkvec-cli/Cargo.toml +++ b/crates/inkvec-cli/Cargo.toml @@ -41,6 +41,7 @@ inkvec-fit = { workspace = true } inkvec-sr = { workspace = true } inkvec-restore = { workspace = true } inkvec-svgmin = { workspace = true } +inkvec-verified = { workspace = true } rayon = { workspace = true } [features] diff --git a/crates/inkvec-cli/src/alpha.rs b/crates/inkvec-cli/src/alpha.rs index 05bc604b..446f0549 100644 --- a/crates/inkvec-cli/src/alpha.rs +++ b/crates/inkvec-cli/src/alpha.rs @@ -18,7 +18,7 @@ //! //! * intake, in `lib.rs`: [`pixel_grid`] (undoing a nearest-neighbour upscale), then, once //! every resampling step is done, [`alpha_source_owned`] (the matte written over the -//! input's own buffer; the probe trace uses the copying [`alpha_source`]) and +//! input's own buffer; the copying [`alpha_source`] is the tests' oracle for it) and //! [`cutout_args`]; everything after traces [`AlphaSource::flat`]; //! //! [`pixel_grid`] (in `alpha/unblock.rs`) is the exact inverse of a nearest-neighbour @@ -585,6 +585,7 @@ pub(crate) struct AlphaSource { /// "Any transparency" means at least one pixel with alpha under 0.999. Unless `quiet`, the /// matte and the share of clear pixels (alpha under 0.05) go to stderr, and so does a note /// when the cutout was turned on here. +#[cfg(test)] pub(crate) fn alpha_source( img: &inkvec_trace::Rgba, quiet: bool, @@ -737,6 +738,7 @@ pub(crate) fn cutout_args<'a>( /// Method from: T. Porter, T. Duff, "Compositing Digital Images", SIGGRAPH '84, /// pp. 253–259, DOI 10.1145/800031.808606 -- "over" with an opaque background. Adapted to /// straight (unpremultiplied) colour, as `inkvec_trace::Rgba` stores it. +#[cfg(test)] pub(crate) fn flatten_over( img: &inkvec_trace::Rgba, matte: [f32; 3], diff --git a/crates/inkvec-cli/src/args.rs b/crates/inkvec-cli/src/args.rs index 3ea9f70a..0a38d608 100644 --- a/crates/inkvec-cli/src/args.rs +++ b/crates/inkvec-cli/src/args.rs @@ -153,6 +153,10 @@ pub struct Args { /// a re-saved screenshot, an export from a chat app -- where the file no longer /// admits what was done to it. pub lossy: inkvec_sr::Mode, + /// Set by the restorer pre-pass, never on the command line: the raster being traced came + /// out of the restorer, so the codec damage `lossy` stands for is gone (see + /// `inkvec_trace::ColorOptions::restored`). + pub restored: bool, /// Whether to run the super-resolution pre-pass before tracing: never, always, /// or `Auto` to trace, measure the fit, and clean and retrace only if the trace /// disagrees with the input where it claims to be flat. @@ -169,10 +173,11 @@ pub struct Args { /// a fixed scale of 4, whatever `sr_scale` is. pub sr_command: Option, /// The trained restorer: removes JPEG, WebP and decoder damage at the input's own size - /// before tracing. Off by default for the same reason SR is: on clean input it costs a - /// little colour accuracy. `Auto` with no restorer to run traces directly and says so - /// in the stats; `On` is an error then. - pub restore: inkvec_restore::Mode, + /// before tracing. `None` is the mode's default ([`Args::restore_mode`]): `Auto` in + /// Quality mode when this build can restore (the network compiled in, or + /// `restore_command`), `Off` otherwise. `Auto` with no restorer to run traces directly + /// and says so in the stats; `On` is an error then. + pub restore: Option, /// Interior residual above which `Auto` restores. pub restore_threshold: f64, /// The built-in restorer's network: an `.onnx` export (ONNX Runtime) or Burn `.bpk` @@ -194,7 +199,8 @@ pub struct Args { pub strokes: bool, /// Detect faces of the colour trace that were drawn as strokes -- a centreline and /// one width, round or butt caps, round or miter joins -- and write each as a stroked - /// path where that is the shorter description of its boundary. Quality mode only. + /// path where that is the shorter description of its boundary. Quality mode only; on + /// by default (`--no-detect-strokes` turns it off). pub detect_strokes: bool, /// Least share of the input's ink the strokes must actually draw, in [0, 1], /// or the drawing falls back to outlines. @@ -236,6 +242,27 @@ pub struct Args { pub mode: TraceMode, } +impl Args { + /// The restorer pre-pass's mode: `restore` when it was given, else the mode's default, + /// `Auto` in Quality mode when this build can restore (a network compiled in, or a + /// `restore_command`) and `Off` otherwise. Fast and balanced keep `Off` unless asked: a + /// restore costs seconds, and their point is speed. A build that cannot restore resolves + /// to `Off` rather than to an `Auto` with nothing to run, so it traces exactly as + /// `--restore off` does, stats included. + pub fn restore_mode(&self) -> inkvec_restore::Mode { + let can_restore = cfg!(any( + feature = "restore-model", + feature = "restore-burn", + feature = "restore-wgpu" + )) || self.restore_command.is_some(); + match self.restore { + Some(m) => m, + None if self.mode == TraceMode::Quality && can_restore => inkvec_restore::Mode::Auto, + None => inkvec_restore::Mode::Off, + } + } +} + impl Default for Args { /// Every default in one place, as the library and every front end see them. `quiet` /// is on (the parser turns it off for a terminal), and `native_alpha` is the one value @@ -272,12 +299,13 @@ impl Default for Args { merge_colors: Vec::new(), quiet: true, lossy: inkvec_sr::Mode::Auto, + restored: false, sr: inkvec_sr::Mode::Off, sr_threshold: inkvec_sr::detect::DEGRADED_RESIDUAL, sr_scale: 2, sr_no_recolour: false, sr_command: None, - restore: inkvec_restore::Mode::Off, + restore: None, restore_threshold: inkvec_sr::detect::DEGRADED_RESIDUAL, restore_weights: None, uncertainty: None, @@ -285,7 +313,7 @@ impl Default for Args { restore_command: None, intake_scale: false, strokes: false, - detect_strokes: false, + detect_strokes: true, stroke_balance: 0.85, stroke_refine: 0, // Per stroke against its own region. Dominant cap and join mismatch @@ -467,10 +495,12 @@ OPTIONS: instead of as filled outlines. 28% of the corpus is drawn this way and costs 3.3x the artist's parameters as outlines. Declines silently on anything else. - --detect-strokes Write the faces of the colour trace that were drawn as - strokes (a centreline and one width) as stroked paths, + --no-detect-strokes Write every face as a filled outline. By default, faces + of the colour trace that were drawn as strokes (a + centreline and one width) are written as stroked paths, wherever that describes their boundary in fewer numbers - at no worse a fit. Quality mode only + at no worse a fit (Quality mode; --detect-strokes asks + for it explicitly) --stroke-balance Least share of the input's ink the strokes must actually draw, or the drawing falls back to outlines [default: 0.85] @@ -513,7 +543,9 @@ SUPER-RESOLUTION PRE-PASS: on always clean first auto trace, measure the fit, clean and retrace only if the trace disagrees with the input where it - claims to be flat; with no upscaler to run (no + claims to be flat and the input shows resampling + or compression (a lossy file, JPEG ringing, wide + edges); with no upscaler to run (no tools/inkvec_sr beside the binary) it traces directly and says so, where `on` fails --sr-threshold Interior residual above which auto cleans [default: 0.5] @@ -529,16 +561,19 @@ RESTORER PRE-PASS: A trained network that removes JPEG, WebP and AI-decoder damage at the input's own size. On damaged input it cuts colour error by 28-45% and parameters by about 30%; on clean input it costs a few percent of colour accuracy, which is - why it is off by default and `auto` measures first. Restored input is traced - with lossy intake on. + why `auto` measures first. Restored input is traced with lossy intake on. - --restore off never (default) + --restore off never on always restore first auto trace, measure the fit, restore and retrace only if the trace disagrees with the input where it - claims to be flat; with no restorer to run (a + claims to be flat and the input shows compression + (a lossy file, or JPEG ringing); with no restorer + to run (a build without the network, no weights) it traces directly and says so, where `on` fails + [default: auto in quality mode when this build + can restore, off in fast and balanced] --restore-threshold Interior residual above which auto restores [default: 0.5] --restore-weights The built-in restorer's network: an .onnx export, @@ -634,7 +669,9 @@ pub(crate) fn parse_args_from(mut it: impl Iterator) -> Result a.sr_no_recolour = true, "--intake-scale" => a.intake_scale = true, "--strokes" => a.strokes = true, - "--detect-strokes" => a.detect_strokes = true, + "--detect-strokes" | "--no-detect-strokes" => { + a.detect_strokes = flag == "--detect-strokes" + } "--stroke-residual" => a.stroke_residual = parse_value(&mut it, "--stroke-residual")?, "--stroke-refine" => a.stroke_refine = parse_value(&mut it, "--stroke-refine")?, "--lambda-scale" => a.lambda_scale = parse_value(&mut it, "--lambda-scale")?, @@ -653,10 +690,11 @@ pub(crate) fn parse_args_from(mut it: impl Iterator) -> Result { - a.restore = it - .next() - .ok_or("--restore needs auto, on or off")? - .parse()? + a.restore = Some( + it.next() + .ok_or("--restore needs auto, on or off")? + .parse()?, + ) } "--restore-threshold" => { a.restore_threshold = parse_value(&mut it, "--restore-threshold")? @@ -802,6 +840,36 @@ mod tests { assert_eq!(format!("{parsed:?}"), format!("{expected:?}")); } + /// `--restore`'s default is the mode's: `auto` in Quality mode when the build can restore, + /// `off` in Fast and balanced and wherever there is nothing to restore with; a given + /// value always wins. + #[test] + fn the_restorer_defaults_to_auto_in_quality_mode_only() { + use inkvec_restore::Mode; + let built_in = cfg!(any( + feature = "restore-model", + feature = "restore-burn", + feature = "restore-wgpu" + )); + let quality = parse("logo.png").expect("parses"); + let expect = if built_in { Mode::Auto } else { Mode::Off }; + assert_eq!(quality.restore_mode(), expect); + let command = parse("logo.png --restore-command my_restore").expect("parses"); + assert_eq!(command.restore_mode(), Mode::Auto); + for mode in ["fast", "balanced"] { + let a = parse(&format!( + "logo.png --mode {mode} --restore-command my_restore" + )) + .expect("parses"); + assert_eq!(a.restore_mode(), Mode::Off, "{mode}"); + } + let fast_auto = parse("logo.png --mode fast --restore auto").expect("parses"); + assert_eq!(fast_auto.restore_mode(), Mode::Auto); + let quality_off = + parse("logo.png --restore off --restore-command my_restore").expect("parses"); + assert_eq!(quality_off.restore_mode(), Mode::Off); + } + #[test] fn flags_set_their_fields() { let a = parse("logo.png --tau 3 --cutout -o out.svg --restore on --colors 8 -q") @@ -812,7 +880,7 @@ mod tests { assert!(a.cutout && a.quiet); assert!(a.harmonize); assert_eq!(a.output, Some(PathBuf::from("out.svg"))); - assert!(matches!(a.restore, inkvec_restore::Mode::On)); + assert!(matches!(a.restore, Some(inkvec_restore::Mode::On))); assert_eq!(a.max_colors, 8); assert_eq!(a.mode, super::TraceMode::Quality); @@ -838,6 +906,19 @@ mod tests { .expect("parses") .native_alpha ); + + // Stroke detection is on unless switched off. + assert!(parse("logo.png").expect("parses").detect_strokes); + assert!( + !parse("logo.png --no-detect-strokes") + .expect("parses") + .detect_strokes + ); + assert!( + parse("logo.png --no-detect-strokes --detect-strokes") + .expect("parses") + .detect_strokes + ); } #[test] @@ -955,7 +1036,7 @@ mod tests { assert_eq!(a.stroke_balance, 0.8); assert!(a.harmonize && a.use_symbols && a.hypotheses); assert_eq!(a.harmonize_threshold, 0.04); - assert!(matches!(a.restore, inkvec_restore::Mode::Auto)); + assert!(matches!(a.restore, Some(inkvec_restore::Mode::Auto))); assert_eq!(a.restore_threshold, 0.03); assert_eq!(a.restore_weights, Some(PathBuf::from("w.onnx"))); assert_eq!(a.restore_command.as_deref(), Some("my_restore")); diff --git a/crates/inkvec-cli/src/damage.rs b/crates/inkvec-cli/src/damage.rs new file mode 100644 index 00000000..5614ddbf --- /dev/null +++ b/crates/inkvec-cli/src/damage.rs @@ -0,0 +1,110 @@ +//! Evidence of damage of the input's own, which `--restore auto` and `--sr auto` need before +//! they act, besides the probe trace's residual. +//! +//! # Why the residual alone is not enough +//! +//! Both pre-passes decide `auto` on one signal: how far the input sits from its own probe +//! trace where the trace claims to be flat ([`inkvec_sr::detect::interior_residual`], above +//! `--restore-threshold` / `--sr-threshold`). Smooth shading in clean, gradient-heavy art +//! reads as that residual too. Measured with `--restore auto` on the gate's opaque 512 px tier +//! (`quality-512ssop`, PNG renders, 2026-10-10): the restorer ran on 7 of 246 clean icons, all +//! Noto emoji with shading, and the condition read dE00 +4.49 % and geom +13.9 % +//! (`emoji_u1f5a8` geom 0.19 -> 3.05, `emoji_u1f469_1f3fb_200d_1f52c` dE00 0.22 -> 0.53). +//! +//! So `auto` acts only when the pixels or the file say the input was damaged, independently +//! of the residual: +//! +//! * the restorer, which undoes compression ([`compressed`]): a lossy container (`--lossy`, +//! resolved from the file's first bytes), or JPEG ringing around the edges +//! ([`inkvec_trace::coverage::ringing_score`] above the gate the palette's noise guard +//! uses), which is how a JPEG re-saved as PNG is told; +//! * the upscaler, which undoes resampling as well ([`soft`]): either of those, or edges +//! wider than a native render's (`coverage::intake_scale` above +//! [`inkvec_trace::color::SOFT_INTAKE_EDGE`]). +//! +//! These are the three signals that open the palette's soft intake, and a clean render +//! passes none of them (`color::SOFT_RINGING`'s and `SOFT_INTAKE_EDGE`'s measurements over +//! the corpus). +//! +//! # Order +//! +//! The evidence is asked first and the residual only when there is some; without evidence +//! `--restore auto` makes no probe at all and the input takes the plain path. The residual +//! is the costly half: it needs the probe trace, rendered at full size. Measured on the gate's +//! transparent 512 px tier in Fast mode (246 icons, 2026-10-10), `auto` asking the residual +//! first cost 16.5 ms of CPU per icon on a 31 ms trace (the render and the residual), and the +//! ringing score 5.5 ms more where the residual fired. Both conditions are needed, so the +//! order changes no decision, only what a clean input pays: a lossy container is a flag, and +//! a lossless one costs the ringing score alone. + +use inkvec_trace::{color, coverage, Rgba}; + +/// Why the input looks compressed, or `None` when nothing says so: `lossy` is the resolved +/// `--lossy` (`On` for a lossy container; `Auto` when the caller never resolved it, which +/// reads as "not known"), and the ringing is measured on the image over white when `pixels` +/// asks for it. +/// +/// Fast mode does not: its whole trace of a 512 px icon costs about 31 ms of CPU, and the +/// ringing score 2.5 ms of it (2.7 ms on the opaque tier, 0.17 ms at 128 px; best of three, +/// 2026-10-10), which `auto` would add to every clean PNG. The container is a flag. What +/// Fast gives up is a JPEG re-saved as PNG: on the `web` tier's own pixels the score passes +/// the gate on 186 of 246 icons, and on the gate's clean tiers on none (128ss, 512ss, 512ssop). +pub(crate) fn compressed(img: &Rgba, lossy: inkvec_sr::Mode, pixels: bool) -> Option<&'static str> { + if lossy == inkvec_sr::Mode::On { + return Some("lossy container"); + } + if !pixels { + return None; + } + let rgb = img.composited([1.0, 1.0, 1.0]); + let gate = if img.width.min(img.height) >= color::RINGING_MIN_DIM { + color::SOFT_RINGING_LARGE + } else { + color::SOFT_RINGING + }; + (coverage::ringing_score(&rgb, img.width, img.height) > gate).then_some("ringing") +} + +/// Why the input looks compressed or resampled, or `None`: [`compressed`], or edges wider +/// than a native render's. +pub(crate) fn soft(img: &Rgba, lossy: inkvec_sr::Mode) -> Option<&'static str> { + compressed(img, lossy, true).or_else(|| { + let rgb = img.composited([1.0, 1.0, 1.0]); + (coverage::intake_scale(&rgb, img.width, img.height) > color::SOFT_INTAKE_EDGE) + .then_some("wide edges") + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A flat two-colour image: no ringing, one-pixel edges. + fn clean(w: usize, h: usize) -> Rgba { + let mut data = Vec::with_capacity(w * h * 4); + for p in 0..w * h { + let v = if (p % w) < w / 2 { 0.1 } else { 0.9 }; + data.extend_from_slice(&[v, v, v, 1.0]); + } + Rgba { + width: w, + height: h, + data, + } + } + + #[test] + fn a_clean_render_shows_no_damage_and_a_lossy_container_does() { + let img = clean(64, 64); + assert_eq!(compressed(&img, inkvec_sr::Mode::Off, true), None); + assert_eq!(compressed(&img, inkvec_sr::Mode::Auto, true), None); + assert_eq!(soft(&img, inkvec_sr::Mode::Off), None); + for pixels in [true, false] { + assert_eq!( + compressed(&img, inkvec_sr::Mode::On, pixels), + Some("lossy container") + ); + } + assert_eq!(soft(&img, inkvec_sr::Mode::On), Some("lossy container")); + } +} diff --git a/crates/inkvec-cli/src/editable.rs b/crates/inkvec-cli/src/editable.rs index 8d704a8e..0e99af36 100644 --- a/crates/inkvec-cli/src/editable.rs +++ b/crates/inkvec-cli/src/editable.rs @@ -1,6 +1,8 @@ //! Editability mode (`--editability`): post-fit passes that spend parameters on -//! structure an artist can edit — G1-smooth joins, axis-aligned and equal-length -//! handles, aligned nodes, and self-symmetric rings locked into exact mirrors. +//! structure an artist can edit — circular arcs written as cubics with their nodes at the +//! extrema, smooth runs re-noded at their extrema ([`curves`]), G1-smooth joins within a +//! ring and across the planar map's junctions ([`junctions`]), axis-aligned and +//! equal-length handles, aligned nodes, and self-symmetric rings locked into exact mirrors. //! //! Every change is accepted the same way: the whole ring is re-sampled and the //! change kept only while every sample sits within `3×` the source point's own @@ -19,10 +21,13 @@ //! emitter, so nothing downstream re-breaks what was locked. `pipeline.rs` calls //! [`edit_all`] once per colour trace when `--editability` is on and prints //! [`EditStats::summary`]. In: one measured polyline per planar-map edge (its sub-pixel -//! points and their sigma), the fitted path for each edge, and which of them were fitted -//! as primitives. Out: the same fitted paths, edited in place, and counts of what changed. -//! A "ring" below is one such fitted path; it is closed for an isolated boundary and open -//! for a run between two junctions. +//! points and their sigma), the fitted path for each edge, which of them were fitted as +//! primitives, the faces' rings over the edges (for the joins at junctions) and the fit's +//! configuration (for the price of a parameter). Out: the same fitted paths, edited in +//! place, and counts of what changed. +//! A "ring" below is one such fitted path: a run between two junctions, or a boundary with +//! no junction on it, which comes as an open path ending where it starts and which the +//! per-ring passes treat as closed ([`isolated_loops`]). //! //! Units: positions in px of the traced raster, with pixel centres at integer coordinates //! (the canvas spans `-0.5 .. w - 0.5`); sigma in px; angles in degrees. Image y points @@ -43,6 +48,30 @@ use inkvec_fit::structural::eval_segment; use inkvec_fit::FittedPath; use crate::diag; +use crate::faces::FaceRings; + +mod curves; +mod junctions; + +/// `path` with every circular arc written as cubics cut at its x and y extrema +/// ([`curves::arc_as_cubics`]), for a stroke's centreline under `--editability`: exact to +/// `1.1e-3` of the radius (`2.7e-4` for a quarter), so it needs no guard of its own. +pub(crate) fn arcs_as_cubics(path: &FittedPath) -> FittedPath { + let mut segments = Vec::with_capacity(path.segments.len()); + let mut cur = path.start; + for s in &path.segments { + match curves::arc_as_cubics(s, cur) { + Some(pieces) => segments.extend(pieces), + None => segments.push(s.clone()), + } + cur = s.end(); + } + FittedPath { + start: path.start, + segments, + closed: path.closed, + } +} /// A handle direction is "on" an axis (0/90/180/270) within this many degrees. const AXIS_SNAP: f64 = 2.5; @@ -51,6 +80,14 @@ const AXIS_SNAP: f64 = 2.5; const DIAG_SNAP: f64 = 1.5; /// A join whose in/out tangents disagree by at most this many degrees is G1-smooth. const G1_SNAP_DEG: f64 = 3.0; +/// A join turning by at most this many degrees is a kink, not a corner, and [`pass_g1`] +/// tries to make it smooth: the artists' joins between curves are smooth or turn by more than +/// this (R3.1 of `docs/theory/chain-representation.md`; 8.6 % of them between 3 and 30 +/// degrees on the screen set, against 25 % of the trace's). +const KINK_DEG: f64 = 30.0; +/// Two lines meeting at a turn of at most this many degrees are one straight run, and +/// [`pass_collinear`] writes them as one line (the battery's `collinear`, its `AXIS_DEG`). +const COLLINEAR_DEG: f64 = 0.5; /// Handle length ratio inside this window symmetrises to the mean. const LEN_MATCH: f64 = 0.10; /// Node coordinates within this distance of a shared target align to it. @@ -95,6 +132,14 @@ pub(crate) struct EditStats { pub(crate) nodes_aligned: usize, /// Rings rewritten as exact mirrors by [`pass_mirror`]. pub(crate) mirror_rings: usize, + /// Circular arcs written as cubics cut at their extrema by [`curves::pass_arcs`]. + pub(crate) arcs_split: usize, + /// Smooth runs re-segmented at their extrema by [`curves::pass_extrema`]. + pub(crate) extrema_runs: usize, + /// Joins at a junction between two edges made smooth by [`junctions::pass_junctions`]. + pub(crate) junction_g1: usize, + /// Nodes in the middle of a straight run removed by [`pass_collinear`]. + pub(crate) collinear_merged: usize, /// Edits tried and undone because the result left the acceptance budget. pub(crate) reverted: usize, } @@ -103,14 +148,19 @@ impl EditStats { /// The one-line report the pipeline prints under `--editability`. pub(crate) fn summary(&self) -> String { format!( - " editability {} rings: {} G1 joins, {} axis + {} diagonal handle snaps, \ -{} length-symmetric curves, {} nodes aligned, {} mirror-locked, {} reverted", + " editability {} rings: {} arcs as cubics, {} runs re-noded at extrema, {} G1 joins, \ +{} at junctions, {} axis + {} diagonal handle snaps, {} length-symmetric curves, {} nodes \ +aligned, {} collinear nodes merged, {} mirror-locked, {} reverted", self.rings, + self.arcs_split, + self.extrema_runs, self.g1_joins, + self.junction_g1, self.axis_snaps, self.diag_snaps, self.len_sym, self.nodes_aligned, + self.collinear_merged, self.mirror_rings, self.reverted ) @@ -171,6 +221,21 @@ fn guarded_slack( }) } +/// How far the chain strays from the evidence: the largest, over 8 samples per segment, of +/// `min_j (|s − q_j| − 3·σ_j)`, the slack the acceptance test would need for it (px). +/// `guarded_slack(.., slack)` is `stray(..) <= slack`. +fn stray(segs: &[Segment], starts: &[Point], pts: &[Point], sigma: &[f64]) -> f64 { + samples(segs, starts, 8) + .iter() + .map(|p| { + pts.iter() + .enumerate() + .map(|(j, q)| p.dist(*q) - 3.0 * sigma[j.min(sigma.len() - 1)]) + .fold(f64::INFINITY, f64::min) + }) + .fold(f64::NEG_INFINITY, f64::max) +} + /// Greedy per-item acceptance: apply one change, keep it if the whole ring still /// guards, revert just that change otherwise. /// @@ -202,23 +267,38 @@ fn cubic(seg: &Segment) -> Option<(Point, Point, Point)> { } } -/// G1: joins whose tangents disagree by at most [`G1_SNAP_DEG`] rotate onto their -/// shared bisector, so an editor drags one tangent and the curve stays smooth. +/// The unit direction of travel arriving at a segment's end (`incoming`) or leaving its +/// start, from its handle at that end, or a line's own direction; `None` for an arc, a +/// degenerate segment, or a handle of zero length. +fn end_direction(seg: &Segment, start: Point, incoming: bool) -> Option<(f64, f64)> { + let (from, to) = match (seg, incoming) { + (&Segment::Line(e), _) => (start, e), + (&Segment::Cubic(_, c2, e), true) => (c2, e), + (&Segment::Cubic(c1, _, _), false) => (start, c1), + (Segment::Arc { .. }, _) => return None, + }; + let (dx, dy) = (to.x - from.x, to.y - from.y); + let l = dx.hypot(dy); + (l > 1e-9).then(|| (dx / l, dy / l)) +} + +/// G1: joins within a ring that turn by at most [`KINK_DEG`] are made smooth, so an editor +/// drags one tangent and the curve stays smooth, and a kink the separate segment fits left +/// (neither smooth nor a corner, which artists do not draw) goes. /// -/// At the node `N` between cubic `i` (second control point `c2`) and cubic `j = i + 1` -/// (first control point `c1`), the incoming tangent is `d_in = N − c2` and the outgoing -/// one `d_out = c1 − N`. Their angle is `θ = acos(d_in·d_out / (|d_in| |d_out|))`, in -/// degrees. When `θ ≤ G1_SNAP_DEG` both handles are turned onto the unit bisector -/// `b = normalise(d_in/|d_in| + d_out/|d_out|)` (flipped if needed so it points the way the -/// curve leaves the node) and keep their own lengths: `c2 ← N − |d_in|·b`, -/// `c1 ← N + |d_out|·b`. The node does not move, and each handle turns by `θ/2`, so the -/// correction is split evenly between them. That is G1 continuity: one tangent direction -/// at the node, with the two handle lengths still free. +/// At the node `N` between segment `i` and segment `j = i + 1`, the incoming direction is +/// `d_in` (from cubic `i`'s second control point, or line `i`'s own direction) and the +/// outgoing one `d_out`; `θ` is the angle between them. When `θ ≤ KINK_DEG` the join takes +/// one direction `b`: between two cubics their unit bisector, each handle turning by `θ/2` +/// (`c2 ← N − |d_in|·b`, `c1 ← N + |d_out|·b`), and next to a line the line's own direction, +/// the cubic's handle turning by `θ`. Handles keep their lengths and the node does not move: +/// G1 continuity, one tangent direction at the node with the two handle lengths still free. +/// Up to [`G1_SNAP_DEG`] this only makes exact what was already smooth to the eye; beyond it, +/// the guard decides whether the pixels allow it. /// -/// Only cubic–cubic joins are considered; a join next to a line or an arc, or with a -/// zero-length handle, is skipped. On an open ring the join -/// from the last segment back to the first does not exist and is skipped too. Each join is -/// accepted or reverted on its own ([`keep_if_guarded`]). +/// Two lines, an arc, or a zero-length handle: skipped. On an open ring the join from the last +/// segment back to the first does not exist and is skipped too. Each join is accepted or +/// reverted on its own ([`keep_if_guarded`]). fn pass_g1( fp: &mut FittedPath, starts: &[Point], @@ -230,38 +310,42 @@ fn pass_g1( let mut count = 0; for i in 0..n { let j = (i + 1) % n; - if !fp.closed && j == 0 { + if (!fp.closed && j == 0) || i == j { continue; } - let (Some((c2, _, _)), Some((c1, _, _))) = (cubic(&fp.segments[i]), cubic(&fp.segments[j])) - else { - continue; - }; - let node = starts[i + 1]; - let (dinx, diny) = (node.x - c2.x, node.y - c2.y); - let (doux, douy) = (c1.x - starts[j].x, c1.y - starts[j].y); - let (ln1, ln2) = (dinx.hypot(diny), doux.hypot(douy)); - if ln1 < 1e-9 || ln2 < 1e-9 { + let (si, sj) = (&fp.segments[i], &fp.segments[j]); + let (line_i, line_j) = ( + matches!(si, Segment::Line(_)), + matches!(sj, Segment::Line(_)), + ); + if line_i && line_j { continue; } - let cos = (dinx * doux + diny * douy) / (ln1 * ln2); + let (Some(din), Some(dout)) = ( + end_direction(si, starts[i], true), + end_direction(sj, starts[j], false), + ) else { + continue; + }; + let cos = din.0 * dout.0 + din.1 * dout.1; let ang = cos.clamp(-1.0, 1.0).acos().to_degrees(); - if ang.abs() > G1_SNAP_DEG { + if ang <= 1e-9 || ang > KINK_DEG { continue; } + let (bx, by) = if line_i { + din + } else if line_j { + dout + } else { + let (x, y) = (din.0 + dout.0, din.1 + dout.1); + let l = x.hypot(y); + if l < 1e-9 { + continue; + } + (x / l, y / l) + }; let before = fp.segments.clone(); - let (mut bx, mut by) = (dinx / ln1 + doux / ln2, diny / ln1 + douy / ln2); - let bn = bx.hypot(by); - if bn < 1e-9 { - continue; - } - bx /= bn; - by /= bn; - if bx * doux + by * douy < 0.0 { - bx = -bx; - by = -by; - } - if let Segment::Cubic(c2m, _, endm) = &mut fp.segments[i] { + if let Segment::Cubic(_, c2m, endm) = &mut fp.segments[i] { let l = (endm.x - c2m.x).hypot(endm.y - c2m.y); *c2m = Point::new(endm.x - bx * l, endm.y - by * l); } @@ -276,18 +360,38 @@ fn pass_g1( st.g1_joins += count; } -/// Axis and diagonal handle snaps, greedy per handle: each snap is applied alone -/// and kept only if the whole ring still guards, so one bad handle never vetoes -/// another and none ever escapes the budget. +/// The snapped direction (degrees) for a direction `deg`, and whether it is an axis: the +/// nearest multiple of 90° within [`AXIS_SNAP`], else the 45° diagonal within [`DIAG_SNAP`]. +fn snap_target(deg: f64) -> Option<(f64, bool)> { + let rem = deg.rem_euclid(90.0); + if rem.min(90.0 - rem) <= AXIS_SNAP { + Some((deg - rem + if rem > 45.0 { 90.0 } else { 0.0 }, true)) + } else if (rem - 45.0).abs() <= DIAG_SNAP { + Some((deg - rem + 45.0, false)) + } else { + None + } +} + +/// Axis and diagonal handle snaps, greedy per node: each snap is applied alone and kept +/// only if the whole ring still guards, so one bad handle never vetoes another and none ever +/// escapes the budget. /// /// A handle is the vector `h` from a cubic's node to its control point (start → `c1`, end /// → `c2`). Its direction `φ = atan2(h_y, h_x)` in degrees is reduced to `r = φ mod 90` in /// `[0, 90)`. If `min(r, 90 − r) ≤ AXIS_SNAP` (2.5°) it snaps to the nearest multiple of /// 90°; otherwise, if `|r − 45| ≤ DIAG_SNAP` (1.5°), to the 45° diagonal in the same -/// quadrant. The snapped handle keeps its length `|h|`, so only its angle moves and the -/// node stays put. The targets and the narrow windows come from the artist corpus: a sharp -/// spike of handles at the axes, a smaller bump at 45°, and nothing to aim for between -/// 10° and 30° (see the module docs). +/// quadrant ([`snap_target`]). The snapped handle keeps its length `|h|`, so only its angle +/// moves and the node stays put. The targets and the narrow windows come from the artist +/// corpus: a sharp spike of handles at the axes, a smaller bump at 45°, and nothing to aim +/// for between 10° and 30° (see the module docs). +/// +/// A smooth node is snapped as one: its two handles share a direction, so they turn +/// together or not at all. Snapping each on its own turned one handle of a pair whose +/// direction sat on either side of the window's edge and left a kink where there was none +/// (the battery's `kinked` rose 3.9 % under `--editability`). A handle that leaves a line +/// smoothly is not snapped: the line's direction is fixed, so turning the handle would kink +/// the join. A handle at a corner, or at an open ring's end, snaps on its own as before. /// /// Lines and arcs have no handles and are skipped, as is a zero-length handle or one that /// is already exactly on its target. @@ -299,60 +403,187 @@ fn pass_handles( st: &mut EditStats, ) { let n = fp.segments.len(); - for i in 0..n { - let end = starts[i + 1]; - let Some((c1, c2, _)) = cubic(&fp.segments[i]) else { - continue; + // Node k sits between segment k − 1 (its end) and segment k (its start); on an open + // ring node 0 and node n are ends with one segment each. + let nodes = if fp.closed { n } else { n + 1 }; + for k in 0..nodes { + let prev = if k > 0 { + Some(k - 1) + } else if fp.closed && n > 0 { + Some(n - 1) + } else { + None }; - let mut handles = [c1, c2]; - for (hi, base) in [(0usize, starts[i]), (1usize, end)] { - let hx = handles[hi].x - base.x; - let hy = handles[hi].y - base.y; - let l = hx.hypot(hy); - if l < 1e-9 { - continue; + let next = (k < n).then_some(k); + let node = starts[k.min(n)]; + // The handles at this node: (segment, which end), with their direction. + let mut hs: Vec<(usize, bool)> = Vec::new(); + if let Some(p) = prev { + if cubic(&fp.segments[p]).is_some() { + hs.push((p, true)); } - let deg = hy.atan2(hx).to_degrees(); - let rem = deg.rem_euclid(90.0); - let dev_axis = rem.min(90.0 - rem); - let dev_diag = (rem - 45.0).abs(); - let target = if dev_axis <= AXIS_SNAP { - Some(deg - rem + if rem > 45.0 { 90.0 } else { 0.0 }) - } else if dev_diag <= DIAG_SNAP { - Some(deg - rem + 45.0) - } else { - None - }; - let Some(t) = target else { continue }; - if (t - deg).abs() <= 1e-9 { - continue; + } + if let Some(q) = next { + if cubic(&fp.segments[q]).is_some() { + hs.push((q, false)); } - let axis = dev_axis <= AXIS_SNAP; - let before = fp.segments.clone(); - let r = t.to_radians(); - handles[hi] = Point::new(base.x + l * r.cos(), base.y + l * r.sin()); - if let Segment::Cubic(a, b, _) = &mut fp.segments[i] { - *a = handles[0]; - *b = handles[1]; + } + if hs.is_empty() { + continue; + } + let din = prev.and_then(|p| end_direction(&fp.segments[p], starts[p], true)); + let dout = next.and_then(|q| end_direction(&fp.segments[q], starts[q], false)); + let smooth = match (din, dout) { + (Some(a), Some(b)) => { + (a.0 * b.0 + a.1 * b.1).clamp(-1.0, 1.0).acos().to_degrees() <= G1_SNAP_DEG } - let starts = chain_starts(fp); - if guarded(&fp.segments, &starts, pts, sigma) { - if axis { - st.axis_snaps += 1; - } else { - st.diag_snaps += 1; - } + _ => false, + }; + let groups: Vec> = if smooth { + if hs.len() < 2 { + // One handle against a line, smoothly: the line decides the direction. + continue; + } + vec![hs] + } else { + hs.into_iter().map(|h| vec![h]).collect() + }; + for group in groups { + snap_group(fp, &group, node, pts, sigma, st); + } + } +} + +/// Snap the handles of `group` (each `(segment, at its end?)`, all at `node`) onto one target +/// together, taken from the first handle's direction, kept only if the ring still guards. +fn snap_group( + fp: &mut FittedPath, + group: &[(usize, bool)], + node: Point, + pts: &[Point], + sigma: &[f64], + st: &mut EditStats, +) { + let handle = |fp: &FittedPath, (q, at_end): (usize, bool)| -> Option { + cubic(&fp.segments[q]).map(|(c1, c2, _)| if at_end { c2 } else { c1 }) + }; + // The direction of travel through the node, read from the first handle. + let Some(h0) = handle(fp, group[0]) else { + return; + }; + let (hx, hy) = (h0.x - node.x, h0.y - node.y); + if hx.hypot(hy) < 1e-9 { + return; + } + let travel = if group[0].1 { (-hx, -hy) } else { (hx, hy) }; + let deg = travel.1.atan2(travel.0).to_degrees(); + let Some((target, axis)) = snap_target(deg) else { + return; + }; + if (target - deg).abs() <= 1e-9 { + return; + } + let before = fp.segments.clone(); + let r = target.to_radians(); + let (tx, ty) = (r.cos(), r.sin()); + for &(q, at_end) in group { + let Some(h) = handle(fp, (q, at_end)) else { + continue; + }; + let l = node.dist(h); + if l < 1e-9 { + continue; + } + // Into the segment: against the travel at its end, with it at its start. + let s = if at_end { -1.0 } else { 1.0 }; + let p = Point::new(node.x + s * tx * l, node.y + s * ty * l); + if let Segment::Cubic(a, b, _) = &mut fp.segments[q] { + if at_end { + *b = p; } else { - handles[hi] = Point::new(base.x + hx, base.y + hy); - if let Segment::Cubic(a, b, _) = &mut fp.segments[i] { - *a = handles[0]; - *b = handles[1]; - } - fp.segments = before; - st.reverted += 1; + *a = p; } } } + let starts = chain_starts(fp); + if guarded(&fp.segments, &starts, pts, sigma) { + let k = group.len(); + if axis { + st.axis_snaps += k; + } else { + st.diag_snaps += k; + } + } else { + fp.segments = before; + st.reverted += 1; + } +} + +/// Two lines meeting at a turn of at most [`COLLINEAR_DEG`] are one straight run: written +/// as one line from the first's start to the second's end. Node alignment ([`pass_nodes`]) +/// lines nodes up on shared coordinates, and mirror lock ([`pass_mirror`]) splits a line +/// where the axis crosses it; both leave a node in the middle of a straight run, which +/// artists do not draw (the battery's `collinear` rose 15 % under `--editability`). On a +/// closed ring the join where it starts counts too: the ring then starts at the next node. +/// +/// Only the merged line is judged, against the two it replaces: it is kept when it strays +/// from the evidence ([`stray`]) no further than [`EDIT_SLACK`] or than they did. Judged +/// on the whole ring, a mirror-locked ring, held to the wider [`MIRROR_SLACK`], could never +/// lose the node its lock put on the axis. +fn pass_collinear(fp: &mut FittedPath, pts: &[Point], sigma: &[f64], st: &mut EditStats) { + let mut i = 0; + while fp.segments.len() >= 2 && i < fp.segments.len() { + let n = fp.segments.len(); + let j = (i + 1) % n; + if !fp.closed && j == 0 { + break; + } + let starts = chain_starts(fp); + let (Segment::Line(a), Segment::Line(b)) = (&fp.segments[i], &fp.segments[j]) else { + i += 1; + continue; + }; + let (a, b) = (*a, *b); + let (d1, d2) = ( + (a.x - starts[i].x, a.y - starts[i].y), + (b.x - a.x, b.y - a.y), + ); + let (l1, l2) = (d1.0.hypot(d1.1), d2.0.hypot(d2.1)); + let collinear = l1 > 1e-9 + && l2 > 1e-9 + && ((d1.0 * d2.0 + d1.1 * d2.1) / (l1 * l2)) + .clamp(-1.0, 1.0) + .acos() + .to_degrees() + <= COLLINEAR_DEG; + if !collinear { + i += 1; + continue; + } + let old = stray( + &[Segment::Line(a), Segment::Line(b)], + &[starts[i], a], + pts, + sigma, + ); + let new = stray(&[Segment::Line(b)], &[starts[i]], pts, sigma); + if new > old.max(EDIT_SLACK) { + st.reverted += 1; + i += 1; + continue; + } + if j == 0 { + // The ring's own start is the middle node: start at the next one instead. + fp.start = fp.segments[0].end(); + fp.segments.remove(0); + let last = fp.segments.len() - 1; + fp.segments[last] = Segment::Line(fp.start); + } else { + fp.segments[i] = Segment::Line(b); + fp.segments.remove(j); + } + st.collinear_merged += 1; + } } /// Equal handle lengths within [`LEN_MATCH`]. (This used to be called "the smooth-point @@ -749,6 +980,41 @@ locked ring strays {stray:.3} px (budget {MIRROR_SLACK})", } } +/// Move node `node` of `fp` (0 its start, `k` the end of segment `k − 1`) to `p`, with its +/// handles: the control points either side of it move by the same amount. On a closed ring +/// node 0 is also the last segment's end. +fn move_node(fp: &mut FittedPath, node: usize, p: Point) { + let n = fp.segments.len(); + let old = match node { + 0 => fp.start, + k if k <= n => fp.segments[k - 1].end(), + _ => return, + }; + let d = (p.x - old.x, p.y - old.y); + // The segment arriving at the node and the one leaving it. + let arriving = if node > 0 { + Some(node - 1) + } else if fp.closed && n > 0 { + Some(n - 1) + } else { + None + }; + if node == 0 { + fp.start = p; + } + if let Some(k) = arriving { + set_end(&mut fp.segments[k], p); + if let Segment::Cubic(_, c2, _) = &mut fp.segments[k] { + *c2 = Point::new(c2.x + d.0, c2.y + d.1); + } + } + if node < n { + if let Segment::Cubic(c1, _, _) = &mut fp.segments[node] { + *c1 = Point::new(c1.x + d.0, c1.y + d.1); + } + } +} + /// Move a segment's on-curve endpoint, whatever kind of segment it is. Control points /// and arc parameters stay as they were: an arc, which SVG defines by its endpoints, is /// redrawn with the same radii and flags between the new endpoints (SVG scales the radii @@ -774,9 +1040,11 @@ fn set_end(seg: &mut Segment, p: Point) { /// the rings listed in `free` (the non-primitive ones) are sorted by that coordinate; a /// cluster is a run of consecutive values each within [`NODE_ALIGN`] (0.3 px) of the run's /// first value, and every member moves to the value of the run's middle element (its -/// median). A node can therefore join one cluster in x and another in y. Handles are not -/// touched, so a moved node's handles shift relative to it by at most `NODE_ALIGN` in each -/// axis. +/// median). A node can therefore join one cluster in x and another in y. A moved node +/// carries its handles, as it does in an editor: the control points either side of it move +/// by the same amount, so its handles keep their directions and a smooth node stays smooth. +/// (Left behind, a handle a pixel long turned by up to 15 degrees for a 0.3 px move, and +/// the smooth node became a kink.) /// /// The moves are then applied ring by ring, and each ring is held to the acceptance test /// against its own polyline (`polys[i]` belongs to `fps[i]`). Unlike the other passes the @@ -870,17 +1138,8 @@ fn pass_nodes( for (fi, edits) in by_ring { let fp = &mut fps[fi]; let before = fp.clone(); - let n = fp.segments.len(); - for (node, x, y) in &edits { - let p = Point::new(*x, *y); - if *node == 0 { - fp.start = p; - if fp.closed && n > 0 { - set_end(&mut fp.segments[n - 1], p); - } - } else if *node <= n { - set_end(&mut fp.segments[*node - 1], p); - } + for &(node, x, y) in &edits { + move_node(fp, node, Point::new(x, y)); } let poly = &polys[fi]; let starts = chain_starts(fp); @@ -893,28 +1152,48 @@ fn pass_nodes( } } -/// Apply every pass to every ring: first the passes that move on-curve nodes, mirror -/// lock (it rewrites halves wholesale) and then node alignment across the whole drawing -/// (it crosses ring borders); then, ring by ring, G1, the handle snaps and equal lengths. -/// The comment in the body gives the measurement behind that order. -/// Rings that are already a primitive element (circle/ellipse/rect) are finished -/// geometry — their nodes are load-bearing for the element and are left alone. +/// Apply every pass to every ring: first the passes that rewrite segments, arcs as cubics +/// and runs re-noded at their extrema; then the passes that move on-curve nodes, mirror +/// lock (it rewrites halves wholesale) and node alignment across the whole drawing (it +/// crosses ring borders); then, ring by ring, collinear lines merged, G1, the handle snaps +/// and equal lengths; last the joins at junctions, across rings. The comments in the body +/// give the reasons for that order. Rings that are already a primitive element (circle/ellipse/rect) are +/// finished geometry — their nodes are load-bearing for the element and are left alone. /// /// `polys`, `fps` and `prims` are parallel, one entry per planar-map edge: the measured /// boundary (points and sigma, px), its fitted path (edited in place) and its primitive, -/// if the fit found one. Each pass is guarded, so the output never strays from the +/// if the fit found one. `order` holds each face's rings over those edges, and `cfg` the +/// fit's price of a parameter. Each pass is guarded, so the output never strays from the /// evidence further than the budgets in the module docs. In a `research` build -/// `INKVEC_EDIT_PASSES` can switch passes off ([`on`]). +/// `INKVEC_EDIT_PASSES` can switch passes off ([`on`]): `arcs`, `extrema`, `mirror`, +/// `nodes`, `collinear`, `g1`, `handles`, `equalize`, `junctions`. pub(crate) fn edit_all( polys: &[inkvec_core::Polyline], fps: &mut [FittedPath], prims: &[Option], + order: &[FaceRings], + cfg: &inkvec_fit::FitConfig, ) -> EditStats { let mut st = EditStats { rings: fps.len(), ..Default::default() }; let free: Vec = (0..fps.len()).filter(|&i| prims[i].is_none()).collect(); + // First the curves themselves: arcs written as the cubics a drawing tool writes, cut at + // their extrema, then each smooth run re-segmented at its extrema where the stronger + // preference of this mode finds it worth it. Both rewrite segments, so they run before + // anything that reads a node or a handle. + for (fp, (poly, prim)) in fps.iter_mut().zip(polys.iter().zip(prims.iter())) { + if prim.is_some() { + continue; + } + if on("arcs") { + curves::pass_arcs(fp, poly, &mut st); + } + if on("extrema") { + curves::pass_extrema(fp, poly, cfg, &mut st); + } + } // The passes that move on-curve NODES run first: mirror lock rewrites a whole // half, and node alignment slides nodes onto shared targets. Only then are the // handles pointed, because a handle's direction is measured from its node, and @@ -932,13 +1211,24 @@ pub(crate) fn edit_all( if on("nodes") { pass_nodes(fps, &free, polys, &mut st); } + // A boundary with no junction on it is one edge that ends where it starts, an open path + // from a point the planar map chose. Its closing join is a join like any other, so the + // per-ring passes below see it closed (and no other edge ends there, so its start may + // move); the flag is put back after them. + let loops = isolated_loops(fps, &free); + for &i in &loops { + fps[i].closed = true; + } for (fp, (poly, prim)) in fps.iter_mut().zip(polys.iter().zip(prims.iter())) { if prim.is_some() { continue; } let sigma = &poly.sigma; // Each reads the chain the pass before it left: mirror lock can change how - // many segments a ring has. + // many segments a ring has, and alignment can leave two lines end to end. + if on("collinear") { + pass_collinear(fp, &poly.points, sigma, &mut st); + } if on("g1") { pass_g1(fp, &chain_starts(fp), &poly.points, sigma, &mut st); } @@ -949,9 +1239,43 @@ pub(crate) fn edit_all( pass_equalize(fp, &chain_starts(fp), &poly.points, sigma, &mut st); } } + for &i in &loops { + fps[i].closed = false; + } + // Joins between edges, which no per-ring pass sees, last: a junction whose one side was + // just snapped onto an axis keeps that side's direction (`junctions`), so the snap + // survives the smoothing. + if on("junctions") { + junctions::pass_junctions(order, fps, polys, prims, &mut st); + } st } +/// The rings among `free` that are open paths ending exactly where they start, at a point no +/// other ring starts or ends at: a boundary with no junction on it. +fn isolated_loops(fps: &[FittedPath], free: &[usize]) -> Vec { + const SAME: f64 = 1e-6; + let ends: Vec<(usize, Point)> = fps + .iter() + .enumerate() + .filter(|(_, fp)| !fp.segments.is_empty()) + .flat_map(|(i, fp)| [(i, fp.start), (i, fp.segments[fp.segments.len() - 1].end())]) + .collect(); + free.iter() + .copied() + .filter(|&i| { + let fp = &fps[i]; + let Some(last) = fp.segments.last() else { + return false; + }; + !fp.closed + && fp.segments.len() >= 2 + && last.end().dist(fp.start) <= SAME + && ends.iter().all(|&(j, p)| j == i || p.dist(fp.start) > SAME) + }) + .collect() +} + /// Whether a pass runs. In a `research` build `INKVEC_EDIT_PASSES` names the ones to keep, /// comma separated, so each can be priced on its own against the corpus; unset (and every /// release build) runs all of them, which is what the flag means. @@ -966,275 +1290,4 @@ fn on(pass: &str) -> bool { } #[cfg(test)] -mod tests { - use super::*; - use inkvec_core::Polyline; - - fn pt(x: f64, y: f64) -> Point { - Point::new(x, y) - } - - /// A ring sampled densely enough that the guard has real evidence to hold the - /// passes to, with the sigma the tracer would give a clean edge. - fn poly_of(fp: &FittedPath, per: usize) -> Polyline { - let starts = chain_starts(fp); - let pts = samples(&fp.segments, &starts, per); - let n = pts.len(); - Polyline::new(pts, vec![0.25; n], true) - } - - /// A diamond: four lines, symmetric about x = 50, with nodes on the axis. - fn diamond() -> FittedPath { - FittedPath { - start: pt(50.0, 10.0), - segments: vec![ - Segment::Line(pt(90.0, 50.0)), - Segment::Line(pt(50.0, 90.0)), - Segment::Line(pt(10.0, 50.0)), - Segment::Line(pt(50.0, 10.0)), - ], - closed: true, - } - } - - #[test] - fn reflecting_a_segment_twice_gives_it_back() { - let seg = Segment::Cubic(pt(12.0, 3.0), pt(31.0, 47.0), pt(40.0, 60.0)); - let start = pt(5.0, 1.0); - let once = mirror_reverse(&seg, start, 25.0); - // the reflected copy runs backwards from the reflection of the original's - // end, which is where its own start is - let twice = mirror_reverse(&once, pt(2.0 * 25.0 - 40.0, 60.0), 25.0); - let (Segment::Cubic(a1, a2, ae), Segment::Cubic(b1, b2, be)) = (&seg, &twice) else { - panic!("expected cubics"); - }; - for (p, q) in [(a1, b1), (a2, b2), (ae, be)] { - assert!(p.dist(*q) < 1e-9, "{p:?} != {q:?}"); - } - } - - #[test] - fn splitting_a_curve_draws_what_it_drew_before() { - let seg = Segment::Cubic(pt(10.0, 0.0), pt(30.0, 80.0), pt(40.0, 40.0)); - let start = pt(0.0, 0.0); - let (a, b) = split_at(&seg, start, 0.375).expect("a cubic splits"); - let mid = a.end(); - for k in 0..=40 { - let t = f64::from(k) / 40.0; - let whole = eval_segment(&seg, start, t); - // the same parameter, expressed on whichever half holds it - let part = if t <= 0.375 { - eval_segment(&a, start, t / 0.375) - } else { - eval_segment(&b, mid, (t - 0.375) / 0.625) - }; - assert!(whole.dist(part) < 1e-9, "t={t}: {whole:?} vs {part:?}"); - } - } - - #[test] - fn the_axis_crossing_is_found_inside_a_segment() { - // a line from x=10 to x=90 crosses x=50 at its midpoint - let seg = Segment::Line(pt(90.0, 7.0)); - let t = interior_crossing(&seg, pt(10.0, 7.0), 50.0).expect("it crosses"); - assert!((t - 0.5).abs() < 1e-6, "t = {t}"); - // and a segment that stays on one side has no crossing - assert!(interior_crossing(&seg, pt(10.0, 7.0), 200.0).is_none()); - } - - #[test] - fn a_symmetric_ring_is_locked_onto_its_axis_exactly() { - let mut fp = diamond(); - // pull one side off true by more than the emitter's step, less than the budget - fp.segments[0] = Segment::Line(pt(90.6, 50.3)); - let poly = poly_of(&fp, 24); - let mut st = EditStats::default(); - let starts = chain_starts(&fp); - pass_mirror(&mut fp, &starts, &poly.points, &poly.sigma, &mut st); - assert_eq!(st.mirror_rings, 1, "the ring should lock: {st:?}"); - - // every node now has a partner at its exact reflection - let nodes = chain_starts(&fp); - let xs: Vec = nodes.iter().map(|p| p.x).collect(); - let cx = (xs.iter().cloned().fold(f64::MAX, f64::min) - + xs.iter().cloned().fold(f64::MIN, f64::max)) - / 2.0; - for p in &nodes { - let m = Point::new(2.0 * cx - p.x, p.y); - let best = nodes - .iter() - .map(|q| m.dist(*q)) - .fold(f64::INFINITY, f64::min); - assert!(best < 1e-9, "{p:?} has no exact mirror (nearest {best})"); - } - } - - #[test] - fn an_asymmetric_ring_is_left_alone() { - let mut fp = diamond(); - fp.segments[0] = Segment::Line(pt(140.0, 50.0)); // a long spur on one side only - let poly = poly_of(&fp, 24); - let before = fp.clone(); - let mut st = EditStats::default(); - let starts = chain_starts(&fp); - pass_mirror(&mut fp, &starts, &poly.points, &poly.sigma, &mut st); - assert_eq!(st.mirror_rings, 0, "nothing should have locked"); - assert_eq!(fp.segments.len(), before.segments.len()); - } - - /// The nodes of a ring are its segment *ends*; `Cubic`'s first field is a - /// control point. Writing node positions into it moved handles onto nodes and - /// collapsed every `Line` to zero length -- which is how a heart lost its point. - #[test] - fn aligning_nodes_moves_nodes_and_not_handles() { - let fp = FittedPath { - start: pt(0.0, 0.0), - segments: vec![ - Segment::Cubic(pt(10.0, 30.0), pt(30.0, 30.0), pt(40.0, 0.2)), - Segment::Line(pt(40.0, 40.0)), - Segment::Cubic(pt(20.0, 50.0), pt(5.0, 50.0), pt(0.0, 0.0)), - ], - closed: true, - }; - let poly = poly_of(&fp, 32); - let handles_before = fp - .segments - .iter() - .filter_map(cubic) - .map(|(c1, c2, _)| (c1, c2)) - .collect::>(); - let mut fps = [fp.clone()]; - pass_nodes( - &mut fps, - &[0], - std::slice::from_ref(&poly), - &mut EditStats::default(), - ); - let out = &fps[0]; - // the y = 0.2 node may align to y = 0; no line may collapse - for (k, seg) in out.segments.iter().enumerate() { - let starts = chain_starts(out); - assert!( - starts[k].dist(seg.end()) > 1e-6, - "segment {k} collapsed to a point" - ); - } - // handles keep their own positions, give or take the node they hang from - for (k, (c1, c2)) in out - .segments - .iter() - .filter_map(cubic) - .map(|(a, b, _)| (a, b)) - .enumerate() - { - let (b1, b2) = handles_before[k]; - assert!( - c1.dist(b1) <= NODE_ALIGN + 1e-9, - "handle 1 of {k} moved {}", - c1.dist(b1) - ); - assert!( - c2.dist(b2) <= NODE_ALIGN + 1e-9, - "handle 2 of {k} moved {}", - c2.dist(b2) - ); - } - } - - #[test] - fn a_handle_within_the_window_snaps_onto_the_axis() { - // a curve whose first handle leaves its node 1.4 deg off horizontal - let off = 1.4_f64.to_radians(); - let mut fp = FittedPath { - start: pt(0.0, 0.0), - segments: vec![ - Segment::Cubic( - pt(20.0 * off.cos(), 20.0 * off.sin()), - pt(60.0, 10.0), - pt(80.0, 0.0), - ), - Segment::Cubic(pt(90.0, -20.0), pt(20.0, -30.0), pt(0.0, 0.0)), - ], - closed: true, - }; - let poly = poly_of(&fp, 48); - let mut st = EditStats::default(); - let starts = chain_starts(&fp); - pass_handles(&mut fp, &starts, &poly.points, &poly.sigma, &mut st); - assert!(st.axis_snaps >= 1, "the handle should have snapped: {st:?}"); - let (c1, _, _) = cubic(&fp.segments[0]).expect("a cubic"); - assert!(c1.y.abs() < 1e-9, "handle is still {} off the axis", c1.y); - } - - #[test] - fn a_pass_that_would_stray_too_far_is_refused() { - // sigma of zero and no room: any move at all breaks the guard - let fp = diamond(); - let starts = chain_starts(&fp); - let pts = samples(&fp.segments, &starts, 16); - let sigma = vec![0.0; pts.len()]; - let mut moved = fp.segments.clone(); - moved[0] = Segment::Line(pt(200.0, 50.0)); - assert!(!guarded(&moved, &starts, &pts, &sigma)); - assert!(guarded(&fp.segments, &starts, &pts, &sigma)); - } - - #[test] - fn test_edit_all_on_diamond() { - let fp = diamond(); - let poly = poly_of(&fp, 48); - let mut fps = vec![fp]; - let polys = vec![poly]; - let prims = vec![None]; - let st = edit_all(&polys, &mut fps, &prims); - assert!(st.rings > 0); - let summary = st.summary(); - assert!(summary.contains("editability")); - } - - #[test] - fn test_pass_g1() { - let p0 = pt(10.0, 50.0); - let p_mid = pt(50.0, 50.0); - let p_end = pt(90.0, 50.0); - let seg1 = Segment::Cubic(pt(30.0, 50.0), pt(40.0, 50.0), p_mid); - let seg2 = Segment::Cubic(pt(60.0, 50.3), pt(70.0, 50.0), p_end); - let mut fp = FittedPath { - start: p0, - segments: vec![seg1, seg2], - closed: false, - }; - let poly = poly_of(&fp, 48); - let mut st = EditStats::default(); - let starts = chain_starts(&fp); - pass_g1(&mut fp, &starts, &poly.points, &poly.sigma, &mut st); - assert_eq!(st.g1_joins, 1); - } - - #[test] - fn test_pass_equalize() { - let p0 = pt(0.0, 0.0); - let p_end = pt(100.0, 0.0); - let seg = Segment::Cubic(pt(10.0, 0.0), pt(90.5, 0.0), p_end); - let mut fp = FittedPath { - start: p0, - segments: vec![seg], - closed: false, - }; - let poly = poly_of(&fp, 48); - let mut st = EditStats::default(); - let starts = chain_starts(&fp); - pass_equalize(&mut fp, &starts, &poly.points, &poly.sigma, &mut st); - assert_eq!(st.len_sym, 1); - } - - #[test] - fn test_pass_mirror_on_diamond() { - let mut fp = diamond(); - let poly = poly_of(&fp, 48); - let mut st = EditStats::default(); - let starts = chain_starts(&fp); - pass_mirror(&mut fp, &starts, &poly.points, &poly.sigma, &mut st); - assert!(st.mirror_rings >= 1); - } -} +mod tests; diff --git a/crates/inkvec-cli/src/editable/curves.rs b/crates/inkvec-cli/src/editable/curves.rs new file mode 100644 index 00000000..0fb474d0 --- /dev/null +++ b/crates/inkvec-cli/src/editable/curves.rs @@ -0,0 +1,266 @@ +//! Editability passes that rewrite a ring's curves with their nodes at the x and y extrema: +//! circular arcs written as the cubics a drawing tool would write, and smooth runs +//! re-segmented at their extrema with a stronger preference than the default fit's. +//! +//! A drawing tool writes a circle as four cubics with their nodes at the top, bottom, left +//! and right and every handle horizontal or vertical, each `κ = 4/3·tan(θ/4)` of the radius +//! long (0.5523 for a quarter), and an arc as the same pieces cut at its ends. Type design +//! asks the same of every curve: points at the extrema, handles on the axes (Adobe, *Type 1 +//! Font Format*, 1990, and the Apple and Microsoft font tools since: an outline without +//! points at its extrema fails their checks). The fit writes arcs as `A`, which an editor +//! shows as two nodes with no handles at all, wherever on the circle they fall. + +use inkvec_core::{Point, Polyline}; +use inkvec_fit::curves::{arc_ellipse_center, Segment}; +use inkvec_fit::extrema::Preference; +use inkvec_fit::{FitConfig, FittedPath}; + +use super::{chain_starts, guarded, EditStats}; + +/// How `--editability` prefers nodes at extrema: three parameters credited per anchored +/// node against the fit's one (`inkvec_fit::extrema::FIT`), and the written count free to +/// change, so a run gains a node where a segment spans an extremum. The mode spends +/// parameters on structure; the fidelity budget is the same as every other editability +/// pass's. +pub(super) const EDIT_PREFERENCE: Preference = Preference { + credit: 3.0, + same_count: false, +}; + +/// Write every circular arc of the ring as cubics cut at its x and y extrema +/// ([`arc_as_cubics`]). The pieces are within `1.1e-3` of the radius of the arc, so the +/// guard holds wherever the radius is under a few thousand pixels; it is checked anyway. +pub(super) fn pass_arcs(fp: &mut FittedPath, poly: &Polyline, st: &mut EditStats) { + if !fp + .segments + .iter() + .any(|s| matches!(s, Segment::Arc { .. }) && s.is_circular()) + { + return; + } + let before = fp.segments.clone(); + let mut out = Vec::with_capacity(before.len() + 4); + let mut cur = fp.start; + let mut arcs = 0; + for s in &before { + match arc_as_cubics(s, cur) { + Some(pieces) => { + out.extend(pieces); + arcs += 1; + } + None => out.push(s.clone()), + } + cur = s.end(); + } + fp.segments = out; + if guarded(&fp.segments, &chain_starts(fp), &poly.points, &poly.sigma) { + st.arcs_split += arcs; + } else { + fp.segments = before; + st.reverted += 1; + } +} + +/// A cut closer than this to an arc's end, along the arc (px), is not made: the arc's end +/// is then all but at the extremum, and the cut would leave a sliver whose handles are too +/// short for two decimals to point them (a 0.4 px piece on `material-icons/dining`). The +/// same gap as the fit's for an extremum near a run's end (`inkvec_fit::extrema`). +const ARC_CUT_GAP_PX: f64 = 1.0; + +/// A circular arc as cubics: cut at every angle that is a multiple of 90 degrees inside it +/// and at least [`ARC_CUT_GAP_PX`] from its ends, so each piece turns by at most a quarter +/// (a little more beside a cut left out) and every cut is an x or y extremum with its +/// handles exactly on an axis. Each piece is the standard approximation, handles along the +/// circle's tangents and `4/3·tan(Δ/4)·r` long, whose largest radial error is `2.7e-4·r` +/// for a quarter (Riškus 2006; Goldapp 1991). The first piece starts on the arc's stored +/// start and the last ends on its stored end, so the ring stays watertight. `None` for +/// anything that is not a circular arc, or a degenerate one. +pub(super) fn arc_as_cubics(seg: &Segment, start: Point) -> Option> { + let Segment::Arc { + rx, + ry, + phi, + large_arc, + sweep, + end, + } = *seg + else { + return None; + }; + if !seg.is_circular() { + return None; + } + let f = arc_ellipse_center(start, rx, ry, phi, large_arc, sweep, end); + if f.delta.abs() < 1e-9 || f.rx <= 1e-9 { + return None; + } + let quarter = std::f64::consts::FRAC_PI_2; + let (a0, a1) = (f.theta1, f.theta1 + f.delta); + // Cut angles inside, clear of the ends, in the direction of travel, as whole quarter + // turns `k`. The gap is at most an eighth of a half turn, so no piece turns by more + // than 112.5 degrees (radial error under 1.1e-3 of the radius). + let gap = (ARC_CUT_GAP_PX / f.rx).clamp(1e-9, std::f64::consts::FRAC_PI_8); + let mut cuts: Vec = Vec::new(); + let (lo, hi) = (a0.min(a1), a0.max(a1)); + let mut k = (lo / quarter).floor() as i64 + 1; + while (k as f64) * quarter < hi - gap { + if (k as f64) * quarter > lo + gap { + cuts.push(k); + } + k += 1; + } + if f.delta < 0.0 { + cuts.reverse(); + } + let sgn = f.delta.signum(); + let r = f.rx; + // A point of the circle and the unit direction of travel there; exact at a cut. + let at = |th: f64, k: Option| -> (Point, (f64, f64)) { + let (s, c) = match k { + Some(k) => match k.rem_euclid(4) { + 0 => (0.0, 1.0), + 1 => (1.0, 0.0), + 2 => (0.0, -1.0), + _ => (-1.0, 0.0), + }, + None => th.sin_cos(), + }; + ( + Point::new(f.c.x + r * c, f.c.y + r * s), + (-sgn * s, sgn * c), + ) + }; + let mut angles: Vec<(f64, Option)> = vec![(a0, None)]; + angles.extend(cuts.iter().map(|&k| (k as f64 * quarter, Some(k)))); + angles.push((a1, None)); + let mut out = Vec::with_capacity(angles.len() - 1); + for (i, w) in angles.windows(2).enumerate() { + let (pa, ta) = at(w[0].0, w[0].1); + let (pb, tb) = at(w[1].0, w[1].1); + let p0 = if i == 0 { start } else { pa }; + let p3 = if i + 2 == angles.len() { end } else { pb }; + let h = 4.0 / 3.0 * ((w[1].0 - w[0].0).abs() / 4.0).tan() * r; + out.push(Segment::Cubic( + Point::new(p0.x + h * ta.0, p0.y + h * ta.1), + Point::new(p3.x - h * tb.0, p3.y - h * tb.1), + p3, + )); + } + Some(out) +} + +/// Re-segment the ring's smooth runs at their extrema with [`EDIT_PREFERENCE`] +/// (`inkvec_fit::extrema::anchor_extrema`), kept only if the whole ring still guards. +pub(super) fn pass_extrema( + fp: &mut FittedPath, + poly: &Polyline, + cfg: &FitConfig, + st: &mut EditStats, +) { + let before = fp.clone(); + let runs = inkvec_fit::extrema::anchor_extrema(fp, poly, cfg, EDIT_PREFERENCE); + if runs == 0 { + return; + } + if guarded(&fp.segments, &chain_starts(fp), &poly.points, &poly.sigma) { + st.extrema_runs += runs; + } else { + *fp = before; + st.reverted += 1; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use inkvec_fit::structural::eval_segment; + + fn start_of(k: usize, start: Point, segs: &[Segment]) -> Point { + if k == 0 { + start + } else { + segs[k - 1].end() + } + } + + #[test] + fn an_arc_is_cut_at_its_extrema_with_axis_handles() { + // Three eighths of a circle of radius 20 round (5, 5), from -45 to 90 degrees. + let (c, r) = (Point::new(5.0, 5.0), 20.0); + let at = |deg: f64| { + let t = deg.to_radians(); + Point::new(c.x + r * t.cos(), c.y + r * t.sin()) + }; + let start = at(-45.0); + let arc = Segment::circular_arc(r, false, true, at(90.0)); + let pieces = arc_as_cubics(&arc, start).expect("a circular arc"); + // Cut at 0 degrees only: 90 is the arc's end. + assert_eq!(pieces.len(), 2, "{pieces:?}"); + let mid = pieces[0].end(); + assert!( + mid.dist(Point::new(c.x + r, c.y)) < 1e-9, + "the cut is the x extremum: {mid:?}" + ); + let (Segment::Cubic(_, c2, _), Segment::Cubic(c1, _, e)) = (&pieces[0], &pieces[1]) else { + panic!("cubics"); + }; + assert_eq!(c2.x, mid.x, "the handle into the cut is vertical"); + assert_eq!(c1.x, mid.x, "and so is the one out of it"); + assert_eq!(*e, at(90.0), "the arc's own end, as stored"); + // Within the standard approximation's error of the circle everywhere. + for (k, p) in pieces.iter().enumerate() { + let s = start_of(k, start, &pieces); + for i in 0..=32 { + let q = eval_segment(p, s, i as f64 / 32.0); + assert!((q.dist(c) - r).abs() < 3e-4 * r, "piece {k} strays at {i}"); + } + } + assert!(arc_as_cubics(&Segment::Line(at(0.0)), start).is_none()); + } + + #[test] + fn no_cut_leaves_a_sliver_at_the_arcs_end() { + // A quarter of radius 10 that ends 0.4 px (along the arc) past the y extremum: the + // cut there would leave a 0.4 px piece, so the arc is one piece. + let (c, r) = (Point::new(0.0, 0.0), 10.0); + let at = |rad: f64| Point::new(c.x + r * rad.cos(), c.y + r * rad.sin()); + let half_pi = std::f64::consts::FRAC_PI_2; + let start = at(0.04 - half_pi); + let arc = Segment::circular_arc(r, false, true, at(0.04)); + let pieces = arc_as_cubics(&arc, start).expect("a circular arc"); + assert_eq!(pieces.len(), 1, "{pieces:?}"); + for i in 0..=32 { + let q = eval_segment(&pieces[0], start, i as f64 / 32.0); + assert!((q.dist(c) - r).abs() < 1.1e-3 * r, "strays at {i}"); + } + // With room on both sides the cut is made. + let arc = Segment::circular_arc(r, false, true, at(0.2)); + assert_eq!(arc_as_cubics(&arc, start).expect("an arc").len(), 2); + } + + #[test] + fn a_ring_of_arcs_becomes_cubics_and_still_guards() { + // A circle as two half arcs, sampled for the guard. + let r = 30.0; + let mut fp = FittedPath { + start: Point::new(r, 0.0), + segments: vec![ + Segment::circular_arc(r, false, true, Point::new(-r, 0.0)), + Segment::circular_arc(r, false, true, Point::new(r, 0.0)), + ], + closed: true, + }; + let pts: Vec = (0..240) + .map(|k| { + let t = std::f64::consts::TAU * k as f64 / 240.0; + Point::new(r * t.cos(), r * t.sin()) + }) + .collect(); + let poly = Polyline::with_uniform_sigma(pts, 0.05, true); + let mut st = EditStats::default(); + pass_arcs(&mut fp, &poly, &mut st); + assert_eq!(st.arcs_split, 2); + assert_eq!(fp.segments.len(), 4, "a quarter each side of every cut"); + assert!(fp.segments.iter().all(|s| matches!(s, Segment::Cubic(..)))); + } +} diff --git a/crates/inkvec-cli/src/editable/junctions.rs b/crates/inkvec-cli/src/editable/junctions.rs new file mode 100644 index 00000000..1f407939 --- /dev/null +++ b/crates/inkvec-cli/src/editable/junctions.rs @@ -0,0 +1,343 @@ +//! Smooth joins across the planar map's junctions, read on the faces' rings. +//! +//! Every other editability pass works on one fitted edge at a time, between two junctions, +//! so it never sees the join where a face's outline passes from one edge to the next. That +//! join is where a drawing made of layers shows most: a shape painted over another leaves +//! the lower one's visible outline with a T-junction on each side, and the upper one's +//! outline runs straight through both. The two edges of the upper outline were fitted +//! apart, each with its own end direction, so the outline comes out kinked at the junction +//! where the artist's runs on smoothly. +//! +//! The pass walks each face's rings ([`crate::faces::Ring`]) and, at each join between two +//! different edges that turns by at most [`JUNCTION_G1_DEG`], turns the handles either side +//! onto one direction: the line's when one side is a line, a handle's when it alone is +//! exactly on an axis (the handle snaps run first), else the bisector of the two. Handles keep their lengths and no node moves, so the junction stays shared and +//! no seam opens. A change is kept only if both edges still pass the editability guard +//! (`3·σ + EDIT_SLACK`, one-sided, see the parent module); otherwise both are restored. + +use inkvec_core::{Point, Polyline, Vec2}; +use inkvec_fit::curves::Segment; +use inkvec_fit::primitives::PrimitiveFit; +use inkvec_fit::FittedPath; + +use super::{chain_starts, guarded, EditStats}; +use crate::faces::FaceRings; + +/// Largest turn (degrees) at a junction that the pass makes smooth. The artists' joins +/// between curves are smooth or corners, with 8.6 % between 3 and 30 degrees against the +/// trace's 25 % (`bench/theory/node_stats.py`, 512 px on white); this reaches the kinked +/// band, and the guard decides which of them the pixels allow. +const JUNCTION_G1_DEG: f64 = 30.0; + +/// Which end of an edge a junction is at. +#[derive(Clone, Copy, PartialEq, Eq)] +enum End { + Start, + Finish, +} + +/// One edge's side of a join: the edge, which end, and whether the ring arrives along it +/// (`incoming`) or leaves along it. +#[derive(Clone, Copy)] +struct Side { + edge: usize, + end: End, + incoming: bool, +} + +impl Side { + /// The junction point. + fn node(&self, fps: &[FittedPath]) -> Point { + match self.end { + End::Start => fps[self.edge].start, + End::Finish => fps[self.edge].end(), + } + } + + /// The segment at this end, its index, and the point it starts at. + fn segment<'a>(&self, fp: &'a FittedPath) -> Option<(usize, &'a Segment, Point)> { + let n = fp.segments.len(); + if n == 0 { + return None; + } + let q = match self.end { + End::Start => 0, + End::Finish => n - 1, + }; + let start = if q == 0 { + fp.start + } else { + fp.segments[q - 1].end() + }; + Some((q, &fp.segments[q], start)) + } + + /// The direction the ring travels in at the junction, on this side: arriving along an + /// incoming side, leaving along an outgoing one. + fn direction(&self, fps: &[FittedPath]) -> Option { + let fp = &fps[self.edge]; + let (_, seg, start) = self.segment(fp)?; + let node = self.node(fps); + // The point next to the junction on this side: the handle, or a line's other end. + let near = match (seg, self.end) { + (&Segment::Cubic(c1, _, e), End::Start) => first_distinct(node, &[c1, e]), + (&Segment::Cubic(_, c2, _), End::Finish) => first_distinct(node, &[c2, start]), + (&Segment::Line(e), End::Start) => first_distinct(node, &[e]), + (Segment::Line(_), End::Finish) => first_distinct(node, &[start]), + (Segment::Arc { .. }, _) => return None, + }?; + // `near − node` points away from the junction into this edge. + let away = unit(near - node)?; + Some(if self.incoming { + Vec2 { + x: -away.x, + y: -away.y, + } + } else { + away + }) + } + + /// Turn this side's handle at the junction so the ring travels along `dir` there. A + /// line has no handle and is left alone (its direction is the target); `false` for + /// anything else that cannot be turned. + fn turn_to(&self, fps: &mut [FittedPath], dir: Vec2) -> bool { + let node = self.node(fps); + let fp = &mut fps[self.edge]; + let Some((q, seg, _)) = self.segment(fp) else { + return false; + }; + // The handle points into the edge: against the travel when incoming, with it when + // leaving. + let away = if self.incoming { + Vec2 { + x: -dir.x, + y: -dir.y, + } + } else { + dir + }; + match (seg.clone(), self.end) { + (Segment::Line(_), _) => true, + (Segment::Cubic(c1, c2, e), End::Start) => { + let l = node.dist(c1); + fp.segments[q] = + Segment::Cubic(Point::new(node.x + away.x * l, node.y + away.y * l), c2, e); + l > 1e-9 + } + (Segment::Cubic(c1, c2, e), End::Finish) => { + let l = node.dist(c2); + fp.segments[q] = + Segment::Cubic(c1, Point::new(node.x + away.x * l, node.y + away.y * l), e); + l > 1e-9 + } + (Segment::Arc { .. }, _) => false, + } + } + + fn is_line(&self, fps: &[FittedPath]) -> bool { + self.segment(&fps[self.edge]) + .is_some_and(|(_, s, _)| matches!(s, Segment::Line(_))) + } +} + +/// The first of `cands` not at `node`. +fn first_distinct(node: Point, cands: &[Point]) -> Option { + cands.iter().copied().find(|p| p.dist(node) > 1e-9) +} + +fn unit(v: Vec2) -> Option { + let n = v.norm(); + (n > 1e-12 && n.is_finite()).then(|| Vec2 { + x: v.x / n, + y: v.y / n, + }) +} + +/// Make the joins between consecutive edges of every face's rings smooth where they turn by +/// at most [`JUNCTION_G1_DEG`] and both edges still guard. Primitives are not touched. +pub(super) fn pass_junctions( + order: &[FaceRings], + fps: &mut [FittedPath], + polys: &[Polyline], + prims: &[Option], + st: &mut EditStats, +) { + let n = fps.len(); + let free = |e: usize| e < n && prims.get(e).is_none_or(|p| p.is_none()); + for ring in order.iter().flatten() { + let k = ring.len(); + if k < 2 { + continue; + } + for i in 0..k { + let (ea, ra) = ring[i]; + let (eb, rb) = ring[(i + 1) % k]; + if ea == eb || !free(ea) || !free(eb) { + continue; + } + let a = Side { + edge: ea, + end: if ra { End::Start } else { End::Finish }, + incoming: true, + }; + let b = Side { + edge: eb, + end: if rb { End::Finish } else { End::Start }, + incoming: false, + }; + smooth_join(a, b, fps, polys, st); + } + } +} + +/// Make one join smooth if it is nearly so and both edges still guard. +fn smooth_join(a: Side, b: Side, fps: &mut [FittedPath], polys: &[Polyline], st: &mut EditStats) { + let debug = inkvec_core::env::flag("INKVEC_EDIT_DEBUG"); + let gap = a.node(fps).dist(b.node(fps)); + if gap > 1e-6 { + crate::diag::debug(debug, || { + format!(" junction: ends {gap:.3} px apart -- skipped") + }); + return; + } + let (Some(da), Some(db)) = (a.direction(fps), b.direction(fps)) else { + return; + }; + let cos = (da.x * db.x + da.y * db.y).clamp(-1.0, 1.0); + let turn = cos.acos().to_degrees(); + crate::diag::debug(debug, || { + format!( + " junction: turn {turn:.1} deg, lines {} {}", + a.is_line(fps), + b.is_line(fps) + ) + }); + if turn <= 1e-6 || turn > JUNCTION_G1_DEG { + return; + } + // A line's direction is fixed; a handle already exactly on an axis (the handle snaps ran + // before this pass) keeps its snap; otherwise the two meet half way. + let on_axis = |d: Vec2| d.x.abs() < 1e-12 || d.y.abs() < 1e-12; + let target = match (a.is_line(fps), b.is_line(fps)) { + (true, true) => return, + (true, false) => da, + (false, true) => db, + (false, false) if on_axis(da) && !on_axis(db) => da, + (false, false) if on_axis(db) && !on_axis(da) => db, + (false, false) => match unit(Vec2 { + x: da.x + db.x, + y: da.y + db.y, + }) { + Some(t) => t, + None => return, + }, + }; + let saved = (fps[a.edge].clone(), fps[b.edge].clone()); + let ok = a.turn_to(fps, target) + && b.turn_to(fps, target) + && [a.edge, b.edge].iter().all(|&e| { + guarded( + &fps[e].segments, + &chain_starts(&fps[e]), + &polys[e].points, + &polys[e].sigma, + ) + }); + if ok { + st.junction_g1 += 1; + } else { + fps[a.edge] = saved.0; + fps[b.edge] = saved.1; + st.reverted += 1; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A smooth S of two quarter circles meeting at the origin, as two edges whose + /// handles at the shared node turn by `kink_deg` between them. + fn two_edges(kink_deg: f64) -> (Vec, Vec) { + let r = 30.0; + let k = 0.5523 * r; + let off = kink_deg.to_radians(); + // Edge 0: from (-r, -r) down to the origin, arriving horizontally (+x). + let e0 = FittedPath { + start: Point::new(-r, -r), + segments: vec![Segment::Cubic( + Point::new(-r, -r + k), + Point::new(-k * off.cos(), -k * off.sin()), + Point::new(0.0, 0.0), + )], + closed: false, + }; + // Edge 1: from the origin, leaving horizontally (+x), up to (r, r). + let e1 = FittedPath { + start: Point::new(0.0, 0.0), + segments: vec![Segment::Cubic( + Point::new(k, 0.0), + Point::new(r, r - k), + Point::new(r, r), + )], + closed: false, + }; + let arc = |cx: f64, cy: f64, a0: f64| -> Vec { + (0..=60) + .map(|i| { + let t = a0 + std::f64::consts::FRAC_PI_2 * i as f64 / 60.0; + Point::new(cx + r * t.cos(), cy + r * t.sin()) + }) + .collect() + }; + let p0 = arc(0.0, -r, std::f64::consts::PI); + let p0: Vec = p0 + .into_iter() + .map(|p| Point::new(p.x, -r - (p.y + r))) + .collect(); + let p1 = arc(0.0, r, -std::f64::consts::FRAC_PI_2); + let polys = vec![ + Polyline::with_uniform_sigma(p0, 0.05, false), + Polyline::with_uniform_sigma(p1, 0.05, false), + ]; + (vec![e0, e1], polys) + } + + fn turn_at_origin(fps: &[FittedPath]) -> f64 { + let (Segment::Cubic(_, c2, _), Segment::Cubic(c1, _, _)) = + (&fps[0].segments[0], &fps[1].segments[0]) + else { + panic!("cubics"); + }; + let (a, b) = ((-c2.x, -c2.y), (c1.x, c1.y)); + let cos = (a.0 * b.0 + a.1 * b.1) / (a.0.hypot(a.1) * b.0.hypot(b.1)); + cos.clamp(-1.0, 1.0).acos().to_degrees() + } + + #[test] + fn a_kink_where_two_edges_meet_is_made_smooth() { + let (mut fps, polys) = two_edges(4.0); + assert!(turn_at_origin(&fps) > 3.9); + let order = vec![vec![vec![(0usize, false), (1usize, false)]]]; + let mut st = EditStats::default(); + pass_junctions(&order, &mut fps, &polys, &[None, None], &mut st); + assert_eq!( + st.junction_g1, 1, + "one join at the junction; the ring's other join is a corner" + ); + assert!(turn_at_origin(&fps) < 1e-9); + assert_eq!(fps[0].end(), fps[1].start, "the junction did not move"); + } + + #[test] + fn a_corner_at_a_junction_is_left_alone() { + let (mut fps, polys) = two_edges(50.0); + let before = turn_at_origin(&fps); + let order = vec![vec![vec![(0usize, false), (1usize, false)]]]; + let mut st = EditStats::default(); + pass_junctions(&order, &mut fps, &polys, &[None, None], &mut st); + assert_eq!(st.junction_g1, 0); + assert!((turn_at_origin(&fps) - before).abs() < 1e-12); + } +} diff --git a/crates/inkvec-cli/src/editable/tests.rs b/crates/inkvec-cli/src/editable/tests.rs new file mode 100644 index 00000000..ce5846ea --- /dev/null +++ b/crates/inkvec-cli/src/editable/tests.rs @@ -0,0 +1,540 @@ +//! The editability passes on rings whose answer is known. + +use super::*; +use inkvec_core::Polyline; + +fn pt(x: f64, y: f64) -> Point { + Point::new(x, y) +} + +/// A ring sampled densely enough that the guard has real evidence to hold the +/// passes to, with the sigma the tracer would give a clean edge. +fn poly_of(fp: &FittedPath, per: usize) -> Polyline { + let starts = chain_starts(fp); + let pts = samples(&fp.segments, &starts, per); + let n = pts.len(); + Polyline::new(pts, vec![0.25; n], true) +} + +/// A diamond: four lines, symmetric about x = 50, with nodes on the axis. +fn diamond() -> FittedPath { + FittedPath { + start: pt(50.0, 10.0), + segments: vec![ + Segment::Line(pt(90.0, 50.0)), + Segment::Line(pt(50.0, 90.0)), + Segment::Line(pt(10.0, 50.0)), + Segment::Line(pt(50.0, 10.0)), + ], + closed: true, + } +} + +#[test] +fn reflecting_a_segment_twice_gives_it_back() { + let seg = Segment::Cubic(pt(12.0, 3.0), pt(31.0, 47.0), pt(40.0, 60.0)); + let start = pt(5.0, 1.0); + let once = mirror_reverse(&seg, start, 25.0); + // the reflected copy runs backwards from the reflection of the original's + // end, which is where its own start is + let twice = mirror_reverse(&once, pt(2.0 * 25.0 - 40.0, 60.0), 25.0); + let (Segment::Cubic(a1, a2, ae), Segment::Cubic(b1, b2, be)) = (&seg, &twice) else { + panic!("expected cubics"); + }; + for (p, q) in [(a1, b1), (a2, b2), (ae, be)] { + assert!(p.dist(*q) < 1e-9, "{p:?} != {q:?}"); + } +} + +#[test] +fn splitting_a_curve_draws_what_it_drew_before() { + let seg = Segment::Cubic(pt(10.0, 0.0), pt(30.0, 80.0), pt(40.0, 40.0)); + let start = pt(0.0, 0.0); + let (a, b) = split_at(&seg, start, 0.375).expect("a cubic splits"); + let mid = a.end(); + for k in 0..=40 { + let t = f64::from(k) / 40.0; + let whole = eval_segment(&seg, start, t); + // the same parameter, expressed on whichever half holds it + let part = if t <= 0.375 { + eval_segment(&a, start, t / 0.375) + } else { + eval_segment(&b, mid, (t - 0.375) / 0.625) + }; + assert!(whole.dist(part) < 1e-9, "t={t}: {whole:?} vs {part:?}"); + } +} + +#[test] +fn the_axis_crossing_is_found_inside_a_segment() { + // a line from x=10 to x=90 crosses x=50 at its midpoint + let seg = Segment::Line(pt(90.0, 7.0)); + let t = interior_crossing(&seg, pt(10.0, 7.0), 50.0).expect("it crosses"); + assert!((t - 0.5).abs() < 1e-6, "t = {t}"); + // and a segment that stays on one side has no crossing + assert!(interior_crossing(&seg, pt(10.0, 7.0), 200.0).is_none()); +} + +#[test] +fn a_symmetric_ring_is_locked_onto_its_axis_exactly() { + let mut fp = diamond(); + // pull one side off true by more than the emitter's step, less than the budget + fp.segments[0] = Segment::Line(pt(90.6, 50.3)); + let poly = poly_of(&fp, 24); + let mut st = EditStats::default(); + let starts = chain_starts(&fp); + pass_mirror(&mut fp, &starts, &poly.points, &poly.sigma, &mut st); + assert_eq!(st.mirror_rings, 1, "the ring should lock: {st:?}"); + + // every node now has a partner at its exact reflection + let nodes = chain_starts(&fp); + let xs: Vec = nodes.iter().map(|p| p.x).collect(); + let cx = (xs.iter().cloned().fold(f64::MAX, f64::min) + + xs.iter().cloned().fold(f64::MIN, f64::max)) + / 2.0; + for p in &nodes { + let m = Point::new(2.0 * cx - p.x, p.y); + let best = nodes + .iter() + .map(|q| m.dist(*q)) + .fold(f64::INFINITY, f64::min); + assert!(best < 1e-9, "{p:?} has no exact mirror (nearest {best})"); + } +} + +#[test] +fn an_asymmetric_ring_is_left_alone() { + let mut fp = diamond(); + fp.segments[0] = Segment::Line(pt(140.0, 50.0)); // a long spur on one side only + let poly = poly_of(&fp, 24); + let before = fp.clone(); + let mut st = EditStats::default(); + let starts = chain_starts(&fp); + pass_mirror(&mut fp, &starts, &poly.points, &poly.sigma, &mut st); + assert_eq!(st.mirror_rings, 0, "nothing should have locked"); + assert_eq!(fp.segments.len(), before.segments.len()); +} + +/// The nodes of a ring are its segment *ends*; `Cubic`'s first field is a +/// control point. Writing node positions into it moved handles onto nodes and +/// collapsed every `Line` to zero length -- which is how a heart lost its point. +/// A moved node carries its handles, so each handle keeps its offset from its node. +#[test] +fn aligning_nodes_moves_nodes_with_their_handles() { + let fp = FittedPath { + start: pt(0.0, 0.0), + segments: vec![ + Segment::Cubic(pt(10.0, 30.0), pt(30.0, 30.0), pt(40.0, 0.2)), + Segment::Line(pt(40.0, 40.0)), + Segment::Cubic(pt(20.0, 50.0), pt(5.0, 50.0), pt(0.0, 0.0)), + ], + closed: true, + }; + let poly = poly_of(&fp, 32); + let handles_before = fp + .segments + .iter() + .filter_map(cubic) + .map(|(c1, c2, _)| (c1, c2)) + .collect::>(); + // Each cubic's handles as offsets from the nodes they hang from. + let offsets = |fp: &FittedPath| -> Vec<(f64, f64, f64, f64)> { + let starts = chain_starts(fp); + fp.segments + .iter() + .enumerate() + .filter_map(|(k, s)| { + cubic(s).map(|(c1, c2, e)| { + ( + c1.x - starts[k].x, + c1.y - starts[k].y, + c2.x - e.x, + c2.y - e.y, + ) + }) + }) + .collect() + }; + let offsets_before = offsets(&fp); + let mut fps = [fp.clone()]; + pass_nodes( + &mut fps, + &[0], + std::slice::from_ref(&poly), + &mut EditStats::default(), + ); + let out = &fps[0]; + // the y = 0.2 node may align to y = 0; no line may collapse + for (k, seg) in out.segments.iter().enumerate() { + let starts = chain_starts(out); + assert!( + starts[k].dist(seg.end()) > 1e-6, + "segment {k} collapsed to a point" + ); + } + for (a, b) in offsets(out).iter().zip(&offsets_before) { + for (x, y) in [(a.0, b.0), (a.1, b.1), (a.2, b.2), (a.3, b.3)] { + assert!((x - y).abs() < 1e-9, "a handle left its node: {a:?} {b:?}"); + } + } + // handles keep their own positions, give or take the node they hang from + for (k, (c1, c2)) in out + .segments + .iter() + .filter_map(cubic) + .map(|(a, b, _)| (a, b)) + .enumerate() + { + let (b1, b2) = handles_before[k]; + assert!( + c1.dist(b1) <= NODE_ALIGN + 1e-9, + "handle 1 of {k} moved {}", + c1.dist(b1) + ); + assert!( + c2.dist(b2) <= NODE_ALIGN + 1e-9, + "handle 2 of {k} moved {}", + c2.dist(b2) + ); + } +} + +#[test] +fn a_handle_within_the_window_snaps_onto_the_axis() { + // a curve whose first handle leaves its node 1.4 deg off horizontal + let off = 1.4_f64.to_radians(); + let mut fp = FittedPath { + start: pt(0.0, 0.0), + segments: vec![ + Segment::Cubic( + pt(20.0 * off.cos(), 20.0 * off.sin()), + pt(60.0, 10.0), + pt(80.0, 0.0), + ), + Segment::Cubic(pt(90.0, -20.0), pt(20.0, -30.0), pt(0.0, 0.0)), + ], + closed: true, + }; + let poly = poly_of(&fp, 48); + let mut st = EditStats::default(); + let starts = chain_starts(&fp); + pass_handles(&mut fp, &starts, &poly.points, &poly.sigma, &mut st); + assert!(st.axis_snaps >= 1, "the handle should have snapped: {st:?}"); + let (c1, _, _) = cubic(&fp.segments[0]).expect("a cubic"); + assert!(c1.y.abs() < 1e-9, "handle is still {} off the axis", c1.y); +} + +#[test] +fn a_pass_that_would_stray_too_far_is_refused() { + // sigma of zero and no room: any move at all breaks the guard + let fp = diamond(); + let starts = chain_starts(&fp); + let pts = samples(&fp.segments, &starts, 16); + let sigma = vec![0.0; pts.len()]; + let mut moved = fp.segments.clone(); + moved[0] = Segment::Line(pt(200.0, 50.0)); + assert!(!guarded(&moved, &starts, &pts, &sigma)); + assert!(guarded(&fp.segments, &starts, &pts, &sigma)); +} + +#[test] +fn test_edit_all_on_diamond() { + let fp = diamond(); + let poly = poly_of(&fp, 48); + let mut fps = vec![fp]; + let polys = vec![poly]; + let prims = vec![None]; + let st = edit_all( + &polys, + &mut fps, + &prims, + &[], + &inkvec_fit::FitConfig::default(), + ); + assert!(st.rings > 0); + let summary = st.summary(); + assert!(summary.contains("editability")); +} + +#[test] +fn test_pass_g1() { + let p0 = pt(10.0, 50.0); + let p_mid = pt(50.0, 50.0); + let p_end = pt(90.0, 50.0); + let seg1 = Segment::Cubic(pt(30.0, 50.0), pt(40.0, 50.0), p_mid); + let seg2 = Segment::Cubic(pt(60.0, 50.3), pt(70.0, 50.0), p_end); + let mut fp = FittedPath { + start: p0, + segments: vec![seg1, seg2], + closed: false, + }; + let poly = poly_of(&fp, 48); + let mut st = EditStats::default(); + let starts = chain_starts(&fp); + pass_g1(&mut fp, &starts, &poly.points, &poly.sigma, &mut st); + assert_eq!(st.g1_joins, 1); +} + +/// The handles that turn are the two at the join: the incoming cubic's second control point +/// and the outgoing one's first. (The pass once turned the incoming cubic's *first* control +/// point, at its far end, so the join kept its kink and the far end gained one.) +#[test] +fn g1_turns_the_two_handles_at_the_join_and_no_other() { + let a = 10f64.to_radians(); + let mut fp = FittedPath { + start: pt(0.0, 0.0), + segments: vec![ + Segment::Cubic(pt(15.0, 0.0), pt(35.0, 0.0), pt(50.0, 0.0)), + Segment::Cubic( + pt(50.0 + 15.0 * a.cos(), 15.0 * a.sin()), + pt(85.0, 6.0), + pt(100.0, 8.0), + ), + ], + closed: false, + }; + let poly = poly_of(&fp, 48); + let before = fp.segments.clone(); + let mut st = EditStats::default(); + let starts = chain_starts(&fp); + pass_g1(&mut fp, &starts, &poly.points, &poly.sigma, &mut st); + assert_eq!(st.g1_joins, 1); + let starts = chain_starts(&fp); + let din = end_direction(&fp.segments[0], starts[0], true).expect("a direction"); + let dout = end_direction(&fp.segments[1], starts[1], false).expect("a direction"); + assert!( + (din.0 - dout.0).abs() < 1e-9 && (din.1 - dout.1).abs() < 1e-9, + "{din:?} {dout:?}" + ); + let (c1, _, _) = cubic(&fp.segments[0]).expect("a cubic"); + let (b1, _, _) = cubic(&before[0]).expect("a cubic"); + assert_eq!(c1, b1, "the far handle stays"); + let (_, c2, _) = cubic(&fp.segments[1]).expect("a cubic"); + let (_, b2, _) = cubic(&before[1]).expect("a cubic"); + assert_eq!(c2, b2, "the far handle stays"); +} + +/// A boundary with no junction comes as an open path ending where it starts; its closing +/// join is a join like any other, and the per-ring passes see it. +#[test] +fn the_closing_join_of_a_loop_edge_is_edited() { + // A trapezoid (no mirror, which would put nodes of its own on an axis) whose path + // starts in the middle of its top side: the closing join joins two halves of one + // straight line. + let fp = FittedPath { + start: pt(30.0, 0.0), + segments: vec![ + Segment::Line(pt(60.0, 0.0)), + Segment::Line(pt(45.0, 40.0)), + Segment::Line(pt(0.0, 40.0)), + Segment::Line(pt(0.0, 0.0)), + Segment::Line(pt(30.0, 0.0)), + ], + closed: false, + }; + let poly = poly_of(&fp, 48); + let mut fps = vec![fp]; + let st = edit_all( + &[poly], + &mut fps, + &[None], + &[], + &inkvec_fit::FitConfig::default(), + ); + assert_eq!(st.collinear_merged, 1); + assert_eq!(fps[0].segments.len(), 4); + assert!(!fps[0].closed, "the flag is put back"); + assert_eq!(fps[0].segments[3].end(), fps[0].start, "still a loop"); +} + +/// The same path is not a loop when another edge ends at its start: that is a junction. +#[test] +fn a_loop_through_a_junction_is_not_isolated() { + let ring = FittedPath { + start: pt(30.0, 0.0), + segments: vec![ + Segment::Line(pt(60.0, 0.0)), + Segment::Line(pt(60.0, 40.0)), + Segment::Line(pt(30.0, 0.0)), + ], + closed: false, + }; + let spoke = FittedPath { + start: pt(30.0, 0.0), + segments: vec![Segment::Line(pt(30.0, -20.0))], + closed: false, + }; + assert_eq!(isolated_loops(std::slice::from_ref(&ring), &[0]), vec![0]); + assert!(isolated_loops(&[ring, spoke], &[0, 1]).is_empty()); +} + +#[test] +fn a_kink_between_a_line_and_a_curve_is_made_smooth_along_the_line() { + // A horizontal line into a curve whose handle leaves 8 degrees off it; the points + // are those of the smooth curve, so the kink is the fit's, not the drawing's. + let off = 8f64.to_radians(); + let smooth = FittedPath { + start: pt(0.0, 0.0), + segments: vec![ + Segment::Line(pt(40.0, 0.0)), + Segment::Cubic(pt(50.0, 0.0), pt(60.0, 5.0), pt(70.0, 20.0)), + ], + closed: false, + }; + let poly = poly_of(&smooth, 48); + let mut fp = smooth.clone(); + fp.segments[1] = Segment::Cubic( + pt(40.0 + 10.0 * off.cos(), 10.0 * off.sin()), + pt(60.0, 5.0), + pt(70.0, 20.0), + ); + let mut st = EditStats::default(); + let starts = chain_starts(&fp); + pass_g1(&mut fp, &starts, &poly.points, &poly.sigma, &mut st); + assert_eq!(st.g1_joins, 1); + let (c1, _, _) = cubic(&fp.segments[1]).expect("a cubic"); + assert!( + c1.y.abs() < 1e-9, + "the handle now runs along the line: {c1:?}" + ); +} + +#[test] +fn a_smooth_nodes_handles_snap_together_or_not_at_all() { + // Two cubics meeting smoothly at (50, 0), the shared direction 2 degrees off + // horizontal: both handles snap, and the join stays smooth. + let a = 2f64.to_radians(); + let (dx, dy) = (a.cos(), a.sin()); + let mut fp = FittedPath { + start: pt(0.0, 20.0), + segments: vec![ + Segment::Cubic( + pt(10.0, 0.0), + pt(50.0 - 15.0 * dx, -15.0 * dy), + pt(50.0, 0.0), + ), + Segment::Cubic( + pt(50.0 + 12.0 * dx, 12.0 * dy), + pt(90.0, 0.0), + pt(100.0, 20.0), + ), + ], + closed: false, + }; + let poly = poly_of(&fp, 48); + let mut st = EditStats::default(); + let starts = chain_starts(&fp); + pass_handles(&mut fp, &starts, &poly.points, &poly.sigma, &mut st); + let (_, c2, _) = cubic(&fp.segments[0]).expect("a cubic"); + let (c1, _, _) = cubic(&fp.segments[1]).expect("a cubic"); + assert!( + c2.y.abs() < 1e-9 && c1.y.abs() < 1e-9, + "both on the axis: {c2:?} {c1:?}" + ); +} + +#[test] +fn two_lines_end_to_end_on_one_axis_become_one() { + let mut fp = FittedPath { + start: pt(0.0, 0.0), + segments: vec![ + Segment::Line(pt(30.0, 0.0)), + Segment::Line(pt(60.0, 0.0)), + Segment::Line(pt(60.0, 40.0)), + Segment::Line(pt(0.0, 0.0)), + ], + closed: true, + }; + let poly = poly_of(&fp, 48); + let mut st = EditStats::default(); + pass_collinear(&mut fp, &poly.points, &poly.sigma, &mut st); + assert_eq!(st.collinear_merged, 1); + assert_eq!(fp.segments.len(), 3); + assert_eq!(fp.segments[0].end(), pt(60.0, 0.0)); + // A real corner stays. + assert!(fp.segments.iter().all(|s| matches!(s, Segment::Line(_)))); +} + +/// The merged line is judged against the two it replaces, not the whole ring: a ring that +/// strays elsewhere (a mirror lock is allowed to) still loses a node in a straight run. +#[test] +fn a_straight_run_merges_on_a_ring_that_strays_elsewhere() { + let truth = FittedPath { + start: pt(0.0, 0.0), + segments: vec![ + Segment::Line(pt(30.0, 0.0)), + Segment::Line(pt(60.0, 0.0)), + Segment::Line(pt(60.0, 40.0)), + Segment::Line(pt(0.0, 0.0)), + ], + closed: true, + }; + let poly = poly_of(&truth, 48); + let mut fp = truth.clone(); + // The right side 1.4 px out: beyond EDIT_SLACK, within MIRROR_SLACK. + fp.segments[1] = Segment::Line(pt(61.4, 0.0)); + fp.segments[2] = Segment::Line(pt(61.4, 40.0)); + fp.segments[0] = Segment::Line(pt(30.0, 0.0)); + assert!(!guarded( + &fp.segments, + &chain_starts(&fp), + &poly.points, + &poly.sigma + )); + let mut st = EditStats::default(); + pass_collinear(&mut fp, &poly.points, &poly.sigma, &mut st); + assert_eq!(st.collinear_merged, 1, "{:?}", fp.segments); + assert_eq!(fp.segments[0].end(), pt(61.4, 0.0)); +} + +#[test] +fn test_pass_equalize() { + let p0 = pt(0.0, 0.0); + let p_end = pt(100.0, 0.0); + let seg = Segment::Cubic(pt(10.0, 0.0), pt(90.5, 0.0), p_end); + let mut fp = FittedPath { + start: p0, + segments: vec![seg], + closed: false, + }; + let poly = poly_of(&fp, 48); + let mut st = EditStats::default(); + let starts = chain_starts(&fp); + pass_equalize(&mut fp, &starts, &poly.points, &poly.sigma, &mut st); + assert_eq!(st.len_sym, 1); +} + +#[test] +fn a_centrelines_arcs_become_cubics_and_its_lines_stay() { + // A line, then a half circle of radius 10 round (10, 0): cut at its extremum. + let path = FittedPath { + start: pt(-10.0, 0.0), + segments: vec![ + Segment::Line(pt(0.0, 0.0)), + Segment::circular_arc(10.0, false, true, pt(20.0, 0.0)), + ], + closed: false, + }; + let out = arcs_as_cubics(&path); + assert_eq!(out.start, path.start); + assert!(matches!(out.segments[0], Segment::Line(_))); + assert_eq!(out.segments.len(), 3, "{:?}", out.segments); + assert_eq!(out.end(), pt(20.0, 0.0)); + let Segment::Cubic(_, c2, mid) = out.segments[1] else { + panic!("a cubic"); + }; + assert!( + (c2.y - mid.y).abs() < 1e-9, + "a horizontal handle at the extremum" + ); +} + +#[test] +fn test_pass_mirror_on_diamond() { + let mut fp = diamond(); + let poly = poly_of(&fp, 48); + let mut st = EditStats::default(); + let starts = chain_starts(&fp); + pass_mirror(&mut fp, &starts, &poly.points, &poly.sigma, &mut st); + assert!(st.mirror_rings >= 1); +} diff --git a/crates/inkvec-cli/src/emit.rs b/crates/inkvec-cli/src/emit.rs index 9d6f0a06..a23da73c 100644 --- a/crates/inkvec-cli/src/emit.rs +++ b/crates/inkvec-cli/src/emit.rs @@ -47,7 +47,7 @@ //! instead, and 30% of the screen set's files filled their holes back in for any //! consumer that ignored it. -use std::collections::{BTreeMap, HashMap, HashSet}; +use std::collections::{HashMap, HashSet}; use inkvec_core::Point; use inkvec_fit::{ @@ -65,6 +65,8 @@ use crate::primitive::{annulus_stroke, primitive_d, primitive_element, stroke_el use crate::rings::{self, point_in_ring, ring_area, Nesting}; use crate::seams; +mod completion; +mod holes; mod winding; pub(crate) use winding::for_nonzero; @@ -104,10 +106,11 @@ pub(crate) struct ColorDoc<'a> { pub layers: Option>, /// The colour transparent pixels were composited onto before tracing, sRGB 0..1. pub matte: [f32; 3], - /// `--detect-strokes`: faces written as strokes instead of fills, face -> - /// finished element text ([`crate::ribbons`]). Empty unless the switch is on, and an - /// empty map changes nothing below. - pub ribbons: &'a BTreeMap, + /// Stroke detection ([`crate::ribbons`]): the faces written as strokes instead of + /// fills (face -> finished element text), and the faces that leave with them where the + /// face beneath is still painted their colour ([`crate::ribbons::absorbed_by`]). Empty + /// when the stage does not run, and empty changes nothing below. + pub ribbons: &'a crate::ribbons::Ribbons, /// Width of the traced raster, px. pub w: usize, /// Height of the traced raster, px. @@ -117,7 +120,7 @@ pub(crate) struct ColorDoc<'a> { impl<'a> ColorDoc<'a> { /// The same document with `ribbons` as the faces written as strokes /// ([`crate::ribbons`]). - pub(crate) fn with_ribbons(self, ribbons: &'a BTreeMap) -> ColorDoc<'a> { + pub(crate) fn with_ribbons(self, ribbons: &'a crate::ribbons::Ribbons) -> ColorDoc<'a> { ColorDoc { ribbons, ..self } } } @@ -139,6 +142,8 @@ pub(crate) struct EmitOptions { pub harmonize_threshold: f64, /// Write harmonized shapes as `` of one shared definition. pub use_symbols: bool, + /// Complete each face behind what is painted over it ([`crate::layers`]). + pub layers: bool, } /// Emit the map as a **stacked** document: faces painted back to front, each drawing only @@ -177,11 +182,21 @@ pub(crate) fn emit_color(doc: &ColorDoc, opts: &EmitOptions) -> String { let mut stack = stack_faces(doc, opts, &nest); // Faces written as strokes are not painted as fills: their children paint at the // nearest painted ancestor's level, and the strokes go on top ([`write_ribbons`]). - for &f in doc.ribbons.keys() { + for &f in doc.ribbons.elements.keys() { if let Some(d) = stack.dropped.get_mut(f) { *d = true; } } + // And the faces that leave with them, where what now paints beneath is their colour + // and nothing is punched out of them. + for &g in &doc.ribbons.absorbed { + let under = surviving_parent(&nest.parent, &stack.dropped, g); + let hex = |i: usize| flat_colour(doc, i).map(inkvec_trace::color::to_hex); + let same = under.is_some_and(|a| hex(a).is_some() && hex(a) == hex(g)); + if same && stack.holes.get(g).is_some_and(Vec::is_empty) { + stack.dropped[g] = true; + } + } debug_dump(doc, &nest, &stack); // Repeated shapes redrawn from one consensus, where their own evidence agrees; see @@ -210,6 +225,7 @@ pub(crate) fn emit_color(doc: &ColorDoc, opts: &EmitOptions) -> String { let paint = face_paint(doc, &stack, &mut defs); let (roots, children) = paint_tree(doc, &nest, &stack, paint.fills.len()); let ids = face_ids(doc); + let no_completions = HashMap::new(); let strokes = if opts.native { annulus_strokes(doc, drawn, &stack, &paint, &harmonized, decimals) } else { @@ -230,17 +246,35 @@ pub(crate) fn emit_color(doc: &ColorDoc, opts: &EmitOptions) -> String { harmonized_d: &harmonized.d, symbol_use: &harmonized.symbols, strokes: &strokes, + completed: &no_completions, }; let mut painted = Vec::new(); let mut body = writer.body(&roots, &seams::Overrides::new(), &mut painted); write_ribbons(doc, &mut body, &mut painted); + // Each face completed behind what is painted over it (see `crate::layers`), in the paint + // ranks the first pass settled. The second pass writes completed faces in the same + // places, so every rank a completion relied on still holds. + let completed = if opts.layers { + completion::complete_layers(doc, &nest, &stack, &paint, &writer, &painted, decimals) + } else { + HashMap::new() + }; + let writer = Writer { + completed: &completed, + ..writer + }; + // Side-by-side faces: the lower reaches under the upper so no ground shows through - // their shared edge (see `crate::seams`). The first pass settled the paint order; the - // second writes the moved outlines, and is skipped when nothing moves. + // their shared edge (see `crate::seams`); a completed face already does. The first pass + // settled the paint order; the second writes the moved and completed outlines, and is + // skipped when nothing changes. if let Some(moved) = seam_overrides(doc, &nest, &stack, &paint, &writer, &painted) { body = writer.body(&roots, &moved, &mut Vec::new()); write_ribbons(doc, &mut body, &mut Vec::new()); + } else if !completed.is_empty() { + body = writer.body(&roots, &seams::Overrides::new(), &mut Vec::new()); + write_ribbons(doc, &mut body, &mut Vec::new()); } write_layers(doc, decimals, &mut body); @@ -291,8 +325,8 @@ struct Stacking { /// /// In order: the canvas background under `--no-background` ([`canvas_background`]) and /// the faces of its colour that are holes in a glyph ([`punch_background_coloured`]); -/// clear and translucent faces ([`punch_transparent`]); then the hole lists are made -/// parity-safe ([`dedupe_holes`]). +/// clear and translucent faces ([`punch_transparent`]); counters cut out of their glyph +/// ([`holes::cut_ground_holes`]); then the hole lists are made parity-safe ([`dedupe_holes`]). fn stack_faces(doc: &ColorDoc, opts: &EmitOptions, nest: &Nesting) -> Stacking { let n = doc.order.len(); let mut stack = Stacking { @@ -319,6 +353,7 @@ fn stack_faces(doc: &ColorDoc, opts: &EmitOptions, nest: &Nesting) -> Stacking { } } punch_transparent(doc, opts, nest, &mut stack); + holes::cut_ground_holes(doc, nest, &mut stack); dedupe_holes(&nest.parent, &mut stack.holes); stack } @@ -922,6 +957,7 @@ enum Element { /// Stage 7: the element writer. Holds every per-face decision made so far and writes the /// paint tree as SVG elements. +#[derive(Clone, Copy)] struct Writer<'a> { /// The rings of each face. order: &'a [FaceRings], @@ -949,6 +985,8 @@ struct Writer<'a> { symbol_use: &'a HashMap, /// Faces written as one stroked primitive ([`annulus_strokes`]). strokes: &'a HashMap, + /// Faces completed behind what is painted over them ([`crate::layers`]). + completed: &'a HashMap, } impl Writer<'_> { @@ -973,6 +1011,15 @@ impl Writer<'_> { if let Some(h_d) = self.harmonized_d.get(&i) { return h_d.clone(); } + match self.completed.get(&i).map(|c| &c.shape) { + Some(crate::layers::Shape::Path(d)) => return d.clone(), + Some(crate::layers::Shape::Prim(k)) => { + if let Some(d) = primitive_d(k, self.decimals) { + return d; + } + } + None => {} + } let (order, fitted, decimals) = (self.order, self.fitted, self.decimals); let mut d = String::new(); // A face's own outline is its primitive too, when it fitted one, and for the same @@ -1037,6 +1084,20 @@ impl Writer<'_> { } return Some((Element::Ready(el), true)); } + // A face completed behind its cover: its primitive, or its path. + if let Some(c) = self.completed.get(&i) { + match &c.shape { + crate::layers::Shape::Prim(kind) => { + if let Some(mut el) = primitive_element(kind, fill, alpha, self.decimals) { + if let Some(sp) = el.find(' ') { + el.insert_str(sp, &format!(" id=\"{id}\"")); + } + return Some((Element::Ready(el), true)); + } + } + crate::layers::Shape::Path(d) => return Some((Element::Path(d.clone()), false)), + } + } // A primitive element cannot carry a hole, so a face that has to show one through // is written as a path even when its outline would have fitted a circle. let drawn = &self.drawn[i]; @@ -1058,6 +1119,39 @@ impl Writer<'_> { Some((Element::Path(d), false)) } + /// Whether face `i` is written as an element of its own, not merged into a compound path + /// with its same-coloured siblings, *before* any completion: a symbol's ``, a + /// stroke, or a primitive outline with nothing punched out of it -- but a square-cornered + /// rectangle, which a path writes in the same six numbers, joins its siblings' compound + /// path ([`holes::plain_rect`]). Grouping is decided on this, so a completion never moves + /// a face to another place in the paint order. + fn stands_alone(&self, i: usize) -> bool { + if self.symbol_use.contains_key(&i) || self.strokes.contains_key(&i) { + return true; + } + let drawn = &self.drawn[i]; + drawn.len() == 1 + && self.order[i][drawn[0]].len() == 1 + && self.holes[i].is_empty() + && self + .prims + .get(self.order[i][drawn[0]][0].0) + .and_then(|p| p.as_ref()) + .is_some_and(|pf| { + !holes::plain_rect(&pf.kind) + && primitive_element(&pf.kind, "", "", self.decimals).is_some() + }) + } + + /// Whether face `i` is completed as a primitive element of its own: any but a + /// square-cornered rectangle, which a path writes as cheaply ([`holes::plain_rect`]). + fn completed_prim(&self, i: usize) -> bool { + matches!( + self.completed.get(&i).map(|c| &c.shape), + Some(crate::layers::Shape::Prim(k)) if !holes::plain_rect(k) + ) + } + /// The `` of face `i` -- its id, fill and opacity -- drawing `d`, a compound path /// of its rings and, when siblings were merged into it, theirs. /// @@ -1080,10 +1174,10 @@ impl Writer<'_> { /// which is how an artist draws them: a whole word is one ``, not one per /// letter. Before this the tracer wrote one element per connected face and came /// back with 3.5x the artist's path count on a detailed wordmark at the same - /// colour error. Primitives stay their own element and gradient faces each own a - /// gradient, so neither merges; nor does a harmonized ``. The merged path takes - /// the first member's place in the paint order and its id; every member's children - /// follow it. + /// colour error. Primitives other than a square-cornered rectangle stay their own + /// element and gradient faces each own a gradient, so neither merges; nor does a + /// harmonized ``. The merged path takes the first member's place in the paint + /// order and its id; every member's children follow it. fn emit_level( &self, members: &[usize], @@ -1099,11 +1193,11 @@ impl Writer<'_> { } done[a] = true; let i = members[a]; - let Some((element, is_prim)) = self.face_element(i, under) else { + if self.face_element(i, under).is_none() { continue; - }; + } let mut group = vec![i]; - if !is_prim && fills[i].starts_with('#') && !self.symbol_use.contains_key(&i) { + if !self.stands_alone(i) && fills[i].starts_with('#') { for b in a + 1..members.len() { if done[b] || fills[members[b]] != fills[i] @@ -1113,30 +1207,43 @@ impl Writer<'_> { continue; } let j = members[b]; - let Some((_, prim_b)) = self.face_element(j, under) else { + if self.face_element(j, under).is_none() { done[b] = true; continue; - }; - if prim_b { + } + if self.stands_alone(j) { continue; } done[b] = true; group.push(j); } } - let element = match element { - Element::Ready(el) => el, - Element::Path(d) if group.len() == 1 => self.path_element(i, &d), - Element::Path(_) => { - let mut d = String::new(); - for &j in &group { - d.push_str(&self.face_d(j, under)); + // Members completed as primitives are written as elements of their own, in the + // group's place; the rest as one path, wound as a whole: a member's depth is + // counted among every ring of the merged element, not only its own. + let (alone, merged): (Vec, Vec) = + group.iter().partition(|&&j| self.completed_prim(j)); + let mut element = String::new(); + if let Some(&lead) = merged.first() { + match self.face_element(lead, under) { + Some((Element::Ready(el), _)) if merged.len() == 1 => element.push_str(&el), + Some((Element::Path(d), _)) if merged.len() == 1 => { + element.push_str(&self.path_element(lead, &d)) + } + _ => { + let mut d = String::new(); + for &j in &merged { + d.push_str(&self.face_d(j, under)); + } + element.push_str(&self.path_element(lead, &d)); } - // Wound as one path: a member's depth is counted among every ring of - // the merged element, not only its own. - self.path_element(i, &d) } - }; + } + for &j in &alone { + if let Some((Element::Ready(el), _)) = self.face_element(j, under) { + element.push_str(&el); + } + } // One element is one paint: its members share a rank, so none of them reaches // under another -- inside one compound path an overlap would cancel to a hole // (or, wound for nonzero, count twice), and a shared edge inside one path cannot @@ -1222,7 +1329,8 @@ fn seam_overrides( && !writer.harmonized_d.contains_key(&i) && !writer.symbol_use.contains_key(&i) && !writer.strokes.contains_key(&i) - && !doc.ribbons.contains_key(&i) + && !writer.completed.contains_key(&i) + && !doc.ribbons.elements.contains_key(&i) }) .collect(); let upper_ok: Vec = (0..n) @@ -1297,7 +1405,7 @@ fn seam_overrides( /// else (the stage accepts a face only when the strokes' outline matches the face's /// boundary), and faces of a planar map do not overlap. fn write_ribbons(doc: &ColorDoc, body: &mut String, painted: &mut Vec<(usize, usize)>) { - for (&f, el) in doc.ribbons { + for (&f, el) in &doc.ribbons.elements { body.push_str(el); let rank = painted.last().map_or(0, |&(_, r)| r + 1); painted.push((f, rank)); diff --git a/crates/inkvec-cli/src/emit/completion.rs b/crates/inkvec-cli/src/emit/completion.rs new file mode 100644 index 00000000..162c7f67 --- /dev/null +++ b/crates/inkvec-cli/src/emit/completion.rs @@ -0,0 +1,135 @@ +//! Stage 7b of the emitter: faces completed behind what is painted over them +//! ([`crate::layers`]), with the writer's paint ranks and the gate's count of what each +//! face is written as now. Split from `emit.rs`, whose private types it reads. + +use super::*; + +/// Stage 7b: each face completed behind what is painted over it, in the paint ranks the +/// first writing pass recorded in `painted` ([`crate::layers`]). +/// +/// What covers: every painted face that paints opaque everywhere (no opacity attribute, no +/// fade, no alpha ramp), and the strokes of [`crate::ribbons`], which go on top of +/// everything; a face written as strokes is not a face here. What may be completed: such a +/// face written from its own rings (not a harmonized consensus, a symbol or an annulus +/// stroke) with nothing punched out of it. Its cost now is the gate's count of the element +/// it is written as. +pub(super) fn complete_layers( + doc: &ColorDoc, + nest: &Nesting, + stack: &Stacking, + paint: &Paint, + writer: &Writer, + painted: &[(usize, usize)], + decimals: usize, +) -> HashMap { + let n = doc.order.len(); + let mut rank = vec![None; n]; + for &(f, r) in painted { + if f < n && !doc.ribbons.elements.contains_key(&f) { + rank[f] = Some(r); + } + } + let covers: Vec = (0..n) + .map(|i| { + rank[i].is_some() + && paint.opac[i].is_empty() + && doc.fades.get(i).is_none_or(|f| f.is_none()) + && doc.alpha_ramps.get(i).is_none_or(|r| r.is_none()) + }) + .collect(); + let candidate: Vec = (0..n) + .map(|i| { + covers[i] + && stack.holes[i].is_empty() + && !writer.harmonized_d.contains_key(&i) + && !writer.symbol_use.contains_key(&i) + && !writer.strokes.contains_key(&i) + }) + .collect(); + let empty = seams::Overrides::new(); + let cost_now = |i: usize| -> f64 { + match writer.face_element(i, &empty) { + Some((Element::Path(d), _)) => crate::layers::gate_count(&d), + Some((Element::Ready(el), _)) => element_count(&el), + None => 0.0, + } + }; + let strokes: Vec = doc.ribbons.shapes.values().cloned().collect(); + let stroke_faces: Vec = doc.ribbons.shapes.keys().copied().collect(); + let (done, tried) = crate::layers::complete_report(&crate::layers::Input { + order: doc.order, + fitted: doc.fitted, + prims: doc.prims, + outer: &nest.outer, + holes: &stack.holes, + rank: &rank, + covers: &covers, + candidate: &candidate, + cost_now: &cost_now, + strokes: &strokes, + stroke_faces: &stroke_faces, + canvas: Some((-0.5, -0.5, doc.w as f64 - 0.5, doc.h as f64 - 0.5)), + decimals, + }); + let debug = inkvec_core::env::number("INKVEC_COMPLETION_DEBUG").unwrap_or(0.0); + if debug != 0.0 { + let (b, a): (f64, f64) = done + .values() + .map(|c| (c.before, c.after)) + .fold((0.0, 0.0), |s, c| (s.0 + c.0, s.1 + c.1)); + eprintln!( + "layers: {} face(s) completed of {} tried, {b:.0} -> {a:.0} parameters", + done.len(), + tried.len() + ); + } + // `3`: one tab-separated line per tried face, for `bench/theory/amodal_eval.py`: the face, + // completed or refused, the winning candidate, the ink, and the element before and after. + if debug >= 3.0 { + let element = |el: Option<(Element, bool)>| -> String { + match el { + Some((Element::Path(d), _)) => format!(""), + Some((Element::Ready(el), _)) => el, + None => String::new(), + } + }; + for &f in &tried { + let before = element(writer.face_element(f, &empty)); + let (status, kind, after) = match done.get(&f) { + Some(c) => { + let after = match &c.shape { + crate::layers::Shape::Prim(k) => { + primitive_element(k, "#000000", "", decimals).unwrap_or_default() + } + crate::layers::Shape::Path(d) => format!(""), + }; + ("completed", c.kind.as_str(), after) + } + None => ("refused", "-", String::new()), + }; + eprintln!( + "completion\t{f}\t{status}\t{kind}\t{}\t{before}\t{after}", + writer.fills[f] + ); + } + } + done +} + +/// The gate's count of one finished element: a primitive's own (circle 3, ellipse 4, +/// rectangle 6), else the path data's. +fn element_count(el: &str) -> f64 { + let t = el.trim_start(); + if t.starts_with("= 1.0; + // A face painted one flat colour, opaque: that colour. + let solid = |i: usize, stack: &Stacking| -> Option<[f32; 3]> { + let flat = doc + .fill_fits + .get(i) + .is_none_or(|f| matches!(f.model, gradient::FillModel::Flat(_))); + (painted(i, stack) + && flat + && opaque(i, stack) + && doc.fades.get(i).is_none_or(|f| f.is_none()) + && doc.alpha_ramps.get(i).is_none_or(|r| r.is_none()) + && !in_layer(i)) + .then(|| flat_colour(doc, i)) + .flatten() + }; + let Some((page, ink)) = canvas_background(doc, nest).and_then(|b| Some((b, solid(b, stack)?))) + else { + return; + }; + // The page's colour exactly as it is written. Nearly is not enough: the bottle cap of + // `noto-emoji/emoji_u1f9d1_1f3fc_200d_1f37c` is #fdfefa on a #ffffff page, one palette + // ink and within `same_rgb`, and taken for page it went white, geom 0.065 -> 0.346. + let hex = inkvec_trace::color::to_hex; + let page_ink = |o: usize| flat_colour(doc, o).is_some_and(|oc| hex(oc) == hex(ink)); + for c in 0..order.len() { + if c == page || solid(c, stack).is_none() || !page_ink(c) { + continue; + } + let Some(p) = parent[c].filter(|&p| p != page && painted(p, stack)) else { + continue; + }; + if parent[p] != Some(page) || !opaque(p, stack) || stack.holes[page].contains(&p) { + continue; + } + if (0..order.len()).any(|o| parent[o] == Some(p) && !stack.dropped[o] && !page_ink(o)) + || !strictly_inside(nest, c, p) + { + continue; + } + // Written as a ``, an ellipse or a rounded rectangle, an outline costs a + // fraction of the arcs a path needs for it: cut only where that is not given up. + // A ring of two such outlines would be one stroke ([`annulus_strokes`]), but a + // stroke's outline is the renderer's offset of the centre line, not the fitted + // circles: `material-icons/group_remove` read dE00 +20 % at 512 px, and + // `lucide/app-window-mac` on `web` +3 % and its turning gap +37 %. + let costly = |f: usize| lone_prim(doc, nest, f).is_some_and(|k| !plain_rect(k)); + if costly(p) || costly(c) { + continue; + } + let in_hole = outer[c].iter().any(|&kc| { + order[p].iter().enumerate().any(|(kp, pr)| { + !outer[p].contains(&kp) + && pr + .iter() + .any(|&(pe, _)| order[c][kc].iter().any(|&(ce, _)| ce == pe)) + }) + }); + if in_hole { + stack.dropped[c] = true; + if !stack.holes[p].contains(&c) { + stack.holes[p].push(c); + } + } + } +} + +/// The primitive face `f`'s outline is, when it is one ring of one edge that fitted one. +fn lone_prim<'a>(doc: &ColorDoc<'a>, nest: &Nesting, f: usize) -> Option<&'a PrimitiveKind> { + let &[k] = nest.outer[f].as_slice() else { + return None; + }; + let &[(e, _)] = doc.order[f][k].as_slice() else { + return None; + }; + doc.prims.get(e).and_then(|p| p.as_ref()).map(|p| &p.kind) +} + +/// A rectangle with square corners: in a compound path it is three lines, the six numbers +/// of a ``, so it joins the path of its same-coloured siblings rather than standing +/// alone. The artist draws the bars of `material-icons/border_left` as one path of +/// seventeen rectangles; written one element each, the trace had seventeen elements. +pub(super) fn plain_rect(kind: &PrimitiveKind) -> bool { + matches!(*kind, PrimitiveKind::RoundRect { rx, .. } if rx.abs() < 1e-4) +} + +#[cfg(test)] +mod tests { + use super::*; + use inkvec_fit::curves::Segment; + use inkvec_fit::primitives::PrimitiveFit; + + /// A closed square edge from `(a, a)` to `(b, b)`. + fn square(a: f64, b: f64) -> FittedPath { + FittedPath { + start: Point::new(a, a), + segments: vec![ + Segment::Line(Point::new(b, a)), + Segment::Line(Point::new(b, b)), + Segment::Line(Point::new(a, b)), + Segment::Line(Point::new(a, a)), + ], + closed: true, + } + } + + fn rect(x: f64, y: f64, w: f64, h: f64) -> Option { + Some(PrimitiveFit { + kind: PrimitiveKind::RoundRect { + x, + y, + w, + h, + rx: 0.0, + }, + chi2: 0.0, + params: 6.0, + }) + } + + /// The document of faces `order` in palette inks `ink`: white, black, red, grey. + fn emit( + order: &[Vec], + fitted: &[FittedPath], + prims: &[Option], + ink: &[usize], + ) -> String { + let pal = inkvec_trace::Palette { + colors: vec![], + rgb: vec![ + [1.0, 1.0, 1.0], + [0.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [0.5, 0.5, 0.5], + ], + weight: vec![1.0; 4], + alpha: vec![1.0; 4], + }; + let n = order.len(); + let doc = ColorDoc { + order, + fitted, + prims, + fill_fits: &[], + pal: &pal, + face_color: ink, + clear: &vec![false; n], + opacity: &vec![1.0; n], + alpha_ramps: &vec![None; n], + fades: &vec![None; n], + layers: None, + matte: [1.0, 1.0, 1.0], + ribbons: &Default::default(), + w: 40, + h: 40, + }; + let opts = EmitOptions { + precision: 0.1, + native: true, + harmonize: false, + harmonize_threshold: 0.05, + use_symbols: false, + layers: false, + cutout: false, + no_background: false, + }; + emit_color(&doc, &opts) + } + + fn elements(svg: &str) -> usize { + [" String { + let order = vec![ + vec![vec![(0, false)], vec![(1, true)]], + vec![vec![(1, false)], vec![(2, true)]], + vec![vec![(2, false)]], + ]; + let fitted = vec![square(-0.5, 39.5), square(8.0, 30.0), square(14.0, 24.0)]; + emit(&order, &fitted, &[None, None, None], &inks) + } + + #[test] + fn counter_in_the_page_colour_is_cut_out_of_its_glyph() { + let svg = glyph([0, 1, 0]); + // The page and the glyph, the counter a second ring of the glyph's path. + assert_eq!(elements(&svg), 2, "{svg}"); + let glyph_d = svg + .split("` is cheaper than the arcs a hole + // would need, so it is painted over. + let svg = emit(&order, &fitted, &[None, None, circle(5.0)], &[0, 1, 0]); + assert_eq!(svg.matches("`. + let svg = emit(&order, &fitted, &prims, &[0, 1, 2]); + assert_eq!(svg.matches("".to_string()); + let mut ribbons = crate::ribbons::Ribbons::default(); + ribbons + .elements + .insert(0, "".to_string()); let pal = inkvec_trace::Palette { colors: vec![], rgb: vec![], @@ -154,6 +155,7 @@ fn test_emit_color_single_face() { harmonize: true, harmonize_threshold: 0.05, use_symbols: false, + layers: false, cutout: false, no_background: false, }; @@ -283,6 +285,7 @@ fn test_emit_color_with_layers() { harmonize: true, harmonize_threshold: 0.05, use_symbols: false, + layers: false, cutout: false, no_background: false, }; diff --git a/crates/inkvec-cli/src/layers.rs b/crates/inkvec-cli/src/layers.rs new file mode 100644 index 00000000..7b3d1a00 --- /dev/null +++ b/crates/inkvec-cli/src/layers.rs @@ -0,0 +1,1324 @@ +//! Layers: each face completed behind what is painted over it. +//! +//! **The problem.** The emitter paints faces back to front, so a face's outline is only +//! seen where nothing painted later covers it. It already uses that where faces nest -- a +//! face draws its outer rings and the faces inside it paint its holes -- but not where they +//! sit side by side: there a face draws exactly what it shows, its shared edge with the +//! neighbour painted over it is written twice, and the anti-aliasing seam that leaves is +//! patched by moving it half a pixel under the neighbour ([`crate::seams`]). An artist draws +//! the lower shape whole instead: a blue rectangle with two white triangles over it, not +//! the blue that shows between them (`openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F`: 20 +//! numbers in the artist's file, 54 in the trace before this stage). +//! +//! **The theorem.** With the paint order fixed, a shape `E` drawn for a face that shows `V`, +//! under the regions `U` painted after it, leaves every visible point unchanged exactly +//! when `V ⊆ E ⊆ V ∪ U` (`docs/theory/chain-representation.md`, R4.1; in Lean, +//! `InkvecTheory.Design.Layers.painter_interval_iff`). The condition names no other face's +//! shape, so each face is completed on its own; and inside the interval the pixels do not +//! care, so the shape is the cheapest one in it: here, the one with the fewest numbers the +//! gate counts. +//! +//! Anti-aliasing adds one effect the theorem's exact areas do not have: where a completed +//! edge meets the rim of what covers it and a third paint, the edge pixel composites all +//! three (R4.1b of the chain page). The inputs are renders of the artists' own layered +//! files, which have exactly that mix wherever the artist layered (a face's disc under a +//! shading crescent that reaches its rim), so the upper bound is the exact interval `V ∪ U` +//! ([`allowed_region`], with a margin [`MARGIN`] of zero), and +//! the candidates try first to reach [`REACH`] under the cover, which keeps their edge out +//! of the cover's own anti-aliasing where there is room. +//! +//! **The method.** For every painted, opaque face with something painted over it, in the +//! paint ranks the first writing pass settled ([`crate::emit`]): +//! +//! 1. the regions: `E` the face as written now, `U` everything painted later that paints +//! opaque (faces and the strokes of [`crate::ribbons`], which go on top of everything), +//! `V = E \ U`, and the allowed region `H = V ∪ U`; +//! 2. candidate shapes, cheapest first: a circle or an ellipse through the face's own +//! boundary (the part no cover reaches), the rectangle round what it shows; and the +//! face's own rings with each run of covered segments replaced by the corner its owned +//! lines meet at, or by a chord reaching a pixel under the cover; +//! 3. each candidate is accepted only by [`check::certify_completion`], the painter-interval +//! check, and only when it writes fewer numbers than the face does now +//! ([`check::gate_count`]). +//! +//! A completed face is written from its completion and not underlapped: its edge already +//! lies under what covers it. Everything else is as before. +//! +//! **Where it sits.** Inside [`crate::emit::emit_color`], after the first writing pass (which +//! fixes the paint ranks) and before the seams: Quality mode, unless `INKVEC_COMPLETION=0`. +//! +//! Not from the literature in this form; the closest are layered vectorisers that recover +//! occluded shapes by generative inpainting (LayerPeeler, AmodalSVG; `docs/DESIGN.md` §2.4), +//! which this is not: no pixel anyone can see is invented, by the theorem. + +mod check; +mod region; +mod shape; + +use std::collections::HashMap; + +use inkvec_core::Point; +use inkvec_fit::curves::Segment; +use inkvec_fit::primitives::{PrimitiveFit, PrimitiveKind}; +use inkvec_fit::FittedPath; + +use crate::faces::FaceRings; +use crate::pathdata::{fmt_segments, ring_to_segments}; +pub(crate) use check::gate_count; +use region::{Region, Rule}; +pub(crate) use shape::{EndCap, JoinKind}; + +/// How far a completed edge first tries to reach under its cover, px: a pixel, so the +/// cover's anti-aliased pixels have the completed face under them and not the ground. +pub(crate) const REACH: f64 = 1.0; + +/// The cover shrunk by this much, px, before it bounds a completion: none, the exact +/// interval (measured against 0.5 px in phase 2 of chain R: no gain at any condition). +const MARGIN: f64 = 0.0; + +/// How far around a face the cover is read, px. +const PAD: f64 = 8.0; + +/// How far around what one run's replacement changes it is judged, px: past the reach and +/// the junction taper of the lower bound. +const WINDOW: f64 = 3.0; + +/// Whether every candidate's verdict is printed (`INKVEC_COMPLETION_DEBUG=2`; `1` prints +/// one summary line per trace). +fn trace() -> bool { + inkvec_core::env::number("INKVEC_COMPLETION_DEBUG").is_some_and(|v| v >= 2.0) +} + +/// Whether the stage runs: on, unless `INKVEC_COMPLETION=0` (the A/B switch). +pub(crate) fn enabled() -> bool { + inkvec_core::env::number("INKVEC_COMPLETION").is_none_or(|v| v != 0.0) +} + +/// A stroke painted over every face ([`crate::ribbons`]): its centrelines, width and ends. +#[derive(Clone, Debug)] +pub(crate) struct StrokeShape { + /// Centrelines, px. + pub(crate) lines: Vec, + /// Closed primitive centrelines (a stroked circle or rectangle), px. + pub(crate) prims: Vec, + /// `stroke-width`, px. + pub(crate) width: f64, + /// How open ends are drawn. + pub(crate) cap: EndCap, + /// How pieces meet. + pub(crate) join: JoinKind, +} + +/// What the stage reads, per face where indexed by face. +pub(crate) struct Input<'a> { + /// The rings of each face, as walks over shared edges. + pub(crate) order: &'a [FaceRings], + /// The fitted curve of each edge. + pub(crate) fitted: &'a [FittedPath], + /// Per edge, the primitive the whole edge fitted, when it did. + pub(crate) prims: &'a [Option], + /// Per face, the rings it draws (its outline). + pub(crate) outer: &'a [Vec], + /// Per face, the faces punched out of it. + pub(crate) holes: &'a [Vec], + /// Per face, its paint rank in the first writing pass; `None` when not painted. + pub(crate) rank: &'a [Option], + /// Per face, whether it paints opaque everywhere it paints (it can cover). + pub(crate) covers: &'a [bool], + /// Per face, whether it may be completed (opaque, written from its own rings, nothing + /// punched out of it). + pub(crate) candidate: &'a [bool], + /// Per face, the gate's count of the element it is written as now. + pub(crate) cost_now: &'a dyn Fn(usize) -> f64, + /// Strokes painted over every face. + pub(crate) strokes: &'a [StrokeShape], + /// The faces those strokes are written for: their regions in the map lie above every + /// face, though the stroke drawn for one may be narrower than its region. + pub(crate) stroke_faces: &'a [usize], + /// Decimals per written coordinate. + pub(crate) decimals: usize, + /// The image's frame, `(x0, y0, x1, y1)` in the faces' coordinates, when known: no + /// completion may fill it ([`CANVAS_NEAR`]). + pub(crate) canvas: Option<(f64, f64, f64, f64)>, +} + +/// How close to the canvas's edge, as a share of its side, a completed shape counts as +/// filling it ([`complete_face`] refuses those): 2 %, so a logo that touches the frame on one +/// side and comes within a few pixels of it on the others is not made the page. +const CANVAS_NEAR: f64 = 0.02; + +/// Whether every ring face `f` draws is one edge fitted by a primitive. +fn is_primitive_face(inp: &Input, f: usize) -> bool { + let Some(rings) = inp.order.get(f) else { + return false; + }; + let outer = &inp.outer[f]; + !outer.is_empty() + && outer.iter().all(|&k| { + let ring = &rings[k]; + ring.len() == 1 && inp.prims.get(ring[0].0).and_then(|p| p.as_ref()).is_some() + }) +} + +/// A completed face's new shape. +#[derive(Clone, Debug)] +pub(crate) enum Shape { + /// One primitive element. + Prim(PrimitiveKind), + /// Path data. + Path(String), +} + +/// One face's completion, with the gate's count before and after. +#[derive(Clone, Debug)] +pub(crate) struct Completion { + pub(crate) shape: Shape, + pub(crate) before: f64, + pub(crate) after: f64, + /// Which candidate won: `circle`, `ellipse`, `rect`, or for a path the replacements its + /// runs took (`corner`, `corner-cut`, `chord`, `offset`, `bulge`, `bridge`), joined by `+`. + pub(crate) kind: String, +} + +/// The region a face is written as now: its outline rings, its punched holes cut out. +fn face_region(inp: &Input, f: usize) -> Region { + let mut polys = face_rings(inp, f); + for &c in &inp.holes[f] { + polys.extend(face_rings(inp, c)); + } + Region::from_polygons(&polys, Rule::EvenOdd) +} + +/// The region a face holds in the map: every ring of it by parity, so the faces nested in it +/// are not part of it (as against [`face_region`], what it is drawn as). +fn map_region(inp: &Input, f: usize) -> Region { + let n = inp.order.get(f).map_or(0, Vec::len); + Region::from_polygons(&rings_of(inp, f, 0..n), Rule::EvenOdd) +} + +/// The closed polygons of a face's outline rings. +fn face_rings(inp: &Input, f: usize) -> Vec> { + rings_of(inp, f, inp.outer[f].iter().copied()) +} + +/// The closed polygons of rings `ks` of face `f`. +fn rings_of(inp: &Input, f: usize, ks: impl Iterator) -> Vec> { + let Some(rings) = inp.order.get(f) else { + return Vec::new(); + }; + ks.filter(|&k| k < rings.len()) + .filter_map(|k| { + let ring = &rings[k]; + if ring.len() == 1 { + if let Some(pf) = inp.prims.get(ring[0].0).and_then(|p| p.as_ref()) { + return Some(shape::flatten_primitive(&pf.kind)); + } + } + let (start, segs) = ring_to_segments(ring, inp.fitted); + if segs.is_empty() { + return None; + } + let mut pts = shape::flatten_path(&FittedPath { + start, + segments: segs, + closed: true, + }); + if pts.len() > 1 && pts.first() == pts.last() { + pts.pop(); + } + (pts.len() >= 3).then_some(pts) + }) + .collect() +} + +/// Everything the strokes paint. +fn stroke_cover(strokes: &[StrokeShape]) -> Region { + let mut all = Region::empty(); + for s in strokes { + let mut band = shape::stroke_band(&s.lines, s.width, s.cap, s.join); + for p in &s.prims { + let mut pts = shape::flatten_primitive(p); + if let Some(&first) = pts.first() { + pts.push(first); + } + let path = FittedPath { + start: pts[0], + segments: pts[1..].iter().map(|&q| Segment::Line(q)).collect(), + closed: true, + }; + band = band.union(&shape::stroke_band( + &[path], + s.width, + s.cap, + JoinKind::Round, + )); + } + all = all.union(&band); + } + all +} + +/// How far a completion must reach under its cover wherever the face meets it, px: the +/// half pixel the underlap of [`crate::seams`] reaches, so a completed face, which the +/// underlap no longer moves, keeps the ground out of the cover's anti-aliased edge. +pub(crate) const UNDER: f64 = 0.5; + +/// Over how many pixels from a junction the reach under the cover ramps up to [`UNDER`]: +/// where the face, its cover and a third paint meet, the reach tapers to nothing, as the +/// underlap's does over the same distance (`crate::seams`'s taper). +const TAPER: f64 = 12.0; + +/// Steps of the ramp in [`required_region`]. +const RAMP: usize = 4; + +/// The region a completion of a face that shows `v` must cover: what it shows, and the +/// cover `u` within [`UNDER`] of it, the reach ramping from nothing at a third paint to +/// [`UNDER`] at [`TAPER`] from it (in [`RAMP`] steps). The lower end of the interval, +/// raised from `V` so that no completion opens a seam where the face meets what is painted +/// over it, and no higher than the underlap it replaces. +pub(crate) fn required_region(v: &Region, u: &Region) -> Region { + let third = v.dilate(UNDER).minus(v).minus(u); + let mut need = v.clone(); + for k in 1..=RAMP { + let s = k as f64 / RAMP as f64; + let reach = v.dilate(UNDER * s).intersect(u); + need = need.union(&reach.minus(&third.dilate(TAPER * s))); + } + need +} + +/// The region a completion of a face that shows `v` may reach: what it shows and the cover +/// `u`, `V ∪ U` (the face as written now lies in it). With a margin `m > 0`, the cover only +/// where it is at least `m` from a third paint: `V ∪ (V ∪ U) ⊖ m`. Shrinking `V ∪ U` and +/// not `U` alone keeps the boundary between the face and its cover inside, so a completion +/// may run along it. +pub(crate) fn allowed_region(e_now: &Region, v: &Region, u: &Region, m: f64) -> Region { + if m <= 0.0 { + return e_now.union(u).union(v); + } + v.union(&e_now.union(u).erode(m)) +} + +/// Completes every face it can; returns the completed faces. +#[cfg(test)] +pub(crate) fn complete(inp: &Input) -> HashMap { + complete_report(inp).0 +} + +/// [`complete`], and the faces it tried: those with something painted over them that were +/// candidates. A tried face missing from the completions was refused (no candidate was +/// cheaper and certified). +pub(crate) fn complete_report(inp: &Input) -> (HashMap, Vec) { + let n = inp.order.len(); + let mut out = HashMap::new(); + let mut tried = Vec::new(); + let mut painted: Vec = (0..n) + .filter(|&f| inp.rank.get(f).copied().flatten().is_some()) + .collect(); + if painted.is_empty() { + return (out, tried); + } + // From the top down, with the running union of everything above. + painted.sort_by_key(|&f| std::cmp::Reverse(inp.rank[f])); + let regions: HashMap = + painted.iter().map(|&f| (f, face_region(inp, f))).collect(); + let mut above = stroke_cover(inp.strokes); + // What the faces above cover in the map, as against what they paint (`above`): where + // the two differ next to a face, its underlap painted the gap, and so must its completion. + let mut map_above = inp + .stroke_faces + .iter() + .fold(Region::empty(), |acc, &s| acc.union(&map_region(inp, s))); + // Every painted face's region in the map, to tell a seam only one face borders from one + // at a junction. + let maps: HashMap = painted.iter().map(|&f| (f, map_region(inp, f))).collect(); + let all_faces = maps.values().fold(Region::empty(), |acc, r| acc.union(r)); + let mut i = 0; + while i < painted.len() { + let r = inp.rank[painted[i]]; + let mut j = i; + while j < painted.len() && inp.rank[painted[j]] == r { + j += 1; + } + for &f in &painted[i..j] { + if inp.candidate.get(f).copied().unwrap_or(false) { + if let Some(attempt) = + complete_face(inp, f, ®ions[&f], &above, &map_above, &all_faces) + { + tried.push(f); + if let Some(c) = attempt { + out.insert(f, c); + } + } + } + } + for &f in &painted[i..j] { + if inp.covers.get(f).copied().unwrap_or(false) { + above = above.union(®ions[&f]); + map_above = map_above.union(&maps[&f]); + } + } + i = j; + } + (out, tried) +} + +/// The cheapest certified completion of face `f`, written now as `e_now`, under `above`. +fn complete_face( + inp: &Input, + f: usize, + e_now: &Region, + above: &Region, + map_above: &Region, + all_faces: &Region, +) -> Option> { + let (x0, y0, x1, y1) = e_now.bbox()?; + let u = above.crop(x0 - PAD, y0 - PAD, x1 + PAD, y1 + PAD); + if u.is_empty() || e_now.dilate(0.75).intersect(&u).area() < 0.5 { + return None; + } + // What the face shows: its own region outside the cover, and the seam between its region + // and a cover drawn narrower than the face above's region in the map, where the face's + // underlap paints it today. As the underlap does, the reach into the seam tapers off + // towards any other face over [`TAPER`]: at a junction of three paints, nothing. + let crop = (x0 - PAD, y0 - PAD, x1 + PAD, y1 + PAD); + let seam = map_above + .crop(crop.0, crop.1, crop.2, crop.3) + .minus(&u) + .minus(e_now); + let others = all_faces + .crop( + crop.0 - TAPER, + crop.1 - TAPER, + crop.2 + TAPER, + crop.3 + TAPER, + ) + .minus(e_now) + .minus(map_above); + let v0 = e_now.minus(&u); + let mut gap = Region::empty(); + if !seam.is_empty() { + for k in 1..=RAMP { + let s = k as f64 / RAMP as f64; + let reach = e_now.dilate(UNDER * s).intersect(&seam); + gap = gap.union(&reach.minus(&others.dilate(TAPER * s))); + } + } + if trace() && !gap.is_empty() { + eprintln!( + "layers face {f}: seam gap area {:.3} box {:?}; others empty {}", + gap.area(), + gap.bbox(), + others.is_empty() + ); + } + let v = v0.union(&gap); + if v.area() < 1.0 { + return None; + } + let h = allowed_region(e_now, &v, &u, MARGIN); + let l = required_region(&v, &u); + let hb = h.bbox()?; + let before = (inp.cost_now)(f); + let mut best: Option = None; + // A face written as a primitive gets no underlap, so a tie buys it nothing. + let prim_now = is_primitive_face(inp, f); + // Never the whole canvas: a face completed to the frame becomes the page, and which face + // is the page (and whether the artist drew one at all) is the emitter's decision, not a + // completion's. On an opaque intake a logo touching the frame was otherwise completed to + // a black canvas with the white page painted over it in pieces. + let canvas = inp.canvas; + let fills_canvas = |region: &Region| -> bool { + match (canvas, region.bbox()) { + (Some(c), Some(r)) => { + let near = CANVAS_NEAR * (c.2 - c.0).max(c.3 - c.1); + r.0 <= c.0 + near && r.1 <= c.1 + near && r.2 >= c.2 - near && r.3 >= c.3 - near + } + _ => false, + } + }; + let mut consider = |shape: Shape, kind: &str, after: f64, allow: f64, region: &Region| { + // Never more than the face writes now. A tie is kept: the completed face reaches under + // its cover and is spared the underlap, which only adds numbers. + if after > before + allow + || (prim_now && after >= before) + || best.as_ref().is_some_and(|b| b.after <= after) + || fills_canvas(region) + { + return; + } + // The solver proposes only what its own measure passes; the checker decides. + let m = check::measure(&l, region, &h); + let certified = m.holds() && check::certify_completion(&l, region, &h); + if trace() { + eprintln!( + "layers face {f}: {} -> {after}: lost {:.3} spilled {:.3} certified {certified}", + match &shape { + Shape::Prim(k) => format!("{k:?}").chars().take(140).collect::(), + Shape::Path(_) => "path".to_string(), + }, + m.lost, + m.spilled + ); + } + if certified { + best = Some(Completion { + shape, + before, + after, + kind: kind.to_string(), + }); + } + }; + + // Primitives through the boundary the face owns. + let owned = owned_points(inp, f, &u); + if owned.len() >= 8 { + let sigma = vec![0.05; owned.len()]; + if let Some(c) = inkvec_fit::primitives::fit_circle(&owned, &sigma) { + for e in [REACH, 0.5, 0.0] { + let kind = PrimitiveKind::Circle { c: c.c, r: c.r + e }; + if let Some(reg) = bounded_region(&[shape::flatten_primitive(&kind)], hb) { + consider(Shape::Prim(kind), "circle", 3.0, 0.0, ®); + } + } + } + if let Some(el) = inkvec_fit::primitives::fit_ellipse(&owned, &sigma) { + for e in [REACH, 0.5, 0.0] { + let kind = PrimitiveKind::Ellipse { + c: el.c, + rx: el.rx + e, + ry: el.ry + e, + angle: el.angle, + }; + if let Some(reg) = bounded_region(&[shape::flatten_primitive(&kind)], hb) { + consider(Shape::Prim(kind), "ellipse", 4.0, 0.0, ®); + } + } + } + } + // The rectangle round what the face shows. A region's box is exact across a scan line + // but known along it only to a line's spacing, so first each side is put on the face's + // own geometry when a vertex lies that close, then on the box as sampled. + // The box of the lower bound comes first: what the face shows with its reach under the + // cover, and nothing round the sides that meet no cover. + let pts: Vec = face_rings(inp, f).into_iter().flatten().collect(); + let snap = |t: f64, of: fn(&Point) -> f64| -> f64 { + pts.iter() + .map(of) + .filter(|q| (q - t).abs() <= region::DY) + .min_by(|a, b| (a - t).abs().total_cmp(&(b - t).abs())) + .unwrap_or(t) + }; + for (b, grow) in [(l.bbox(), &[0.0][..]), (v.bbox(), &[REACH, 0.5, 0.0][..])] { + let Some((bx0, by0, bx1, by1)) = b else { + continue; + }; + let snapped = ( + snap(bx0, |q| q.x), + snap(by0, |q| q.y), + snap(bx1, |q| q.x), + snap(by1, |q| q.y), + ); + for (vx0, vy0, vx1, vy1) in [snapped, (bx0, by0, bx1, by1)] { + for &e in grow { + let kind = PrimitiveKind::RoundRect { + x: vx0 - e, + y: vy0 - e, + w: vx1 - vx0 + 2.0 * e, + h: vy1 - vy0 + 2.0 * e, + rx: 0.0, + }; + if let Some(reg) = bounded_region(&[shape::flatten_primitive(&kind)], hb) { + consider(Shape::Prim(kind), "rect", 6.0, 0.0, ®); + } + } + } + } + // The face's own rings with the covered runs replaced. + let simplified = simplified_rings(inp, f, e_now, &u, &l, &h, hb); + if let Some((d, reg, allow, kinds)) = &simplified { + consider(Shape::Path(d.clone()), kinds, gate_count(d), *allow, reg); + } + if inkvec_core::env::number("INKVEC_COMPLETION_DUMP").is_some_and(|x| x as usize == f) { + dump( + f, + &[ + (&u, [90, 90, 200]), + (&v, [200, 200, 90]), + (&l.minus(&v), [90, 200, 90]), + ], + simplified.as_ref().map(|s| &s.1), + (x0 - PAD, y0 - PAD, x1 + PAD, y1 + PAD), + ); + } + Some(best) +} + +/// Debugging (`INKVEC_COMPLETION_DUMP=`): the regions as colours, the candidate's edge in +/// red, eight pixels per pixel, written to `layers-.ppm` in the working directory. +fn dump(f: usize, layers: &[(&Region, [u8; 3])], cand: Option<&Region>, b: (f64, f64, f64, f64)) { + const S: f64 = 8.0; + let (w, h) = ( + ((b.2 - b.0) * S) as usize + 1, + ((b.3 - b.1) * S) as usize + 1, + ); + if w * h > 40_000_000 { + return; + } + let mut img = vec![[255u8, 255, 255]; w * h]; + let inside = |r: &Region, x: f64, y: f64| r.contains(Point::new(x, y)); + for py in 0..h { + for px in 0..w { + let (x, y) = (b.0 + px as f64 / S, b.1 + py as f64 / S); + for (r, c) in layers { + if inside(r, x, y) { + img[py * w + px] = *c; + } + } + if let Some(c) = cand { + let here = inside(c, x, y); + let right = inside(c, x + 1.0 / S, y); + let down = inside(c, x, y + 1.0 / S); + if here != right || here != down { + img[py * w + px] = [220, 30, 30]; + } + } + } + } + let mut out = format!("P6\n{w} {h}\n255\n").into_bytes(); + out.extend(img.iter().flatten()); + let _ = std::fs::write(format!("layers-{f}.ppm"), out); +} + +/// The region of `polys`, or `None` when they leave the box `hb` (the allowed region's) by +/// more than the check's slack: such a shape spills for certain, and a primitive fitted to +/// nearly straight points can be large enough to exhaust memory as a region. +fn bounded_region(polys: &[Vec], hb: (f64, f64, f64, f64)) -> Option { + let s = check::LINE_SLACK + region::DY; + let inside = polys.iter().flatten().all(|p| { + p.x.is_finite() + && p.y.is_finite() + && p.x >= hb.0 - s + && p.x <= hb.2 + s + && p.y >= hb.1 - s + && p.y <= hb.3 + s + }); + inside.then(|| Region::from_polygons(polys, Rule::EvenOdd)) +} + +/// Points of the face's outline that no cover reaches within [`REACH`]: the boundary it +/// owns, through which a primitive completion must pass. +fn owned_points(inp: &Input, f: usize, u: &Region) -> Vec { + let near = u.dilate(REACH); + let mut pts: Vec = face_rings(inp, f) + .into_iter() + .flatten() + .filter(|&p| !near.contains(p)) + .collect(); + // Evenly thinned, so a long straight run does not outweigh a curved one. + if pts.len() > 400 { + let step = pts.len() as f64 / 400.0; + pts = (0..400).map(|i| pts[(i as f64 * step) as usize]).collect(); + } + pts +} + +/// One replacement of a run: the ring with it, the allowance it spends (numbers the +/// underlap would have added), and what kind of replacement it is. +type Option3 = (CycRing, f64, &'static str); + +/// A ring as cyclic vertices and the segment leaving each one. +#[derive(Clone)] +struct CycRing { + verts: Vec, + segs: Vec, + /// Covered by something painted over the face, and not yet tried. + covered: Vec, +} + +impl CycRing { + fn len(&self) -> usize { + self.verts.len() + } + + /// The segment leaving vertex `i`, re-targeted to end at vertex `i + 1`. + fn seg(&self, i: usize) -> Segment { + let to = self.verts[(i + 1) % self.len()]; + match self.segs[i] { + Segment::Line(_) => Segment::Line(to), + Segment::Cubic(a, b, _) => Segment::Cubic(a, b, to), + Segment::Arc { + rx, + ry, + phi, + large_arc, + sweep, + .. + } => Segment::Arc { + rx, + ry, + phi, + large_arc, + sweep, + end: to, + }, + } + } + + fn polygon(&self) -> Vec { + let mut pts = Vec::new(); + for i in 0..self.len() { + if i == 0 { + pts.push(self.verts[0]); + } + shape::flatten_segment(self.verts[i], &self.seg(i), &mut pts); + } + if pts.len() > 1 && pts.first() == pts.last() { + pts.pop(); + } + pts + } + + /// Path data, closed by `Z`: a final line back to the start is left to the `Z`. + fn d(&self, decimals: usize, out: &mut String) { + let mut segs: Vec = (0..self.len()).map(|i| self.seg(i)).collect(); + if matches!(segs.last(), Some(Segment::Line(_))) { + segs.pop(); + } + fmt_segments(self.verts[0], &segs, decimals, out); + } +} + +/// The face's outline rings with each run of covered segments replaced by a cheaper piece +/// that keeps the face within its interval: the corner its owned neighbours meet at, else a +/// chord a margin under the cover, else a chord at the run's ends. Each replacement is kept +/// only when the whole face still passes the check. `None` when no ring changed, or when a +/// ring is a primitive. +fn simplified_rings( + inp: &Input, + f: usize, + e_now: &Region, + u: &Region, + v: &Region, + h: &Region, + hb: (f64, f64, f64, f64), +) -> Option<(String, Region, f64, String)> { + let rings = inp.order.get(f)?; + let mut cyc: Vec = Vec::new(); + for &k in &inp.outer[f] { + let ring = &rings[k]; + if ring.len() == 1 && inp.prims.get(ring[0].0).and_then(|p| p.as_ref()).is_some() { + return None; + } + let (start, mut segs) = ring_to_segments(ring, inp.fitted); + if segs.len() < 2 { + return None; + } + if segs.last().map(|s| s.end().dist(start)).unwrap_or(0.0) > 1e-6 { + segs.push(Segment::Line(start)); + } + let mut verts = vec![start]; + for s in &segs[..segs.len() - 1] { + verts.push(s.end()); + } + let covered = (0..segs.len()) + .map(|i| segment_covered(verts[i], &segs[i], e_now, u)) + .collect(); + cyc.push(CycRing { + verts, + segs, + covered, + }); + } + let region_of = |cyc: &[CycRing]| -> Option { + let polys: Vec> = cyc.iter().map(CycRing::polygon).collect(); + bounded_region(&polys, hb) + }; + // Each run is judged in a window round what it changes: the face's other runs still lie + // on their cover's edge until their own turn, and would fail the reach of the lower + // bound anywhere. The whole face is certified once at the end, by the caller. + let mut changed = false; + let mut allowance = 0.0; + let mut kinds: Vec<&'static str> = Vec::new(); + let mut current = region_of(&cyc)?; + for r in 0..cyc.len() { + loop { + let Some((a, b)) = next_run(&cyc[r]) else { + break; + }; + // Whatever happens, this run has been tried; the options inherit that, so one + // that keeps some of the run's segments does not hand them back untried. + mark_tried(&mut cyc[r], a, b); + let mut options = corner_cuts(&cyc[r], a, b); + options.extend(replacements(&cyc[r], a, b, e_now)); + options.extend(bridges(&cyc[r], a, b)); + options.extend(offset_run(&cyc[r], a, b, e_now).map(|o| (o, 0.0, "offset"))); + // The lower bound along this run: the band round its own geometry. The face's + // other runs keep their own reach to meet, in their own turn. + let band = run_band(&cyc[r], a, b); + let need = v.intersect(&band); + for (opt, extra, what) in options { + let mut trial = cyc.clone(); + trial[r] = opt; + let Some(reg) = region_of(&trial) else { + continue; + }; + let Some((wx0, wy0, wx1, wy1)) = + reg.minus(¤t).union(¤t.minus(®)).bbox() + else { + continue; + }; + let w = WINDOW; + let crop = |x: &Region| x.crop(wx0 - w, wy0 - w, wx1 + w, wy1 + w); + let verdict = check::Interval { + lost: need.minus(®).widest_line(), + spilled: crop(®).minus(&crop(h)).widest_line(), + }; + if trace() { + eprintln!( + "layers face {f} ring {r} run {a}..={b}: lost {:.3} spilled {:.3}", + verdict.lost, verdict.spilled + ); + } + if verdict.holds() { + cyc = trial; + current = reg; + allowance += extra; + changed = true; + if !kinds.iter().any(|k| *k == what) { + kinds.push(what); + } + break; + } + } + } + } + if !changed { + return None; + } + let mut d = String::new(); + for c in &cyc { + c.d(inp.decimals, &mut d); + } + Some((d, region_of(&cyc)?, allowance, kinds.join("+"))) +} + +/// The band round run `a ..= b` of a ring: its own geometry widened by the reach and a scan +/// line, square at its ends. +fn run_band(c: &CycRing, a: usize, b: usize) -> Region { + let n = c.len(); + let mut pts = vec![c.verts[a]]; + let mut i = a; + loop { + shape::flatten_segment(c.verts[i], &c.seg(i), &mut pts); + if i == b { + break; + } + i = (i + 1) % n; + } + let path = FittedPath { + start: pts[0], + segments: pts[1..].iter().map(|&p| Segment::Line(p)).collect(), + closed: false, + }; + shape::stroke_band( + &[path], + 2.0 * (UNDER + region::DY), + EndCap::Butt, + JoinKind::Round, + ) +} + +/// Run `a ..= b` moved [`UNDER`] under its cover, its ends kept: every interior vertex along +/// its outward normal, every cubic control point along its segment's. The underlap of +/// [`crate::seams`], done inside the completion, for a run nothing cheaper can replace. The +/// same segments, so the same numbers. `None` when the run holds an arc or nothing moves. +fn offset_run(c: &CycRing, a: usize, b: usize, e_now: &Region) -> Option { + let n = c.len(); + let outward = |p: Point, q: Point| -> Option { + let d = unit(Point::new(q.x - p.x, q.y - p.y))?; + let nrm = Point::new(-d.y, d.x); + let mid = Point::new(0.5 * (p.x + q.x), 0.5 * (p.y + q.y)); + let probe = Point::new(mid.x + 0.35 * nrm.x, mid.y + 0.35 * nrm.y); + Some(if e_now.contains(probe) { + Point::new(-nrm.x, -nrm.y) + } else { + nrm + }) + }; + let mut out = c.clone(); + let mut moved = false; + let mut i = a; + loop { + let (p, q) = (c.verts[i], c.verts[(i + 1) % n]); + match c.segs[i] { + Segment::Arc { .. } => return None, + Segment::Cubic(c1, c2, e) => { + let nrm = outward(p, q)?; + let mv = |x: Point| Point::new(x.x + UNDER * nrm.x, x.y + UNDER * nrm.y); + out.segs[i] = Segment::Cubic(mv(c1), mv(c2), e); + moved = true; + } + Segment::Line(_) => {} + } + if i == b { + break; + } + // The vertex between segment i and segment i + 1 is interior to the run. + let j = (i + 1) % n; + let (n0, n1) = (outward(p, q), outward(q, c.verts[(j + 1) % n])); + if let (Some(n0), Some(n1)) = (n0, n1) { + if let Some(m) = unit(Point::new(n0.x + n1.x, n0.y + n1.y)) { + out.verts[j] = Point::new(q.x + UNDER * m.x, q.y + UNDER * m.y); + moved = true; + } + } + i = j; + } + moved.then_some(out) +} + +/// Whether segment `seg` from `a` lies along a cover: at its quarter points, the point a +/// third of a pixel off it on the side away from the face is under the cover. +fn segment_covered(a: Point, seg: &Segment, e_now: &Region, u: &Region) -> bool { + let at = |t: f64| -> (Point, Point) { + let p = point_on(a, seg, t); + let q = point_on(a, seg, (t + 0.01).min(1.0)); + let o = point_on(a, seg, (t - 0.01).max(0.0)); + (p, Point::new(q.x - o.x, q.y - o.y)) + }; + [0.25, 0.5, 0.75].iter().all(|&t| { + let (p, d) = at(t); + let l = d.x.hypot(d.y); + if l < 1e-12 { + return false; + } + let n = Point::new(-d.y / l * 0.35, d.x / l * 0.35); + let (p1, p2) = ( + Point::new(p.x + n.x, p.y + n.y), + Point::new(p.x - n.x, p.y - n.y), + ); + let (in1, in2) = (e_now.contains(p1), e_now.contains(p2)); + match (in1, in2) { + (true, false) => u.contains(p2), + (false, true) => u.contains(p1), + _ => false, + } + }) +} + +/// The point at parameter `t` of segment `seg` starting at `a`. +fn point_on(a: Point, seg: &Segment, t: f64) -> Point { + match *seg { + Segment::Line(p) => Point::new(a.x + t * (p.x - a.x), a.y + t * (p.y - a.y)), + Segment::Cubic(c1, c2, p) => inkvec_fit::curves::eval_cubic([a, c1, c2, p], t), + Segment::Arc { + rx, + ry, + phi, + large_arc, + sweep, + end, + } => { + let f = inkvec_fit::curves::arc_ellipse_center(a, rx, ry, phi, large_arc, sweep, end); + f.at(f.theta1 + f.delta * t) + } + } +} + +/// The first run of covered, untried segments `a ..= b` (cyclic indices), with an +/// uncovered segment before it. `None` when there is none, or when every segment is +/// covered (a primitive completion's case). +fn next_run(c: &CycRing) -> Option<(usize, usize)> { + let n = c.len(); + if c.covered.iter().all(|&x| x) { + return None; + } + // Start the scan just after an uncovered segment, so no run wraps unseen. + let s0 = c.covered.iter().position(|&x| !x)?; + for o in 1..=n { + let i = (s0 + o) % n; + if c.covered[i] { + let mut b = i; + while c.covered[(b + 1) % n] && (b + 1) % n != i { + b = (b + 1) % n; + } + return Some((i, b)); + } + } + None +} + +/// Marks segments `a ..= b` tried. +fn mark_tried(c: &mut CycRing, a: usize, b: usize) { + let n = c.len(); + let mut i = a; + loop { + c.covered[i] = false; + if i == b { + break; + } + i = (i + 1) % n; + } +} + +/// The rings with run `a ..= b` replaced, best first: the corner of the owned lines on +/// either side, then a chord reaching [`REACH`] and half that under the cover, then a +/// plain chord. Only replacements that write fewer numbers than the run. +fn replacements(c: &CycRing, a: usize, b: usize, e_now: &Region) -> Vec { + let n = c.len(); + let run_len = if b >= a { b - a + 1 } else { b + n - a + 1 }; + if run_len >= n { + return Vec::new(); + } + let run_cost: f64 = (0..run_len).map(|o| c.seg((a + o) % n).params()).sum(); + let prev = (a + n - 1) % n; // owned segment ending at vertex a + let next = (b + 1) % n; // owned segment starting at vertex b + 1 + let va = c.verts[a]; + let vb = c.verts[next]; + let mut out = Vec::new(); + + // Removes the run's interior vertices a+1 ..= b and its segments, splicing `insert` + // (vertices, each followed by a line) after vertex a, which becomes `new_a`. + let splice = |new_a: Point, mid: &[Point], new_b: Point| -> CycRing { + let mut verts = Vec::new(); + let mut segs = Vec::new(); + let mut covered = Vec::new(); + // Walk from `next` round to `prev`, then the replacement. + let mut i = next; + loop { + verts.push(if i == next { new_b } else { c.verts[i] }); + segs.push(c.segs[i].clone()); + covered.push(c.covered[i]); + if i == prev { + break; + } + i = (i + 1) % n; + } + // Vertex a (moved) and the replacement's own vertices, joined by lines. + verts.push(new_a); + segs.push(Segment::Line(Point::new(0.0, 0.0))); + covered.push(false); + for &m in mid { + verts.push(m); + segs.push(Segment::Line(Point::new(0.0, 0.0))); + covered.push(false); + } + // The last pushed line runs to `new_b`, the first vertex. + CycRing { + verts, + segs, + covered, + } + }; + + let is_line = |i: usize| matches!(c.segs[i], Segment::Line(_)); + // 1. The corner where the owned lines on either side meet. + if is_line(prev) && is_line(next) && prev != next { + let p0 = c.verts[prev]; + let q1 = c.verts[(next + 1) % n]; + if let Some((x, s, t)) = intersect(p0, va, vb, q1) { + // Beyond `va` along the incoming line and before `vb` along the outgoing one. + if s > 1.0 && t < 0.0 { + // The corner replaces both va and vb: the incoming line now ends at x and + // the outgoing one starts there. Encoded as a zero-length line from x to x, + // dropped below. + let mut r = splice(x, &[], x); + // `splice` put x first (as new_b) and last (as new_a), joined by a line of + // zero length: drop that last vertex. + r.verts.pop(); + r.segs.pop(); + r.covered.pop(); + if run_cost > 0.0 { + out.push((r, 0.0, "corner")); + } + } + } + } + // 2. A chord a margin under the cover, the owned lines extended to reach it; 3. a plain + // chord between the run's ends. + for d in [REACH, 0.5 * REACH, 0.0] { + // A plain chord over one line is that line. + if d == 0.0 && run_len == 1 && matches!(c.segs[a], Segment::Line(_)) { + continue; + } + let ta = tangent_at_end(c, prev); + let tb = tangent_at_start(c, next); + let (Some(ta), Some(tb)) = (ta, tb) else { + continue; + }; + let new_a = Point::new(va.x + d * ta.x, va.y + d * ta.y); + let new_b = Point::new(vb.x - d * tb.x, vb.y - d * tb.y); + // A line's end moves with its vertex; a curve keeps its end and gains a line. + let mut mid = Vec::new(); + let a_vertex = if d > 0.0 && !is_line(prev) { + mid.push(new_a); + va + } else { + new_a + }; + let b_vertex = if d > 0.0 && !is_line(next) { + mid.push(new_b); + vb + } else { + new_b + }; + let r = splice(a_vertex, &mid, b_vertex); + let new_cost: f64 = 2.0 * (mid.len() + 1) as f64; + // No more than the run: a chord that costs what the run did still pays, because the + // face then reaches under its cover and needs no underlap ([`crate::seams`]), which + // adds vertices. + if new_cost <= run_cost { + out.push((r, 0.0, "chord")); + } + } + // 4. A straight run that continues its owned neighbours cannot be reached under by a + // chord: bulge it under the cover by [`UNDER`], with one vertex at its middle or two + // a taper in from its ends -- what the underlap would add, and charged as such (the + // second number is the allowance it spends). + if run_len == 1 && is_line(a) { + let len = va.dist(vb); + if let (Some(dir), Some(nrm)) = ( + unit(Point::new(vb.x - va.x, vb.y - va.y)), + outward_normal(va, vb, e_now), + ) { + let at = |t: f64| { + Point::new( + va.x + t * dir.x + UNDER * nrm.x, + va.y + t * dir.y + UNDER * nrm.y, + ) + }; + out.push((splice(va, &[at(0.5 * len)], vb), 2.0, "bulge")); + let t = TAPER.min(len / 3.0); + if len > 2.0 * t { + out.push((splice(va, &[at(t), at(len - t)], vb), 4.0, "bulge")); + } + } + } + out +} + +/// Corners a blur cut off, restored under the cover: each segment `k` of run `a ..= b` +/// between two lines is dropped, and the lines extended to meet, when they meet beyond the +/// end of the incoming one and before the start of the outgoing one. At an acute corner a +/// blur (anti-aliasing, a resampling filter, a lossy codec's) removes the tip, and the fit +/// writes the chamfer it leaves as one more segment; under a cover nobody can see the tip, +/// so the face takes the artist's corner back for free. First every such cut at once, then +/// each alone; each writes the numbers of the segments it drops fewer. +fn corner_cuts(c: &CycRing, a: usize, b: usize) -> Vec { + let n = c.len(); + let run_len = if b >= a { b - a + 1 } else { b + n - a + 1 }; + // The run's segments, by the vertex each starts at (indices shift as cuts are made). + let starts: Vec = (0..run_len).map(|o| c.verts[(a + o) % n]).collect(); + let mut out = Vec::new(); + let mut all = c.clone(); + let mut cuts = 0; + for &p in &starts { + let Some(k) = all.verts.iter().position(|&q| q == p) else { + continue; + }; + if let Some(cut) = cut_corner(&all, k) { + all = cut; + cuts += 1; + } + } + if cuts > 1 { + out.push((all, 0.0, "corner-cut")); + } + for o in 0..run_len { + if let Some(cut) = cut_corner(c, (a + o) % n) { + out.push((cut, 0.0, "corner-cut")); + } + } + out +} + +/// One G1 cubic across run `a ..= b`, leaving its start along the incoming segment and +/// arriving at its end along the outgoing one: the boundary continued smoothly under the +/// cover between the two points where it goes under. The arms are tried as the circular +/// arc between the two tangents would set them, longer and shorter, and as the cubics whose +/// area and first moment match the run as it is now (`fit_cubic_moments`, the cubic that +/// hugs the cover's edge). Only when it writes no more numbers than the run. +fn bridges(c: &CycRing, a: usize, b: usize) -> Vec { + let n = c.len(); + let run_len = if b >= a { b - a + 1 } else { b + n - a + 1 }; + if run_len >= n { + return Vec::new(); + } + let run_cost: f64 = (0..run_len).map(|o| c.seg((a + o) % n).params()).sum(); + if run_cost < 6.0 { + return Vec::new(); + } + let prev = (a + n - 1) % n; + let next = (b + 1) % n; + let (Some(ta), Some(tb)) = (tangent_at_end(c, prev), tangent_at_start(c, next)) else { + return Vec::new(); + }; + let va = c.verts[a]; + let vb = c.verts[next]; + let chord = va.dist(vb); + if chord < 1e-6 { + return Vec::new(); + } + // The turn between the two tangents, and the circular arc's arm for it. + let turn = (ta.x * tb.y - ta.y * tb.x) + .atan2(ta.x * tb.x + ta.y * tb.y) + .abs(); + let arm = if turn < 1e-6 { + chord / 3.0 + } else { + chord * (2.0 / 3.0) * (turn / 4.0).tan() / (turn / 2.0).sin() + }; + let mut arms: Vec<(f64, f64)> = [1.0, 1.25, 0.8, 1.5] + .iter() + .map(|k| (k * arm, k * arm)) + .collect(); + // The cubics with the run's own area and first moment. + let mut pts = vec![va]; + let mut i = a; + loop { + shape::flatten_segment(c.verts[i], &c.seg(i), &mut pts); + if i == b { + break; + } + i = (i + 1) % n; + } + let to_vec = |p: Point| inkvec_core::Vec2 { x: p.x, y: p.y }; + for (c1, c2) in inkvec_fit::multimodel::fit_cubic_moments(&pts, to_vec(ta), to_vec(tb)) { + arms.push((c1.dist(va), c2.dist(vb))); + } + let mut out = Vec::new(); + for (d0, d1) in arms { + if !(d0.is_finite() && d1.is_finite()) + || d0 <= 0.0 + || d1 <= 0.0 + || d0 > 2.0 * chord + || d1 > 2.0 * chord + { + continue; + } + let c1 = Point::new(va.x + d0 * ta.x, va.y + d0 * ta.y); + let c2 = Point::new(vb.x - d1 * tb.x, vb.y - d1 * tb.y); + // The run's segments go; vertex a is joined to vertex b + 1 by the cubic. + let mut verts = Vec::new(); + let mut segs = Vec::new(); + let mut covered = Vec::new(); + let mut j = next; + loop { + verts.push(c.verts[j]); + segs.push(c.segs[j].clone()); + covered.push(c.covered[j]); + if j == prev { + break; + } + j = (j + 1) % n; + } + verts.push(va); + segs.push(Segment::Cubic(c1, c2, vb)); + covered.push(false); + out.push(( + CycRing { + verts, + segs, + covered, + }, + 0.0, + "bridge", + )); + } + out +} + +/// Ring `c` with segment `k` dropped and the lines either side extended to their meeting +/// point, or `None` when either neighbour is not a line, the ring would fall below three +/// segments, or the lines do not meet ahead of the incoming one and behind the outgoing one. +fn cut_corner(c: &CycRing, k: usize) -> Option { + let n = c.len(); + if n < 4 { + return None; + } + let prev = (k + n - 1) % n; + let next = (k + 1) % n; + if !matches!(c.segs[prev], Segment::Line(_)) || !matches!(c.segs[next], Segment::Line(_)) { + return None; + } + let (p0, p1) = (c.verts[prev], c.verts[k]); + let (q0, q1) = (c.verts[next], c.verts[(next + 1) % n]); + let (x, s, t) = intersect(p0, p1, q0, q1)?; + if !(s > 1.0 && t < 0.0) { + return None; + } + let mut out = c.clone(); + // Vertex k becomes the corner; vertex k + 1 and segment k go. The segment now leaving + // vertex k is the old segment k + 1, a line re-targeted to its own end by `seg`. + out.verts[k] = x; + out.segs[k] = c.segs[next].clone(); + out.covered[k] = c.covered[next]; + out.verts.remove(next); + out.segs.remove(next); + out.covered.remove(next); + Some(out) +} + +/// The unit normal of the chord `p → q` pointing away from the face (`e_now`). +fn outward_normal(p: Point, q: Point, e_now: &Region) -> Option { + let d = unit(Point::new(q.x - p.x, q.y - p.y))?; + let nrm = Point::new(-d.y, d.x); + let mid = Point::new(0.5 * (p.x + q.x), 0.5 * (p.y + q.y)); + let probe = Point::new(mid.x + 0.35 * nrm.x, mid.y + 0.35 * nrm.y); + Some(if e_now.contains(probe) { + Point::new(-nrm.x, -nrm.y) + } else { + nrm + }) +} + +/// The unit direction a segment leaves vertex `i` in. +fn tangent_at_start(c: &CycRing, i: usize) -> Option { + let a = c.verts[i]; + let s = c.seg(i); + let q = match s { + Segment::Line(p) => p, + Segment::Cubic(c1, c2, p) => [c1, c2, p].into_iter().find(|q| q.dist(a) > 1e-9)?, + Segment::Arc { .. } => point_on(a, &s, 0.01), + }; + unit(Point::new(q.x - a.x, q.y - a.y)) +} + +/// The unit direction a segment arrives at its end in. +fn tangent_at_end(c: &CycRing, i: usize) -> Option { + let a = c.verts[i]; + let s = c.seg(i); + let e = s.end(); + let q = match s { + Segment::Line(_) => a, + Segment::Cubic(c1, c2, _) => [c2, c1, a].into_iter().find(|q| q.dist(e) > 1e-9)?, + Segment::Arc { .. } => point_on(a, &s, 0.99), + }; + unit(Point::new(e.x - q.x, e.y - q.y)) +} + +fn unit(v: Point) -> Option { + let l = v.x.hypot(v.y); + (l > 1e-12).then(|| Point::new(v.x / l, v.y / l)) +} + +/// The intersection of line `p0 → p1` with line `q0 → q1`: the point, and its parameters +/// `s` on the first (0 at `p0`, 1 at `p1`) and `t` on the second (0 at `q0`, 1 at `q1`). +fn intersect(p0: Point, p1: Point, q0: Point, q1: Point) -> Option<(Point, f64, f64)> { + let (dx, dy) = (p1.x - p0.x, p1.y - p0.y); + let (ex, ey) = (q1.x - q0.x, q1.y - q0.y); + let den = dx * ey - dy * ex; + let scale = (dx.hypot(dy) * ex.hypot(ey)).max(1e-12); + if den.abs() < 1e-6 * scale { + return None; + } + let (fx, fy) = (q0.x - p0.x, q0.y - p0.y); + let s = (fx * ey - fy * ex) / den; + let t = (fx * dy - fy * dx) / den; + Some((Point::new(p0.x + s * dx, p0.y + s * dy), s, t)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/inkvec-cli/src/layers/check.rs b/crates/inkvec-cli/src/layers/check.rs new file mode 100644 index 00000000..e83d1c69 --- /dev/null +++ b/crates/inkvec-cli/src/layers/check.rs @@ -0,0 +1,349 @@ +//! The checks a completion must pass before it is used. +//! +//! The rule of `docs/theory/verification.md`: a solver may propose anything, and a result a +//! theorem speaks about is used only when a checker accepts it, on a certificate the solver +//! emits. Here the theorem is the painter's interval (`docs/theory/chain-representation.md`, +//! R4.1; Lean: `Inkvec.Design.painter_interval_iff`): with the paint order fixed, a shape `E` +//! written for a face that shows `V`, under the regions `U` painted after it, leaves every +//! visible point of the picture unchanged exactly when `V ⊆ E ⊆ V ∪ U`. +//! +//! The check runs on the scan lines of [`super::region`]. On each line, each span of the +//! inner region must lie in a chain of consecutive spans of the outer region, each widened +//! by [`SPAN_SLACK`] at both ends, neighbours touching once widened (regions computed from +//! different polygons leave cracks of a thousandth of a pixel where they meet). The solver +//! ([`propose_cover`]) names, for every inner span, the first and last outer span of its +//! chain: the certificate. The checker ([`check_cover`]) walks every inner span itself and +//! accepts it only when the generated kernels say so: `span_within_iv` against the chain's +//! first start and last end, `span_link_iv` between neighbours, every output non-negative +//! (`inkvec_verified::generated::design`; Lean: `Inkvec.Gen.spanWithinK`, `spanLinkK`, their +//! meaning `chain_cover` and the fold over a line `line_cover`). The enclosures are outward +//! rounded, so what is accepted holds in exact arithmetic; a refusal (`None`) rejects the +//! completion and the face keeps its shape. +//! +//! What is trusted rather than checked: the scan conversion of the shapes into spans +//! ([`super::region::Region::from_polygons`], flattened within [`super::shape::FLAT_TOL`]) and +//! the region algebra that builds `V` and `U`. The containment of the spans is checked. + +use inkvec_verified::generated::design::{span_link_iv, span_within_iv}; +use inkvec_verified::iv::Iv; + +use super::region::Region; + +/// The most a scan line may show of `V` outside the completed shape, or of the shape +/// outside the allowed region, px (summed over the line's crossings): the solver's own +/// test while it searches ([`Interval::holds`]); it proposes only shapes that pass it. A +/// tenth of a pixel: below what a renderer's anti-aliasing can show at an edge, and above +/// the flattening error of [`super::shape::FLAT_TOL`] at both ends of a line. +pub(crate) const LINE_SLACK: f64 = 0.1; + +/// The checker's slack at each crossing of a scan line, px: what the certificate states is +/// that no boundary of the shape sits more than this far, along the line, outside where the +/// interval puts it. The solver's per-line test ([`LINE_SLACK`], summed over a line's +/// crossings) implies it, so the checker refuses nothing the solver's search meant. +pub(crate) const SPAN_SLACK: f64 = LINE_SLACK; + +/// The solver's measure of how far a shape is from the interval. Not a verdict: it steers +/// the search and the diagnostics; [`certify_completion`] decides. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Interval { + /// The widest scan line of `V \ E`, px: what the face shows that the shape would lose. + pub(crate) lost: f64, + /// The widest scan line of `E \ H`, px: what the shape would paint where it may not. + pub(crate) spilled: f64, +} + +impl Interval { + /// Both within [`LINE_SLACK`]. + pub(crate) fn holds(&self) -> bool { + self.lost <= LINE_SLACK && self.spilled <= LINE_SLACK + } +} + +/// The solver's measure of `lower ⊆ e ⊆ upper` (see [`Interval`]). +pub(crate) fn measure(lower: &Region, e: &Region, upper: &Region) -> Interval { + Interval { + lost: lower.minus(e).widest_line(), + spilled: e.minus(upper).widest_line(), + } +} + +/// A certificate that `inner ⊆ outer` on every scan line: for line `k0 + i`, `rows[i][n]` +/// is the first and last index of the chain of `outer`'s spans claimed to contain the `n`-th +/// span of `inner`. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct Cover { + k0: i32, + rows: Vec>, +} + +impl Cover { + fn row(&self, k: i32) -> Option<&[(usize, usize)]> { + let i = usize::try_from(k - self.k0).ok()?; + self.rows.get(i).map(Vec::as_slice) + } +} + +/// **The solver's certificate**: for each span `[a₀, a₁]` of `inner`, the outer spans on +/// the same line from the last one starting at or before `a₀ + slack` to the first one +/// ending at or after `a₁ − slack` (the first span, when there is none; the checker then +/// refuses). +pub(crate) fn propose_cover(inner: &Region, outer: &Region, slack: f64) -> Cover { + let lines = inner.lines(); + let rows = lines + .clone() + .map(|k| { + let outs = outer.line(k); + inner + .line(k) + .iter() + .map(|&(a0, a1)| { + let first = outs + .iter() + .rposition(|&(b0, _)| b0 <= a0 + slack) + .unwrap_or(0); + let last = (first..outs.len()) + .find(|&j| outs[j].1 >= a1 - slack) + .unwrap_or(first); + (first, last) + }) + .collect() + }) + .collect(); + Cover { + k0: lines.start, + rows, + } +} + +/// **The checker**: every span of `inner`, on every line, lies in the chain of `outer`'s +/// spans the certificate names, each widened by `slack` at both ends, as decided by the +/// generated kernels on outward-rounded intervals: `span_within_iv` against the chain's +/// first start and last end, `span_link_iv` between neighbours. Any refusal, missing entry or +/// index out of range is a rejection. +pub(crate) fn check_cover(inner: &Region, outer: &Region, slack: f64, cert: &Cover) -> bool { + let Some(s) = Iv::point(slack) else { + return false; + }; + for k in inner.lines() { + let spans = inner.line(k); + if spans.is_empty() { + continue; + } + let Some(row) = cert.row(k) else { + return false; + }; + if row.len() != spans.len() { + return false; + } + let outs = outer.line(k); + for (&(a0, a1), &(first, last)) in spans.iter().zip(row) { + if first > last || last >= outs.len() { + return false; + } + let (Some(a0), Some(a1), Some(b0), Some(b1)) = ( + Iv::point(a0), + Iv::point(a1), + Iv::point(outs[first].0), + Iv::point(outs[last].1), + ) else { + return false; + }; + match span_within_iv(&[a0, a1, b0, b1, s]) { + Some([lo, hi]) if lo.is_nonneg() && hi.is_nonneg() => {} + _ => return false, + } + for j in first..last { + let (Some(p1), Some(q0)) = (Iv::point(outs[j].1), Iv::point(outs[j + 1].0)) else { + return false; + }; + match span_link_iv(&[p1, q0, s]) { + Some([g]) if g.is_nonneg() => {} + _ => return false, + } + } + } + } + true +} + +/// **The painter-interval check**: `lower ⊆ e ⊆ upper` on every scan line, each certified by +/// [`check_cover`] on the solver's [`propose_cover`]. The shape `e` contains the lower end +/// (what the face shows, with the half pixel of its cover it must reach under; +/// [`super::required_region`]) and stays within the upper end (what the face shows and what +/// is painted over it; [`super::allowed_region`]). +pub(crate) fn certify_completion(lower: &Region, e: &Region, upper: &Region) -> bool { + check_cover(lower, e, SPAN_SLACK, &propose_cover(lower, e, SPAN_SLACK)) + && check_cover(e, upper, SPAN_SLACK, &propose_cover(e, upper, SPAN_SLACK)) +} + +/// The gate's parameter count of path data, as `bench/inkvec_bench/svgmodel.py` counts it: +/// a line 2 (`L`, `H`, `V`), a quadratic 4 (`Q`, `T`), a cubic 6 (`C`, `S`), an arc 7; a +/// move-to and a close-path nothing. Repeated arguments after one command letter count as +/// repeated segments; a move-to's extra pairs are lines. +pub(crate) fn gate_count(d: &str) -> f64 { + let mut total = 0.0; + let bytes = d.as_bytes(); + let mut i = 0; + while i < bytes.len() { + let c = bytes[i] as char; + if c.is_ascii_alphabetic() { + let mut j = i + 1; + while j < bytes.len() && !(bytes[j] as char).is_ascii_alphabetic() { + j += 1; + } + let args = count_numbers(&d[i + 1..j], c.to_ascii_uppercase()); + let (per, each) = match c.to_ascii_uppercase() { + 'L' => (2, 2.0), + 'T' => (2, 4.0), + 'H' | 'V' => (1, 2.0), + 'Q' | 'S' => ( + 4, + if c.to_ascii_uppercase() == 'Q' { + 4.0 + } else { + 6.0 + }, + ), + 'C' => (6, 6.0), + 'A' => (7, 7.0), + 'M' => (2, 2.0), + _ => (0, 0.0), + }; + if per > 0 { + let n = args / per; + total += if c.to_ascii_uppercase() == 'M' { + each * n.saturating_sub(1) as f64 + } else { + each * n as f64 + }; + } + i = j; + } else { + i += 1; + } + } + total +} + +/// How many numbers an argument list holds. Arc flags may be written without separators +/// (`0 01` or `011`), so for an arc command the flags are counted one character each. +fn count_numbers(s: &str, cmd: char) -> usize { + let b = s.as_bytes(); + let mut n = 0; + let mut i = 0; + let mut in_arc = 0; // position within the current arc's 7 arguments + while i < b.len() { + let c = b[i] as char; + if c == ' ' || c == ',' || c == '\n' || c == '\t' || c == '\r' { + i += 1; + continue; + } + if cmd == 'A' && (in_arc == 3 || in_arc == 4) && (c == '0' || c == '1') { + n += 1; + in_arc = (in_arc + 1) % 7; + i += 1; + continue; + } + // A number: optional sign, digits, one dot, more digits, an exponent. + let start = i; + if c == '-' || c == '+' { + i += 1; + } + let mut seen_dot = false; + while i < b.len() { + let ch = b[i] as char; + if ch.is_ascii_digit() { + i += 1; + } else if ch == '.' && !seen_dot { + seen_dot = true; + i += 1; + } else if (ch == 'e' || ch == 'E') && i > start { + i += 1; + if i < b.len() && (b[i] == b'-' || b[i] == b'+') { + i += 1; + } + } else { + break; + } + } + if i == start { + i += 1; + continue; + } + n += 1; + if cmd == 'A' { + in_arc = (in_arc + 1) % 7; + } + } + n +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn counts_as_the_gate_does() { + assert_eq!(gate_count("M0,0L10,0L10,10Z"), 4.0); + assert_eq!(gate_count("M0 0H10V10Z"), 4.0); + assert_eq!(gate_count("M0,0C1,1 2,2 3,3S5,5 6,6Z"), 12.0); + assert_eq!(gate_count("M0,0A5,5 0 1,0 10,0A5,5 0 1 0 0,0Z"), 14.0); + assert_eq!(gate_count("M0,0 10,0 10,10Z"), 4.0); + assert_eq!(gate_count("M1 2a2 2 0 012-2"), 7.0); + } + + fn spans(items: &[(i32, f64, f64)]) -> Region { + Region::from_line_spans(items.to_vec()) + } + + #[test] + fn cover_accepts_containment_and_refuses_a_forged_certificate() { + let inner = spans(&[(0, 1.0, 2.0), (0, 5.0, 6.0), (1, 1.0, 6.0)]); + let outer = spans(&[(0, 0.0, 3.0), (0, 4.93, 7.0), (1, 0.0, 7.0)]); + let cert = propose_cover(&inner, &outer, SPAN_SLACK); + assert!(check_cover(&inner, &outer, SPAN_SLACK, &cert)); + // Naming the wrong span is refused, as is a missing line. + let mut forged = cert.clone(); + forged.rows[0][1] = (0, 0); + assert!(!check_cover(&inner, &outer, SPAN_SLACK, &forged)); + let mut short = cert.clone(); + short.rows.pop(); + assert!(!check_cover(&inner, &outer, SPAN_SLACK, &short)); + // Out by more than the slack at one end. + let wide = spans(&[(0, 1.0, 3.12)]); + assert!(!check_cover( + &wide, + &outer, + SPAN_SLACK, + &propose_cover(&wide, &outer, SPAN_SLACK) + )); + let near = spans(&[(0, 1.0, 3.08)]); + assert!(check_cover( + &near, + &outer, + SPAN_SLACK, + &propose_cover(&near, &outer, SPAN_SLACK) + )); + // A span bridging a gap of the outer region is refused, even when the certificate + // claims the chain across it ... + let bridge = spans(&[(0, 2.0, 5.5)]); + assert!(!check_cover( + &bridge, + &outer, + SPAN_SLACK, + &propose_cover(&bridge, &outer, SPAN_SLACK) + )); + let mut claim = propose_cover(&bridge, &outer, SPAN_SLACK); + claim.rows[0][0] = (0, 1); + assert!(!check_cover(&bridge, &outer, SPAN_SLACK, &claim)); + // ... and accepted across a crack narrower than twice the slack. + let cracked = spans(&[(0, 0.0, 3.0), (0, 3.15, 7.0)]); + let across = spans(&[(0, 2.0, 5.5)]); + assert!(check_cover( + &across, + &cracked, + SPAN_SLACK, + &propose_cover(&across, &cracked, SPAN_SLACK) + )); + } +} diff --git a/crates/inkvec-cli/src/layers/region.rs b/crates/inkvec-cli/src/layers/region.rs new file mode 100644 index 00000000..894aaf14 --- /dev/null +++ b/crates/inkvec-cli/src/layers/region.rs @@ -0,0 +1,455 @@ +//! Regions of the plane as spans on horizontal scan lines. +//! +//! The layers stage compares sets: what a face shows, what is painted over it, what a +//! completed shape covers. A region here is its cross-section on the lines `y = y_k`, +//! `y_k = -0.5 + (k + ½)·DY` (pixel centres at integers, as everywhere in the emitter, and +//! four lines per pixel row): per line, a sorted list of disjoint open intervals. Each +//! cross-section is exact for the polygons it is built from (the crossings are computed, +//! not sampled), so union, intersection and difference are exact on every line; only what +//! happens between two lines is not seen, which is why the checks that use these regions +//! add a margin of a pixel and more (see [`super::check`]). + +use inkvec_core::Point; + +/// Scan-line spacing, px: four lines per pixel row. +pub(crate) const DY: f64 = 0.25; + +/// The `y` of scan line `k`. +#[inline] +pub(crate) fn line_y(k: i32) -> f64 { + -0.5 + (k as f64 + 0.5) * DY +} + +/// The first scan line at or above `y` (the smallest `k` with `line_y(k) >= y`). +#[inline] +fn first_line_at_or_after(y: f64) -> i32 { + ((y + 0.5) / DY - 0.5).ceil() as i32 +} + +/// A region: per scan line `k0 + i`, its spans `[x0, x1)`, sorted and disjoint (touching +/// spans are merged). Lines outside `k0 .. k0 + rows.len()` are empty. +#[derive(Clone, Debug, Default)] +pub(crate) struct Region { + k0: i32, + rows: Vec>, +} + +/// How crossings become spans: even-odd parity, or a non-zero winding number. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Rule { + EvenOdd, + #[cfg_attr(not(test), allow(dead_code))] + NonZero, +} + +impl Region { + /// The empty region. + pub(crate) fn empty() -> Self { + Self::default() + } + + /// True when no line has a span. + pub(crate) fn is_empty(&self) -> bool { + self.rows.iter().all(Vec::is_empty) + } + + /// The spans of line `k`. + pub(crate) fn line(&self, k: i32) -> &[(f64, f64)] { + let i = k - self.k0; + if i < 0 || i as usize >= self.rows.len() { + return &[]; + } + &self.rows[i as usize] + } + + /// The range of lines that may hold spans. + pub(crate) fn lines(&self) -> std::ops::Range { + self.k0..self.k0 + self.rows.len() as i32 + } + + /// The region bounded by closed polygons (each a list of vertices, implicitly closed), + /// under `rule`. Each edge is entered once per line it crosses, so the cost is the + /// number of crossings, not lines × edges. + pub(crate) fn from_polygons(polys: &[Vec], rule: Rule) -> Self { + let (mut ymin, mut ymax) = (f64::INFINITY, f64::NEG_INFINITY); + for p in polys.iter().flatten() { + if p.y.is_finite() { + ymin = ymin.min(p.y); + ymax = ymax.max(p.y); + } + } + if !(ymin <= ymax) { + return Self::empty(); + } + let k0 = first_line_at_or_after(ymin); + let k1 = first_line_at_or_after(ymax); // exclusive: line_y(k1) >= ymax + if k1 <= k0 { + return Self::empty(); + } + let n = (k1 - k0) as usize; + let mut crossings: Vec> = vec![Vec::new(); n]; + for poly in polys { + let m = poly.len(); + if m < 3 { + continue; + } + for i in 0..m { + let (a, b) = (poly[i], poly[(i + 1) % m]); + if a.y == b.y || !a.y.is_finite() || !b.y.is_finite() { + continue; + } + let (lo, hi, dir) = if a.y < b.y { (a, b, 1) } else { (b, a, -1) }; + // Lines with lo.y <= y < hi.y: half-open, so a vertex shared by two edges + // is counted once. + let ka = first_line_at_or_after(lo.y).max(k0); + let kb = first_line_at_or_after(hi.y).min(k1); + let inv = (hi.x - lo.x) / (hi.y - lo.y); + for k in ka..kb { + let y = line_y(k); + if y < lo.y || y >= hi.y { + continue; + } + crossings[(k - k0) as usize].push((lo.x + (y - lo.y) * inv, dir)); + } + } + } + let rows = crossings + .into_iter() + .map(|mut c| { + c.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut spans = Vec::new(); + match rule { + Rule::EvenOdd => { + for pair in c.chunks_exact(2) { + push_span(&mut spans, pair[0].0, pair[1].0); + } + } + Rule::NonZero => { + let mut w = 0; + let mut start = 0.0; + for &(x, d) in &c { + let was = w != 0; + w += d; + if !was && w != 0 { + start = x; + } else if was && w == 0 { + push_span(&mut spans, start, x); + } + } + } + } + spans + }) + .collect(); + Self { k0, rows }.trimmed() + } + + /// Builds a region from spans added line by line in any order. + pub(crate) fn from_line_spans(mut items: Vec<(i32, f64, f64)>) -> Self { + items.retain(|&(_, a, b)| b > a && a.is_finite() && b.is_finite()); + if items.is_empty() { + return Self::empty(); + } + let k0 = items.iter().map(|t| t.0).min().unwrap_or(0); + let k1 = items.iter().map(|t| t.0).max().unwrap_or(0) + 1; + let mut rows: Vec> = vec![Vec::new(); (k1 - k0) as usize]; + for (k, a, b) in items { + rows[(k - k0) as usize].push((a, b)); + } + for r in &mut rows { + *r = normalized(std::mem::take(r)); + } + Self { k0, rows }.trimmed() + } + + /// Drops empty lines at either end. + fn trimmed(mut self) -> Self { + let first = self.rows.iter().position(|r| !r.is_empty()); + let Some(first) = first else { + return Self::empty(); + }; + let last = self + .rows + .iter() + .rposition(|r| !r.is_empty()) + .unwrap_or(first); + self.rows.truncate(last + 1); + self.rows.drain(..first); + self.k0 += first as i32; + self + } + + /// Applies `f` line by line over the union of both regions' line ranges. + fn combine( + &self, + other: &Self, + f: impl Fn(&[(f64, f64)], &[(f64, f64)]) -> Vec<(f64, f64)>, + ) -> Self { + let lo = self.lines().start.min(other.lines().start); + let hi = self.lines().end.max(other.lines().end); + if hi <= lo { + return Self::empty(); + } + let rows = (lo..hi).map(|k| f(self.line(k), other.line(k))).collect(); + Self { k0: lo, rows }.trimmed() + } + + /// `self ∪ other`. + pub(crate) fn union(&self, other: &Self) -> Self { + if other.is_empty() { + return self.clone(); + } + if self.is_empty() { + return other.clone(); + } + self.combine(other, |a, b| { + let mut v: Vec<(f64, f64)> = a.iter().chain(b.iter()).copied().collect(); + v.sort_by(|p, q| p.0.total_cmp(&q.0)); + normalized_sorted(v) + }) + } + + /// `self ∩ other`. + pub(crate) fn intersect(&self, other: &Self) -> Self { + self.combine(other, intersect_spans) + } + + /// `self \ other`. + pub(crate) fn minus(&self, other: &Self) -> Self { + if other.is_empty() { + return self.clone(); + } + self.combine(other, subtract_spans) + } + + /// The region within the box `[x0, x1] × [y0, y1]`. + pub(crate) fn crop(&self, x0: f64, y0: f64, x1: f64, y1: f64) -> Self { + let ka = first_line_at_or_after(y0).max(self.lines().start); + let kb = first_line_at_or_after(y1).min(self.lines().end); + if kb <= ka { + return Self::empty(); + } + let rows = (ka..kb) + .map(|k| intersect_spans(self.line(k), &[(x0, x1)])) + .collect(); + Self { k0: ka, rows }.trimmed() + } + + /// The region grown by `m` px: every span widened by `m` on each side, and every line + /// joined by the lines within `m` of it. A square structuring element, which contains + /// the disc of radius `m`. + pub(crate) fn dilate(&self, m: f64) -> Self { + if self.is_empty() || m <= 0.0 { + return self.clone(); + } + let r = (m / DY).round() as i32; + let (lo, hi) = (self.lines().start - r, self.lines().end + r); + let rows = (lo..hi) + .map(|k| { + let mut v: Vec<(f64, f64)> = ((k - r)..=(k + r)) + .flat_map(|j| self.line(j).iter().map(|&(a, b)| (a - m, b + m))) + .collect(); + v.sort_by(|p, q| p.0.total_cmp(&q.0)); + normalized_sorted(v) + }) + .collect(); + Self { k0: lo, rows }.trimmed() + } + + /// The region shrunk by `m` px: a point stays when the square of half-side `m` about it + /// lies inside (on every line within `m`, the span shrunk by `m` on each side). + pub(crate) fn erode(&self, m: f64) -> Self { + if self.is_empty() || m <= 0.0 { + return self.clone(); + } + let r = (m / DY).round() as i32; + let (lo, hi) = (self.lines().start, self.lines().end); + let shrunk = |k: i32| -> Vec<(f64, f64)> { + self.line(k) + .iter() + .filter_map(|&(a, b)| (b - a > 2.0 * m).then_some((a + m, b - m))) + .collect() + }; + let rows = (lo..hi) + .map(|k| { + let mut acc = shrunk(k); + for j in (k - r)..=(k + r) { + if j == k || acc.is_empty() { + continue; + } + acc = intersect_spans(&acc, &shrunk(j)); + } + acc + }) + .collect(); + Self { k0: lo, rows }.trimmed() + } + + /// Area, px²: each line's span length times the line spacing. + pub(crate) fn area(&self) -> f64 { + self.rows.iter().flatten().map(|&(a, b)| b - a).sum::() * DY + } + + /// The longest total span length on any one line, px: how far a boundary is out at + /// worst, summed over its crossings of that line. + pub(crate) fn widest_line(&self) -> f64 { + self.rows + .iter() + .map(|r| r.iter().map(|&(a, b)| b - a).sum::()) + .fold(0.0, f64::max) + } + + /// Whether `p` is inside, read on the nearest scan line. + pub(crate) fn contains(&self, p: Point) -> bool { + let k = ((p.y + 0.5) / DY - 0.5).round() as i32; + self.line(k).iter().any(|&(a, b)| a <= p.x && p.x < b) + } + + /// The bounding box `(x0, y0, x1, y1)` of the spans, or `None` when empty. `y` is the + /// first and last line's `y`, widened by half a line. + pub(crate) fn bbox(&self) -> Option<(f64, f64, f64, f64)> { + let (mut x0, mut x1) = (f64::INFINITY, f64::NEG_INFINITY); + let (mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY); + for (i, r) in self.rows.iter().enumerate() { + if let (Some(f), Some(l)) = (r.first(), r.last()) { + x0 = x0.min(f.0); + x1 = x1.max(l.1); + let y = line_y(self.k0 + i as i32); + y0 = y0.min(y - 0.5 * DY); + y1 = y1.max(y + 0.5 * DY); + } + } + (x0 <= x1).then_some((x0, y0, x1, y1)) + } +} + +/// Appends `[a, b)` to sorted, disjoint spans, merging with the last when they touch. +fn push_span(v: &mut Vec<(f64, f64)>, a: f64, b: f64) { + if b <= a { + return; + } + if let Some(last) = v.last_mut() { + if a <= last.1 { + last.1 = last.1.max(b); + return; + } + } + v.push((a, b)); +} + +/// Spans sorted by start, merged where they overlap or touch. +fn normalized_sorted(v: Vec<(f64, f64)>) -> Vec<(f64, f64)> { + let mut out = Vec::with_capacity(v.len()); + for (a, b) in v { + push_span(&mut out, a, b); + } + out +} + +/// Spans in any order, sorted and merged. +fn normalized(mut v: Vec<(f64, f64)>) -> Vec<(f64, f64)> { + v.sort_by(|p, q| p.0.total_cmp(&q.0)); + normalized_sorted(v) +} + +/// The intersection of two sorted, disjoint span lists. +fn intersect_spans(a: &[(f64, f64)], b: &[(f64, f64)]) -> Vec<(f64, f64)> { + let (mut i, mut j) = (0, 0); + let mut out = Vec::new(); + while i < a.len() && j < b.len() { + let lo = a[i].0.max(b[j].0); + let hi = a[i].1.min(b[j].1); + if hi > lo { + out.push((lo, hi)); + } + if a[i].1 < b[j].1 { + i += 1; + } else { + j += 1; + } + } + out +} + +/// `a \ b` for two sorted, disjoint span lists. +fn subtract_spans(a: &[(f64, f64)], b: &[(f64, f64)]) -> Vec<(f64, f64)> { + let mut out = Vec::new(); + let mut j = 0; + for &(mut lo, hi) in a { + while j < b.len() && b[j].1 <= lo { + j += 1; + } + let mut jj = j; + while jj < b.len() && b[jj].0 < hi { + if b[jj].0 > lo { + out.push((lo, b[jj].0)); + } + lo = lo.max(b[jj].1); + if lo >= hi { + break; + } + jj += 1; + } + if lo < hi { + out.push((lo, hi)); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec { + vec![ + Point::new(x0, y0), + Point::new(x1, y0), + Point::new(x1, y1), + Point::new(x0, y1), + ] + } + + #[test] + fn a_square_has_its_area() { + let r = Region::from_polygons(&[square(0.0, 0.0, 10.0, 4.0)], Rule::EvenOdd); + assert!((r.area() - 40.0).abs() < 1e-9, "{}", r.area()); + } + + #[test] + fn set_operations_are_exact_on_each_line() { + let a = Region::from_polygons(&[square(0.0, 0.0, 10.0, 10.0)], Rule::EvenOdd); + let b = Region::from_polygons(&[square(5.0, 5.0, 15.0, 15.0)], Rule::EvenOdd); + assert!((a.union(&b).area() - 175.0).abs() < 1e-9); + assert!((a.intersect(&b).area() - 25.0).abs() < 1e-9); + assert!((a.minus(&b).area() - 75.0).abs() < 1e-9); + } + + #[test] + fn even_odd_makes_a_hole_and_non_zero_does_not_when_wound_alike() { + let outer = square(0.0, 0.0, 10.0, 10.0); + let inner = square(2.0, 2.0, 8.0, 8.0); + let eo = Region::from_polygons(&[outer.clone(), inner.clone()], Rule::EvenOdd); + assert!((eo.area() - 64.0).abs() < 1e-9); + let nz = Region::from_polygons(&[outer, inner], Rule::NonZero); + assert!((nz.area() - 100.0).abs() < 1e-9); + } + + #[test] + fn erosion_and_dilation_move_the_boundary_by_the_margin() { + let a = Region::from_polygons(&[square(0.0, 0.0, 10.0, 10.0)], Rule::EvenOdd); + let e = a.erode(1.0); + assert!((e.area() - 64.0).abs() < 1.0, "{}", e.area()); + let d = a.dilate(1.0); + assert!((d.area() - 144.0).abs() < 1.5, "{}", d.area()); + assert!(e.minus(&a).is_empty()); + assert!(a.minus(&d).is_empty()); + } + + #[test] + fn contains_reads_the_nearest_line() { + let a = Region::from_polygons(&[square(0.0, 0.0, 10.0, 10.0)], Rule::EvenOdd); + assert!(a.contains(Point::new(5.0, 5.0))); + assert!(!a.contains(Point::new(11.0, 5.0))); + } +} diff --git a/crates/inkvec-cli/src/layers/shape.rs b/crates/inkvec-cli/src/layers/shape.rs new file mode 100644 index 00000000..31d99585 --- /dev/null +++ b/crates/inkvec-cli/src/layers/shape.rs @@ -0,0 +1,310 @@ +//! Geometry to regions: fitted paths, primitives and stroke bands, flattened finely enough +//! that the region of [`super::region`] is the shape to within [`FLAT_TOL`]. + +use inkvec_core::Point; +use inkvec_fit::curves::Segment; +use inkvec_fit::primitives::PrimitiveKind; +use inkvec_fit::FittedPath; + +use super::region::{line_y, Region, DY}; + +/// Largest distance, px, between a curve and the polyline that stands for it. +pub(crate) const FLAT_TOL: f64 = 0.02; + +/// How many pieces a curve of the given control-polygon length and turn needs so that the +/// chord error stays under [`FLAT_TOL`]: for an arc of radius `r` cut into `n` pieces the +/// sagitta is `r(1 − cos(θ/2n)) ≈ rθ²/8n²`, and a control polygon bounds `rθ` from above. +fn pieces(len: f64, turn: f64) -> usize { + let s = (len.max(0.0) * turn.abs().max(0.05) / (8.0 * FLAT_TOL)).sqrt(); + (s.ceil() as usize).clamp(2, 512) +} + +/// Appends the points of `seg` after `from` (excluding `from` itself). +pub(crate) fn flatten_segment(from: Point, seg: &Segment, out: &mut Vec) { + match *seg { + Segment::Line(p) => out.push(p), + Segment::Cubic(c1, c2, p) => { + let len = from.dist(c1) + c1.dist(c2) + c2.dist(p); + let turn = angle_between(sub(c1, from), sub(c2, c1)).abs() + + angle_between(sub(c2, c1), sub(p, c2)).abs() + + 0.5; + let n = pieces(len, turn); + for i in 1..=n { + let t = i as f64 / n as f64; + out.push(inkvec_fit::curves::eval_cubic([from, c1, c2, p], t)); + } + } + Segment::Arc { + rx, + ry, + phi, + large_arc, + sweep, + end, + } => { + let f = + inkvec_fit::curves::arc_ellipse_center(from, rx, ry, phi, large_arc, sweep, end); + let n = pieces(rx.max(ry) * f.delta.abs(), f.delta); + for i in 1..=n { + out.push(f.at(f.theta1 + f.delta * i as f64 / n as f64)); + } + if let Some(last) = out.last_mut() { + *last = end; + } + } + } +} + +/// A path's points: its start and every segment flattened. +pub(crate) fn flatten_path(path: &FittedPath) -> Vec { + let mut out = vec![path.start]; + let mut at = path.start; + for s in &path.segments { + flatten_segment(at, s, &mut out); + at = s.end(); + } + out +} + +/// A primitive's outline as a closed polygon. +pub(crate) fn flatten_primitive(kind: &PrimitiveKind) -> Vec { + match *kind { + PrimitiveKind::Circle { c, r } => ellipse_points(c, r, r, 0.0), + PrimitiveKind::Ellipse { c, rx, ry, angle } => ellipse_points(c, rx, ry, angle), + PrimitiveKind::RoundRect { x, y, w, h, rx } => { + let rx = rx.clamp(0.0, 0.5 * w.min(h)); + if rx <= 1e-9 { + return vec![ + Point::new(x, y), + Point::new(x + w, y), + Point::new(x + w, y + h), + Point::new(x, y + h), + ]; + } + let n = pieces( + rx * std::f64::consts::FRAC_PI_2, + std::f64::consts::FRAC_PI_2, + ); + let mut out = Vec::new(); + let corners = [ + (x + w - rx, y + rx, -std::f64::consts::FRAC_PI_2), + (x + w - rx, y + h - rx, 0.0), + (x + rx, y + h - rx, std::f64::consts::FRAC_PI_2), + (x + rx, y + rx, std::f64::consts::PI), + ]; + for (cx, cy, a0) in corners { + for i in 0..=n { + let a = a0 + std::f64::consts::FRAC_PI_2 * i as f64 / n as f64; + out.push(Point::new(cx + rx * a.cos(), cy + rx * a.sin())); + } + } + out + } + } +} + +fn ellipse_points(c: Point, rx: f64, ry: f64, angle: f64) -> Vec { + let tau = std::f64::consts::TAU; + let n = pieces(rx.max(ry) * tau, tau).max(16); + let (s, co) = angle.sin_cos(); + (0..n) + .map(|i| { + let t = tau * i as f64 / n as f64; + let (ex, ey) = (rx * t.cos(), ry * t.sin()); + Point::new(c.x + ex * co - ey * s, c.y + ex * s + ey * co) + }) + .collect() +} + +/// How a stroke's open ends are drawn. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum EndCap { + Butt, + Round, + Square, +} + +/// How a stroke's pieces meet. Only `Round` is drawn as such; a miter or bevel join is +/// taken as no join at all, which can only make the band smaller than the renderer's. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum JoinKind { + Round, + Other, +} + +/// The band a stroke of width `width` paints along the centrelines `lines`. Smaller than or +/// equal to what a renderer paints wherever the two differ (miter and bevel joins are left +/// out), which is the safe side for a region used as cover: a face may reach under it only +/// where it certainly is. +pub(crate) fn stroke_band(lines: &[FittedPath], width: f64, cap: EndCap, join: JoinKind) -> Region { + let r = 0.5 * width; + if r <= 0.0 { + return Region::empty(); + } + let mut spans: Vec<(i32, f64, f64)> = Vec::new(); + for line in lines { + let mut pts = flatten_path(line); + if line.closed && pts.len() > 1 && pts.first() != pts.last() { + pts.push(pts[0]); + } + let n = pts.len(); + if n == 0 { + continue; + } + if n == 1 { + if cap == EndCap::Round { + disc_spans(pts[0], r, &mut spans); + } + continue; + } + for i in 0..n - 1 { + let (mut a, mut b) = (pts[i], pts[i + 1]); + if !line.closed && cap == EndCap::Square { + let d = sub(b, a); + let l = d.x.hypot(d.y); + if l > 0.0 { + let u = Point::new(d.x / l, d.y / l); + if i == 0 { + a = Point::new(a.x - u.x * r, a.y - u.y * r); + } + if i == n - 2 { + b = Point::new(b.x + u.x * r, b.y + u.y * r); + } + } + } + rect_spans(a, b, r, &mut spans); + } + // Discs: at interior vertices (a flattened curve is a run of round joins, which is + // what a curve's band is), at written joins when they are round, at open ends with + // round caps. A written join and a flattening vertex cannot be told apart here, so + // a non-round join is only honoured at the path's own segment ends. + let mut ends: Vec = Vec::new(); + let mut at = line.start; + for s in &line.segments { + at = s.end(); + ends.push(at); + } + let _ = at; + for (i, &p) in pts.iter().enumerate() { + let open_end = !line.closed && (i == 0 || i == n - 1); + let written_join = ends.iter().any(|e| e.dist(p) < 1e-9) && !open_end; + let disc = if open_end { + cap == EndCap::Round + } else if written_join { + join == JoinKind::Round + } else { + true + }; + if disc { + disc_spans(p, r, &mut spans); + } + } + } + Region::from_line_spans(spans) +} + +/// Spans of the disc of radius `r` about `c`. +fn disc_spans(c: Point, r: f64, out: &mut Vec<(i32, f64, f64)>) { + let ka = ((c.y - r + 0.5) / DY - 0.5).ceil() as i32; + let kb = ((c.y + r + 0.5) / DY - 0.5).floor() as i32; + for k in ka..=kb { + let dy = line_y(k) - c.y; + let h2 = r * r - dy * dy; + if h2 > 0.0 { + let h = h2.sqrt(); + out.push((k, c.x - h, c.x + h)); + } + } +} + +/// Spans of the rectangle `{a + t(b − a) + s·n : t ∈ [0, 1], |s| ≤ r}`. +fn rect_spans(a: Point, b: Point, r: f64, out: &mut Vec<(i32, f64, f64)>) { + let d = sub(b, a); + let l = d.x.hypot(d.y); + if l <= 1e-12 { + return; + } + let (ux, uy) = (d.x / l, d.y / l); + let (nx, ny) = (-uy, ux); + let corners = [ + Point::new(a.x + nx * r, a.y + ny * r), + Point::new(b.x + nx * r, b.y + ny * r), + Point::new(b.x - nx * r, b.y - ny * r), + Point::new(a.x - nx * r, a.y - ny * r), + ]; + let ymin = corners.iter().map(|p| p.y).fold(f64::INFINITY, f64::min); + let ymax = corners + .iter() + .map(|p| p.y) + .fold(f64::NEG_INFINITY, f64::max); + let ka = ((ymin + 0.5) / DY - 0.5).ceil() as i32; + let kb = ((ymax + 0.5) / DY - 0.5).floor() as i32; + for k in ka..=kb { + let y = line_y(k); + let mut lo = f64::INFINITY; + let mut hi = f64::NEG_INFINITY; + for i in 0..4 { + let (p, q) = (corners[i], corners[(i + 1) % 4]); + if (p.y <= y && y <= q.y) || (q.y <= y && y <= p.y) { + let x = if (q.y - p.y).abs() < 1e-15 { + lo = lo.min(p.x.min(q.x)); + hi = hi.max(p.x.max(q.x)); + continue; + } else { + p.x + (y - p.y) * (q.x - p.x) / (q.y - p.y) + }; + lo = lo.min(x); + hi = hi.max(x); + } + } + if hi > lo { + out.push((k, lo, hi)); + } + } +} + +fn sub(a: Point, b: Point) -> Point { + Point::new(a.x - b.x, a.y - b.y) +} + +fn angle_between(a: Point, b: Point) -> f64 { + (a.x * b.y - a.y * b.x).atan2(a.x * b.x + a.y * b.y) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::layers::region::Rule; + + #[test] + fn a_circle_flattens_to_its_area() { + let poly = flatten_primitive(&PrimitiveKind::Circle { + c: Point::new(20.0, 20.0), + r: 10.0, + }); + let r = Region::from_polygons(&[poly], Rule::EvenOdd); + // An inscribed polygon within FLAT_TOL of the curve loses less than the perimeter + // times that tolerance. + let want = std::f64::consts::PI * 100.0; + let slack = std::f64::consts::TAU * 10.0 * FLAT_TOL; + assert!((r.area() - want).abs() < slack, "{} vs {want}", r.area()); + } + + #[test] + fn a_round_capped_stroke_is_a_capsule() { + let line = FittedPath { + start: Point::new(0.0, 10.0), + segments: vec![Segment::Line(Point::new(20.0, 10.0))], + closed: false, + }; + let band = stroke_band(&[line.clone()], 4.0, EndCap::Round, JoinKind::Round); + let want = 20.0 * 4.0 + std::f64::consts::PI * 4.0; + assert!( + (band.area() - want).abs() < 0.6, + "{} vs {want}", + band.area() + ); + let butt = stroke_band(&[line], 4.0, EndCap::Butt, JoinKind::Round); + assert!((butt.area() - 80.0).abs() < 0.6, "{}", butt.area()); + } +} diff --git a/crates/inkvec-cli/src/layers/tests.rs b/crates/inkvec-cli/src/layers/tests.rs new file mode 100644 index 00000000..8498f3f3 --- /dev/null +++ b/crates/inkvec-cli/src/layers/tests.rs @@ -0,0 +1,198 @@ +//! The stage on hand-built faces: what it completes, and what it must refuse. + +use super::*; + +fn p(x: f64, y: f64) -> Point { + Point::new(x, y) +} + +/// A closed polygon as one fitted edge of lines. +fn polygon(pts: &[(f64, f64)]) -> FittedPath { + let mut segs: Vec = pts[1..] + .iter() + .map(|&(x, y)| Segment::Line(p(x, y))) + .collect(); + segs.push(Segment::Line(p(pts[0].0, pts[0].1))); + FittedPath { + start: p(pts[0].0, pts[0].1), + segments: segs, + closed: true, + } +} + +/// Runs the stage on faces given as one polygon each, painted in the given ranks. +fn run( + faces: &[Vec<(f64, f64)>], + rank: &[Option], + candidate: &[bool], + strokes: &[StrokeShape], +) -> HashMap { + let fitted: Vec = faces.iter().map(|f| polygon(f)).collect(); + let order: Vec = (0..faces.len()).map(|k| vec![vec![(k, false)]]).collect(); + let prims = vec![None; faces.len()]; + let outer = vec![vec![0usize]; faces.len()]; + let holes = vec![Vec::new(); faces.len()]; + let covers = vec![true; faces.len()]; + let decimals = 2; + let cost = |f: usize| -> f64 { + let mut d = String::new(); + crate::pathdata::fmt_ring(&order[f][0], &fitted, decimals, &mut d); + gate_count(&d) + }; + let inp = Input { + order: &order, + fitted: &fitted, + prims: &prims, + outer: &outer, + holes: &holes, + rank, + covers: &covers, + candidate, + cost_now: &cost, + strokes, + stroke_faces: &[], + // The faces' own box stands for the image's frame. + canvas: faces.iter().flatten().fold(None, |b, &(x, y)| { + let (x0, y0, x1, y1) = b.unwrap_or((x, y, x, y)); + Some((x0.min(x), y0.min(y), x1.max(x), y1.max(y))) + }), + decimals, + }; + complete(&inp) +} + +#[test] +fn an_l_under_the_square_in_its_corner_completes_to_the_whole_square() { + // Face 0 shows an L; face 1, the square in its top-right corner, is painted over it. + let l = vec![ + (0.0, 0.0), + (10.0, 0.0), + (10.0, 10.0), + (20.0, 10.0), + (20.0, 20.0), + (0.0, 20.0), + ]; + let corner = vec![(10.0, 0.0), (20.0, 0.0), (20.0, 10.0), (10.0, 10.0)]; + // Both on a page larger than they are, painted first. + let page = vec![(-20.0, -20.0), (40.0, -20.0), (40.0, 40.0), (-20.0, 40.0)]; + let got = run( + &[l.clone(), corner.clone(), page], + &[Some(1), Some(2), Some(0)], + &[true, false, false], + &[], + ); + let c = got.get(&0).expect("the L is completed"); + assert!(c.after < c.before, "{c:?}"); + assert!(c.after <= 6.0, "a square writes six numbers: {c:?}"); + // Alone, the two fill the canvas: completed to the square, the L would become the page. + let alone = run(&[l, corner], &[Some(0), Some(1)], &[true, false], &[]); + assert!(alone.is_empty(), "{alone:?}"); +} + +#[test] +fn nothing_painted_over_a_face_leaves_it_alone() { + let a = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]; + let b = vec![(20.0, 0.0), (30.0, 0.0), (30.0, 10.0), (20.0, 10.0)]; + let got = run(&[a, b], &[Some(0), Some(1)], &[true, true], &[]); + assert!(got.is_empty(), "{got:?}"); +} + +#[test] +fn a_face_painted_over_a_lower_one_cannot_reach_into_it() { + // Face 1 (upper) is the L; face 0 (lower) the corner square. The L may not grow into + // the square, which is painted beneath it, and nothing is painted over the L. + let l = vec![ + (0.0, 0.0), + (10.0, 0.0), + (10.0, 10.0), + (20.0, 10.0), + (20.0, 20.0), + (0.0, 20.0), + ]; + let corner = vec![(10.0, 0.0), (20.0, 0.0), (20.0, 10.0), (10.0, 10.0)]; + let got = run(&[corner, l], &[Some(0), Some(1)], &[false, true], &[]); + assert!(got.is_empty(), "{got:?}"); +} + +#[test] +fn a_face_under_a_stroke_reaches_under_it() { + // A square whose right side is a staircase under a thick vertical stroke: completed + // to a square that runs under the stroke. + let stairs = vec![ + (0.0, 0.0), + (20.0, 0.0), + (20.5, 2.0), + (19.5, 4.0), + (20.5, 6.0), + (19.5, 8.0), + (20.0, 10.0), + (20.0, 20.0), + (0.0, 20.0), + ]; + let stroke = StrokeShape { + lines: vec![FittedPath { + start: p(20.0, -2.0), + segments: vec![Segment::Line(p(20.0, 22.0))], + closed: false, + }], + prims: Vec::new(), + width: 4.0, + cap: EndCap::Butt, + join: JoinKind::Round, + }; + let got = run(&[stairs], &[Some(0)], &[true], &[stroke]); + let c = got.get(&0).expect("completed under the stroke"); + assert!(c.after < c.before, "{c:?}"); +} + +#[test] +fn the_check_refuses_a_shape_that_loses_what_the_face_shows() { + let v = Region::from_polygons( + &[vec![p(0.0, 0.0), p(10.0, 0.0), p(10.0, 10.0), p(0.0, 10.0)]], + Rule::EvenOdd, + ); + let small = Region::from_polygons( + &[vec![p(0.0, 0.0), p(9.0, 0.0), p(9.0, 10.0), p(0.0, 10.0)]], + Rule::EvenOdd, + ); + let big = Region::from_polygons( + &[vec![ + p(-1.0, -1.0), + p(11.0, -1.0), + p(11.0, 11.0), + p(-1.0, 11.0), + ]], + Rule::EvenOdd, + ); + assert!(!check::certify_completion(&v, &small, &big)); + assert!(check::certify_completion(&v, &v, &big)); + assert!(!check::certify_completion(&v, &big, &v)); +} + +#[test] +fn a_corner_a_blur_cut_off_under_the_cover_is_restored() { + // Face 1, a frame's left bar and arms, is painted over face 0, a triangle whose acute + // corners sit in the frame's inner corners. A blur took the tips: the fit wrote each as a + // chamfer along the frame's inner edge. Under the frame nobody sees the tips, so the + // completion extends the triangle's sides to meet again. + let tri = vec![ + (31.0, 11.0), + (1.6, 1.2), + (0.5, 0.9), + (0.5, 21.1), + (1.6, 20.8), + ]; + let frame = vec![ + (-4.0, -4.0), + (40.0, -4.0), + (40.0, 1.0), + (1.0, 1.0), + (1.0, 21.0), + (40.0, 21.0), + (40.0, 25.0), + (-4.0, 25.0), + ]; + let got = run(&[tri, frame], &[Some(0), Some(1)], &[true, false], &[]); + let c = got.get(&0).expect("the triangle is completed"); + assert!(c.after <= 4.0, "a triangle writes four numbers: {c:?}"); +} diff --git a/crates/inkvec-cli/src/lib.rs b/crates/inkvec-cli/src/lib.rs index d2333ffc..1cfd0baf 100644 --- a/crates/inkvec-cli/src/lib.rs +++ b/crates/inkvec-cli/src/lib.rs @@ -47,12 +47,14 @@ mod alpha; mod args; mod border; +mod damage; mod diag; mod editable; mod emit; mod faces; mod fast; mod harmonize; +mod layers; mod mirror_fit; mod mono; mod naming; @@ -72,7 +74,7 @@ mod units; #[cfg(test)] mod lib_tests; -use alpha::{alpha_source, pixel_grid}; +use alpha::pixel_grid; use args::{parse_args, usage}; pub use args::{parse_color_groups, Args, TraceMode}; pub use fast::fast_ignored; @@ -543,7 +545,7 @@ pub fn trace_prepared(prepared: Intake) -> Result Result Result Result Result p, None => trace_once(&img, args)?, }; - // `Some(stats line)` when `auto` traces the input as it is instead of cleaning it. - let direct = match inkvec_sr::decide(&img, &probe, args.sr_threshold) { - inkvec_sr::Decision::Keep { residual } => Some(match residual { + // `Some(stats line)` when `auto` traces the input as it is instead of cleaning it. As + // for `--restore auto`: the residual alone reads clean shading as damage, so cleaning + // also needs a sign of resampling or compression (see `damage`), and that cheaper + // half is asked first. + let decision = damage::soft(&img, args.lossy) + .map(|_| inkvec_sr::decide(&img, &probe.0, args.sr_threshold)); + let direct = match decision { + None => { + Some("sr no sign of resampling or compression; traced directly".into()) + } + Some(inkvec_sr::Decision::Keep { residual }) => Some(match residual { Some(r) => format!( "sr residual {r:.3} <= {:.3}, traced directly", args.sr_threshold ), None => "sr could not measure the fit; traced directly".into(), }), - inkvec_sr::Decision::Clean { residual } => { + Some(inkvec_sr::Decision::Clean { residual }) => { let measured = residual.map(|r| format!("residual {r:.3} > {:.3}", args.sr_threshold)); match build_upscaler(args) { @@ -651,20 +663,22 @@ fn trace_prepared_priced(prepared: Intake) -> Result, - /// The probe trace `--restore auto` made of an input it kept, for SR's `auto` to reuse or, - /// with SR off, to return as the trace. - probe: Option, + /// The probe trace `--restore auto` made of an input it kept (SVG, stage log, lambda), for + /// SR's `auto` to reuse or, with SR off, to return as the trace. + probe: Option, /// Whether the image was restored, which forces soft intake for the trace that follows. restored: bool, } @@ -1017,26 +1031,39 @@ fn restore_prepass( probe: None, restored: false, }; - if args.restore == inkvec_restore::Mode::Off { + let mode = args.restore_mode(); + if mode == inkvec_restore::Mode::Off { return Ok(pass); } let mut auto_probe = None; - if args.restore == inkvec_restore::Mode::Auto { + if mode == inkvec_restore::Mode::Auto { + // The residual alone reads smooth shading in clean art as damage, so `auto` also + // needs the file or the pixels to say the input was compressed (see `damage`). That + // evidence is asked first: it is the cheap half (a flag, or the ringing score), while + // the residual needs a probe trace rendered at full size. Without it there is nothing + // to decide, so no probe is made and the input takes the plain path: a clean input + // pays the evidence alone, and its trace is the plain one by construction. Fast mode + // reads the container only (`damage::compressed`). + let pixels = args.mode != TraceMode::Fast; + let Some(why) = damage::compressed(&pass.img, args.lossy, pixels) else { + pass.note = Some("restore no sign of compression; traced directly".into()); + return Ok(pass); + }; inkvec_core::progress::note(|| { "a first trace, to see whether the denoiser is needed".into() }); let probe = trace_once(&pass.img, args)?; let decision = inkvec_restore::decide( &pass.img, - &probe, + &probe.0, inkvec_restore::Options { residual_threshold: args.restore_threshold, }, ); match decision { inkvec_restore::Decision::Restore { residual } => { - pass.note = - residual.map(|r| format!("residual {r:.3} > {:.3}", args.restore_threshold)); + pass.note = residual + .map(|r| format!("residual {r:.3} > {:.3}, {why}", args.restore_threshold)); auto_probe = Some(probe); } inkvec_restore::Decision::Keep { residual } => { @@ -1138,7 +1165,18 @@ fn build_restorer( /// Always in colour: `auto` compares the probe with the input, and a monochrome drawing /// disagrees with a colour input everywhere it is not black or white, which would read as /// damage on every image. A monochrome trace discards the probe and traces again. -fn trace_once(img: &inkvec_trace::Rgba, args: &Args) -> Result { +/// +/// Otherwise the probe is the trace the plain path makes (`trace_bordered`, through the +/// border pad, and through `--hypotheses` when it applies), so a probe `auto` keeps is byte +/// for byte what `--restore off` / `--sr off` returns. It used to skip the border pad, and +/// on the gate's transparent 128 px tier a third of the probes `--restore auto` kept differed +/// from the plain trace (81 of 246). The stage log and lambda come with it, so a kept probe +/// reports what the plain trace reports; they used to be dropped, leaving only the `restore` +/// or `sr` line. +fn trace_once( + img: &inkvec_trace::Rgba, + args: &Args, +) -> Result> { let colour_args; let args = if args.monochrome { colour_args = Args { @@ -1149,19 +1187,13 @@ fn trace_once(img: &inkvec_trace::Rgba, args: &Args) -> Result { } else { args }; - let cfg = fit_config(img, args); - if args.bilevel { - Ok(run_bilevel(img, args, &cfg).0) + let traced = if args.hypotheses && hypotheses_apply(args) { + let base = trace_bordered(img.clone(), args)?; + select::choose(img, args, base, |a| trace_bordered(img.clone(), a))? } else { - // The probe sees what the real trace will see, matte and all. - match alpha_source(img, true, args.cutout, args.native_alpha) { - Some(src) => { - let args = alpha::cutout_args(args, Some(&src)); - Ok(run_color(&src.flat, &args, &cfg, Some(&src))?.0) - } - None => Ok(run_color(img, args, &cfg, None)?.0), - } - } + trace_bordered(img.clone(), args)? + }; + Ok(traced) } /// Apply the output options ([`post_process`]), write the SVG to `--output` (default: the diff --git a/crates/inkvec-cli/src/lib_tests.rs b/crates/inkvec-cli/src/lib_tests.rs index ef0ebb2c..17d25ffd 100644 --- a/crates/inkvec-cli/src/lib_tests.rs +++ b/crates/inkvec-cli/src/lib_tests.rs @@ -237,8 +237,10 @@ fn test_sr_and_restore_error_recovery_paths() { // Restore Auto with threshold -1.0 forcing Restore decision; since tools/inkvec_restore does not exist, recovers gracefully let args_restore = Args { - restore: inkvec_restore::Mode::Auto, + restore: Some(inkvec_restore::Mode::Auto), restore_threshold: -1.0, + // A lossy container, the sign of compression `auto` needs besides the residual. + lossy: inkvec_sr::Mode::On, ..Args::default() }; let res_rest = trace_image(sq, &args_restore); @@ -396,7 +398,7 @@ fn test_sr_prepass_execution() { fn test_restore_prepass_execution() { let img = make_square(); let args_res = Args { - restore: inkvec_restore::Mode::On, + restore: Some(inkvec_restore::Mode::On), restore_command: Some(IDENTITY_RESTORER.into()), quiet: false, ..Args::default() @@ -464,10 +466,12 @@ fn test_cli_main_from_valid_args() { fn test_restore_auto_kept_probe_with_normalisation() { let img = make_square(); let args = Args { - restore: inkvec_restore::Mode::Auto, + restore: Some(inkvec_restore::Mode::Auto), restore_threshold: 1000.0, // High threshold -> Decision::Keep max_dim: 32, // Forces normalised = true sr: inkvec_sr::Mode::Off, + // A sign of compression, without which `auto` makes no probe to keep. + lossy: inkvec_sr::Mode::On, ..Args::default() }; let res = trace_image(img, &args); diff --git a/crates/inkvec-cli/src/pipeline.rs b/crates/inkvec-cli/src/pipeline.rs index 28bc9068..b228e305 100644 --- a/crates/inkvec-cli/src/pipeline.rs +++ b/crates/inkvec-cli/src/pipeline.rs @@ -160,6 +160,7 @@ pub(crate) fn color_options(args: &Args, width: usize, height: usize) -> ColorOp // `Auto` should already have been resolved by `resolve_lossy`; if a caller skipped // that, treating it as "not known to be lossy" keeps a clean intake untouched. lossy_intake: args.lossy == inkvec_sr::Mode::On, + restored: args.restored, alpha_inks: args.cutout, native_alpha: args.native_alpha, simplify_faint: args.simplify_faint, @@ -407,11 +408,10 @@ fn finish_color( &traced.face_fade, ); - // Editability mode: post-fit structure passes, every one guarded to the ring's - // own tolerance. Runs after repair and harmonization so nothing downstream - // re-breaks what was locked. + // Editability mode: post-fit structure passes, every one guarded to the ring's own + // tolerance. Runs after repair and harmonization so nothing re-breaks what was locked. if args.editability { - let stats = editable::edit_all(&polys, &mut fitted, &prims); + let stats = editable::edit_all(&polys, &mut fitted, &prims, &order, cfg); diag::stage(args.quiet, || stats.summary()); } let doc = ColorDoc { @@ -431,9 +431,9 @@ fn finish_color( w, h, }; - // `--detect-strokes` (off by default): stroke-drawn faces written as strokes. + // Stroke detection (on by default, `--no-detect-strokes` off): stroke-drawn faces written as strokes. let ribbons = crate::ribbons::stage(args, cfg, fast, &doc, &map, &traced_labels); - let doc = doc.with_ribbons(&ribbons.elements); + let doc = doc.with_ribbons(&ribbons); // Monochrome: the ink faces as one black shape, from the same fitted edges. It replaces // the colour document, and with it the layer form, which only ever repaints colours. let (svg, mono_line) = if args.monochrome { @@ -533,6 +533,7 @@ fn emit_options(args: &Args, fast: bool) -> EmitOptions { harmonize: args.harmonize && !fast, harmonize_threshold: args.harmonize_threshold, use_symbols: args.use_symbols, + layers: !fast && crate::layers::enabled(), } } diff --git a/crates/inkvec-cli/src/pipeline_tests.rs b/crates/inkvec-cli/src/pipeline_tests.rs index 47db7d67..d0d8bc6e 100644 --- a/crates/inkvec-cli/src/pipeline_tests.rs +++ b/crates/inkvec-cli/src/pipeline_tests.rs @@ -282,6 +282,7 @@ fn test_write_colour() { harmonize: true, harmonize_threshold: 0.05, use_symbols: false, + layers: false, cutout: false, no_background: false, }; diff --git a/crates/inkvec-cli/src/ribbons.rs b/crates/inkvec-cli/src/ribbons.rs index 73a4a222..89f7e745 100644 --- a/crates/inkvec-cli/src/ribbons.rs +++ b/crates/inkvec-cli/src/ribbons.rs @@ -1,7 +1,8 @@ -//! `--detect-strokes` (`Options::detect_strokes`; off by default): faces that were drawn -//! as strokes, written as strokes -- centrelines with one `stroke-width`, round or butt -//! caps, round or miter joins -- instead of as filled outlines. Off, nothing here runs and -//! the output is byte-identical to the pipeline without the stage. +//! Stroke detection (`Options::detect_strokes`, on by default in Quality mode; +//! `--no-detect-strokes` turns it off): faces that were drawn as strokes, written as +//! strokes -- centrelines with one `stroke-width`, round or butt caps, round or miter +//! joins -- instead of as filled outlines. Off, nothing here runs and the output is +//! byte-identical to the pipeline without the stage. //! //! **Where it runs.** In the colour pipeline after every boundary is fitted, repaired and //! mirrored and every face's fill and transparency are settled, before the document is @@ -47,7 +48,7 @@ //! error against its number of curves; ours uses that trade to choose between strokes and //! fills per face, with the error measured on the painted outline. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use inkvec_core::Polyline; use inkvec_fit::primitives::PrimitiveFit; @@ -61,11 +62,12 @@ use crate::pathdata::fmt_fitted; use crate::primitive::stroke_element; use crate::rings; -/// Whether the stage runs: `--detect-strokes` (`Options::detect_strokes`), or the -/// variable `INKVEC_RIBBONS=1`, which the benchmark scripts use to switch the opt-in stage -/// on for a build they cannot pass flags to (the gate's fixed conditions). +/// Whether the stage runs: `Options::detect_strokes` (on unless `--no-detect-strokes`), +/// overridden by the variable `INKVEC_RIBBONS` (`0` off, anything else on), which the +/// benchmark scripts use to switch the stage for a build they cannot pass flags to (the +/// gate's fixed conditions). pub(crate) fn on(args: &crate::args::Args) -> bool { - args.detect_strokes || inkvec_core::env::flag("INKVEC_RIBBONS") + inkvec_core::env::switch("INKVEC_RIBBONS", args.detect_strokes) } /// The stage as the colour pipeline calls it, on the colour document `doc` before its @@ -102,6 +104,7 @@ pub(crate) fn stage( h: map.height, cfg: &cfg_r, decimals: crate::pathdata::emit_decimals(args.precision), + editable: args.editability, }); if let Some(line) = &out.line { crate::diag::stage(args.quiet, || line.clone()); @@ -140,6 +143,9 @@ pub(crate) struct Inputs<'a> { pub(crate) cfg: &'a FitConfig, /// Decimals per written coordinate. pub(crate) decimals: usize, + /// `--editability`: a centreline's circular arcs are written as cubics cut at their + /// extrema (`crate::editable::arcs_as_cubics`), as the fill outlines' are. + pub(crate) editable: bool, } /// What the stage decided: per face written as strokes, its element text, and a report @@ -148,8 +154,40 @@ pub(crate) struct Inputs<'a> { pub(crate) struct Ribbons { /// Face -> the stroke element(s) that replace it, in face order. pub(crate) elements: BTreeMap, + /// Faces that leave with a face written as strokes: each enclosed by that face alone + /// and the colour of what is painted beneath it ([`absorbed_by`]). + pub(crate) absorbed: BTreeSet, /// One report line (`None` when the stage did not run). pub(crate) line: Option, + /// Face -> the geometry its strokes paint, for the faces beneath them to be completed + /// under ([`crate::layers`]). + pub(crate) shapes: BTreeMap, +} + +/// The geometry a ribbon's strokes paint: centrelines (a primitive centreline as its +/// primitive), width, cap and join. +fn stroke_shape(r: &Ribbon) -> crate::layers::StrokeShape { + use crate::layers::{EndCap, JoinKind}; + let (mut lines, mut prims) = (Vec::new(), Vec::new()); + for c in &r.lines { + match c.prim { + Some(p) => prims.push(p.kind), + None => lines.push(c.path.clone()), + } + } + crate::layers::StrokeShape { + lines, + prims, + width: r.width, + cap: match r.cap { + ribbon::Cap::Round => EndCap::Round, + ribbon::Cap::Butt => EndCap::Butt, + }, + join: match r.join { + ribbon::Join::Round => JoinKind::Round, + ribbon::Join::Miter => JoinKind::Other, + }, + } } /// One candidate's outcome, for the decision and the debug line. @@ -192,16 +230,23 @@ pub(crate) fn choose(inp: &Inputs) -> Ribbons { if area < 16.0 || area > 0.5 * image_area { return None; } - let k_vanish = vanishing_params(inp, &nest, &drawers, f); + let k_vanish = vanishing_params(inp, &nest, &drawers, f) + + absorbed_by(inp, &nest, f) + .iter() + .map(|&g| outline_params(inp, &nest, g)) + .sum::(); // Nothing to save: no stroke description can beat writing nothing more. if k_vanish < 4.0 { return None; } - let fit = ribbon::fit_face(&face_rings(inp, f), &mask, inp.cfg, k_vanish); + let chi2_outline = outline_chi2(inp, f); + // The fidelity half of [`decide`], for the solve's merges to stay within. + let cap = |n: usize| chi2_outline + FIT_MARGIN_SD * (2.0 * n as f64).sqrt(); + let fit = ribbon::fit_face(&face_rings(inp, f), &mask, inp.cfg, k_vanish, &cap); Some(Outcome { face: f, fit, - chi2_outline: outline_chi2(inp, f), + chi2_outline, k_vanish, }) }) @@ -221,8 +266,16 @@ pub(crate) fn choose(inp: &Inputs) -> Ribbons { let hex = inkvec_trace::color::to_hex(*c); out.elements.insert( o.face, - element(r, &hex, inp.decimals, &format!("stroke-{}", o.face)), + element( + r, + &hex, + inp.decimals, + &format!("stroke-{}", o.face), + inp.editable, + ), ); + out.shapes.insert(o.face, stroke_shape(r)); + out.absorbed.extend(absorbed_by(inp, &nest, o.face)); saved += o.k_vanish - r.params(); } } @@ -332,7 +385,7 @@ fn face_rings(inp: &Inputs, f: usize) -> Vec { /// its rings once, against its own fitted curve, by exact nearest distance /// ([`ribbon::path_chi2`], the same measure as the strokes' score). fn outline_chi2(inp: &Inputs, f: usize) -> f64 { - let mut seen = std::collections::BTreeSet::new(); + let mut seen = BTreeSet::new(); let mut chi2 = 0.0; for ring in &inp.order[f] { for &(k, _) in ring { @@ -404,6 +457,74 @@ fn vanishing_params(inp: &Inputs, nest: &rings::Nesting, drawers: &[Vec], total } +/// The faces that leave the document with face `f` when it is written as strokes: its +/// children in the nesting that `f` alone encloses (every edge of their outline has `f` +/// on its other side) and that are painted exactly the colour of the face `f` sits in -- +/// flat, opaque, not transparent, the same `#rrggbb`. In a stacked document `f`'s parent +/// is painted across all of `f`'s area, so once `f` is not, such a child paints what +/// already shows: the white inside a black ring on a white page. The emitter drops them +/// only where that still holds after its own stacking ([`crate::emit`]). +/// +/// This is the stacking the artist would have written: a ring drawn as one stroke over the +/// page, not a black disc with a white disc on top. Not from the literature. +pub(crate) fn absorbed_by(inp: &Inputs, nest: &rings::Nesting, f: usize) -> Vec { + let hex = |i: usize| -> Option { + let painted = !inp.clear.get(i).copied().unwrap_or(false) + && inp.opacity.get(i).copied().unwrap_or(1.0) >= 1.0; + match inp.fills.get(i).map(|x| &x.model) { + Some(gradient::FillModel::Flat(c)) if painted => Some(inkvec_trace::color::to_hex(*c)), + _ => None, + } + }; + let Some(under) = nest.parent.get(f).copied().flatten().and_then(hex) else { + return Vec::new(); + }; + (0..inp.order.len()) + .filter(|&g| { + g != f + && nest.parent[g] == Some(f) + && !nest.outer[g].is_empty() + && hex(g).as_deref() == Some(under.as_str()) + && nest.outer[g].iter().all(|&r| { + inp.order[g][r].iter().all(|&(k, _)| { + let e = &inp.map.edges[k]; + let other = if e.left as usize == g { + e.right + } else { + e.left + }; + other as usize == f + }) + }) + }) + .collect() +} + +/// The parameters face `g`'s outline rings write: each ring's segments and move-to, or +/// its primitive's count when the ring is one. +fn outline_params(inp: &Inputs, nest: &rings::Nesting, g: usize) -> f64 { + nest.outer[g] + .iter() + .map(|&r| match inp.order[g][r].as_slice() { + [(k, _)] if inp.prims.get(*k).is_some_and(Option::is_some) => { + inp.prims[*k].as_ref().map_or(0.0, |p| p.params) + } + ring => { + 2.0 + ring + .iter() + .map(|&(k, _)| { + inp.fitted[k] + .segments + .iter() + .map(|s| s.params()) + .sum::() + }) + .sum::() + } + }) + .sum() +} + /// The SVG for a face written as strokes: each centreline its own element, as stroke icon /// sets draw them (lucide writes one `` per stroke), stroked `hex` at the ribbon's /// width with its caps and joins (SVG's default miter limit) -- a path per centreline that @@ -416,7 +537,7 @@ fn vanishing_params(inp: &Inputs, nest: &rings::Nesting, drawers: &[Vec], /// the gate's `turning` signal does -- does not read the pen lifts between strokes as /// turns (lucide at 128 px: 0.0303 -> 0.0389 with one compound path per face, 0.0303 -> /// 0.0306 with the move-tos taken as breaks). -fn element(r: &Ribbon, hex: &str, decimals: usize, id: &str) -> String { +fn element(r: &Ribbon, hex: &str, decimals: usize, id: &str, editable: bool) -> String { let style = format!( "fill=\"none\" stroke=\"{hex}\" stroke-width=\"{w:.decimals$}\" stroke-linecap=\"{c}\" stroke-linejoin=\"{j}\"", w = r.width, @@ -438,7 +559,12 @@ fn element(r: &Ribbon, hex: &str, decimals: usize, id: &str) -> String { } None => { let mut d = String::new(); - fmt_fitted(&line.path, line.path.closed, decimals, &mut d); + if editable { + let path = crate::editable::arcs_as_cubics(&line.path); + fmt_fitted(&path, path.closed, decimals, &mut d); + } else { + fmt_fitted(&line.path, line.path.closed, decimals, &mut d); + } parts.push(format!("")); } } @@ -524,17 +650,17 @@ mod tests { #[test] fn element_writes_one_stroked_path_with_its_join() { - let el = element(&ribbon(1.0, Join::Miter), "#000000", 2, "stroke-3"); + let el = element(&ribbon(1.0, Join::Miter), "#000000", 2, "stroke-3", false); assert_eq!( el, "" ); - assert!(element(&ribbon(1.0, Join::Round), "#123456", 2, "s") + assert!(element(&ribbon(1.0, Join::Round), "#123456", 2, "s", false) .contains("stroke-linejoin=\"round\"")); // Two centrelines: one path each, under a group that carries the style. let mut two = ribbon(1.0, Join::Round); two.lines.push(two.lines[0].clone()); - let el = element(&two, "#000000", 2, "s"); + let el = element(&two, "#000000", 2, "s", false); assert_eq!( el, "" diff --git a/crates/inkvec-cli/src/seams.rs b/crates/inkvec-cli/src/seams.rs index aa07fb14..25a1ffb3 100644 --- a/crates/inkvec-cli/src/seams.rs +++ b/crates/inkvec-cli/src/seams.rs @@ -39,6 +39,7 @@ use std::collections::HashMap; use inkvec_core::Point; use inkvec_fit::curves::{arc_ellipse_center, Segment}; +use inkvec_fit::structural::eval_segment; use inkvec_fit::FittedPath; use crate::faces::FaceRings; @@ -66,6 +67,11 @@ const TAPER: f64 = 12.0; /// it, the most a seam can show, is then under 3% of full scale. const FAINT_SEAM: f32 = 0.12; +/// The lower face's outline, for the test that a move does not cut into it, is flattened +/// with chords within this distance of its curves (px), and a point counts as inside only +/// when it is more than twice this far inside. +const FLAT_TOL: f64 = 0.01; + /// The reach, overridable (`INKVEC_UNDERLAP`, 0 to switch it off) for A/B measurement. pub(crate) fn underlap_width() -> f64 { inkvec_core::env::number("INKVEC_UNDERLAP") @@ -133,6 +139,82 @@ fn oriented(fitted: &[FittedPath], (k, rev): (usize, bool)) -> FittedPath { } } +/// A ring as a polygon within [`FLAT_TOL`] of its curves: each segment cut into as many +/// equal steps of its parameter as that takes. +/// +/// The nesting's own polygon for the ring ([`crate::rings::ring_points`]) has four points +/// per curve, and its chords stray from a long curve that turns far by more than the reach +/// itself: 0.55 px on a cubic turning 74 degrees over 78 px (`noto-emoji/emoji_u1f3c4_1f3fe`, +/// a cubic between two extrema). Where the curve bulges into the lower face, its middle lies +/// that far inside the polygon, so a span moved the full half pixel outward still read as +/// cutting into the lower face, and the whole run went unmended. +fn fine_ring(ring: &[(usize, bool)], fitted: &[FittedPath]) -> Vec { + let mut out = Vec::new(); + for &e in ring { + let path = oriented(fitted, e); + let mut at = path.start; + if out.is_empty() { + out.push(at); + } + for s in &path.segments { + let n = flat_steps(at, s); + out.extend((1..=n).map(|i| eval_segment(s, at, i as f64 / n as f64))); + at = s.end(); + } + } + out +} + +/// Steps of its parameter that keep a segment's chords within [`FLAT_TOL`] of it. A chord +/// over a parameter step `h` strays at most `max|B''|·h²/8`; a cubic's `|B''|` is at most +/// six times its larger second difference of control points, and a circular arc's is +/// `r·Δ²` over its whole sweep `Δ`. At most 1024. +fn flat_steps(a: Point, s: &Segment) -> usize { + let curvature = match *s { + Segment::Line(_) => return 1, + Segment::Cubic(c1, c2, p) => { + let d1 = sub(add(a, c2), scale(c1, 2.0)); + let d2 = sub(add(c1, p), scale(c2, 2.0)); + 6.0 * d1.x.hypot(d1.y).max(d2.x.hypot(d2.y)) + } + Segment::Arc { + rx, + ry, + phi, + large_arc, + sweep, + end, + } => { + let f = arc_ellipse_center(a, rx, ry, phi, large_arc, sweep, end); + f.rx.max(f.ry) * f.delta * f.delta + } + }; + let n = (curvature / (8.0 * FLAT_TOL)).sqrt().ceil(); + if n.is_finite() { + (n as usize).clamp(1, 1024) + } else { + 1 + } +} + +/// The distance from `q` to the closed polygon `r`, px. +fn ring_distance(q: Point, r: &[Point]) -> f64 { + let n = r.len(); + (0..n) + .map(|k| { + let (a, b) = (r[k], r[(k + 1) % n]); + let ab = sub(b, a); + let l2 = dot(ab, ab); + let t = if l2 > 0.0 { + (dot(sub(q, a), ab) / l2).clamp(0.0, 1.0) + } else { + 0.0 + }; + q.dist(add(a, scale(ab, t))) + }) + .fold(f64::INFINITY, f64::min) +} + /// The signed shoelace area of a closed polygon, px²: `Σ_k (x_k·y_(k+1) - x_(k+1)·y_k) / 2`. /// Its sign gives the ring's winding, which fixes which side of each edge is the face's. fn signed_area(r: &[Point]) -> f64 { @@ -670,6 +752,9 @@ pub(crate) fn underlap(f: &Faces, under: &dyn Fn(usize, usize) -> bool, delta: f if area.abs() < 1.0 { continue; } + // The lower face itself, not the nesting's coarse polygon of it ([`fine_ring`]); + // a point on its outline is not inside. + let fine_v = fine_ring(ring, f.fitted); // The upper face across each edge, where that edge needs mending. let need: Vec> = ring .iter() @@ -706,7 +791,9 @@ pub(crate) fn underlap(f: &Faces, under: &dyn Fn(usize, usize) -> bool, delta: f } let inside_u = |q: Point| f.outer[u].iter().any(|&ko| point_in_ring(q, &f.pts[u][ko])); - let inside_v = |q: Point| point_in_ring(q, &f.pts[v][k]); + let inside_v = |q: Point| { + point_in_ring(q, &fine_v) && ring_distance(q, &fine_v) > 2.0 * FLAT_TOL + }; // An arc's ends first move with the run; where that cannot be done // safely anywhere in it, the run is tried again with them pinned. for (d, arcs_move) in [ @@ -870,4 +957,38 @@ mod tests { assert!((m1.y - m0.y - 0.5).abs() < 1e-9 && (m1.x - m0.x).abs() < 1e-9); assert_eq!(b.end(), Point::new(30.0, 0.0)); } + + /// The lower face's polygon follows a long, far-turning cubic to within `FLAT_TOL`, where + /// the nesting's four points per curve leave its middle half a pixel off. + #[test] + fn the_lower_face_is_flattened_close_to_its_curves() { + // The cubic of `noto-emoji/emoji_u1f3c4_1f3fe` between two extrema, closed by a line. + let a = Point::new(183.43, 207.42); + let cubic = Segment::Cubic( + Point::new(187.34, 194.13), + Point::new(198.76, 163.49), + Point::new(239.90, 163.49), + ); + let path = FittedPath { + start: a, + segments: vec![cubic.clone(), Segment::Line(a)], + closed: true, + }; + let fine = fine_ring(&[(0, false)], std::slice::from_ref(&path)); + let mid = eval_segment(&cubic, a, 0.5); + assert!( + ring_distance(mid, &fine) <= FLAT_TOL, + "{}", + ring_distance(mid, &fine) + ); + let coarse = crate::rings::ring_points(&vec![(0, false)], std::slice::from_ref(&path)); + assert!( + ring_distance(mid, &coarse) > 0.3, + "{}", + ring_distance(mid, &coarse) + ); + // A point on the outline is not inside it; one well inside is. + assert!(!(point_in_ring(mid, &fine) && ring_distance(mid, &fine) > 2.0 * FLAT_TOL)); + assert!(point_in_ring(Point::new(200.0, 190.0), &fine)); + } } diff --git a/crates/inkvec-cli/tests/pipeline.rs b/crates/inkvec-cli/tests/pipeline.rs index 425c0a27..27a113fd 100644 --- a/crates/inkvec-cli/tests/pipeline.rs +++ b/crates/inkvec-cli/tests/pipeline.rs @@ -367,14 +367,25 @@ fn a_lone_small_shape_on_a_near_empty_canvas_is_drawn() { /// load for one with it, so both builds take the same path. fn no_restorer(mode: inkvec_restore::Mode) -> Args { Args { - restore: mode, + restore: Some(mode), // Below any residual, so `auto` always decides to restore. restore_threshold: -1.0, restore_weights: Some("no-such-dir/restorer.onnx".into()), + // A lossy container: the sign of compression `auto` needs besides the residual. + lossy: inkvec_sr::Mode::On, ..Args::default() } } +/// The plain trace of `square()` from a lossy container, which `auto`'s fallbacks match. +fn lossy_direct() -> String { + let args = Args { + lossy: inkvec_sr::Mode::On, + ..Args::default() + }; + trace_image(square(), &args).expect("trace succeeds").svg +} + /// `--restore auto` asks for the restorer only where it helps, so a binary that cannot /// restore traces the input as it is and says why, instead of failing the whole trace. #[test] @@ -388,8 +399,59 @@ fn restore_auto_without_a_restorer_traces_directly() { .expect("a restore line"); assert!(note.contains("no restorer is available"), "{note}"); assert!(note.contains("traced directly"), "{note}"); + assert_eq!(t.svg, lossy_direct(), "the fallback is the plain trace"); +} + +/// `--restore auto` restores only an input the file or the pixels say was compressed: the +/// residual alone reads smooth shading in clean art as damage. A clean input whose residual +/// fires (the threshold below any residual) is traced as it is, and the stats say why. +#[test] +fn restore_auto_needs_a_sign_of_compression() { + let args = Args { + lossy: inkvec_sr::Mode::Off, + ..no_restorer(inkvec_restore::Mode::Auto) + }; + let t = trace_image(square(), &args).expect("auto traces directly"); + let note = t + .stats + .iter() + .find(|l| l.starts_with("restore")) + .expect("a restore line"); + assert!(note.contains("no sign of compression"), "{note}"); + let direct = trace_image(square(), &Args::default()).expect("trace succeeds"); + assert_eq!(t.svg, direct.svg, "the plain trace"); + // The kept probe reports what the plain trace reports, apart from the restore line. + let rest: Vec<&String> = t + .stats + .iter() + .filter(|l| !l.starts_with("restore")) + .collect(); + assert_eq!(rest, direct.stats.iter().collect::>()); + assert_eq!(t.lambda, direct.lambda); +} + +/// `--sr auto` likewise cleans only an input that shows resampling or compression. +#[test] +fn sr_auto_needs_a_sign_of_resampling_or_compression() { + let args = Args { + lossy: inkvec_sr::Mode::Off, + ..no_upscaler(inkvec_sr::Mode::Auto) + }; + let t = trace_image(square(), &args).expect("auto traces directly"); + let note = t + .stats + .iter() + .find(|l| l.starts_with("sr ")) + .expect("an sr line"); + assert!( + note.contains("no sign of resampling or compression"), + "{note}" + ); let direct = trace_image(square(), &Args::default()).expect("trace succeeds"); - assert_eq!(t.svg, direct.svg, "the fallback is the plain trace"); + assert_eq!(t.svg, direct.svg, "the plain trace"); + let rest: Vec<&String> = t.stats.iter().filter(|l| !l.starts_with("sr ")).collect(); + assert_eq!(rest, direct.stats.iter().collect::>()); + assert_eq!(t.lambda, direct.lambda); } /// Upscaler flags that cannot give an upscaler: an empty `--sr-command`, the same failure a @@ -400,6 +462,8 @@ fn no_upscaler(mode: inkvec_sr::Mode) -> Args { // Below any residual, so `auto` always decides to clean. sr_threshold: -1.0, sr_command: Some(String::new()), + // A lossy container: the sign of damage `auto` needs besides the residual. + lossy: inkvec_sr::Mode::On, ..Args::default() } } @@ -418,8 +482,7 @@ fn sr_auto_without_an_upscaler_traces_directly() { .expect("an sr line"); assert!(note.contains("no upscaler is available"), "{note}"); assert!(note.contains("traced directly"), "{note}"); - let direct = trace_image(square(), &Args::default()).expect("trace succeeds"); - assert_eq!(t.svg, direct.svg, "the fallback is the plain trace"); + assert_eq!(t.svg, lossy_direct(), "the fallback is the plain trace"); // Monochrome: the probe is a colour trace, so the fallback traces again as asked. let mono = Args { monochrome: true, @@ -432,6 +495,7 @@ fn sr_auto_without_an_upscaler_traces_directly() { .any(|l| l.contains("no upscaler is available"))); let plain_mono = Args { monochrome: true, + lossy: inkvec_sr::Mode::On, ..Args::default() }; assert_eq!( @@ -496,6 +560,45 @@ fn pipeline_with_detect_strokes_and_use_symbols() { assert!(!t.svg.is_empty()); } +/// A black ring of width 10 round a white middle, on a white page: anti-aliased by 4x4 +/// supersampling. +fn ring_on_white() -> Rgba { + image(128, 128, |x, y| { + let mut ink = 0.0; + for sy in 0..4 { + for sx in 0..4 { + let (px, py) = ( + x as f32 + (sx as f32 + 0.5) / 4.0, + y as f32 + (sy as f32 + 0.5) / 4.0, + ); + let r = ((px - 64.0).powi(2) + (py - 64.0).powi(2)).sqrt(); + if (r - 36.0).abs() <= 5.0 { + ink += 1.0 / 16.0; + } + } + } + let v = 1.0 - ink; + [v, v, v, 1.0] + }) +} + +#[test] +fn a_ring_on_white_becomes_one_stroke_and_its_middle_leaves_with_it() { + let args = Args { + detect_strokes: true, + ..Args::default() + }; + let svg = traced_svg(ring_on_white(), &args); + assert!( + svg.contains("stroke=\"#000000\"") || svg.contains("stroke=\"#000\""), + "{svg}" + ); + // The page and the stroke: the white middle is the page showing through, not a white + // disc painted over a black one. + assert_eq!(svg.matches("fill=\"#fff").count(), 1, "{svg}"); + assert_eq!(shapes(&svg), 2, "{svg}"); +} + #[test] fn pipeline_with_layers() { let img = image(64, 64, |x, y| { @@ -533,7 +636,7 @@ fn pipeline_with_select_hypotheses() { #[test] fn pipeline_with_restore_auto() { let args = Args { - restore: inkvec_restore::Mode::Auto, + restore: Some(inkvec_restore::Mode::Auto), ..Args::default() }; let t = trace_image(square(), &args).expect("trace succeeds"); diff --git a/crates/inkvec-core/src/lib.rs b/crates/inkvec-core/src/lib.rs index 341013a8..5ac50dc0 100644 --- a/crates/inkvec-core/src/lib.rs +++ b/crates/inkvec-core/src/lib.rs @@ -26,6 +26,8 @@ //! down, as `f64`. pub mod env; +pub mod likelihood; +pub mod noise; pub mod predicates; pub mod progress; diff --git a/crates/inkvec-core/src/likelihood.rs b/crates/inkvec-core/src/likelihood.rs new file mode 100644 index 00000000..0d594ef5 --- /dev/null +++ b/crates/inkvec-core/src/likelihood.rs @@ -0,0 +1,1243 @@ +//! The boundary likelihood: the interface between recovering the picture (boundary chain) +//! and writing it with the fewest coordinates (representation chain). +//! +//! An anti-aliased pixel holds the area of each face inside it, so summed over any set of +//! whole pixels a face's unmixed weights are its exact area there, whatever the shape +//! (`docs/theory/chain-boundary.md`, B2.1; `column_sum_eq_average` in +//! `formal/InkvecTheory`). A candidate description is therefore scored against the pixels by +//! computing, for each *window* of pixels, the area its curves give the face, and comparing +//! that with the measured sum: no boundary points are extracted first. This module holds the +//! vocabulary both chains share: +//! +//! * [`Piece`]: a candidate curve's pieces (lines, quadratic and cubic Béziers, elliptical +//! arcs), in pixels, with pixel centres on integers; +//! * [`RenderModel`]: how the renderer draws them (arcs as the cubics usvg writes); +//! * [`Window`] and [`left_area`]: a window of whole pixels along one grid line, and the exact +//! area a curve crossing it gives its left face there; +//! * [`RunObs`], [`Chi2`], [`Floor`], [`RunMoments`]: one measured window, a score, the +//! renderer floor, and least-squares fits of polynomial graphs over ranges of windows in +//! `O(p²)` per range; +//! * [`JunctionReport`], [`CornerProposal`]: what the boundary chain reports where runs end; +//! * [`BoundaryLikelihood`]: the evaluator the representation chain scores descriptions with. +//! +//! Coordinates are inkvec's: pixel `(x, y)` covers `[x − ½, x + ½] × [y − ½, y + ½]`, `y` +//! down. A curve's *left* face lies on `(d.y, −d.x)` of its direction `d` (walking right, the +//! face above; walking down, the face to the east), the planar map's convention. + +use crate::Point; +use std::f64::consts::PI; +use std::ops::Range; + +/// One piece of a candidate curve, in pixels. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Piece { + /// A straight segment. + Line([Point; 2]), + /// A quadratic Bézier. + Quad([Point; 3]), + /// A cubic Bézier. + Cubic([Point; 4]), + /// An elliptical arc, drawn as the renderer draws it ([`RenderModel::as_rendered`]). + Arc(EllipticalArc), +} + +/// An elliptical arc in centre form: the points `centre + R(x_rotation)·(rx cos θ, ry sin θ)` +/// for `θ` from `start_angle` through `start_angle + sweep_angle` (kurbo's `Arc`, which usvg +/// builds from SVG's endpoint form). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct EllipticalArc { + /// Centre, px. + pub centre: Point, + /// Radii along the rotated axes, px. + pub radii: (f64, f64), + /// Rotation of the ellipse's first axis from `+x` towards `+y`, radians. + pub x_rotation: f64, + /// Parameter angle at the start, radians. + pub start_angle: f64, + /// Signed parameter sweep, radians. + pub sweep_angle: f64, +} + +impl Piece { + /// The point at parameter `t ∈ [0, 1]`. + pub fn point(&self, t: f64) -> Point { + match *self { + Piece::Line([a, b]) => Point::new(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)), + Piece::Quad([a, b, c]) => { + let m = 1.0 - t; + Point::new( + m * m * a.x + 2.0 * m * t * b.x + t * t * c.x, + m * m * a.y + 2.0 * m * t * b.y + t * t * c.y, + ) + } + Piece::Cubic([a, b, c, d]) => { + let m = 1.0 - t; + let (k0, k1, k2, k3) = (m * m * m, 3.0 * m * m * t, 3.0 * m * t * t, t * t * t); + Point::new( + k0 * a.x + k1 * b.x + k2 * c.x + k3 * d.x, + k0 * a.y + k1 * b.y + k2 * c.y + k3 * d.y, + ) + } + Piece::Arc(arc) => arc.at(arc.start_angle + t * arc.sweep_angle), + } + } + + /// An SVG elliptical arc in endpoint form (`A rx ry phi large-arc sweep x y` from + /// `start`), converted to centre form as SVG's implementation notes (F.6.5) do, with + /// out-of-range radii scaled up (F.6.6); a line where the arc degenerates. `phi` in + /// radians; `sweep` true runs towards increasing angle (clockwise on a y-down screen). + pub fn from_svg_arc( + start: Point, + rx: f64, + ry: f64, + phi: f64, + large_arc: bool, + sweep: bool, + end: Point, + ) -> Piece { + let (mut rx, mut ry) = (rx.abs(), ry.abs()); + if start.dist(end) < 1e-12 || rx < 1e-12 || ry < 1e-12 { + return Piece::Line([start, end]); + } + let (sp, cp) = phi.sin_cos(); + let (hx, hy) = ((start.x - end.x) / 2.0, (start.y - end.y) / 2.0); + let (x1, y1) = (cp * hx + sp * hy, -sp * hx + cp * hy); + let lambda = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry); + if lambda > 1.0 { + let k = lambda.sqrt(); + rx *= k; + ry *= k; + } + let num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1; + let den = rx * rx * y1 * y1 + ry * ry * x1 * x1; + let mut coef = (num.max(0.0) / den.max(1e-300)).sqrt(); + if large_arc == sweep { + coef = -coef; + } + let (cx1, cy1) = (coef * rx * y1 / ry, -coef * ry * x1 / rx); + let centre = Point::new( + cp * cx1 - sp * cy1 + (start.x + end.x) / 2.0, + sp * cx1 + cp * cy1 + (start.y + end.y) / 2.0, + ); + let angle = |ux: f64, uy: f64, vx: f64, vy: f64| -> f64 { + (ux * vy - uy * vx).atan2(ux * vx + uy * vy) + }; + let (ux, uy) = ((x1 - cx1) / rx, (y1 - cy1) / ry); + let (vx, vy) = ((-x1 - cx1) / rx, (-y1 - cy1) / ry); + let start_angle = angle(1.0, 0.0, ux, uy); + let mut sweep_angle = angle(ux, uy, vx, vy); + if !sweep && sweep_angle > 0.0 { + sweep_angle -= 2.0 * PI; + } else if sweep && sweep_angle < 0.0 { + sweep_angle += 2.0 * PI; + } + Piece::Arc(EllipticalArc { + centre, + radii: (rx, ry), + x_rotation: phi, + start_angle, + sweep_angle, + }) + } +} + +impl EllipticalArc { + /// The point at parameter angle `a`. + pub fn at(&self, a: f64) -> Point { + let (u, v) = rotated(self.radii, self.x_rotation, a); + Point::new(self.centre.x + u, self.centre.y + v) + } + + /// The cubics kurbo's `Arc::append_iter(tolerance)` writes for this arc, which is how + /// usvg converts every SVG arc, circle, ellipse and rounded corner before resvg draws + /// it (`usvg::parser::shapes`, tolerance 0.1 user units). `tolerance` is in the arc's own + /// units (px here). Port of kurbo 0.13.1 `arc.rs`; the subdivision count is + /// `ceil(max((1.1163·r_max/tolerance)^(1/6), 4)·|sweep|/2π)`, so an arc of under a quarter + /// turn is one cubic for every radius under about 3600 tolerances. + pub fn to_cubics(&self, tolerance: f64) -> Vec { + let (rx, ry) = self.radii; + if rx <= 0.0 || ry <= 0.0 || self.sweep_angle == 0.0 || tolerance <= 0.0 { + return vec![Piece::Line([ + self.at(self.start_angle), + self.at(self.start_angle + self.sweep_angle), + ])]; + } + let sign = self.sweep_angle.signum(); + let scaled_err = rx.max(ry) / tolerance; + let n_err = (1.1163 * scaled_err).powf(1.0 / 6.0).max(3.999_999); + let n = (n_err * self.sweep_angle.abs() * (1.0 / (2.0 * PI))) + .ceil() + .max(1.0); + let step = self.sweep_angle / n; + let arm = (4.0 / 3.0) * (0.25 * step).abs().tan() * sign; + let mut out = Vec::with_capacity(n as usize); + let mut a0 = self.start_angle; + let mut p0 = rotated(self.radii, self.x_rotation, a0); + let c = self.centre; + for _ in 0..n as usize { + let a1 = a0 + step; + let d0 = rotated(self.radii, self.x_rotation, a0 + PI / 2.0); + let p3 = rotated(self.radii, self.x_rotation, a1); + let d3 = rotated(self.radii, self.x_rotation, a1 + PI / 2.0); + out.push(Piece::Cubic([ + Point::new(c.x + p0.0, c.y + p0.1), + Point::new(c.x + p0.0 + arm * d0.0, c.y + p0.1 + arm * d0.1), + Point::new(c.x + p3.0 - arm * d3.0, c.y + p3.1 - arm * d3.1), + Point::new(c.x + p3.0, c.y + p3.1), + ])); + a0 = a1; + p0 = p3; + } + out + } +} + +/// `R(rot)·(rx cos a, ry sin a)`. +fn rotated(radii: (f64, f64), rot: f64, a: f64) -> (f64, f64) { + let (u, v) = (radii.0 * a.cos(), radii.1 * a.sin()); + let (s, c) = rot.sin_cos(); + (u * c - v * s, u * s + v * c) +} + +/// How the gate's renderer draws a description: resvg 0.48 (usvg converts arcs to cubics at +/// 0.1 user units; tiny-skia then rasterises at 8× with 4 × 4 samples per device pixel, +/// which the corpus builder box-filters to the intake). The window areas of this module are +/// exact for the cubics; the sampling lattice and tiny-skia's own curve flattening are the +/// renderer floor ([`Floor`]). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct RenderModel { + /// Draw arcs as usvg's cubics at this tolerance (px: 0.1 times the pixels per user unit + /// of the artist's file), as resvg does; `None` (the default) draws them exactly. The + /// engine's model is the exact geometry, with whatever a renderer adds left to the + /// intake's calibrated floor; the cubics remain for measuring a known renderer. + pub arc_tolerance_px: Option, + /// The intake's blur, as its second moment along a window's strip, px² (0 on a native + /// render): a window's sum is the face's area profile convolved with the blur, which + /// moves it by `½ μ₂ A''` on a curve (`chain-boundary.md`, "Blur"). + pub psf_mu2: f64, +} + +impl Default for RenderModel { + /// Exact geometry on a native render. + fn default() -> Self { + Self { + arc_tolerance_px: None, + psf_mu2: 0.0, + } + } +} + +impl RenderModel { + /// usvg's model: arcs as its cubics at 0.1 user units, one user unit per pixel. + pub fn usvg() -> Self { + Self { + arc_tolerance_px: Some(0.1), + psf_mu2: 0.0, + } + } + + /// The pieces as the renderer draws them: with an arc tolerance, every arc replaced by + /// usvg's cubics; the rest unchanged. + pub fn as_rendered(&self, pieces: &[Piece]) -> Vec { + let Some(tol) = self.arc_tolerance_px else { + return pieces.to_vec(); + }; + let mut out = Vec::with_capacity(pieces.len()); + for p in pieces { + match p { + Piece::Arc(a) => out.extend(a.to_cubics(tol)), + other => out.push(*other), + } + } + out + } + + /// The area the drawn curve `drawn` gives its left face in window `w`, as this intake + /// measures it: [`left_area`], plus `½ μ₂ A''` under a blur, `A''` the second difference + /// of the window's area profile across its strip (the curve moved one pixel either way). + pub fn window_area(&self, drawn: &[Piece], w: &Window) -> f64 { + let a = left_area(drawn, w); + if self.psf_mu2 <= 0.0 { + return a; + } + let (dx, dy) = match w.axis { + Axis::Column => (1.0, 0.0), + Axis::Row => (0.0, 1.0), + }; + let plus = left_area(&translated(drawn, -dx, -dy), w); + let minus = left_area(&translated(drawn, dx, dy), w); + if !(plus.is_finite() && minus.is_finite()) { + return a; + } + a + 0.5 * self.psf_mu2 * (plus - 2.0 * a + minus) + } +} + +/// `pieces` moved by `(dx, dy)`. +pub fn translated(pieces: &[Piece], dx: f64, dy: f64) -> Vec { + let m = |p: Point| Point::new(p.x + dx, p.y + dy); + pieces + .iter() + .map(|p| match *p { + Piece::Line(q) => Piece::Line(q.map(m)), + Piece::Quad(q) => Piece::Quad(q.map(m)), + Piece::Cubic(q) => Piece::Cubic(q.map(m)), + Piece::Arc(a) => Piece::Arc(EllipticalArc { + centre: m(a.centre), + ..a + }), + }) + .collect() +} + +/// Which grid lines a window runs along. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Axis { + /// A column of pixels: the boundary crosses it as a graph over `x`, within 45° of + /// horizontal. + Column, + /// A row of pixels: the boundary crosses it as a graph over `y`. + Row, +} + +/// A window: the pixels `lo..=hi` along one grid line (`x = line` for a column, `y = line` +/// for a row). Its strip is `[line − ½, line + ½]` across and `[lo − ½, hi + ½]` along. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Window { + /// Column or row. + pub axis: Axis, + /// The column's `x` (or the row's `y`). + pub line: i32, + /// First pixel along the line. + pub lo: i32, + /// Last pixel along the line, inclusive. + pub hi: i32, +} + +impl Window { + /// Number of pixels. + pub fn len(&self) -> usize { + (self.hi - self.lo + 1).max(0) as usize + } + + /// Whether the window holds no pixel. + pub fn is_empty(&self) -> bool { + self.hi < self.lo + } + + /// The pixels `(x, y)` in order along the line. + pub fn pixels(&self) -> impl Iterator + '_ { + (self.lo..=self.hi).map(move |k| match self.axis { + Axis::Column => (self.line, k), + Axis::Row => (k, self.line), + }) + } +} + +/// A cubic polynomial `c0 + c1 t + c2 t² + c3 t³`. +#[derive(Debug, Clone, Copy)] +struct Poly([f64; 4]); + +impl Poly { + fn eval(&self, t: f64) -> f64 { + let c = self.0; + c[0] + t * (c[1] + t * (c[2] + t * c[3])) + } +} + +/// Power-basis coordinates of a piece over `t ∈ [0, 1]`; `None` for an arc (convert first). +fn power(p: &Piece) -> Option<(Poly, Poly)> { + let comp = |f: &dyn Fn(Point) -> f64| -> Poly { + match p { + Piece::Line([a, b]) => Poly([f(*a), f(*b) - f(*a), 0.0, 0.0]), + Piece::Quad([a, b, c]) => Poly([ + f(*a), + 2.0 * (f(*b) - f(*a)), + f(*a) - 2.0 * f(*b) + f(*c), + 0.0, + ]), + Piece::Cubic([a, b, c, d]) => Poly([ + f(*a), + 3.0 * (f(*b) - f(*a)), + 3.0 * (f(*a) - 2.0 * f(*b) + f(*c)), + -f(*a) + 3.0 * f(*b) - 3.0 * f(*c) + f(*d), + ]), + Piece::Arc(_) => Poly([0.0; 4]), + } + }; + if matches!(p, Piece::Arc(_)) { + return None; + } + Some((comp(&|q| q.x), comp(&|q| q.y))) +} + +/// The roots in `(0, 1)` of `q(t) = level`, appended to `out`. Monotone pieces between the +/// critical points of `q` are bisected; a double root (a tangency) changes no sign and is +/// not reported, which is what the integrals below need. +fn roots_in_unit(q: &Poly, level: f64, out: &mut Vec) { + let c = q.0; + let (a, b, cc) = (3.0 * c[3], 2.0 * c[2], c[1]); + let mut cuts = [0.0, 1.0, 1.0, 1.0]; + let mut n = 1; + let scale = c.iter().fold(0.0f64, |m, v| m.max(v.abs())).max(1e-300); + if a.abs() > 1e-14 * scale { + let disc = b * b - 4.0 * a * cc; + if disc > 0.0 { + let s = disc.sqrt(); + let q0 = -0.5 * (b + if b >= 0.0 { s } else { -s }); + for r in [q0 / a, if q0 != 0.0 { cc / q0 } else { f64::NAN }] { + if r > 0.0 && r < 1.0 { + cuts[n] = r; + n += 1; + } + } + } + } else if b.abs() > 1e-14 * scale { + let r = -cc / b; + if r > 0.0 && r < 1.0 { + cuts[n] = r; + n += 1; + } + } + cuts[n] = 1.0; + n += 1; + let cuts = &mut cuts[..n]; + cuts.sort_by(f64::total_cmp); + for w in cuts.windows(2) { + let (mut lo, mut hi) = (w[0], w[1]); + if hi - lo <= 0.0 { + continue; + } + let (flo, fhi) = (q.eval(lo) - level, q.eval(hi) - level); + if flo == 0.0 && lo > 0.0 { + out.push(lo); + continue; + } + if flo * fhi >= 0.0 { + continue; + } + let up = fhi > flo; + for _ in 0..80 { + let mid = 0.5 * (lo + hi); + if mid <= lo || mid >= hi { + break; + } + if (q.eval(mid) - level > 0.0) == up { + hi = mid; + } else { + lo = mid; + } + } + out.push(0.5 * (lo + hi)); + } +} + +/// One pass of a curve through a strip: the integral `∫ (clamp(v) − v_lo) du`, the net advance +/// `∫ du`, and the range of `v` it reached. +#[derive(Debug, Clone, Copy)] +struct Pass { + area: f64, + adv: f64, + vmin: f64, + vmax: f64, +} + +/// The passes of one piece through the strip `u ∈ [u0, u1]`: per maximal `t`-interval inside +/// it, `∫ (clamp(v(t), vlo, vhi) − vlo) u'(t) dt` and `∫ u'(t) dt`, with whether the interval +/// touches `t = 0` and `t = 1` (so that passes continue across pieces). Exact up to the root +/// finding: between breakpoints the integrand is a polynomial integrated in closed form. +fn passes( + u: &Poly, + v: &Poly, + u0: f64, + u1: f64, + vlo: f64, + vhi: f64, + out: &mut Vec<(Pass, bool, bool)>, +) { + let mut ts: Vec = Vec::with_capacity(16); + ts.push(0.0); + for (q, lv) in [(u, u0), (u, u1), (v, vlo), (v, vhi)] { + roots_in_unit(q, lv, &mut ts); + } + ts.push(1.0); + ts.sort_by(f64::total_cmp); + // (v − vlo)·u' as a degree-5 polynomial, and its antiderivative. + let va = [v.0[0] - vlo, v.0[1], v.0[2], v.0[3]]; + let ud = [u.0[1], 2.0 * u.0[2], 3.0 * u.0[3]]; + let mut prod = [0.0f64; 6]; + for (i, a) in va.iter().enumerate() { + for (j, b) in ud.iter().enumerate() { + prod[i + j] += a * b; + } + } + let anti = |t: f64| -> f64 { + let mut acc = 0.0; + for k in (0..6).rev() { + acc = acc * t + prod[k] / (k as f64 + 1.0); + } + acc * t + }; + let mut cur: Option<(Pass, bool)> = None; + for w in ts.windows(2) { + let (ta, tb) = (w[0], w[1]); + if tb <= ta { + continue; + } + let tm = 0.5 * (ta + tb); + let um = u.eval(tm); + if um < u0 || um > u1 { + if let Some((p, at0)) = cur.take() { + out.push((p, at0, false)); + } + continue; + } + let du = u.eval(tb) - u.eval(ta); + let (va, vm, vb) = (v.eval(ta), v.eval(tm), v.eval(tb)); + let add = if vm <= vlo { + 0.0 + } else if vm >= vhi { + (vhi - vlo) * du + } else { + anti(tb) - anti(ta) + }; + let p = cur.get_or_insert(( + Pass { + area: 0.0, + adv: 0.0, + vmin: f64::INFINITY, + vmax: f64::NEG_INFINITY, + }, + ta == 0.0, + )); + p.0.area += add; + p.0.adv += du; + p.0.vmin = p.0.vmin.min(va.min(vm).min(vb)); + p.0.vmax = p.0.vmax.max(va.max(vm).max(vb)); + } + if let Some((p, at0)) = cur.take() { + out.push((p, at0, true)); + } +} + +/// The area the curve `pieces` gives its *left* face inside window `w`, px². +/// +/// Exact for lines and Béziers (arcs are integrated through their renderer cubics at a +/// tolerance of `1e-6` px, so convert them with [`RenderModel::as_rendered`] first to score +/// a candidate as drawn). By the window identity this is what the left face's unmixed +/// weights summed over the window measure. The curve must cross the window's strip once +/// (enter through one side, leave through the other), as a run's curve does; it may wiggle +/// or fold inside it, and leave the window along the line, which is the clamp. +/// +/// With `I = ∫ (clamp(v) − v_lo) du` along the curve's pass through the strip and `Δ = ±1` its +/// net advance (`u` across the strip, `v` along it): a column's left face has area +/// `I + h(1 − Δ)/2`, a row's `−I + h(1 + Δ)/2`, `h` the window's length (Green's theorem with +/// the form `(v − v_lo) du`; `chain-boundary.md` B2.1). Only the passes that reach the +/// window (within a pixel of it along the line) count, so a curve that crosses the same +/// column twice, a U, is scored at each window by its own pass. A curve with no pass near +/// the window leaves it wholly to one face: the left one when the nearest pass has the +/// window on its left. +pub fn left_area(pieces: &[Piece], w: &Window) -> f64 { + let (u0, u1) = (w.line as f64 - 0.5, w.line as f64 + 0.5); + let (vlo, vhi) = (w.lo as f64 - 0.5, w.hi as f64 + 0.5); + let h = vhi - vlo; + // The passes of every piece, joined across piece boundaries. + let mut all: Vec = Vec::new(); + let mut open = false; + let mut scratch = Vec::with_capacity(4); + let mut acc = |p: &Piece, all: &mut Vec, open: &mut bool| { + let Some((px, py)) = power(p) else { return }; + let (u, v) = match w.axis { + Axis::Column => (px, py), + Axis::Row => (py, px), + }; + let (umin, umax) = u_range(p, w.axis); + if umax < u0 || umin > u1 { + *open = false; + return; + } + scratch.clear(); + passes(&u, &v, u0, u1, vlo, vhi, &mut scratch); + if scratch.is_empty() { + *open = false; + } + for (k, &(ps, at0, at1)) in scratch.iter().enumerate() { + match all.last_mut() { + Some(last) if *open && k == 0 && at0 => { + last.area += ps.area; + last.adv += ps.adv; + last.vmin = last.vmin.min(ps.vmin); + last.vmax = last.vmax.max(ps.vmax); + } + _ => all.push(ps), + } + *open = at1; + } + }; + for p in pieces { + match p { + Piece::Arc(a) => { + for c in a.to_cubics(1e-6) { + acc(&c, &mut all, &mut open); + } + } + other => acc(other, &mut all, &mut open), + } + } + let near: Vec<&Pass> = all + .iter() + .filter(|p| p.vmax >= vlo - 1.0 && p.vmin <= vhi + 1.0) + .collect(); + let (i_sum, adv) = if near.is_empty() { + // The window is one face's: the nearest pass's side decides. + let Some(p) = all.iter().min_by(|a, b| { + let da = (a.vmin - vhi).max(vlo - a.vmax); + let db = (b.vmin - vhi).max(vlo - b.vmax); + da.total_cmp(&db) + }) else { + return f64::NAN; + }; + let below = p.vmin > vhi; // the curve passes beyond the window's high end + let forward = p.adv > 0.0; + // Column: walking +x the left face is on the low side (towards v_lo): it covers a + // window that lies on the low side of the pass, i.e. when the pass is below it. + let left_has_it = match w.axis { + Axis::Column => below == forward, + Axis::Row => below != forward, + }; + return if left_has_it { h } else { 0.0 }; + } else { + near.iter() + .fold((0.0, 0.0), |(a, d), p| (a + p.area, d + p.adv)) + }; + match w.axis { + Axis::Column => i_sum + h * (1.0 - adv) / 2.0, + Axis::Row => -i_sum + h * (1.0 + adv) / 2.0, + } +} + +fn u_range(p: &Piece, axis: Axis) -> (f64, f64) { + let pts: &[Point] = match p { + Piece::Line(q) => q, + Piece::Quad(q) => q, + Piece::Cubic(q) => q, + Piece::Arc(_) => return (f64::NEG_INFINITY, f64::INFINITY), + }; + let f = |q: &Point| if axis == Axis::Column { q.x } else { q.y }; + pts.iter() + .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), q| { + (lo.min(f(q)), hi.max(f(q))) + }) +} + +/// One measured run window of an edge. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct RunObs { + /// The window. + pub window: Window, + /// Position along the edge's starting geometry, px of arclength from its start. + pub s: f64, + /// Measured area of the edge's left face in the window: the sum of its unmixed weights + /// over the window's pixels, unclamped. + pub sum: f64, + /// Variance of `sum`: quantisation of the partial pixels and the intake's per-window + /// floor (not the per-edge offset, [`BoundaryLikelihood::edge_offset_var`]), times the + /// window's replica count (see `share`). + pub var: f64, + /// Whether the left face lies on the window's low side (above a column, west of a row) + /// on the starting geometry. + pub left_low: bool, + /// This window's share of one independent measurement: `1/k` in a stretch of `k` + /// replicas (neighbouring windows that see the edge at the same sub-pixel phase repeat one + /// measurement and its error, as on an axis or a diagonal), else 1. `var` is already `k` + /// times one window's, so that the stretch weighs as one measurement. + pub share: f64, +} + +impl RunObs { + /// The measured mean position of the boundary across the window's strip, along the + /// line (a column's `y`, a row's `x`), px: the window identity read as a point + /// measurement for curves that are graphs over the strip. + pub fn mean_position(&self) -> f64 { + let lo = self.window.lo as f64 - 0.5; + if self.left_low { + lo + self.sum + } else { + lo + self.window.len() as f64 - self.sum + } + } +} + +/// A score: `χ²` and the number of measurements it sums, so that at the truth +/// `E χ² = dof` (`chain-boundary.md` B2.4). +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct Chi2 { + /// `Σ r² / V` over the windows, with each window's own variance. + pub chi2: f64, + /// Number of windows (constant over any segmentation of a run: the partition). + pub m: usize, + /// `χ²` with the per-edge offset as well: the windows of one edge share an unknown offset + /// of variance [`BoundaryLikelihood::edge_offset_var`] (A3), so this is + /// `χ² − (b² (Σ r/V)²) / (1 + b² Σ 1/V)`, the Sherman–Morrison form of the covariance + /// `V + b² 1 1ᵀ` ([`chi2_correlated`] with `ρ = 1`). Equal to `chi2` where it is zero. + pub chi2_floor: f64, + /// Independent measurements among the windows: `Σ share` (replicas count once). + pub dof: f64, + /// The robust cost: Huber's at [`crate::noise::huber_kappa`] of the intake's tail, summed + /// over the standardised innovations of `chi2_floor`. Equal to `chi2_floor` while every + /// innovation is within the threshold (always, on a clean intake's truth). + pub cost: f64, +} + +/// Sum of two scores over disjoint measurements. +impl std::ops::Add for Chi2 { + type Output = Chi2; + + fn add(self, o: Chi2) -> Chi2 { + Chi2 { + chi2: self.chi2 + o.chi2, + m: self.m + o.m, + chi2_floor: self.chi2_floor + o.chi2_floor, + dof: self.dof + o.dof, + cost: self.cost + o.cost, + } + } +} + +/// Score residuals `r` (one per window, variances `v`, shares `share`) with an offset of +/// variance `offset_var` shared by all of them and Huber's threshold `kappa`. +pub fn score(r: &[f64], v: &[f64], share: &[f64], offset_var: f64, kappa: f64) -> Chi2 { + let c = Correlated { + tau2: offset_var.max(0.0), + rho: 1.0, + }; + let cs = vec![c; r.len()]; + let z = innovations(r, v, &cs); + let chi2_floor: f64 = z.iter().map(|z| z * z).sum(); + Chi2 { + chi2: r.iter().zip(v).map(|(r, v)| r * r / v.max(1e-300)).sum(), + m: r.len(), + chi2_floor, + dof: share.iter().sum(), + cost: z.iter().map(|&z| crate::noise::huber(z, kappa)).sum(), + } +} + +/// The renderer floor: what the renderer adds to the window sums beyond quantisation +/// (`chain-boundary.md` B2.3; measured by `bench/theory/renderer_floor.py`). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Floor { + /// Samples per pixel along each axis of the renderer's sampling lattice (32 for the + /// corpus intake: 8× rendering, 4 × 4 samples per device pixel). + pub lattice: u32, + /// Variance per window that behaves as independent noise (generic slopes), px². + pub window_var: f64, + /// Variance of the offset shared by every window of one edge running within a lattice + /// step of an axis or a diagonal, px²: `1/(12 n²)` for an `n`-lattice. Different edges are + /// independent (A3). Add it to tests of absolute positions; leave it out of tests along + /// one edge. + pub edge_var: f64, +} + +impl Floor { + /// The floor of an `n × n` point-sampling lattice: `1/(12 n³)` per window at generic + /// slopes, `1/(12 n²)` per near-axis edge. + pub fn lattice(n: u32) -> Self { + let n = n.max(1) as f64; + Self { + lattice: n as u32, + window_var: 1.0 / (12.0 * n * n * n), + edge_var: 1.0 / (12.0 * n * n), + } + } +} + +/// The correlated part of the renderer floor at one run window: a stationary first-order +/// autoregression along the run, with variance `tau2` (px²) and correlation `rho` with the +/// window before (`rho = 1`: an offset the windows share, A3; `tau2 = 0`: none). +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct Correlated { + /// Variance of the correlated part, px². + pub tau2: f64, + /// Correlation with the previous window's correlated part, in `[0, 1]`. + pub rho: f64, +} + +/// `−2 log L` of residuals `r` whose errors are independent with variances `v` plus a +/// correlated part `c` (per window), split into its quadratic part `rᵀ Σ⁻¹ r` and +/// `log det Σ`: a scalar Kalman filter along the run, `O(n)`. With `rho = 1` and one `tau2` +/// this is the Sherman–Morrison form of `V + τ² 1 1ᵀ`; with `tau2 = 0`, `Σ r²/v`. +/// +/// The correlated part follows `g_i = ρ_i (τ_i/τ_{i−1}) g_{i−1} + η_i`, so that its variance +/// is `τ_i²` at every window and a class change along the run (a line meeting a curve) needs +/// no special case. +pub fn chi2_correlated(r: &[f64], v: &[f64], c: &[Correlated]) -> (f64, f64) { + let (mut chi2, mut logdet) = (0.0, 0.0); + filter(r, v, c, |nu, f| { + chi2 += nu * nu / f; + logdet += f.ln(); + }); + (chi2, logdet) +} + +/// The standardised innovations `νᵢ/√Fᵢ` of [`chi2_correlated`]'s filter: independent unit +/// normals at the truth, whatever the correlation, so a robust cost applies to them one by +/// one. +pub fn innovations(r: &[f64], v: &[f64], c: &[Correlated]) -> Vec { + let mut out = Vec::with_capacity(r.len()); + filter(r, v, c, |nu, f| out.push(nu / f.sqrt())); + out +} + +/// The scalar Kalman filter of [`chi2_correlated`], calling `each(νᵢ, Fᵢ)` per window. +fn filter(r: &[f64], v: &[f64], c: &[Correlated], mut each: impl FnMut(f64, f64)) { + // State: the correlated part's mean and variance given the windows so far. + let (mut m, mut p) = (0.0f64, 0.0f64); + let mut tau_prev = 0.0f64; + for i in 0..r.len() { + let ci = c.get(i).copied().unwrap_or_default(); + let tau = ci.tau2.max(0.0).sqrt(); + if i == 0 || tau_prev == 0.0 { + m = 0.0; + p = tau * tau; + } else { + let a = ci.rho.clamp(0.0, 1.0) * tau / tau_prev; + m *= a; + p = a * a * p + tau * tau * (1.0 - ci.rho.clamp(0.0, 1.0).powi(2)); + } + let f = (p + v[i]).max(1e-300); + let nu = r[i] - m; + each(nu, f); + let k = p / f; + m += k * nu; + p *= 1.0 - k; + tau_prev = tau; + } +} + +/// A place where a run may end in a corner, proposed for the representation to test +/// (`chain-boundary.md` B3.3). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CornerProposal { + /// The edge. + pub edge: u32, + /// Index of the run observation at the centre of the five whose fourth difference fired. + pub index: usize, + /// `|D| / √(70 V)`: the fourth difference in standard deviations. + pub z: f64, + /// Where, on the starting geometry. + pub at: Point, +} + +/// One arm of a junction. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Arm { + /// The edge. + pub edge: u32, + /// Whether the edge starts at the junction (else it ends there). + pub at_start: bool, + /// Direction leaving the junction, radians from `+x` towards `+y`. + pub direction: f64, + /// Standard deviation of `direction`, radians. + pub direction_sd: f64, +} + +/// A junction where three or more faces meet, its arms in cyclic order, and the pairs of +/// arms that may be one curve continuing through it (`chain-representation.md` A4). +#[derive(Debug, Clone, PartialEq)] +pub struct JunctionReport { + /// Node id in the planar map. + pub node: u32, + /// Starting position. + pub at: Point, + /// Arms in increasing `direction` (counter-clockwise on screen is decreasing; this is + /// the order of angles from `+x` towards `+y`). + pub arms: Vec, + /// `(i, j, z)`: arms `i` and `j` (indices into `arms`) leave in opposite directions to + /// within `z` standard deviations of their difference, so they may continue one another. + pub continuations: Vec<(usize, usize, f64)>, +} + +/// Owner of a local term: the vertex or thin stretch whose pixels it scores. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Owner { + /// A junction node of the planar map. + Junction(u32), + /// A corner proposal, by index. + Corner(u32), +} + +/// Least-squares fits of polynomial graphs over ranges of an edge's run windows from prefix +/// sums (`chain-boundary.md` B2.4): the window identity read as a linear model, +/// `mean_position = Σ_k θ_k · mean over the strip of (u − u_ref)^k`. +#[derive(Debug, Clone, PartialEq)] +pub struct RunMoments { + /// Polynomial degree. + pub degree: usize, + /// Reference abscissa `u_ref`. + pub u_ref: f64, + /// Axis of every window (`None` past an axis switch: such a range cannot be fitted). + axis: Vec, + /// Prefix sums: per window, `G = Σ g gᵀ/V` (upper triangle), `b = Σ g h/V`, `c = Σ h²/V`. + pre: Vec>, +} + +impl RunMoments { + /// Build from an edge's run windows. + pub fn new(obs: &[RunObs], degree: usize) -> Self { + let degree = degree.min(3); + let p = degree + 1; + let u_ref = obs.first().map_or(0.0, |o| o.window.line as f64); + let width = p * (p + 1) / 2 + p + 1; + let mut pre = vec![vec![0.0; width]]; + let mut axis = Vec::with_capacity(obs.len()); + for o in obs { + let (u0, u1) = ( + o.window.line as f64 - 0.5 - u_ref, + o.window.line as f64 + 0.5 - u_ref, + ); + // g_k = mean of (u − u_ref)^k over the strip. + let g: Vec = (0..p) + .map(|k| (u1.powi(k as i32 + 1) - u0.powi(k as i32 + 1)) / (k as f64 + 1.0)) + .collect(); + let h = o.mean_position(); + let wv = 1.0 / o.var.max(1e-300); + let last = pre.last().expect("seeded").clone(); + let mut row = last; + let mut idx = 0; + for i in 0..p { + for j in i..p { + row[idx] += g[i] * g[j] * wv; + idx += 1; + } + } + for i in 0..p { + row[idx + i] += g[i] * h * wv; + } + row[idx + p] += h * h * wv; + pre.push(row); + axis.push(o.window.axis); + } + Self { + degree, + u_ref, + axis, + pre, + } + } + + /// The weighted least-squares polynomial over windows `r` and its `χ²`, or `None` when the + /// range mixes columns and rows, has fewer windows than coefficients, or is singular. + #[allow(clippy::needless_range_loop)] // a 4 × 4 symmetric matrix filled from its triangle + pub fn fit(&self, r: Range) -> Option<(Vec, Chi2)> { + let p = self.degree + 1; + if r.end > self.axis.len() + || r.len() < p + || self.axis[r.clone()] + .iter() + .any(|a| *a != self.axis[r.start]) + { + return None; + } + let (a, b) = (&self.pre[r.end], &self.pre[r.start]); + let d: Vec = a.iter().zip(b).map(|(x, y)| x - y).collect(); + let mut g = vec![vec![0.0; p]; p]; + let mut idx = 0; + for i in 0..p { + for j in i..p { + g[i][j] = d[idx]; + g[j][i] = d[idx]; + idx += 1; + } + } + let rhs: Vec = (0..p).map(|i| d[idx + i]).collect(); + let c = d[idx + p]; + let theta = solve_spd(&g, &rhs)?; + let fit: f64 = theta.iter().zip(&rhs).map(|(t, b)| t * b).sum(); + let chi2 = (c - fit).max(0.0); + Some(( + theta, + Chi2 { + chi2, + m: r.len(), + chi2_floor: chi2, + dof: r.len() as f64, + cost: chi2, + }, + )) + } +} + +/// Solve `G θ = b` for a small symmetric positive definite `G` (Cholesky); `None` when not +/// positive definite to working precision. +fn solve_spd(g: &[Vec], b: &[f64]) -> Option> { + let n = b.len(); + let mut l = vec![vec![0.0; n]; n]; + for i in 0..n { + for j in 0..=i { + let s: f64 = (0..j).map(|k| l[i][k] * l[j][k]).sum(); + if i == j { + let d = g[i][i] - s; + if d <= 1e-14 * g[i][i].abs().max(1e-300) { + return None; + } + l[i][i] = d.sqrt(); + } else { + l[i][j] = (g[i][j] - s) / l[j][j]; + } + } + } + let mut y = vec![0.0; n]; + for i in 0..n { + y[i] = (b[i] - (0..i).map(|k| l[i][k] * y[k]).sum::()) / l[i][i]; + } + let mut x = vec![0.0; n]; + for i in (0..n).rev() { + x[i] = (y[i] - (i + 1..n).map(|k| l[k][i] * x[k]).sum::()) / l[i][i]; + } + Some(x) +} + +/// The evaluator the representation chain scores candidate descriptions with. Every score +/// is `−2 log L` up to a constant, calibrated so that `E χ² = M` at the truth. +pub trait BoundaryLikelihood { + /// Number of edges of the starting map. + fn edge_count(&self) -> usize; + /// The run observations of edge `e`, in order along it. + fn runs(&self, e: usize) -> &[RunObs]; + /// How the renderer draws candidates. + fn render_model(&self) -> RenderModel; + /// The renderer floor. + fn floor(&self) -> Floor; + /// Whether edge `e`'s windows share the per-edge floor offset (it runs within a lattice + /// step of an axis or a diagonal). + fn edge_on_lattice(&self, e: usize) -> bool; + /// Variance of the offset all of edge `e`'s windows share, px² (A3): by default the + /// floor's `edge_var` on an edge along the lattice, else 0. + fn edge_offset_var(&self, e: usize) -> f64 { + if self.edge_on_lattice(e) { + self.floor().edge_var + } else { + 0.0 + } + } + /// Student-t degrees of freedom of the intake's window errors (`f64::INFINITY`: + /// Gaussian), which set the robust cost's threshold. + fn tail_nu(&self) -> f64 { + f64::INFINITY + } + /// The score of edge `e`'s run windows `range` against a candidate curve (pieces in + /// order, in px, drawn as the renderer draws them, oriented as the edge). Each window is + /// scored with the candidate's area there, so a span's piece must reach past the span's + /// ends to cover every window of `range`. + fn chi2_run(&self, e: usize, range: Range, curve: &[Piece]) -> Chi2 { + let rm = self.render_model(); + let drawn = rm.as_rendered(curve); + let obs = &self.runs(e)[range]; + let r: Vec = obs + .iter() + .map(|o| o.sum - rm.window_area(&drawn, &o.window)) + .collect(); + let v: Vec = obs.iter().map(|o| o.var.max(1e-300)).collect(); + let share: Vec = obs.iter().map(|o| o.share).collect(); + score( + &r, + &v, + &share, + self.edge_offset_var(e), + crate::noise::huber_kappa(self.tail_nu()), + ) + } + /// The standardised residuals `(S_W − A_W)/√V_W` of the windows `range`. + fn residuals_run(&self, e: usize, range: Range, curve: &[Piece]) -> Vec { + let rm = self.render_model(); + let drawn = rm.as_rendered(curve); + self.runs(e)[range] + .iter() + .map(|o| (o.sum - rm.window_area(&drawn, &o.window)) / o.var.max(1e-300).sqrt()) + .collect() + } + /// Prefix moments of edge `e` for polynomial graphs of `degree` (≤ 3). + fn run_moments(&self, e: usize, degree: usize) -> RunMoments { + RunMoments::new(self.runs(e), degree) + } + /// `χ²` of a vertex neighbourhood's per-pixel terms, given each incident edge's candidate + /// curve near it (oriented as the edge). + fn chi2_local(&self, owner: Owner, curves: &[(usize, &[Piece])]) -> Chi2; + /// Junction reports (A4). + fn junctions(&self) -> &[JunctionReport]; + /// Corner proposals along runs (B3.3). + fn corners(&self) -> &[CornerProposal]; + /// Information density along edge `e`: `(s, ρ)` per run window, `ρ = ℓ_W / V_W` with the + /// window's boundary length from the starting geometry, px⁻³ (B2.5). + fn density(&self, e: usize) -> Vec<(f64, f64)>; + /// Per run window of edge `e`, where its centre falls along the edge's starting polyline + /// (`map.edges[e].points`), as a fractional point index in `[0, n)`: non-decreasing along + /// the run. By default, none (an evaluator that cannot say). + fn window_point_index(&self, _e: usize) -> Vec { + Vec::new() + } + /// A2: the score of a stroke band on the thin-feature pixels edges `pair` share (both + /// reach them), the band's inks given as `[left of it, the band, right of it]` relative to + /// its centreline's direction; each pixel's colour is its three areas' mix. By default + /// nothing is scored. + fn chi2_band(&self, _pair: (usize, usize), _band: &StrokeBand, _inks: [[f32; 3]; 3]) -> Chi2 { + Chi2::default() + } + /// A2: the score of a junction's pixels under per-layer compositing: `layers` in paint + /// order, each a closed boundary (the layer's whole shape near the junction, not only its + /// visible part) with its colour, drawn over `ground`. Where shapes overlap this is what a + /// renderer computes, which the visible partition of [`chi2_local`] is not, by up to + /// 0.04 colour units at a junction (`renderer_floor.py`). By default nothing is scored. + /// + /// [`chi2_local`]: BoundaryLikelihood::chi2_local + fn chi2_local_layers( + &self, + _node: u32, + _layers: &[(&[Piece], [f32; 3])], + _ground: [f32; 3], + ) -> Chi2 { + Chi2::default() + } +} + +/// A stroke: a centreline drawn with a width, its sides half the width either way (caps and +/// joins are the representation chain's to add). A2's thin features: the pixels its two +/// edges share are scored against it whole ([`BoundaryLikelihood::chi2_band`]). +#[derive(Debug, Clone, PartialEq)] +pub struct StrokeBand { + /// The centreline, in order. + pub centre: Vec, + /// The stroke's width, px. + pub width: f64, +} + +impl StrokeBand { + /// The band's left and right sides (left of the centreline's direction), the centreline + /// sampled every `step` px or so and offset along its normal. + pub fn sides(&self, step: f64) -> (Vec, Vec) { + let mut pts: Vec = Vec::new(); + for p in &self.centre { + let (a, b) = (p.point(0.0), p.point(1.0)); + let n = ((a.dist(b) + 1.0) / step.max(1e-3)) + .ceil() + .clamp(1.0, 4096.0) as usize; + for k in 0..=n { + if k == 0 && !pts.is_empty() { + continue; + } + pts.push(p.point(k as f64 / n as f64)); + } + } + let h = 0.5 * self.width; + let m = pts.len(); + let (mut left, mut right) = (Vec::with_capacity(m), Vec::with_capacity(m)); + for i in 0..m { + let (a, b) = (pts[i.saturating_sub(1)], pts[(i + 1).min(m - 1)]); + let (dx, dy) = (b.x - a.x, b.y - a.y); + let l = dx.hypot(dy).max(1e-12); + // Left of direction d is (d.y, −d.x). + let (nx, ny) = (dy / l, -dx / l); + left.push(Point::new(pts[i].x + h * nx, pts[i].y + h * ny)); + right.push(Point::new(pts[i].x - h * nx, pts[i].y - h * ny)); + } + (left, right) + } +} + +/// One edge's windows as the representation chain's dynamic program reads them +/// (`chain-boundary.md`, "The adapter"). The windows are **partitioned** among any +/// segmentation of the edge's points: a window belongs to the span `[i, j)` of point indices +/// that holds its centre, so the windows scored, and their number, do not depend on where +/// the breakpoints fall (the corner and junction terms are fixed per edge in the same way). +/// A span's piece is scored on all of its windows, so it must reach past the span's ends far +/// enough to cross them. +pub struct EdgeScorer<'a, L: BoundaryLikelihood + ?Sized> { + lik: &'a L, + edge: usize, + /// Fractional point index of each window's centre. + at: Vec, + /// Number of points of the edge's polyline (for the wrap of a closed edge). + n_points: usize, + /// Least-squares graphs of degree 1, 2, 3 over any range. + moments: [RunMoments; 3], + /// Prefix sums of `Σ w u^p`, `p = 0..6`, `w = 1/var`, `u` the line less the first + /// window's. + weights: Vec<[f64; 7]>, +} + +impl<'a, L: BoundaryLikelihood + ?Sized> EdgeScorer<'a, L> { + /// The scorer of edge `edge`, whose starting polyline has `n_points` points. + pub fn new(lik: &'a L, edge: usize, n_points: usize) -> Self { + let obs = lik.runs(edge); + let mut at = lik.window_point_index(edge); + if at.len() != obs.len() { + at = vec![0.0; obs.len()]; + } + let u_ref = obs.first().map_or(0.0, |o| o.window.line as f64); + let mut weights = Vec::with_capacity(obs.len() + 1); + let mut acc = [0.0f64; 7]; + weights.push(acc); + for o in obs { + let w = 1.0 / o.var.max(1e-300); + let u = o.window.line as f64 - u_ref; + let mut up = 1.0; + for a in acc.iter_mut() { + *a += w * up; + up *= u; + } + weights.push(acc); + } + EdgeScorer { + lik, + edge, + at, + n_points, + moments: [ + RunMoments::new(obs, 1), + RunMoments::new(obs, 2), + RunMoments::new(obs, 3), + ], + weights, + } + } + + /// The run windows whose centres lie in the span of point indices `[i, j)`; on a closed + /// edge a span with `j ≤ i` runs through the seam, and its windows come as two ranges + /// (the second empty otherwise). + pub fn windows_between_points(&self, i: usize, j: usize) -> (Range, Range) { + let pos = |p: usize| self.at.partition_point(|&t| t < p as f64); + if j > i { + (pos(i)..pos(j), 0..0) + } else { + (pos(i)..self.at.len(), 0..pos(j.min(self.n_points))) + } + } + + /// The score of a candidate on windows `r` (pieces in px, oriented as the edge). + pub fn chi2(&self, r: Range, pieces: &[Piece]) -> Chi2 { + self.lik.chi2_run(self.edge, r, pieces) + } + + /// The least-squares polynomial graph of `degree` (1 to 3) over windows `r`, in the + /// windows' strip frame (`mean_position = Σ θ_k · mean over the strip of (u − u_ref)^k`, + /// `u_ref` the first window's line of the edge), with its `χ²`, in `O(1)`; `None` across + /// an axis switch or with fewer windows than coefficients. + pub fn best_graph(&self, r: Range, degree: usize) -> Option<(Vec, Chi2)> { + let m = &self.moments[degree.clamp(1, 3) - 1]; + m.fit(r) + } + + /// `Σ w u^p` over windows `r`, `p = 0..6`, with `w = 1/var` (the window's whole variance, + /// replicas deflated) and `u` its line less the edge's first window's: the moments a + /// degree ≤ 3 graph's Fisher matrix is built from, in `O(1)`. Meaningful on a range of one + /// axis. + pub fn weight_moments(&self, r: Range) -> [f64; 7] { + let (a, b) = (&self.weights[r.end], &self.weights[r.start]); + std::array::from_fn(|k| a[k] - b[k]) + } +} + +#[cfg(test)] +#[path = "likelihood_tests.rs"] +mod tests; diff --git a/crates/inkvec-core/src/likelihood_tests.rs b/crates/inkvec-core/src/likelihood_tests.rs new file mode 100644 index 00000000..d7281301 --- /dev/null +++ b/crates/inkvec-core/src/likelihood_tests.rs @@ -0,0 +1,655 @@ +use super::*; + +fn p(x: f64, y: f64) -> Point { + Point::new(x, y) +} + +fn col(line: i32, lo: i32, hi: i32) -> Window { + Window { + axis: Axis::Column, + line, + lo, + hi, + } +} + +fn row(line: i32, lo: i32, hi: i32) -> Window { + Window { + axis: Axis::Row, + line, + lo, + hi, + } +} + +/// A horizontal line walked right has the face above on its left; walked left, below. +#[test] +fn horizontal_line_both_ways() { + let w = col(3, 1, 4); // strip x in [2.5, 3.5], y in [0.5, 4.5] + let right = [Piece::Line([p(0.0, 2.3), p(10.0, 2.3)])]; + let left = [Piece::Line([p(10.0, 2.3), p(0.0, 2.3)])]; + assert!((left_area(&right, &w) - 1.8).abs() < 1e-12); + assert!((left_area(&left, &w) - 2.2).abs() < 1e-12); +} + +/// A vertical line walked down has the face to the east on its left; walked up, west. +#[test] +fn vertical_line_both_ways() { + let w = row(5, 0, 3); // strip y in [4.5, 5.5], x in [-0.5, 3.5] + let down = [Piece::Line([p(1.2, 0.0), p(1.2, 10.0)])]; + let up = [Piece::Line([p(1.2, 10.0), p(1.2, 0.0)])]; + assert!( + (left_area(&down, &w) - 2.3).abs() < 1e-12, + "{}", + left_area(&down, &w) + ); + assert!((left_area(&up, &w) - 1.7).abs() < 1e-12); +} + +/// A slanted line leaving the window through its bottom is clamped there. +#[test] +fn clamped_at_the_window_end() { + // y = 2 + 3(x - 2.5): enters the strip at y = 2, leaves at y = 5 > 4.5. + let w = col(3, 1, 4); + let l = [Piece::Line([p(2.0, 0.5), p(4.0, 6.5)])]; + // area above the line within y in [0.5, 4.5]: ∫ clamp(2 + 3s, ., 4.5) - 0.5 ds, s in [0,1] + // = ∫_0^{5/6} (1.5 + 3s) ds + (1/6)·4 = 1.25 + 1.0417 + 0.6667 + let want = 1.5 * (5.0 / 6.0) + 1.5 * (5.0f64 / 6.0).powi(2) + 4.0 / 6.0; + assert!( + (left_area(&l, &w) - want).abs() < 1e-12, + "{} vs {want}", + left_area(&l, &w) + ); +} + +/// A cubic graph's left area against direct numerical integration of its clamped height. +#[test] +fn cubic_graph_matches_integration() { + // x linear in t (control x equally spaced), so y(x) is the cubic itself. + let c = [p(1.0, 3.0), p(3.0, 1.2), p(5.0, 4.9), p(7.0, 2.2)]; + let piece = [Piece::Cubic(c)]; + let y_of_x = |x: f64| { + let t = (x - 1.0) / 6.0; + let m = 1.0 - t; + m * m * m * 3.0 + 3.0 * m * m * t * 1.2 + 3.0 * m * t * t * 4.9 + t * t * t * 2.2 + }; + for line in 2..=6 { + for (lo, hi) in [(1, 4), (2, 3), (3, 5)] { + let w = col(line, lo, hi); + let (ylo, yhi) = (lo as f64 - 0.5, hi as f64 + 0.5); + let n = 200_000; + let x0 = line as f64 - 0.5; + let mut acc = 0.0; + for k in 0..n { + let x = x0 + (k as f64 + 0.5) / n as f64; + acc += y_of_x(x).clamp(ylo, yhi) - ylo; + } + acc /= n as f64; + let got = left_area(&piece, &w); + assert!( + (got - acc).abs() < 1e-8, + "line {line} [{lo},{hi}]: {got} vs {acc}" + ); + } + } +} + +/// A curve that folds inside the strip (an S that doubles back in x) still gives the area of +/// its left face: the two passes over the doubled part cancel. +#[test] +fn a_fold_inside_the_strip() { + // Polyline: (2.5→3.3) at y=2, back (3.3→2.9) at y=2.4, on (2.9→3.5) at y=2.8. + let pl = [ + Piece::Line([p(2.0, 2.0), p(3.3, 2.0)]), + Piece::Line([p(3.3, 2.0), p(2.9, 2.4)]), + Piece::Line([p(2.9, 2.4), p(4.0, 2.8)]), + ]; + let w = col(3, 1, 4); + // Cross-section of the region above the curve, x in [2.5, 3.5]: + // x in [2.5, 2.9): 2.0 - 0.5; x in [2.9, 3.3): above the third leg... the region left of + // the walk is the set with odd crossing count above; evaluate by brute force. + let n = 400_000; + let mut acc = 0.0; + for k in 0..n { + let x = 2.5 + (k as f64 + 0.5) / n as f64; + let mut ys: Vec = Vec::new(); + for pc in &pl { + if let Piece::Line([a, b]) = pc { + if (a.x - x) * (b.x - x) < 0.0 { + let t = (x - a.x) / (b.x - a.x); + ys.push(a.y + t * (b.y - a.y)); + } + } + } + ys.sort_by(f64::total_cmp); + // Above the topmost crossing is the left face; then alternating. + let mut inside = true; + let mut prev = 0.5; + let mut len = 0.0; + for y in ys.iter().chain(std::iter::once(&4.5)) { + let y = y.clamp(0.5, 4.5); + if inside { + len += y - prev; + } + prev = y; + inside = !inside; + } + acc += len; + } + acc /= n as f64; + let got = left_area(&pl, &w); + assert!((got - acc).abs() < 1e-5, "{got} vs {acc}"); +} + +/// A U crosses the same column twice: each window is scored by its own pass, and a window +/// between the passes belongs wholly to the face the passes leave it to. +#[test] +fn a_u_crosses_one_column_twice() { + let u = [ + Piece::Line([p(0.0, 2.0), p(5.0, 2.0)]), + Piece::Line([p(5.0, 2.0), p(5.0, 8.0)]), + Piece::Line([p(5.0, 8.0), p(0.0, 8.0)]), + ]; + // Walking +x at y = 2 the left face is above; walking -x at y = 8 it is below. + assert!( + (left_area(&u, &col(3, 1, 3)) - 1.5).abs() < 1e-12, + "{}", + left_area(&u, &col(3, 1, 3)) + ); + assert!( + (left_area(&u, &col(3, 7, 9)) - 1.5).abs() < 1e-12, + "{}", + left_area(&u, &col(3, 7, 9)) + ); + // Between the passes, inside the U: the right face. + assert_eq!(left_area(&u, &col(3, 4, 5)), 0.0); + // Above both passes: the left face of the upper pass. + assert_eq!(left_area(&u, &col(3, -4, -3)), 2.0); +} + +/// usvg's quarter circle is one cubic with arm (4/3)·tan(π/8)·r. +#[test] +fn quarter_circle_as_usvg_draws_it() { + let a = EllipticalArc { + centre: p(0.0, 0.0), + radii: (1.0, 1.0), + x_rotation: 0.0, + start_angle: 0.0, + sweep_angle: PI / 2.0, + }; + let c = a.to_cubics(0.1); + assert_eq!(c.len(), 1); + let k = (4.0 / 3.0) * (PI / 8.0).tan(); + let Piece::Cubic([p0, p1, p2, p3]) = c[0] else { + panic!() + }; + for (q, w) in [ + (p0, (1.0, 0.0)), + (p1, (1.0, k)), + (p2, (k, 1.0)), + (p3, (0.0, 1.0)), + ] { + assert!( + (q.x - w.0).abs() < 1e-12 && (q.y - w.1).abs() < 1e-12, + "{q:?} vs {w:?}" + ); + } + // A half turn is two, a full turn four, below the 3600-tolerance radius. + let half = EllipticalArc { + sweep_angle: PI, + ..a + }; + assert_eq!(half.to_cubics(0.1).len(), 2); + // A large radius against the tolerance needs more. + // (1.1163 · 50000)^(1/6) = 6.18 pieces per turn. + let big = EllipticalArc { + radii: (5000.0, 5000.0), + sweep_angle: 2.0 * PI, + ..a + }; + assert_eq!(big.to_cubics(0.1).len(), 7); +} + +/// A disc drawn as usvg's four cubics loses about 2.7e-4 of its radius at the 45° points, +/// and the window areas see it: the as-rendered and the true areas of a window there differ. +#[test] +fn rendered_circle_differs_from_the_true_one() { + let r = 100.0; + let a = EllipticalArc { + centre: p(0.0, 0.0), + radii: (r, r), + x_rotation: 0.0, + // From (-r, 0) over the top (negative y) to (r, 0). + start_angle: PI, + sweep_angle: PI, + }; + let truth = [Piece::Arc(a)]; + let drawn = RenderModel::usvg().as_rendered(&truth); + // The default model draws arcs exactly. + assert_eq!(RenderModel::default().as_rendered(&truth), truth.to_vec()); + // The cubic is exact at the ends and the middle of each quarter, and furthest out (by + // 2.7e-4 r) about 19° from either end: the column at x = -33 meets the circle at + // y = -94.4, 19.3° from the top. + let w = col(-33, -98, -91); + let d = left_area(&drawn, &w) - left_area(&truth, &w); + assert!(d.abs() > 0.005 && d.abs() < 0.05, "{d}"); +} + +/// Prefix moments recover a quadratic graph from its exact column means. +#[test] +fn run_moments_fit_a_quadratic() { + let (a, b, c) = (3.2, 0.31, -0.017); + let f_mean = |x0: f64| { + // mean over [x0, x0+1] of a + b x + c x² + let pr = |x: f64| a * x + b * x * x / 2.0 + c * x * x * x / 3.0; + pr(x0 + 1.0) - pr(x0) + }; + let obs: Vec = (0..12) + .map(|i| { + let x0 = i as f64 - 0.5; + let m = f_mean(x0); + let lo = (m.floor() as i32) - 1; + RunObs { + window: col(i, lo, lo + 3), + s: i as f64, + sum: m - (lo as f64 - 0.5), + var: 1e-6, + left_low: true, + share: 1.0, + } + }) + .collect(); + let mo = RunMoments::new(&obs, 2); + let (theta, chi) = mo.fit(0..12).expect("fit"); + assert!( + (theta[0] - a).abs() < 1e-9 && (theta[1] - b).abs() < 1e-9 && (theta[2] - c).abs() < 1e-9, + "{theta:?}" + ); + assert!(chi.chi2 < 1e-6, "{chi:?}"); + assert!(mo.fit(0..2).is_none(), "fewer windows than coefficients"); + // A line through the same means misfits by many standard deviations. + let line = RunMoments::new(&obs, 1).fit(0..12).expect("line").1; + assert!(line.chi2 > 100.0, "{line:?}"); +} + +/// A degenerate arc is its chord; a window lists its pixels along its line. +#[test] +fn degenerate_arcs_and_window_pixels() { + let a = EllipticalArc { + centre: p(1.0, 2.0), + radii: (0.0, 3.0), + x_rotation: 0.0, + start_angle: 0.0, + sweep_angle: PI / 2.0, + }; + let c = a.to_cubics(0.1); + let [Piece::Line([s, e])] = c[..] else { + panic!("{c:?}") + }; + assert!( + s.dist(p(1.0, 2.0)) < 1e-12 && e.dist(p(1.0, 5.0)) < 1e-12, + "{s:?} {e:?}" + ); + let w = col(3, 5, 7); + assert_eq!((w.len(), w.is_empty()), (3, false)); + assert_eq!(w.pixels().collect::>(), vec![(3, 5), (3, 6), (3, 7)]); + assert_eq!( + row(2, 0, 1).pixels().collect::>(), + vec![(0, 2), (1, 2)] + ); + let empty = col(0, 4, 3); + assert_eq!((empty.len(), empty.is_empty()), (0, true)); +} + +/// A quadratic and the same curve raised to a cubic give every window the same area. +#[test] +fn a_quadratic_is_its_raised_cubic() { + let (a, b, c) = (p(0.5, 3.0), p(3.0, -1.0), p(6.5, 4.0)); + let towards = + |q: Point, r: Point| p(q.x + 2.0 / 3.0 * (r.x - q.x), q.y + 2.0 / 3.0 * (r.y - q.y)); + let quad = [Piece::Quad([a, b, c])]; + let cubic = [Piece::Cubic([a, towards(a, b), towards(c, b), c])]; + for line in 1..=6 { + for w in [col(line, 0, 4), col(line, 1, 2), col(line, -1, 5)] { + let (q, k) = (left_area(&quad, &w), left_area(&cubic, &w)); + assert!((q - k).abs() < 1e-12, "{w:?}: {q} vs {k}"); + } + } +} + +/// Arcs are integrated through fine cubics; a curve that never enters a window's strip gives +/// no area (NaN); a window no pass comes near is wholly one face's, on rows as on columns. +#[test] +fn arcs_rows_and_curves_that_miss() { + let arc = EllipticalArc { + centre: p(0.0, 0.0), + radii: (10.0, 10.0), + x_rotation: 0.0, + start_angle: PI, + sweep_angle: PI, + }; + assert!(power(&Piece::Arc(arc)).is_none()); + assert_eq!( + u_range(&Piece::Arc(arc), Axis::Column), + (f64::NEG_INFINITY, f64::INFINITY) + ); + // The upper half circle walked from (-10, 0) to (10, 0): at x = 0 it is at y = -10, and + // the left face (above, walking +x) holds y in [-10.5, -10] of the window [-10.5, -9.5], + // plus the circle's mean drop across the column, 1/(24 r) to the next order. + let a = left_area(&[Piece::Arc(arc)], &col(0, -10, -10)); + assert!((a - (0.5 + 1.0 / 240.0)).abs() < 1e-5, "{a}"); + assert!(left_area(&[], &col(0, 0, 1)).is_nan()); + // A cubic whose control polygon reaches x = 4 but whose curve turns back at x = 3. + let bulge = [Piece::Cubic([ + p(0.0, 0.0), + p(4.0, 1.0), + p(4.0, 2.0), + p(0.0, 3.0), + ])]; + assert!(left_area(&bulge, &col(4, 0, 3)).is_nan()); + // Walking +y the left face is east: a row window east of the line is wholly left. + let down = [Piece::Line([p(1.2, 0.0), p(1.2, 10.0)])]; + assert_eq!(left_area(&down, &row(5, 5, 7)), 3.0); + assert_eq!(left_area(&down, &row(5, -6, -4)), 0.0); +} + +/// The lattice floor's two variances. +#[test] +fn lattice_floor() { + let f = Floor::lattice(32); + assert_eq!(f.lattice, 32); + assert!((f.window_var - 1.0 / (12.0 * 32768.0)).abs() < 1e-18); + assert!((f.edge_var - 1.0 / (12.0 * 1024.0)).abs() < 1e-15); + assert_eq!(Floor::lattice(0).lattice, 1); +} + +/// A fixed set of run windows behind the trait, to test its provided methods. +struct Fixed { + runs: Vec, + floor: Floor, + lattice: bool, +} + +/// The same, saying where each window sits along the edge's points. +struct Placed { + inner: Fixed, + at: Vec, +} + +impl BoundaryLikelihood for Placed { + fn edge_count(&self) -> usize { + 1 + } + fn runs(&self, e: usize) -> &[RunObs] { + self.inner.runs(e) + } + fn render_model(&self) -> RenderModel { + RenderModel::default() + } + fn floor(&self) -> Floor { + self.inner.floor + } + fn edge_on_lattice(&self, _: usize) -> bool { + false + } + fn chi2_local(&self, _: Owner, _: &[(usize, &[Piece])]) -> Chi2 { + Chi2::default() + } + fn junctions(&self) -> &[JunctionReport] { + &[] + } + fn corners(&self) -> &[CornerProposal] { + &[] + } + fn density(&self, _: usize) -> Vec<(f64, f64)> { + Vec::new() + } + fn window_point_index(&self, _: usize) -> Vec { + self.at.clone() + } +} + +/// The scorer partitions the windows among any segmentation of the points (each window in +/// exactly one span, wrapping on a closed edge), and its O(1) moments and fits are the direct +/// sums. +#[test] +fn the_scorer_partitions_and_sums() { + let runs: Vec = (0..12) + .map(|i| RunObs { + window: col(i, 1, 4), + s: i as f64, + sum: 1.8 + 0.01 * ((i * 7) % 5) as f64, + var: 1e-4 * (1 + i % 3) as f64, + left_low: true, + share: 1.0, + }) + .collect(); + let at: Vec = (0..12).map(|i| 0.5 + 1.7 * i as f64).collect(); // in [0, 20) + let lik = Placed { + inner: Fixed { + runs: runs.clone(), + floor: Floor::lattice(32), + lattice: false, + }, + at, + }; + let sc = EdgeScorer::new(&lik, 0, 20); + for cuts in [vec![0, 5, 11, 20], vec![0, 1, 2, 3, 19, 20], vec![0, 20]] { + let mut seen = vec![0; 12]; + for w in cuts.windows(2) { + let (a, b) = sc.windows_between_points(w[0], w[1]); + for k in a.chain(b) { + seen[k] += 1; + } + } + assert!(seen.iter().all(|&c| c == 1), "{cuts:?}: {seen:?}"); + } + // A closed edge cut at points 7 and 15: the second span runs through the seam. + let (a1, b1) = sc.windows_between_points(7, 15); + let (a2, b2) = sc.windows_between_points(15, 7); + let mut seen = vec![0; 12]; + for k in a1.chain(b1).chain(a2).chain(b2) { + seen[k] += 1; + } + assert!(seen.iter().all(|&c| c == 1), "{seen:?}"); + // Moments against the direct sums. + let m = sc.weight_moments(3..9); + for (p, mp) in m.iter().enumerate() { + let want: f64 = runs[3..9] + .iter() + .map(|o| (o.window.line as f64).powi(p as i32) / o.var) + .sum(); + assert!( + (mp - want).abs() < 1e-9 * want.abs().max(1.0), + "p {p}: {mp} vs {want}" + ); + } + let (theta, chi) = sc.best_graph(0..12, 1).expect("line"); + let (t2, c2) = RunMoments::new(&runs, 1).fit(0..12).expect("line"); + assert_eq!(theta, t2); + assert_eq!(chi, c2); + assert!(sc.best_graph(0..12, 3).is_some()); + let line = [Piece::Line([p(-1.0, 2.3), p(13.0, 2.3)])]; + assert_eq!(sc.chi2(2..6, &line).m, 4); +} + +/// SVG's endpoint arcs become centre arcs through the same endpoints, with the flags' sense. +#[test] +fn svg_arcs_in_centre_form() { + let (a, b) = (p(10.0, 0.0), p(0.0, 10.0)); + for (large, sweep) in [(false, false), (false, true), (true, false), (true, true)] { + let Piece::Arc(arc) = Piece::from_svg_arc(a, 10.0, 10.0, 0.0, large, sweep, b) else { + panic!("an arc") + }; + let (s, e) = ( + arc.at(arc.start_angle), + arc.at(arc.start_angle + arc.sweep_angle), + ); + assert!( + s.dist(a) < 1e-9 && e.dist(b) < 1e-9, + "{large} {sweep}: {s:?} {e:?}" + ); + assert_eq!(arc.sweep_angle > 0.0, sweep, "{large} {sweep}"); + let quarter = (arc.sweep_angle.abs() - PI / 2.0).abs() < 1e-9; + assert_eq!(quarter, !large, "{large} {sweep}: {}", arc.sweep_angle); + } + // Radii too small for the chord are scaled up to a half circle on it. + let Piece::Arc(half) = + Piece::from_svg_arc(p(0.0, 0.0), 1.0, 1.0, 0.0, false, true, p(4.0, 0.0)) + else { + panic!("an arc") + }; + assert!((half.radii.0 - 2.0).abs() < 1e-9 && (half.sweep_angle.abs() - PI).abs() < 1e-9); + // Coincident ends or a zero radius: a line. + assert!(matches!( + Piece::from_svg_arc(a, 0.0, 3.0, 0.0, false, true, b), + Piece::Line(_) + )); +} + +impl BoundaryLikelihood for Fixed { + fn edge_count(&self) -> usize { + 1 + } + fn runs(&self, _: usize) -> &[RunObs] { + &self.runs + } + fn render_model(&self) -> RenderModel { + RenderModel::default() + } + fn floor(&self) -> Floor { + self.floor + } + fn edge_on_lattice(&self, _: usize) -> bool { + self.lattice + } + fn chi2_local(&self, _: Owner, _: &[(usize, &[Piece])]) -> Chi2 { + Chi2::default() + } + fn junctions(&self) -> &[JunctionReport] { + &[] + } + fn corners(&self) -> &[CornerProposal] { + &[] + } + fn density(&self, _: usize) -> Vec<(f64, f64)> { + Vec::new() + } +} + +/// An offset every window of an edge shares costs `χ²` per window, but next to nothing once +/// the per-edge floor term absorbs it (A3), and only on an edge that shares it. +#[test] +fn a_shared_offset_is_the_floors() { + // A horizontal edge at y = 2.3 walked +x, read 0.01 px low in every window. + let runs: Vec = (0..10) + .map(|i| RunObs { + window: col(i, 1, 4), + s: i as f64, + sum: 1.8 + 0.01, + var: 1e-4, + left_low: true, + share: 1.0, + }) + .collect(); + let line = [Piece::Line([p(-1.0, 2.3), p(11.0, 2.3)])]; + let floor = Floor { + lattice: 32, + window_var: 0.0, + edge_var: 1e-2, + }; + let on = Fixed { + runs: runs.clone(), + floor, + lattice: true, + }; + let c = on.chi2_run(0, 0..10, &line); + assert_eq!(c.m, 10); + assert!((c.chi2 - 10.0).abs() < 1e-6, "{c:?}"); + // χ² − b²(Σr/V)²/(1 + b²Σ1/V) = 10 − 1e4/1001. + assert!((c.chi2_floor - (10.0 - 1e4 / 1001.0)).abs() < 1e-6, "{c:?}"); + let r = on.residuals_run(0, 0..10, &line); + assert!(r.iter().all(|v| (v - 1.0).abs() < 1e-6), "{r:?}"); + let (theta, _) = on.run_moments(0, 1).fit(0..10).expect("fit"); + assert!( + (theta[0] - 2.31).abs() < 1e-9 && theta[1].abs() < 1e-9, + "{theta:?}" + ); + let off = Fixed { + runs, + floor, + lattice: false, + }; + let c = off.chi2_run(0, 0..10, &line); + assert_eq!(c.chi2_floor, c.chi2); + assert_eq!((c + c).m, 20); +} + +/// The Kalman filter's χ² and log det are those of the dense covariance +/// `diag(v) + τ² ρ^|i−j|`, and reduce to the independent and the shared-offset cases. +#[test] +fn correlated_chi2_is_the_dense_one() { + let r = [0.013, -0.004, 0.021, 0.009, -0.011, 0.017]; + let v = [1e-4, 2e-4, 1.5e-4, 1e-4, 3e-4, 1e-4]; + for (tau2, rho) in [ + (0.0f64, 0.5f64), + (4e-4, 0.0), + (4e-4, 0.6), + (4e-4, 1.0), + (1e-2, 1.0), + ] { + let n = r.len(); + let sigma: Vec> = (0..n) + .map(|i| { + (0..n) + .map(|j| { + let d = (i as i32 - j as i32).unsigned_abs() as i32; + tau2 * rho.powi(d) + if i == j { v[i] } else { 0.0 } + }) + .collect() + }) + .collect(); + let x = solve_spd(&sigma, &r).expect("positive definite"); + let want: f64 = x.iter().zip(&r).map(|(a, b)| a * b).sum(); + // log det from the Cholesky factor's diagonal, by the same elimination. + let mut l = vec![vec![0.0; n]; n]; + let mut logdet = 0.0; + for i in 0..n { + for j in 0..=i { + let s: f64 = (0..j).map(|k| l[i][k] * l[j][k]).sum(); + if i == j { + l[i][i] = (sigma[i][i] - s).sqrt(); + logdet += 2.0 * l[i][i].ln(); + } else { + l[i][j] = (sigma[i][j] - s) / l[j][j]; + } + } + } + let c = vec![Correlated { tau2, rho }; n]; + let (chi2, ld) = chi2_correlated(&r, &v, &c); + assert!( + (chi2 - want).abs() < 1e-9 * want.max(1.0), + "tau2 {tau2} rho {rho}: {chi2} vs {want}" + ); + assert!((ld - logdet).abs() < 1e-9, "{ld} vs {logdet}"); + } + // No correlated part: the independent sum. + let plain: f64 = r.iter().zip(&v).map(|(a, b)| a * a / b).sum(); + let (chi2, _) = chi2_correlated(&r, &v, &[]); + assert!((chi2 - plain).abs() < 1e-12 * plain); +} + +/// A singular system (the same column three times cannot fix a slope) is refused. +#[test] +fn a_singular_fit_is_refused() { + let o = RunObs { + window: col(3, 1, 4), + s: 0.0, + sum: 1.8, + var: 1e-4, + left_low: true, + share: 1.0, + }; + assert!(RunMoments::new(&[o, o, o], 1).fit(0..3).is_none()); + assert!(RunMoments::new(&[o, o, o], 0).fit(0..3).is_some()); +} diff --git a/crates/inkvec-core/src/noise.rs b/crates/inkvec-core/src/noise.rs new file mode 100644 index 00000000..dc080ff1 --- /dev/null +++ b/crates/inkvec-core/src/noise.rs @@ -0,0 +1,182 @@ +//! What an intake's noise is, measured once per image by the boundary chain and read by +//! everything that weighs evidence against it (`docs/theory/chain-boundary.md`, "Noise"). +//! +//! A clean render is exact to 8-bit rounding, and the window sums of +//! [`crate::likelihood`] are calibrated on it with nothing measured. A resampled or lossy +//! intake (a logo found on the web: resized, saved as JPEG) is not. Its error sits within a +//! few pixels of every edge, where flat-region estimates cannot see it, and it has heavy +//! tails. The boundary chain therefore estimates the noise *from the edges*: from the fourth +//! differences of consecutive window sums, which a smooth boundary does not move. It +//! summarises that estimate here so that the representation chain weighs its fits the same +//! way. [`NoiseModel::clean`] is today's model, and a clean intake gets exactly it. + +/// The noise of one intake, as the boundary chain measured it. +#[derive(Debug, Clone, PartialEq)] +pub struct NoiseModel { + /// Per-channel noise of interior pixels, sRGB units (`coverage::estimate_noise`). + pub sigma_flat: f64, + /// Per-channel noise by distance from the nearest edge, sRGB units: bands `[0, 1)`, + /// `[1, 2)`, `[2, 3)` and `≥ 3` px. + pub sigma_edge: Vec, + /// How far beyond a native edge's the intake's edge ramp reaches on each side, px: half of + /// `width − 1`, `width` the box-equivalent edge width of `softness::ramp_evidence`. 0 on a + /// native render. + pub psf_radius: f64, + /// The blur's second moment along a window's strip, px²: `(width² − 1)/4`. A window's + /// sum on a blurred intake is the face's area profile convolved with the blur, which on a + /// curve moves it by `½ μ₂ A''` (the forward model, not noise). 0 on a native render. + pub psf_mu2: f64, + /// Tail of the standardised window residuals, as Student-t degrees of freedom; + /// `f64::INFINITY` is Gaussian. + pub nu: f64, + /// The intake was lossy (a JPEG's blocks and subsampled chroma). + pub lossy: bool, + /// Measured window-sum standard deviation over the 8-bit rounding model's; 1 on a clean + /// intake. + pub window_scale: f64, +} + +/// Distance bands of [`NoiseModel::sigma_edge`], px: the upper end of each but the last. +pub const EDGE_BANDS: [f64; 3] = [1.0, 2.0, 3.0]; + +/// One 8-bit level. +const Q: f64 = 1.0 / 255.0; + +impl NoiseModel { + /// A clean render: 8-bit rounding and nothing else, exactly today's model. + pub fn clean() -> Self { + let s = 0.5 * Q; + NoiseModel { + sigma_flat: s, + sigma_edge: vec![s; EDGE_BANDS.len() + 1], + psf_radius: 0.0, + psf_mu2: 0.0, + nu: f64::INFINITY, + lossy: false, + window_scale: 1.0, + } + } + + /// Whether this is [`NoiseModel::clean`]'s model: nothing was measured beyond rounding. + pub fn is_clean(&self) -> bool { + *self == NoiseModel::clean() + } + + /// Per-channel noise at distance `d_px` from the nearest edge, sRGB units. + pub fn sigma_edge_at(&self, d_px: f64) -> f64 { + let k = EDGE_BANDS.iter().take_while(|&&b| d_px >= b).count(); + self.sigma_edge + .get(k) + .or(self.sigma_edge.last()) + .copied() + .unwrap_or(self.sigma_flat) + .max(self.sigma_flat) + } + + /// Whether a band `band_width` px wide along an edge between inks `ink_a` and `ink_b`, + /// coloured `colour`, is what the intake's blur makes of that edge rather than a face of + /// its own: narrower than the blur's reach on both sides (`2·psf_radius + 1`), and its + /// colour on the line through the two inks, between them or overshooting one of them + /// (ringing), to within three times the noise within a pixel of an edge. + pub fn explained_by_psf( + &self, + band_width: f64, + colour: [f32; 3], + ink_a: [f32; 3], + ink_b: [f32; 3], + ) -> bool { + if self.psf_radius <= 0.0 || band_width > 2.0 * self.psf_radius + 1.0 { + return false; + } + let d: [f64; 3] = std::array::from_fn(|c| ink_b[c] as f64 - ink_a[c] as f64); + let q: [f64; 3] = std::array::from_fn(|c| colour[c] as f64 - ink_a[c] as f64); + let dd: f64 = d.iter().map(|v| v * v).sum(); + if dd < 1e-12 { + return false; + } + let t = (q[0] * d[0] + q[1] * d[1] + q[2] * d[2]) / dd; + let off: f64 = (0..3) + .map(|c| (q[c] - t * d[c]).powi(2)) + .sum::() + .sqrt(); + // Ringing overshoots by a fraction of the step, not by more than the step itself. + (-0.5..=1.5).contains(&t) && off <= 3.0 * self.sigma_edge_at(0.0) * 3f64.sqrt() + } +} + +/// Huber's threshold for residuals whose tail is Student-t with `nu` degrees of freedom: +/// `min(3, √ν)`, where the t's influence function `(ν + 1) u/(ν + u²)` peaks and begins to +/// redescend, so the two losses agree on which residuals are outliers. 3 for a Gaussian +/// (`nu = ∞`), so that clean residuals stay in the quadratic part. +pub fn huber_kappa(nu: f64) -> f64 { + if nu.is_finite() { + nu.max(0.0).sqrt().min(3.0) + } else { + 3.0 + } +} + +/// Huber's cost of a standardised residual `z` at threshold `kappa`: `z²` within it, then +/// growing linearly with the same slope (`2κ|z| − κ²`). Equal to `χ²` for small residuals. +pub fn huber(z: f64, kappa: f64) -> f64 { + let a = z.abs(); + if a <= kappa { + z * z + } else { + 2.0 * kappa * a - kappa * kappa + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn clean_is_todays_model() { + let n = NoiseModel::clean(); + assert!(n.is_clean()); + assert_eq!(n.window_scale, 1.0); + assert_eq!(n.nu, f64::INFINITY); + assert_eq!(n.sigma_edge_at(0.3), 0.5 / 255.0); + assert_eq!(n.sigma_edge_at(9.0), 0.5 / 255.0); + assert!(!n.explained_by_psf(0.5, [0.5; 3], [0.0; 3], [1.0; 3])); + } + + #[test] + fn bands_and_ringing() { + let n = NoiseModel { + sigma_flat: 0.001, + sigma_edge: vec![0.04, 0.012, 0.009, 0.006], + psf_radius: 1.0, + psf_mu2: 0.2, + nu: 4.0, + lossy: true, + window_scale: 13.0, + }; + assert!(!n.is_clean()); + assert_eq!(n.sigma_edge_at(0.5), 0.04); + assert_eq!(n.sigma_edge_at(1.0), 0.012); + assert_eq!(n.sigma_edge_at(2.5), 0.009); + assert_eq!(n.sigma_edge_at(7.0), 0.006); + // A band of overshoot beyond black, between black and white: blur. + let (black, white) = ([0.0f32; 3], [1.0f32; 3]); + assert!(n.explained_by_psf(1.5, [-0.05, -0.05, -0.05], black, white)); + assert!(n.explained_by_psf(2.0, [0.4, 0.4, 0.4], black, white)); + // Too wide, or a third colour: a face. + assert!(!n.explained_by_psf(3.5, [0.4, 0.4, 0.4], black, white)); + assert!(!n.explained_by_psf(1.5, [0.9, 0.1, 0.1], black, white)); + } + + #[test] + fn huber_is_chi2_inside_and_linear_outside() { + assert_eq!(huber_kappa(f64::INFINITY), 3.0); + assert_eq!(huber_kappa(4.0), 2.0); + assert!((huber_kappa(3.0) - 3f64.sqrt()).abs() < 1e-15); + assert_eq!(huber_kappa(100.0), 3.0); + assert_eq!(huber(1.5, 2.0), 2.25); + assert_eq!(huber(-3.0, 2.0), 8.0); + // Continuous with a continuous slope at the threshold. + let k = 2.0; + assert!((huber(k + 1e-9, k) - huber(k - 1e-9, k)).abs() < 1e-7); + } +} diff --git a/crates/inkvec-fit/src/extrema.rs b/crates/inkvec-fit/src/extrema.rs new file mode 100644 index 00000000..cde5ae1e --- /dev/null +++ b/crates/inkvec-fit/src/extrema.rs @@ -0,0 +1,1280 @@ +//! Nodes at extrema: each smooth run of a fitted path re-segmented so that its nodes sit +//! where the curve is horizontal or vertical and its joins are smooth, wherever the fit's own +//! objective prefers it. +//! +//! # The convention +//! +//! Type designers and icon artists put a curve's on-curve points at its x and y extrema. +//! Adobe's *Type 1 Font Format* (1990), §4.1 "Points at Extremes": an endpoint "should be +//! placed at most horizontal or vertical extremes. This implies that most curves should not +//! include more than 90 degrees of arc"; §4.2: at a smooth transition the node and the control +//! points either side "should all be collinear. This is especially important at horizontal +//! and vertical extremes". At a smooth node the handles lie along the tangent, and the tangent +//! is horizontal or vertical exactly where the curve has a y or an x extremum: nodes at extrema +//! and axis-aligned handles are one convention. On the 246-icon screen set at 512 px on white +//! (the human battery, `bench/human_stats.py`, family-macro means) the artists' files have +//! 0.38 of their cubic handles within 0.5° of an axis, 0.65 of their smooth joins at an +//! extremum (0.95 in material-icons, 0.33 in noto-emoji) and 0.035 of their joins between +//! curves kinked (3-30°); the trace had 0.061, 0.458 and 0.142. +//! +//! # Why the fit did not find it, and why it is cheaper +//! +//! The dynamic program's cubic takes its end directions from the tangent estimator at measured +//! points, so it puts a node only where a measured point is, with the estimated direction. A +//! node at an extremum with an axis direction is a model it never offers, and sliding a node +//! along a smooth curve barely changes the drawing (the likelihood's null space), so nothing +//! pulls it there. Yet with both end directions fixed a cubic has four free numbers, its end +//! point and two arm lengths, against five for a G1 one: at a node where the convention fixes +//! the direction, the direction is not written. [`FIT`] credits that one coordinate per +//! anchored node, `λ` nats, the price of a coordinate under the fit's objective +//! (`docs/theory/chain-representation.md`, R0.2). +//! +//! # What runs +//! +//! [`anchor_extrema`] finds the runs (consecutive cubics and circular arcs joined at under +//! `RUN_BREAK_DEGREES`), maps every node to a measured point, finds each run's extrema, and +//! searches the cheapest chain through two kinds of candidate node: the run's old interior +//! nodes made G1 on the bisector of their two directions, and the extrema with their axis +//! direction (`shortest_chain`). The chosen nodes are refined (`refine_nodes`), every span's +//! arms polished on all its points, and the chain replaces the run when its exact `χ²` plus +//! prices (the program's: `λ` per parameter, the wobble penalty, the break cost of every kinked +//! join) is lower. Under [`FIT`] it must also write as many numbers as the run: a run with an +//! arc keeps it (`A` is 7 numbers, a cubic 6), and a run of cubics keeps its count, so the +//! pass moves nodes and smooths joins without changing what the file costs. Where a run meets +//! a line at a kink, the chain is also offered leaving along the line, which makes that join +//! smooth. +//! +//! # Where it sits +//! +//! `crate::multimodel` calls it on every uncapped fit after `crate::merge`'s passes, on the +//! centred polyline, except inside [`without`] (a stroke's centreline, whose fit the stroke +//! decision weighs against the fill's); `inkvec-cli`'s `--editability` calls it again with a +//! stronger [`Preference`] on each finished edge. In: a fitted path and the measured polyline it was +//! fitted to, in px. Out: the same path, its smooth runs rewritten as cubics. + +use inkvec_core::{Point, Polyline, Vec2}; +use kurbo::{CubicBez, ParamCurveNearest, Point as KPoint}; + +use crate::candidates::{best_cubic, raw_moments_direct, unit, Cubic}; +use crate::curves::{arc_ellipse_center, cubic_self_intersects, Segment}; +use crate::structural::eval_segment; +use crate::tangents::{arc_lengths, break_cost, turn_angle}; +use crate::{FitConfig, FittedPath}; + +/// How strongly a caller prefers nodes at extrema: what an anchored node is credited, and +/// whether a re-segmentation may change how many numbers the file writes. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Preference { + /// Parameters credited for each node whose direction the convention fixes. + pub credit: f64, + /// Accept only a re-segmentation that writes exactly as many numbers as the run it + /// replaces (the gate's count: line 2, cubic 6, arc 7). + pub same_count: bool, +} + +/// The fit's own preference: one parameter per anchored node, the coordinate (the tangent's +/// angle) the node no longer writes, and no change in the written count. +pub const FIT: Preference = Preference { + credit: 1.0, + same_count: true, +}; + +thread_local! { + /// Set while [`without`] runs: the fits made on this thread skip the pass. + static SKIP: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Run `f` with the pass switched off for every fit `f` makes on this thread. For a caller +/// whose fits feed a decision priced on the plain fit, such as the stroke detection's +/// centrelines, whose description competes with the outline's. +pub fn without(f: impl FnOnce() -> T) -> T { + let prev = SKIP.with(|s| s.replace(true)); + let out = f(); + SKIP.with(|s| s.set(prev)); + out +} + +/// A join turning by at least this many degrees ends a run: a corner, kept where it is (the +/// artists' joins between curves are smooth or turn by more than this, R3.1 of the chain). +const RUN_BREAK_DEGREES: f64 = 30.0; +/// Two extrema of one axis whose extreme values differ by less than this (px) are a wiggle +/// on a flat stretch, not two features: both are dropped. +const WIGGLE_PX: f64 = 0.5; +/// An extremum closer than this (px of arc length) to a run's end gets no node of its own. +const END_GAP_PX: f64 = 1.0; +/// Two extrema of one axis and direction closer than this (px of arc length) are one: a +/// root of the derivative next to a node that is itself the extremum. +const DEDUP_PX: f64 = 0.25; +/// Fewest measured points strictly inside a span between two nodes. +const MIN_INTERIOR: usize = 2; +/// How many candidate nodes ahead one span may reach in the search. +const MAX_REACH: usize = 8; +/// A path node with no measured point within this distance (px) is not mapped, and the +/// path is left alone. +const FAR_PX: f64 = 3.0; +/// Rounds of the node refinement. +const REFINE_ROUNDS: usize = 3; +/// The refinement's compass steps, px; a node's direction turns by twice the step, in degrees. +const REFINE_STEPS: [f64; 5] = [0.5, 0.25, 0.12, 0.06, 0.03]; + +/// Which coordinate is extreme at a node. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Axis { + /// `x` is extreme: the tangent is vertical. + X, + /// `y` is extreme: the tangent is horizontal. + Y, +} + +/// A node of a proposed chain. +#[derive(Debug, Clone, Copy)] +struct Node { + /// Position, px. + p: Point, + /// Unit direction of travel through the node. + t: Vec2, + /// Unrolled index of the measured point nearest the node. + u: usize, + /// Whether the extremum convention fixes the direction. + anchored: bool, +} + +/// An extremum of the old chain. +#[derive(Debug, Clone, Copy)] +struct Extremum { + /// The run-local segment it lies on (`0` for the run's first). + q: usize, + /// Arc length from the run's start, px. + s: f64, + /// Position, px. + p: Point, + /// The coordinate that is extreme. + axis: Axis, + /// The direction of travel there: a unit vector along an axis. + dir: Vec2, +} + +/// What the search reads: the price of a parameter and the credit of an anchored node. +#[derive(Debug, Clone, Copy)] +struct Prices { + /// `λ`, nats per parameter. + lambda: f64, + /// Parameters credited per anchored node. + credit: f64, + /// See [`Preference::same_count`]. + same_count: bool, +} + +/// Re-segment every smooth run of `path` at its x and y extrema where that costs less under +/// the fit's objective, as `pref` prices an anchored node ([`FIT`] in the fit; a stronger +/// preference under `--editability`). `poly` is the measured boundary `path` was fitted to, +/// in the same units. Returns the number of runs replaced; the path is unchanged when that +/// is 0. +pub fn anchor_extrema( + path: &mut FittedPath, + poly: &Polyline, + cfg: &FitConfig, + pref: Preference, +) -> usize { + if SKIP.with(std::cell::Cell::get) { + return 0; + } + let Some(ring) = Ring::new(path, poly) else { + return 0; + }; + let prices = Prices { + lambda: cfg.lambda, + credit: pref.credit, + same_count: pref.same_count, + }; + let accepted: Vec<(Run, Proposal)> = ring + .runs() + .into_iter() + .filter_map(|run| ring.improve(&run, poly, &prices).map(|p| (run, p))) + .collect(); + let count = accepted.len(); + if count > 0 { + let (start, segments) = ring.splice(&accepted); + path.start = start; + path.segments = segments; + } + count +} + +/// A run: consecutive curved segments joined at less than [`RUN_BREAK_DEGREES`]. +#[derive(Debug, Clone, Copy)] +struct Run { + /// Index of its first segment in the path. + first: usize, + /// Number of segments. + len: usize, + /// The run is the whole closed path, with no end. + cyclic: bool, +} + +/// What re-segmenting one run proposes. +struct Proposal { + /// The new chain's start. + start: Point, + /// Its segments, all cubics. + segs: Vec, + /// Its price, nats, comparable with [`OldPrice::cost`]. + cost: f64, + /// Nodes anchored on an axis. + anchored: usize, +} + +/// The price of a run as the path has it. +struct OldPrice { + /// Nats: residual, parameters, wobble and the breaks at its joins. + cost: f64, + /// Numbers the segments write (line 2, cubic 6, arc 7). + written: f64, + /// Whether any join inside it turns by 3 degrees or more. + kinked: bool, +} + +/// A fitted path with what every run's search reads about it. +struct Ring<'a> { + path: &'a FittedPath, + /// Segments. + m: usize, + closed: bool, + /// Node `q` is where segment `q` starts; `m + 1` of them. + starts: Vec, + /// Unrolled measured index of every node, increasing; on a closed path the last is the + /// first plus `n`. + uu: Vec, + /// Segment `q` is a cubic or a circular arc. + curved: Vec, + /// Turn at node `q`, radians (infinite at an open path's ends). + joins: Vec, +} + +impl<'a> Ring<'a> { + fn new(path: &'a FittedPath, poly: &Polyline) -> Option { + let (n, m) = (poly.len(), path.segments.len()); + if m == 0 || n < 4 || path.closed != poly.closed { + return None; + } + let closed = path.closed; + let mut starts = Vec::with_capacity(m + 1); + starts.push(path.start); + starts.extend(path.segments.iter().map(Segment::end)); + let uu = node_indices(poly, path, &starts)?; + let curved = path.segments.iter().map(is_curved).collect(); + let joins = (0..=m) + .map(|q| { + let (a, b) = match q { + 0 if closed => (m - 1, 0), + _ if q == 0 || q == m => return f64::INFINITY, + _ => (q - 1, q), + }; + match ( + tangent_at(&path.segments[a], starts[a], 1.0), + tangent_at(&path.segments[b], starts[b], 0.0), + ) { + (Some(x), Some(y)) => turn_angle(x, y), + _ => f64::INFINITY, + } + }) + .collect(); + Some(Ring { + path, + m, + closed, + starts, + uu, + curved, + joins, + }) + } + + /// Node `q` ends a run: a corner, a line on either side, or an open path's end. + fn boundary(&self, q: usize) -> bool { + let q = q % self.m; + if !self.closed && q == 0 { + return true; + } + let prev = (q + self.m - 1) % self.m; + self.joins[q] >= RUN_BREAK_DEGREES.to_radians() || !self.curved[prev] || !self.curved[q] + } + + /// The runs, walking from a boundary so that none wraps past the walk's start. + fn runs(&self) -> Vec { + let m = self.m; + let b0 = if self.closed { + match (0..m).find(|&q| self.boundary(q)) { + Some(b) => b, + None if self.curved.iter().all(|&c| c) => { + return vec![Run { + first: 0, + len: m, + cyclic: true, + }]; + } + None => return Vec::new(), + } + } else { + 0 + }; + let mut runs = Vec::new(); + let mut k = 0; + while k < m { + let q = (b0 + k) % m; + if !self.curved[q] { + k += 1; + continue; + } + let mut len = 1; + while k + len < m && !self.boundary(q + len) { + len += 1; + } + runs.push(Run { + first: q, + len, + cyclic: false, + }); + k += len; + } + runs + } + + /// The run's own segments, the start of each and its end, and the unrolled index of + /// every node. + fn geometry(&self, run: &Run) -> RunGeom { + let segs: Vec = (0..run.len) + .map(|k| self.path.segments[(run.first + k) % self.m].clone()) + .collect(); + let mut nodes_u = vec![self.uu[run.first]]; + for k in 0..run.len { + let q = (run.first + k) % self.m; + nodes_u.push(nodes_u[k] + self.uu[q + 1] - self.uu[q]); + } + RunGeom::new(segs, self.starts[run.first], nodes_u, run.cyclic) + } + + /// The run's price as the path has it. Its end joins are priced by the caller. + fn old_price(&self, run: &Run, g: &RunGeom, poly: &Polyline, prices: &Prices) -> OldPrice { + let chi2 = g.chain_chi2(poly, g.start(), &g.segs, &g.nodes_u); + let mut cost = 0.5 * chi2; + let mut written = 0.0; + for (q, s) in g.segs.iter().enumerate() { + cost += prices.lambda * s.params() + wobble(g.starts[q], s, prices.lambda); + written += written_count(s); + } + let inner = if run.cyclic { run.len } else { run.len - 1 }; + let mut kinked = false; + for k in 0..inner { + let turn = self.joins[(run.first + k + 1) % self.m]; + cost += break_cost_of(turn, prices.lambda); + kinked |= turn >= 3f64.to_radians(); + } + OldPrice { + cost, + written, + kinked, + } + } + + /// Where a run meets a line at a kink (not a corner): the line's direction, which the + /// run may take instead to make that join smooth, and the break the join pays now. + fn line_ends(&self, run: &Run) -> [(Option, f64); 2] { + let mut out = [(None, 0.0); 2]; + if run.cyclic { + return out; + } + let m = self.m; + let line_dir = |q: usize| match self.path.segments[q] { + Segment::Line(e) => unit(e - self.starts[q]), + _ => None, + }; + let kink = + |q: usize| self.joins[q] < RUN_BREAK_DEGREES.to_radians() && self.joins[q] > 1e-9; + let last = run.first + run.len; + if (self.closed || run.first > 0) && kink(run.first) { + if let Some(d) = line_dir((run.first + m - 1) % m) { + out[0] = (Some(d), self.joins[run.first]); + } + } + if (self.closed || last < m) && kink(last % m) { + if let Some(d) = line_dir(last % m) { + out[1] = (Some(d), self.joins[last % m]); + } + } + out + } + + /// The best re-segmentation of one run, if it is cheaper than the run and writes no + /// more numbers. + fn improve(&self, run: &Run, poly: &Polyline, prices: &Prices) -> Option { + let g = self.geometry(run); + let old = self.old_price(run, &g, poly, prices); + let ends = self.line_ends(run); + let brk = |e: &(Option, f64)| break_cost_of(e.1, prices.lambda); + let old_cost = old.cost + brk(&ends[0]) + brk(&ends[1]); + // As the run leaves now, and (where a line meets it at a kink) along the line. + let plain = g.propose(poly, prices, (None, None)).map(|mut p| { + p.cost += brk(&ends[0]) + brk(&ends[1]); + (p, false) + }); + let smooth = (ends[0].0.is_some() || ends[1].0.is_some()) + .then(|| g.propose(poly, prices, (ends[0].0, ends[1].0))) + .flatten() + .map(|mut p| { + p.cost += ends.iter().filter(|e| e.0.is_none()).map(brk).sum::(); + (p, true) + }); + let (prop, smoothed) = match (plain, smooth) { + (Some(p), Some(s)) => { + if s.0.cost < p.0.cost { + s + } else { + p + } + } + (p, s) => p.or(s)?, + }; + // Only a run that gains a node at an extremum or loses a kink is touched. + if prop.anchored == 0 && !old.kinked && !smoothed { + return None; + } + let written = 6.0 * prop.segs.len() as f64; + let count_ok = if prices.same_count { + (written - old.written).abs() < 1e-9 + } else { + true + }; + (prop.cost < old_cost && count_ok).then_some(prop) + } + + /// The path's start and segments with the accepted runs written in. A cyclic run + /// replaces it whole; otherwise the path is rebuilt from a boundary node, so a closed + /// path may start at another node. + fn splice(&self, accepted: &[(Run, Proposal)]) -> (Point, Vec) { + if let Some((_, prop)) = accepted.iter().find(|(r, _)| r.cyclic) { + return (prop.start, prop.segs.clone()); + } + let m = self.m; + let b0 = if self.closed { + (0..m).find(|&q| self.boundary(q)).unwrap_or(0) + } else { + 0 + }; + let mut segs = Vec::with_capacity(m); + let mut k = 0; + while k < m { + let q = (b0 + k) % m; + if let Some((run, prop)) = accepted.iter().find(|(r, _)| r.first == q) { + segs.extend(prop.segs.iter().cloned()); + k += run.len; + } else { + segs.push(self.path.segments[q].clone()); + k += 1; + } + } + (self.starts[b0], segs) + } +} + +/// One run's segments, in its own order, and where everything on it is. +struct RunGeom { + segs: Vec, + /// Start of each segment, and the run's end: `segs.len() + 1` points. + starts: Vec, + /// Unrolled measured index of each of those nodes. + nodes_u: Vec, + /// Arc length at each node from the run's start, px. + cum: Vec, + cyclic: bool, +} + +impl RunGeom { + fn new(segs: Vec, start: Point, nodes_u: Vec, cyclic: bool) -> Self { + let mut starts = vec![start]; + starts.extend(segs.iter().map(Segment::end)); + let mut cum = vec![0.0]; + for (q, s) in segs.iter().enumerate() { + cum.push(cum[q] + length_to(s, starts[q], 1.0)); + } + RunGeom { + segs, + starts, + nodes_u, + cum, + cyclic, + } + } + + fn start(&self) -> Point { + self.starts[0] + } + + /// `χ²` of the measured points over a chain's index range: each point's squared + /// distance to the nearest of the segment its index falls in and that segment's two + /// neighbours, over its sigma squared. A cyclic chain scores each point once. + fn chain_chi2( + &self, + poly: &Polyline, + start: Point, + segs: &[Segment], + nodes_u: &[usize], + ) -> f64 { + let n = poly.len(); + let m = segs.len(); + let mut starts = vec![start]; + starts.extend(segs.iter().map(Segment::end)); + let end = if self.cyclic { + nodes_u[m] + } else { + nodes_u[m] + 1 + }; + let mut acc = 0.0; + let mut q = 0usize; + for u in nodes_u[0]..end { + while q + 1 < m && u > nodes_u[q + 1] { + q += 1; + } + let p = poly.points[u % n]; + let sg = poly.sigma[u % n].max(1e-6); + let near = [ + Some(q), + if q > 0 { + Some(q - 1) + } else { + self.cyclic.then(|| m - 1) + }, + if q + 1 < m { + Some(q + 1) + } else { + self.cyclic.then_some(0) + }, + ]; + let best = near + .into_iter() + .flatten() + .map(|r| dist2_to(&segs[r], starts[r], p)) + .fold(f64::INFINITY, f64::min); + acc += best / (sg * sg); + } + acc + } + + /// The anchored chain for this run, `ends` overriding the directions it leaves and + /// arrives with, and its price (without the breaks at its ends). + fn propose( + &self, + poly: &Polyline, + prices: &Prices, + ends: (Option, Option), + ) -> Option { + let ext = self.extrema(); + let nodes = self.candidates(poly, &ext, ends)?; + let mut chosen = shortest_chain(poly, &nodes, prices)?; + refine_nodes(poly, &mut chosen, self.cyclic, prices.lambda); + let segs: Vec = chosen + .windows(2) + .map(|w| fit_span(poly, &w[0], &w[1])) + .collect::>()?; + let nodes_u: Vec = chosen.iter().map(|nd| nd.u).collect(); + let start = chosen[0].p; + let chi2 = self.chain_chi2(poly, start, &segs, &nodes_u); + // The start of an open run is the old node, never credited; a cyclic run's first + // node is also its last, credited once. + let anchored = chosen[..chosen.len() - 1] + .iter() + .enumerate() + .filter(|(k, nd)| nd.anchored && (*k > 0 || self.cyclic)) + .count(); + let mut cost = 0.5 * chi2 - prices.lambda * prices.credit * anchored as f64; + let mut st = start; + for s in &segs { + cost += prices.lambda * s.params() + wobble(st, s, prices.lambda); + st = s.end(); + } + Some(Proposal { + start, + segs, + cost, + anchored, + }) + } + + /// The x and y extrema of the run, in order along it: inside segments, and at nodes + /// where a tangent component changes sign. Near-duplicates merged, wiggles on flat + /// stretches dropped, and (on an open run) none within [`END_GAP_PX`] of its ends. + fn extrema(&self) -> Vec { + let (segs, starts) = (&self.segs, &self.starts); + let len = segs.len(); + let mut ext: Vec = Vec::new(); + for q in 0..len { + if q > 0 || self.cyclic { + let prev = (q + len - 1) % len; + if let (Some(ti), Some(to)) = ( + tangent_at(&segs[prev], starts[prev], 1.0), + tangent_at(&segs[q], starts[q], 0.0), + ) { + for axis in [Axis::X, Axis::Y] { + if comp(axis, ti) * comp(axis, to) <= 0.0 { + let d = Vec2 { + x: ti.x + to.x, + y: ti.y + to.y, + }; + ext.push(Extremum { + q, + s: self.cum[q], + p: starts[q], + axis, + dir: axis_dir(axis, d), + }); + } + } + } + } + for (t, axis) in interior_extrema(&segs[q], starts[q]) { + let Some(d) = tangent_at(&segs[q], starts[q], t) else { + continue; + }; + ext.push(Extremum { + q, + s: self.cum[q] + length_to(&segs[q], starts[q], t), + p: eval_segment(&segs[q], starts[q], t), + axis, + dir: axis_dir(axis, d), + }); + } + } + ext.sort_by(|x, y| x.s.total_cmp(&y.s)); + let mut out: Vec = Vec::new(); + for e in ext { + let dup = out + .iter() + .rev() + .find(|d| d.axis == e.axis) + .is_some_and(|last| (e.s - last.s).abs() < DEDUP_PX && last.dir.dot(e.dir) > 0.0); + if !dup { + out.push(e); + } + } + drop_wiggles(&mut out); + if !self.cyclic { + let total = self.cum[len]; + out.retain(|e| e.s > END_GAP_PX && e.s < total - END_GAP_PX); + } + out + } + + /// The nodes a chain may use, in order: the run's ends (open run), its old interior + /// nodes made G1 on the bisector of their two directions, and its extrema, anchored. A + /// cyclic run starts and ends on its first anchored candidate. + fn candidates( + &self, + poly: &Polyline, + ext: &[Extremum], + ends: (Option, Option), + ) -> Option> { + let n = poly.len(); + let (segs, starts) = (&self.segs, &self.starts); + let len = segs.len(); + let (first_u, last_u) = (self.nodes_u[0], self.nodes_u[len]); + let mut cands: Vec<(f64, Node)> = Vec::new(); + for q in 0..len { + if q == 0 && !self.cyclic { + continue; + } + let prev = (q + len - 1) % len; + let (Some(ti), Some(to)) = ( + tangent_at(&segs[prev], starts[prev], 1.0), + tangent_at(&segs[q], starts[q], 0.0), + ) else { + continue; + }; + if let Some(t) = unit(Vec2 { + x: ti.x + to.x, + y: ti.y + to.y, + }) { + let node = Node { + p: starts[q], + t, + u: self.nodes_u[q], + anchored: false, + }; + cands.push((self.cum[q], node)); + } + } + for e in ext { + let lo = self.nodes_u[e.q].saturating_sub(1).max(first_u); + let hi = (self.nodes_u[e.q + 1] + 1).min(last_u); + let node = Node { + p: e.p, + t: e.dir, + u: nearest_index(poly, e.p, lo, hi), + anchored: true, + }; + cands.push((e.s, node)); + } + // By arc length; where two sit at one point, the anchored one first. + cands.sort_by(|x, y| x.0.total_cmp(&y.0).then(y.1.anchored.cmp(&x.1.anchored))); + let mut nodes: Vec = Vec::with_capacity(cands.len() + 2); + if self.cyclic { + if cands.len() < 2 { + return None; + } + let k0 = cands.iter().position(|c| c.1.anchored).unwrap_or(0); + cands.rotate_left(k0); + let u0 = cands[0].1.u; + for (_, c) in &cands { + let mut c = *c; + if c.u < u0 { + c.u += n; + } + nodes.push(c); + } + let mut last = nodes[0]; + last.u += n; + nodes.push(last); + } else { + let t0 = match ends.0 { + Some(d) => d, + None => tangent_at(&segs[0], starts[0], 0.0)?, + }; + let t1 = match ends.1 { + Some(d) => d, + None => tangent_at(&segs[len - 1], starts[len - 1], 1.0)?, + }; + nodes.push(Node { + p: starts[0], + t: t0, + u: first_u, + anchored: false, + }); + nodes.extend(cands.iter().map(|c| c.1)); + nodes.push(Node { + p: starts[len], + t: t1, + u: last_u, + anchored: false, + }); + } + Some(nodes) + } +} + +/// Drop pairs of consecutive extrema of one axis whose extreme values differ by less than +/// [`WIGGLE_PX`]: a bump of that size on a flat stretch is not a feature to put nodes on. +fn drop_wiggles(ext: &mut Vec) { + 'again: loop { + for axis in [Axis::X, Axis::Y] { + let idx: Vec = (0..ext.len()).filter(|&i| ext[i].axis == axis).collect(); + for w in idx.windows(2) { + let v = |e: &Extremum| if axis == Axis::X { e.p.x } else { e.p.y }; + if (v(&ext[w[0]]) - v(&ext[w[1]])).abs() < WIGGLE_PX { + ext.remove(w[1]); + ext.remove(w[0]); + continue 'again; + } + } + } + return; + } +} + +/// The cheapest chain through the candidates from the first to the last: a shortest path +/// in which a span is the cubic with both end directions fixed ([`fit_span_quick`]), priced +/// as the dynamic program prices a cubic, less the credit of the node it ends on when that +/// node is anchored and is not the chain's last. +fn shortest_chain(poly: &Polyline, nodes: &[Node], prices: &Prices) -> Option> { + let c = nodes.len(); + if c < 2 { + return None; + } + let mut best = vec![f64::INFINITY; c]; + let mut from = vec![usize::MAX; c]; + best[0] = 0.0; + for j in 1..c { + let credit = if j + 1 < c && nodes[j].anchored { + prices.lambda * prices.credit + } else { + 0.0 + }; + for i in j.saturating_sub(MAX_REACH)..j { + if !best[i].is_finite() || nodes[j].u < nodes[i].u + 1 + MIN_INTERIOR { + continue; + } + let Some((chi2, wob)) = fit_span_quick(poly, &nodes[i], &nodes[j], prices.lambda) + else { + continue; + }; + let cost = + best[i] + 0.5 * chi2 + prices.lambda * crate::multimodel::params_cubic() + wob + - credit; + if cost < best[j] { + best[j] = cost; + from[j] = i; + } + } + } + if !best[c - 1].is_finite() { + return None; + } + let mut idx = vec![c - 1]; + while let Some(&k) = idx.last() { + if k == 0 { + break; + } + idx.push(from[k]); + } + idx.reverse(); + Some(idx.into_iter().map(|k| nodes[k]).collect()) +} + +/// Move each interior node (and turn one the convention does not anchor) to where its two +/// spans fit best: a compass search on the subsampled residual of the two cubics. A node +/// keeps at least [`MIN_INTERIOR`] measured points on either side. +fn refine_nodes(poly: &Polyline, nodes: &mut [Node], cyclic: bool, lambda: f64) { + let c = nodes.len(); + if c < 3 { + return; + } + let pair = |nodes: &[Node], k: usize| -> f64 { + match ( + fit_span_quick(poly, &nodes[k - 1], &nodes[k], lambda), + fit_span_quick(poly, &nodes[k], &nodes[k + 1], lambda), + ) { + (Some(a), Some(b)) => a.0 + b.0, + _ => f64::INFINITY, + } + }; + for _ in 0..REFINE_ROUNDS { + let mut moved = false; + for k in 1..c - 1 { + let mut cur = pair(nodes, k); + let lo = nodes[k - 1].u + 1 + MIN_INTERIOR; + let hi = nodes[k + 1].u.saturating_sub(1 + MIN_INTERIOR); + if !cur.is_finite() || hi < lo { + continue; + } + for step in REFINE_STEPS { + let turn = if nodes[k].anchored { + 0.0 + } else { + (2.0 * step).to_radians() + }; + let tries = [ + (step, 0.0, 0.0), + (-step, 0.0, 0.0), + (0.0, step, 0.0), + (0.0, -step, 0.0), + (0.0, 0.0, turn), + (0.0, 0.0, -turn), + ]; + let mut improved = true; + while improved { + improved = false; + for &(dx, dy, da) in &tries { + if dx == 0.0 && dy == 0.0 && da == 0.0 { + continue; + } + let saved = nodes[k]; + let (s, co) = da.sin_cos(); + nodes[k].p = Point::new(saved.p.x + dx, saved.p.y + dy); + nodes[k].t = Vec2 { + x: co * saved.t.x - s * saved.t.y, + y: s * saved.t.x + co * saved.t.y, + }; + nodes[k].u = nearest_index(poly, nodes[k].p, lo, hi); + let v = pair(nodes, k); + if v < cur - 1e-9 { + cur = v; + improved = true; + moved = true; + } else { + nodes[k] = saved; + } + } + } + } + } + if !moved { + break; + } + } + if cyclic { + let mut last = nodes[0]; + last.u += poly.len(); + nodes[c - 1] = last; + } +} + +/// The measured points strictly between two nodes, with the nodes themselves as the ends: +/// points, sigmas and cumulative arc lengths. `None` with fewer than [`MIN_INTERIOR`] +/// points inside. +fn span_points(poly: &Polyline, a: &Node, b: &Node) -> Option<(Vec, Vec, Vec)> { + let n = poly.len(); + if b.u < a.u + 1 + MIN_INTERIOR { + return None; + } + let mut pts = Vec::with_capacity(b.u - a.u + 1); + let mut sig = Vec::with_capacity(b.u - a.u + 1); + pts.push(a.p); + sig.push(poly.sigma[a.u % n]); + for u in a.u + 1..b.u { + pts.push(poly.points[u % n]); + sig.push(poly.sigma[u % n]); + } + pts.push(b.p); + sig.push(poly.sigma[b.u % n]); + let s = arc_lengths(&pts); + Some((pts, sig, s)) +} + +/// The cubic from `a` to `b` with both end directions fixed, scored on a subsample for the +/// search: its residual estimate and wobble penalty. Arms by area and moment only. +fn fit_span_quick(poly: &Polyline, a: &Node, b: &Node, lambda: f64) -> Option<(f64, f64)> { + let (pts, sig, s) = span_points(poly, a, b)?; + let j = pts.len() - 1; + let raw = raw_moments_direct(&pts, 0, j); + let (chi2, d0, d1) = best_cubic(&pts, &sig, &s, 0, j, a.t, b.t, raw, true)?; + let cb = Cubic::from_arms(a.p, b.p, a.t, b.t, a.p.dist(b.p), d0, d1); + Some((chi2, cb.wobble_penalty(lambda))) +} + +/// The cubic from `a` to `b` with both end directions fixed: arms by area and moment, then +/// polished on every point (`crate::multimodel::polish_arms`). `None` for a span too short +/// to fit or a cubic that crosses itself. +fn fit_span(poly: &Polyline, a: &Node, b: &Node) -> Option { + let (pts, sig, s) = span_points(poly, a, b)?; + let j = pts.len() - 1; + let raw = raw_moments_direct(&pts, 0, j); + let init = best_cubic(&pts, &sig, &s, 0, j, a.t, b.t, raw, false) + .map_or((1.0 / 3.0, 1.0 / 3.0), |(_, d0, d1)| (d0, d1)); + let ((d0, d1), _) = crate::multimodel::polish_arms(&pts, &sig, &s, 0, j, a.t, b.t, init); + let chord = a.p.dist(b.p); + if chord < 1e-9 { + return None; + } + let cb = Cubic::from_arms(a.p, b.p, a.t, b.t, chord, d0, d1); + if cubic_self_intersects(cb.p0, cb.p1, cb.p2, cb.p3) { + return None; + } + Some(Segment::Cubic(cb.p1, cb.p2, cb.p3)) +} + +/// The measured point nearest each node of the path, as unrolled indices increasing along +/// it (a closed path's last node is its first plus `n`). `None` when a node has no +/// measured point within [`FAR_PX`] or the order cannot be kept. +fn node_indices(poly: &Polyline, path: &FittedPath, starts: &[Point]) -> Option> { + let n = poly.len(); + let m = path.segments.len(); + let s = arc_lengths(&poly.points); + let total = s[n - 1] + + if path.closed { + poly.points[n - 1].dist(poly.points[0]) + } else { + 0.0 + }; + let along = |u: usize| s[u % n] + (u / n) as f64 * total; + let u0 = nearest_index( + poly, + starts[0], + 0, + if path.closed { n - 1 } else { (n - 1).min(8) }, + ); + if poly.points[u0].dist(starts[0]) > FAR_PX { + return None; + } + let end_u = if path.closed { u0 + n } else { n - 1 }; + let mut out = vec![u0]; + for q in 0..m - 1 { + let prev = out[q]; + let reach = 1.5 * length_to(&path.segments[q], starts[q], 1.0) + 4.0; + let (mut best, mut bd) = (usize::MAX, f64::INFINITY); + let mut u = prev + 1; + while u < end_u && along(u) - along(prev) <= reach { + let d = poly.points[u % n].dist(starts[q + 1]); + if d < bd { + (best, bd) = (u, d); + } + u += 1; + } + if best == usize::MAX || bd > FAR_PX { + return None; + } + out.push(best); + } + out.push(end_u); + out.windows(2).all(|w| w[1] > w[0]).then_some(out) +} + +/// The measured point (unrolled index in `lo..=hi`) nearest `p`. +fn nearest_index(poly: &Polyline, p: Point, lo: usize, hi: usize) -> usize { + let n = poly.len(); + (lo..=hi) + .min_by(|&a, &b| { + poly.points[a % n] + .dist(p) + .total_cmp(&poly.points[b % n].dist(p)) + }) + .unwrap_or(lo) +} + +/// The numbers a segment writes into the file, as the gate counts them: line 2, cubic 6, +/// arc 7. +fn written_count(seg: &Segment) -> f64 { + match seg { + Segment::Line(_) => 2.0, + Segment::Cubic(..) => 6.0, + Segment::Arc { .. } => 7.0, + } +} + +/// A cubic, or a circular arc. An elliptical arc ends a run like a line does. +fn is_curved(seg: &Segment) -> bool { + match seg { + Segment::Line(_) => false, + Segment::Cubic(..) => true, + Segment::Arc { .. } => seg.is_circular(), + } +} + +/// [`break_cost`] of a turn given as an angle (radians). +fn break_cost_of(turn: f64, lambda: f64) -> f64 { + if !turn.is_finite() { + return 0.0; + } + let (s, c) = turn.sin_cos(); + break_cost(Vec2 { x: 1.0, y: 0.0 }, Vec2 { x: c, y: s }, lambda) +} + +/// The wobble penalty a cubic carries in the dynamic program's price; 0 for anything else. +fn wobble(p0: Point, seg: &Segment, lambda: f64) -> f64 { + match *seg { + Segment::Cubic(p1, p2, p3) => Cubic { p0, p1, p2, p3 }.wobble_penalty(lambda), + _ => 0.0, + } +} + +/// The component of `v` along `axis`. +fn comp(axis: Axis, v: Vec2) -> f64 { + match axis { + Axis::X => v.x, + Axis::Y => v.y, + } +} + +/// The direction an extremum of `axis` is traversed in, given a direction `d` near it: a +/// vertical unit vector at an x extremum, a horizontal one at a y extremum. +fn axis_dir(axis: Axis, d: Vec2) -> Vec2 { + let sign = |v: f64| if v >= 0.0 { 1.0 } else { -1.0 }; + match axis { + Axis::X => Vec2 { + x: 0.0, + y: sign(d.y), + }, + Axis::Y => Vec2 { + x: sign(d.x), + y: 0.0, + }, + } +} + +/// Unit direction of travel at parameter `t` of a segment starting at `start`. A cubic +/// whose arm has collapsed takes the next leg of its control polygon. +fn tangent_at(seg: &Segment, start: Point, t: f64) -> Option { + match *seg { + Segment::Line(e) => unit(e - start), + Segment::Cubic(c1, c2, e) => { + let mt = 1.0 - t; + let (a, b, c) = (c1 - start, c2 - c1, e - c2); + let w = (mt * mt, 2.0 * mt * t, t * t); + unit(Vec2 { + x: w.0 * a.x + w.1 * b.x + w.2 * c.x, + y: w.0 * a.y + w.1 * b.y + w.2 * c.y, + }) + .or_else(|| { + if t < 0.5 { + unit(c2 - start).or_else(|| unit(e - start)) + } else { + unit(e - c1).or_else(|| unit(e - start)) + } + }) + } + Segment::Arc { + rx, + ry, + phi, + large_arc, + sweep, + end, + } => { + let f = arc_ellipse_center(start, rx, ry, phi, large_arc, sweep, end); + if f.delta == 0.0 { + return unit(end - start); + } + let th = f.theta1 + f.delta * t; + let (sp, cp) = f.phi.sin_cos(); + let (dx, dy) = (-f.rx * th.sin(), f.ry * th.cos()); + let sgn = f.delta.signum(); + unit(Vec2 { + x: sgn * (cp * dx - sp * dy), + y: sgn * (sp * dx + cp * dy), + }) + } + } +} + +/// Parameters strictly inside a segment where one coordinate of its tangent vanishes, in +/// order, with the coordinate that is extreme there. A cubic's derivative is a quadratic +/// per coordinate; a circle's tangent is vertical at angles `kπ` and horizontal at +/// `π/2 + kπ`. Lines and elliptical arcs have none here. +fn interior_extrema(seg: &Segment, start: Point) -> Vec<(f64, Axis)> { + const EPS: f64 = 1e-6; + let mut out = Vec::new(); + match *seg { + Segment::Line(_) => {} + Segment::Cubic(c1, c2, e) => { + for axis in [Axis::X, Axis::Y] { + let (a, b, c) = ( + comp(axis, c1 - start), + comp(axis, c2 - c1), + comp(axis, e - c2), + ); + for r in quadratic_roots(a - 2.0 * b + c, 2.0 * (b - a), a) { + if r > EPS && r < 1.0 - EPS { + out.push((r, axis)); + } + } + } + } + Segment::Arc { + rx, + ry, + phi, + large_arc, + sweep, + end, + } => { + if !seg.is_circular() { + return out; + } + let f = arc_ellipse_center(start, rx, ry, phi, large_arc, sweep, end); + if f.delta.abs() < 1e-12 { + return out; + } + let quarter = std::f64::consts::FRAC_PI_2; + let (lo, hi) = if f.delta > 0.0 { + (f.theta1, f.theta1 + f.delta) + } else { + (f.theta1 + f.delta, f.theta1) + }; + let mut k = (lo / quarter).ceil() as i64; + while (k as f64) * quarter < hi { + let t = (k as f64 * quarter - f.theta1) / f.delta; + if t > EPS && t < 1.0 - EPS { + out.push(( + t, + if k.rem_euclid(2) == 0 { + Axis::X + } else { + Axis::Y + }, + )); + } + k += 1; + } + } + } + out.sort_by(|a, b| a.0.total_cmp(&b.0)); + out +} + +/// Real roots of `a·t² + b·t + c`, by the numerically stable pair of formulas; a vanishing +/// leading coefficient leaves the linear root. +fn quadratic_roots(a: f64, b: f64, c: f64) -> Vec { + let scale = a.abs().max(b.abs()).max(c.abs()).max(1e-300); + if a.abs() <= 1e-12 * scale { + return if b.abs() > 1e-12 * scale { + vec![-c / b] + } else { + Vec::new() + }; + } + let disc = b * b - 4.0 * a * c; + if disc < 0.0 { + return Vec::new(); + } + let q = -0.5 * (b + b.signum() * disc.sqrt()); + if q == 0.0 { + vec![-b / (2.0 * a)] + } else { + vec![q / a, c / q] + } +} + +/// Approximate arc length of `seg` from `t = 0` to `t`, px (16 chords). +fn length_to(seg: &Segment, start: Point, t: f64) -> f64 { + let mut acc = 0.0; + let mut prev = start; + for k in 1..=16 { + let p = eval_segment(seg, start, t * k as f64 / 16.0); + acc += prev.dist(p); + prev = p; + } + acc +} + +/// Squared distance (px²) from `p` to one segment: exact for a line, by kurbo's +/// nearest-point solver for a cubic, and through the centre for a circular arc. +fn dist2_to(seg: &Segment, start: Point, p: Point) -> f64 { + let sq = |v: Vec2| v.dot(v); + match *seg { + Segment::Line(e) => { + let d = e - start; + let l2 = d.dot(d); + if l2 <= 1e-24 { + return sq(p - start); + } + let t = ((p - start).dot(d) / l2).clamp(0.0, 1.0); + sq(p - Point::new(start.x + d.x * t, start.y + d.y * t)) + } + Segment::Cubic(c1, c2, e) => { + let k = |q: Point| KPoint::new(q.x, q.y); + CubicBez::new(k(start), k(c1), k(c2), k(e)) + .nearest(k(p), 1e-7) + .distance_sq + } + Segment::Arc { + rx, + ry, + phi, + large_arc, + sweep, + end, + } => { + let ends = sq(p - start).min(sq(p - end)); + let f = arc_ellipse_center(start, rx, ry, phi, large_arc, sweep, end); + if f.delta == 0.0 || !seg.is_circular() { + // Not reached from a run (an elliptical arc ends one); sampled. + return (1..64) + .map(|k| sq(p - eval_segment(seg, start, k as f64 / 64.0))) + .fold(ends, f64::min); + } + let v = p - f.c; + let rel = (v.y.atan2(v.x) - f.theta1).rem_euclid(std::f64::consts::TAU); + let inside = if f.delta >= 0.0 { + rel <= f.delta + } else { + rel == 0.0 || rel >= std::f64::consts::TAU + f.delta + }; + if inside { + let d = v.norm() - f.rx; + d * d + } else { + ends + } + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/inkvec-fit/src/extrema/tests.rs b/crates/inkvec-fit/src/extrema/tests.rs new file mode 100644 index 00000000..c6db88f5 --- /dev/null +++ b/crates/inkvec-fit/src/extrema/tests.rs @@ -0,0 +1,270 @@ +//! The extremum re-segmentation on curves whose answer is known: ellipses with their nodes +//! off the extrema, rings that are already right, straight runs, and a curve leaving a line +//! at a kink. + +use super::*; + +/// The standard cubic for the arc of the ellipse `(a cos θ, b sin θ) + c` from `t0` to `t1` +/// (radians, `|t1 − t0| ≤ π/2`): the circle's approximation, scaled. +fn ellipse_cubic(c: Point, a: f64, b: f64, t0: f64, t1: f64) -> Segment { + let k = 4.0 / 3.0 * ((t1 - t0) / 4.0).tan(); + let at = |t: f64| Point::new(c.x + a * t.cos(), c.y + b * t.sin()); + let d = |t: f64| (-a * t.sin(), b * t.cos()); + let (p0, p3) = (at(t0), at(t1)); + let (d0, d1) = (d(t0), d(t1)); + Segment::Cubic( + Point::new(p0.x + k * d0.0, p0.y + k * d0.1), + Point::new(p3.x - k * d1.0, p3.y - k * d1.1), + p3, + ) +} + +/// `n` points round the ellipse, starting at angle `t_start`, uniform sigma. +fn ellipse_points(c: Point, a: f64, b: f64, n: usize, t_start: f64, sigma: f64) -> Polyline { + let pts = (0..n) + .map(|k| { + let t = t_start + std::f64::consts::TAU * k as f64 / n as f64; + Point::new(c.x + a * t.cos(), c.y + b * t.sin()) + }) + .collect(); + Polyline::with_uniform_sigma(pts, sigma, true) +} + +/// The ellipse as four cubics whose nodes sit at 45, 135, 225 and 315 degrees: smooth, and +/// none of them at an extremum. +fn ellipse_off_extrema(c: Point, a: f64, b: f64) -> FittedPath { + let q = std::f64::consts::FRAC_PI_4; + let start = Point::new(c.x + a * q.cos(), c.y + b * q.sin()); + let segments = (0..4) + .map(|k| { + let t0 = q + k as f64 * 2.0 * q; + ellipse_cubic(c, a, b, t0, t0 + 2.0 * q) + }) + .collect(); + FittedPath { + start, + segments, + closed: true, + } +} + +fn nodes_of(fp: &FittedPath) -> Vec { + std::iter::once(fp.start) + .chain(fp.segments.iter().map(Segment::end)) + .collect() +} + +/// Every handle of every cubic, as `(node, control point)`. +fn handles(fp: &FittedPath) -> Vec<(Point, Point)> { + let mut out = Vec::new(); + let mut cur = fp.start; + for s in &fp.segments { + if let Segment::Cubic(c1, c2, e) = *s { + out.push((cur, c1)); + out.push((e, c2)); + } + cur = s.end(); + } + out +} + +fn cfg() -> FitConfig { + FitConfig::from_precision(512.0, 0.1, 2.0) +} + +#[test] +fn an_ellipse_noded_off_its_extrema_is_renoded_on_them() { + let c = Point::new(10.0, -5.0); + let (a, b) = (60.0, 40.0); + let poly = ellipse_points(c, a, b, 400, 0.3, 0.05); + let mut fp = ellipse_off_extrema(c, a, b); + let runs = anchor_extrema(&mut fp, &poly, &cfg(), FIT); + assert_eq!(runs, 1, "the whole ring is one smooth run"); + assert_eq!( + fp.segments.len(), + 4, + "four cubics, as before: {:?}", + fp.segments + ); + assert!(fp.segments.iter().all(|s| matches!(s, Segment::Cubic(..)))); + // Every node at one of the four extrema, every handle on an axis. + let extrema = [ + Point::new(c.x + a, c.y), + Point::new(c.x, c.y + b), + Point::new(c.x - a, c.y), + Point::new(c.x, c.y - b), + ]; + for p in nodes_of(&fp) { + let d = extrema + .iter() + .map(|e| e.dist(p)) + .fold(f64::INFINITY, f64::min); + assert!(d < 0.2, "node {p:?} is {d:.3} px from the nearest extremum"); + } + for (node, h) in handles(&fp) { + let (dx, dy) = (h.x - node.x, h.y - node.y); + assert!( + dx.abs() < 1e-9 || dy.abs() < 1e-9, + "handle {dx:.4},{dy:.4} at {node:?} is off the axes" + ); + } + // And it still draws the ellipse. + let dev = poly + .points + .iter() + .map(|p| { + let mut best = f64::INFINITY; + let mut cur = fp.start; + for s in &fp.segments { + best = best.min(dist2_to(s, cur, *p)); + cur = s.end(); + } + best.sqrt() + }) + .fold(0.0, f64::max); + assert!(dev < 0.05, "strays {dev:.4} px from the ellipse"); +} + +#[test] +fn a_ring_already_on_its_extrema_keeps_its_nodes() { + let c = Point::new(0.0, 0.0); + let (a, b) = (50.0, 30.0); + let poly = ellipse_points(c, a, b, 360, 0.0, 0.05); + let half = std::f64::consts::FRAC_PI_2; + let mut fp = FittedPath { + start: Point::new(a, 0.0), + segments: (0..4) + .map(|k| ellipse_cubic(c, a, b, k as f64 * half, (k + 1) as f64 * half)) + .collect(), + closed: true, + }; + let before = nodes_of(&fp); + anchor_extrema(&mut fp, &poly, &cfg(), FIT); + let after = nodes_of(&fp); + assert_eq!(after.len(), before.len()); + for p in after { + let d = before + .iter() + .map(|q| q.dist(p)) + .fold(f64::INFINITY, f64::min); + assert!(d < 0.2, "node moved {d:.3} px"); + } +} + +#[test] +fn straight_runs_are_left_alone() { + let pts: Vec = (0..50) + .map(|k| Point::new(k as f64, 0.5 * k as f64)) + .collect(); + let poly = Polyline::with_uniform_sigma(pts, 0.05, false); + let mut fp = FittedPath { + start: Point::new(0.0, 0.0), + segments: vec![ + Segment::Line(Point::new(20.0, 10.0)), + Segment::Line(Point::new(49.0, 24.5)), + ], + closed: false, + }; + assert_eq!(anchor_extrema(&mut fp, &poly, &cfg(), FIT), 0); + assert_eq!(fp.segments.len(), 2); +} + +#[test] +fn a_curve_leaving_a_line_at_a_kink_is_made_to_leave_along_it() { + // A horizontal line into a quarter circle tangent to it: smooth in truth. The fitted + // cubic leaves the line 6 degrees off. + let r = 40.0; + let mut pts: Vec = (0..40).map(|k| Point::new(-40.0 + k as f64, 0.0)).collect(); + let n_arc = 63; + for k in 0..=n_arc { + let t = std::f64::consts::FRAC_PI_2 * k as f64 / n_arc as f64; + pts.push(Point::new(r * t.sin(), r - r * t.cos())); + } + let poly = Polyline::with_uniform_sigma(pts, 0.05, false); + let (k, off) = (0.5523 * r, 6f64.to_radians()); + let good = Segment::Cubic(Point::new(k, 0.0), Point::new(r, r - k), Point::new(r, r)); + let kinked = Segment::Cubic( + Point::new(k * off.cos(), k * off.sin()), + Point::new(r, r - k), + Point::new(r, r), + ); + let mut fp = FittedPath { + start: Point::new(-40.0, 0.0), + segments: vec![Segment::Line(Point::new(0.0, 0.0)), kinked], + closed: false, + }; + anchor_extrema(&mut fp, &poly, &cfg(), FIT); + let Segment::Cubic(c1, _, _) = fp.segments[1] else { + panic!("the curve stays a cubic: {:?}", fp.segments); + }; + assert!(c1.y.abs() < 1e-9, "leaves the line along it now: {c1:?}"); + let Segment::Cubic(g1, ..) = good else { + unreachable!() + }; + assert!( + (c1.x - g1.x).abs() < 1.0, + "with about the arc's own handle: {c1:?}" + ); +} + +#[test] +fn nodes_map_to_increasing_measured_points_round_a_closed_ring() { + let c = Point::new(0.0, 0.0); + let poly = ellipse_points(c, 30.0, 20.0, 200, 1.0, 0.05); + let fp = ellipse_off_extrema(c, 30.0, 20.0); + let starts = nodes_of(&fp); + let u = node_indices(&poly, &fp, &starts).expect("every node is on the ring"); + assert_eq!(u.len(), 5); + assert!(u.windows(2).all(|w| w[1] > w[0])); + assert_eq!(u[4], u[0] + poly.len(), "the ring closes one turn later"); + // A node nowhere near the points maps to nothing. + let mut far = fp.clone(); + far.start = Point::new(500.0, 500.0); + assert!(node_indices(&poly, &far, &nodes_of(&far)).is_none()); +} + +#[test] +fn extrema_inside_a_cubic_and_an_arc() { + // A cubic from (0,0) bulging to x = 3/4 at t = 1/2 and back: one x extremum, mid-way. + let cub = Segment::Cubic( + Point::new(1.0, 1.0), + Point::new(1.0, 2.0), + Point::new(0.0, 3.0), + ); + let ext = interior_extrema(&cub, Point::new(0.0, 0.0)); + assert_eq!(ext.len(), 1); + assert!((ext[0].0 - 0.5).abs() < 1e-12 && ext[0].1 == Axis::X); + // A half circle from the bottom through the right to the top: its x extremum (at the + // right) is the one inside; the ends are the y extrema. + let arc = Segment::circular_arc(10.0, false, false, Point::new(0.0, -10.0)); + let ext = interior_extrema(&arc, Point::new(0.0, 10.0)); + assert_eq!(ext.len(), 1, "{ext:?}"); + assert_eq!(ext[0].1, Axis::X); + assert!((ext[0].0 - 0.5).abs() < 1e-9); + // And the roots themselves. + assert_eq!(quadratic_roots(0.0, 0.0, 1.0), Vec::::new()); + assert_eq!(quadratic_roots(0.0, 2.0, -1.0), vec![0.5]); + let mut r = quadratic_roots(1.0, -3.0, 2.0); + r.sort_by(f64::total_cmp); + assert_eq!(r, vec![1.0, 2.0]); +} + +#[test] +fn distance_to_an_arc_is_through_its_centre_inside_and_to_its_ends_outside() { + // The upper half of the circle of radius 10 round the origin, from (10, 0) to (-10, 0). + let arc = Segment::circular_arc(10.0, false, true, Point::new(-10.0, 0.0)); + let start = Point::new(10.0, 0.0); + let mid = eval_segment(&arc, start, 0.5); + let outward = Point::new(mid.x * 1.2, mid.y * 1.2); + assert!((dist2_to(&arc, start, outward).sqrt() - 2.0).abs() < 1e-9); + // Opposite the middle, the nearest point of the arc is an end. + let opposite = Point::new(-mid.x, -mid.y); + let d = dist2_to(&arc, start, opposite).sqrt(); + assert!( + (d - opposite + .dist(start) + .min(opposite.dist(Point::new(-10.0, 0.0)))) + .abs() + < 1e-9 + ); +} diff --git a/crates/inkvec-fit/src/lib.rs b/crates/inkvec-fit/src/lib.rs index bb93b52e..8a4fee79 100644 --- a/crates/inkvec-fit/src/lib.rs +++ b/crates/inkvec-fit/src/lib.rs @@ -38,7 +38,9 @@ //! 6. corner runs of chord + cubic + chord are merged into one free cubic where cheaper, //! and cubics cut through a corner's anti-aliasing chamfer are sharpened back into two //! lines (`merge`); -//! 7. research builds only: axis snapping, G1 snapping (`merge::snap`) and the structural +//! 7. each smooth run is re-segmented with its nodes at its x and y extrema and its joins +//! smooth, where the same objective prefers that ([`extrema`]); +//! 8. research builds only: axis snapping, G1 snapping (`merge::snap`) and the structural //! simplifier (`structural`). //! //! Around that entry point: [`simple`] repairs rings whose fit crosses itself by @@ -103,6 +105,7 @@ pub(crate) mod candidates; pub mod choice; pub mod cost; pub mod curves; +pub mod extrema; pub mod harmonize; pub mod merge; pub mod multimodel; diff --git a/crates/inkvec-fit/src/multimodel.rs b/crates/inkvec-fit/src/multimodel.rs index ea18d9ee..2cf81909 100644 --- a/crates/inkvec-fit/src/multimodel.rs +++ b/crates/inkvec-fit/src/multimodel.rs @@ -424,6 +424,9 @@ fn post_fit_passes( if lim.is_free() { crate::merge::merge_free_cubics(&mut fit.path, shifted, &fit.vertices, cfg); crate::merge::sharpen_corners(&mut fit.path); + // Nodes at the extrema, joins smooth, where the same objective prefers it. See + // `crate::extrema`. + crate::extrema::anchor_extrema(&mut fit.path, shifted, cfg, crate::extrema::FIT); #[cfg(feature = "research")] { // A line the measurement cannot tell from axis-aligned has one degree of @@ -867,7 +870,7 @@ pub fn segment_cost_direct( /// 12 iterations or when the relative gain falls under 1e-9. Arms are kept in /// `[1e-3, 1.5]` throughout. Returns the arms and their `χ²`. #[allow(clippy::too_many_arguments)] -fn polish_arms( +pub(crate) fn polish_arms( pts: &[Point], sigma: &[f64], s: &[f64], diff --git a/crates/inkvec-py/README.md b/crates/inkvec-py/README.md index 57f66b90..454eda4f 100644 --- a/crates/inkvec-py/README.md +++ b/crates/inkvec-py/README.md @@ -65,7 +65,7 @@ type, default and description in the editor. | `harmonize_threshold` | number | `0.92` | >= 0 and <= 1 | Shape-equivalence threshold for harmonization: the outline similarity (IoU after affine normalisation) above which two marks count as the same shape. | | `mode` | string | `"quality"` | - | Which engine traces the image. "quality" (the default) is the full engine: the best fidelity and the fewest parameters, at about half a second for a 512 px logo. "fast" is a Potrace-class fit on the same palette, planar map and emitter, with a one-pass gradient check in place of gradient recovery: several times faster (tens of milliseconds at 512 px), a little less faithful, with somewhat more parameters. Options that only steer quality stages (precision, content_units, harmonize, harmonize_threshold, time_budget) are ignored in fast mode. "balanced" (opt-in) is fast plus eight iterations of quality's boundary solve and a fit with tolerances a quarter finer: in between the two in fidelity and time, on rasters up to 1024 px on the longer side; a larger raster is traced exactly as in fast mode. It ignores the same options as fast. | | `hypotheses` | bool | `false` | - | Also trace three structural alternatives -- blend absorption off, a matte instead of native alpha, and a merge distance of 0.020 -- and keep the trace whose render explains the input in the fewest nats (its squared error at the input's resolution against the best one's, plus a price per parameter). Quality colour mode only; up to four traces, about 3.6 times the trace time at 512 px. Measured on the 246-icon screen set: 6 % closer to the artist's file at 128 px, 1 % at 512 px (9 % on the hardest tenth). Off by default. | -| `detect_strokes` | bool | `false` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count. Quality mode only; off by default. | +| `detect_strokes` | bool | `true` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count, and a ring on a plain page as one stroke over the page rather than two discs. Quality mode only; on by default. | | `merge_colors` | string | `""` | - | Colour groups: fills to draw as one, so the shapes between them join rather than being recoloured. Empty (the default) changes nothing. Groups are separated by ';' and members by ','; a member is a colour '#rrggbb' as it appears in a trace of the same image, or a gradient written as its stop colours joined by '>'. An optional '=' says what the group becomes: '=#rrggbb' a flat colour, '=@n' its n-th member (1-based; a gradient there is refitted over the whole group); without it, the member covering the most of the image. Example: '#c0392b,#e74c3c;#f00>#00f,#0a0=@1'. A group costs one extra trace. | diff --git a/crates/inkvec-py/python/inkvec/__init__.pyi b/crates/inkvec-py/python/inkvec/__init__.pyi index f9070113..328e6be0 100644 --- a/crates/inkvec-py/python/inkvec/__init__.pyi +++ b/crates/inkvec-py/python/inkvec/__init__.pyi @@ -73,7 +73,7 @@ def trace( harmonize_threshold: float = 0.92, mode: str = "quality", hypotheses: bool = False, - detect_strokes: bool = False, + detect_strokes: bool = True, merge_colors: str = "", ) -> Traced: """Trace an image to SVG. @@ -188,7 +188,8 @@ def trace( -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back - at about the artist's own parameter count. Quality mode only; off by + at about the artist's own parameter count, and a ring on a plain page as one + stroke over the page rather than two discs. Quality mode only; on by default. merge_colors: Colour groups: fills to draw as one, so the shapes between them join rather @@ -230,7 +231,7 @@ def trace_rgba( harmonize_threshold: float = 0.92, mode: str = "quality", hypotheses: bool = False, - detect_strokes: bool = False, + detect_strokes: bool = True, merge_colors: str = "", ) -> Traced: """Trace raw straight-RGBA8 pixels (row-major, tightly packed) to SVG. @@ -346,7 +347,8 @@ def trace_rgba( -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back - at about the artist's own parameter count. Quality mode only; off by + at about the artist's own parameter count, and a ring on a plain page as one + stroke over the page rather than two discs. Quality mode only; on by default. merge_colors: Colour groups: fills to draw as one, so the shapes between them join rather diff --git a/crates/inkvec-server/README.md b/crates/inkvec-server/README.md index 110c31d6..beeb3ee1 100644 --- a/crates/inkvec-server/README.md +++ b/crates/inkvec-server/README.md @@ -103,7 +103,7 @@ Responses: | `harmonize_threshold` | number | `0.92` | >= 0 and <= 1 | Shape-equivalence threshold for harmonization: the outline similarity (IoU after affine normalisation) above which two marks count as the same shape. | | `mode` | string | `"quality"` | - | Which engine traces the image. "quality" (the default) is the full engine: the best fidelity and the fewest parameters, at about half a second for a 512 px logo. "fast" is a Potrace-class fit on the same palette, planar map and emitter, with a one-pass gradient check in place of gradient recovery: several times faster (tens of milliseconds at 512 px), a little less faithful, with somewhat more parameters. Options that only steer quality stages (precision, content_units, harmonize, harmonize_threshold, time_budget) are ignored in fast mode. "balanced" (opt-in) is fast plus eight iterations of quality's boundary solve and a fit with tolerances a quarter finer: in between the two in fidelity and time, on rasters up to 1024 px on the longer side; a larger raster is traced exactly as in fast mode. It ignores the same options as fast. | | `hypotheses` | bool | `false` | - | Also trace three structural alternatives -- blend absorption off, a matte instead of native alpha, and a merge distance of 0.020 -- and keep the trace whose render explains the input in the fewest nats (its squared error at the input's resolution against the best one's, plus a price per parameter). Quality colour mode only; up to four traces, about 3.6 times the trace time at 512 px. Measured on the 246-icon screen set: 6 % closer to the artist's file at 128 px, 1 % at 512 px (9 % on the hardest tenth). Off by default. | -| `detect_strokes` | bool | `false` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count. Quality mode only; off by default. | +| `detect_strokes` | bool | `true` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count, and a ring on a plain page as one stroke over the page rather than two discs. Quality mode only; on by default. | | `merge_colors` | string | `""` | - | Colour groups: fills to draw as one, so the shapes between them join rather than being recoloured. Empty (the default) changes nothing. Groups are separated by ';' and members by ','; a member is a colour '#rrggbb' as it appears in a trace of the same image, or a gradient written as its stop colours joined by '>'. An optional '=' says what the group becomes: '=#rrggbb' a flat colour, '=@n' its n-th member (1-based; a gradient there is refitted over the whole group); without it, the member covering the most of the image. Example: '#c0392b,#e74c3c;#f00>#00f,#0a0=@1'. A group costs one extra trace. | diff --git a/crates/inkvec-trace/Cargo.toml b/crates/inkvec-trace/Cargo.toml index 213248bf..990f6b95 100644 --- a/crates/inkvec-trace/Cargo.toml +++ b/crates/inkvec-trace/Cargo.toml @@ -13,6 +13,7 @@ categories.workspace = true [dependencies] inkvec-core = { workspace = true } +inkvec-verified = { workspace = true } inkvec-fit = { workspace = true } rayon = { workspace = true } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "bmp", "tiff"] } diff --git a/crates/inkvec-trace/examples/evidence_calibrate.rs b/crates/inkvec-trace/examples/evidence_calibrate.rs new file mode 100644 index 00000000..a3877dd5 --- /dev/null +++ b/crates/inkvec-trace/examples/evidence_calibrate.rs @@ -0,0 +1,210 @@ +//! Every run window of an image against a known truth: the measurement harness behind the +//! renderer floor's per-image calibration (`bench/theory/floor_selfcal.py`, +//! `docs/theory/chain-boundary.md`, Phase 2). +//! +//! Reads a manifest of `namepngtruth` lines, where `truth` is the image the PNG +//! should have been with no renderer floor and no rounding: `height × width × 3` little-endian +//! `f32`, sRGB composited onto white. Each PNG is traced by the Quality front end (composited +//! onto white, as the CLI does) and its evidence built with the PNG's own alpha. One row per +//! run window goes to stdout: +//! +//! `name edge index axis line lo hi s sum quant_var truth left_low pos closed lattice z var` +//! +//! `pos` is the window's measured mean position, `truth` the sum the truth image reads on the +//! same pixels with the same two inks, `z` the fourth difference centred there in standard +//! deviations of quantisation alone (NaN where five consecutive windows are not available). +//! `var` is the window's variance with the image's self-calibrated noise. An `#edge` line per +//! edge scores the truth with the evidence's own `score`: windows, independent measurements, +//! `χ²`, `χ²` with the edge's offset, the Huber cost and the offset's variance. A `#floor` line per +//! image gives the floor, the trace's noise, edge width, soft share and ringing, the +//! calibrated extra variance (straight, curved) with its counts, the tail's `ν`, the window +//! scale and the edge noise of the first band. +//! +//! Run: `cargo run --release -p inkvec-trace --example evidence_calibrate -- manifest.tsv` + +use std::io::{BufRead, Write}; +use std::path::Path; + +use inkvec_core::likelihood::{score, Axis, BoundaryLikelihood, Floor, RunObs}; +use inkvec_core::noise::huber_kappa; +use inkvec_trace::evidence::{self, EvidenceOptions}; +use inkvec_trace::{load_image, trace_color_full, ColorOptions}; + +fn read_truth(path: &Path, n: usize) -> Option> { + let bytes = std::fs::read(path).ok()?; + if bytes.len() != n * 12 { + return None; + } + Some( + bytes + .as_chunks::<12>() + .0 + .iter() + .map(|c| { + let f = |k: usize| f32::from_le_bytes([c[k], c[k + 1], c[k + 2], c[k + 3]]); + [f(0), f(4), f(8)] + }) + .collect(), + ) +} + +fn main() { + let manifest = std::env::args() + .nth(1) + .expect("usage: evidence_calibrate manifest.tsv"); + let file = std::fs::File::open(&manifest).expect("manifest"); + let out = std::io::stdout(); + let mut out = out.lock(); + for line in std::io::BufReader::new(file).lines() { + let line = line.expect("line"); + let f: Vec<&str> = line.split('\t').collect(); + if f.len() != 3 { + continue; + } + let (name, png, truth) = (f[0], Path::new(f[1]), Path::new(f[2])); + let Ok(img) = load_image(png) else { + eprintln!("skip {name}: cannot read {}", png.display()); + continue; + }; + let n = img.width * img.height; + let Some(truth) = read_truth(truth, n) else { + eprintln!("skip {name}: truth has the wrong size"); + continue; + }; + let rgb = img.composited([1.0, 1.0, 1.0]); + let alpha: Vec = img.data.as_chunks::<4>().0.iter().map(|p| p[3]).collect(); + let ct = trace_color_full(&img, &ColorOptions::default()); + let faces: Vec<_> = ct.face_fill.iter().map(|f| f.model.clone()).collect(); + let lossy = matches!( + png.extension().and_then(|e| e.to_str()), + Some("jpg" | "jpeg" | "JPG" | "JPEG") + ); + let ramps = inkvec_trace::softness::ramp_evidence(&rgb, img.width, img.height); + let opts = EvidenceOptions { + floor: Some(Floor { + lattice: 1_000_000, + window_var: 0.0, + edge_var: 0.0, + }), + lossy, + ramp_width: ramps.width.max(1.0), + ..EvidenceOptions::default() + }; + let t0 = std::time::Instant::now(); + let ev = + evidence::build_with_alpha(&ct.map, &rgb, Some(&alpha), &faces, ct.sigma_noise, &opts); + let t_ev = t0.elapsed().as_secs_f64() * 1e3; + let t1 = std::time::Instant::now(); + let _ = inkvec_trace::softness::ramp_evidence(&rgb, img.width, img.height); + let t_ramp = t1.elapsed().as_secs_f64() * 1e3; + eprintln!( + "{name}\tevidence {t_ev:.2} ms\tramp {t_ramp:.2} ms\tedges {}", + ct.map.edges.len() + ); + let fl = ev.floor(); + let ringing = inkvec_trace::coverage::ringing_score(&rgb, img.width, img.height); + let cal = ev.calibration(); + let nm = ev.noise(); + writeln!( + out, + "#floor\t{name}\t{}\t{:.6e}\t{:.6e}\t{:.6e}\t{:.4}\t{:.4}\t{:.4}\t{:.6e}\t{:.6e}\t{}\t{}\t{:.3}\t{:.3}\t{:.5}", + fl.lattice, + fl.window_var, + fl.edge_var, + ct.sigma_noise, + ramps.width, + ramps.soft_fraction, + ringing, + cal.extra[0], + cal.extra[1], + cal.count[0], + cal.count[1], + cal.nu, + nm.window_scale, + nm.sigma_edge[0] + ) + .ok(); + for e in 0..ev.edge_count() { + write_edge(&mut out, name, &ev, e, &truth, ct.map.edges[e].closed); + } + } +} + +/// The fourth difference of five consecutive windows of one axis centred at `i`, in standard +/// deviations of rounding alone; NaN where they are not available. +fn fourth_z(obs: &[RunObs], qv: &[f64], i: usize) -> f64 { + if i < 2 || i + 2 >= obs.len() { + return f64::NAN; + } + let five = &obs[i - 2..=i + 2]; + let ok = five.windows(2).all(|p| { + p[0].window.axis == p[1].window.axis && (p[1].window.line - p[0].window.line).abs() == 1 + }); + if !ok { + return f64::NAN; + } + let w = [1.0, -4.0, 6.0, -4.0, 1.0]; + let d: f64 = five.iter().zip(w).map(|(o, w)| w * o.mean_position()).sum(); + let v: f64 = (0..5).map(|j| w[j] * w[j] * qv[i - 2 + j]).sum(); + d / v.sqrt() +} + +/// One edge's `#edge` line (the truth scored as a candidate would be, by the trait's own +/// `score`) and its window rows. +fn write_edge( + out: &mut impl Write, + name: &str, + ev: &evidence::Evidence, + e: usize, + truth: &[[f32; 3]], + closed: bool, +) { + let obs = ev.runs(e); + if obs.is_empty() { + return; + } + let tsum = ev.window_sums_of(e, truth); + let qv = ev.quantisation_var(e); + let r: Vec = obs.iter().zip(&tsum).map(|(o, t)| o.sum - t).collect(); + let v: Vec = obs.iter().map(|o| o.var).collect(); + let sh: Vec = obs.iter().map(|o| o.share).collect(); + let sc = score( + &r, + &v, + &sh, + ev.edge_offset_var(e), + huber_kappa(ev.tail_nu()), + ); + writeln!( + out, + "#edge\t{name}\t{e}\t{}\t{:.4}\t{:.6}\t{:.6}\t{:.6}\t{:.4e}", + sc.m, + sc.dof, + sc.chi2, + sc.chi2_floor, + sc.cost, + ev.edge_offset_var(e) + ) + .ok(); + for (i, o) in obs.iter().enumerate() { + writeln!( + out, + "{name}\t{e}\t{i}\t{}\t{}\t{}\t{}\t{:.4}\t{:.7}\t{:.4e}\t{:.7}\t{}\t{:.6}\t{}\t{}\t{:.4}\t{:.4e}", + if o.window.axis == Axis::Column { "c" } else { "r" }, + o.window.line, + o.window.lo, + o.window.hi, + o.s, + o.sum, + qv[i], + tsum[i], + o.left_low as u8, + o.mean_position(), + closed as u8, + ev.edge_on_lattice(e) as u8, + fourth_z(obs, qv, i), + o.var + ) + .ok(); + } +} diff --git a/crates/inkvec-trace/src/evidence.rs b/crates/inkvec-trace/src/evidence.rs new file mode 100644 index 00000000..f877246a --- /dev/null +++ b/crates/inkvec-trace/src/evidence.rs @@ -0,0 +1,1195 @@ +//! The evidence a raster gives about the boundaries of a planar map, as window areas, and +//! the evaluator the representation chain scores candidate descriptions with +//! (`docs/theory/chain-boundary.md`, "Interface proposal"; the shared vocabulary is +//! [`inkvec_core::likelihood`]). +//! +//! # What it holds +//! +//! For every edge between two flat fills, its **run windows**: maximal runs of the edge's +//! partial pixels along a column (where the edge runs within 45° of horizontal) or a row, +//! each with the sum of the edge's left face's unmixed weights (which is that face's exact +//! area in the window, whatever the curve: the window identity, B2.1) and the variance of +//! that sum (8-bit quantisation of the partial pixels, B1.2, plus the renderer floor's +//! per-window part, B2.3). Every partial pixel of an edge is in exactly one window. Around +//! every **junction** (a node where three or more edges end) the pixels within a small +//! radius are kept per pixel, in colour, for the local term (B3.2), with the junction's arms +//! in cyclic order and the pairs that may continue one another (A4). Along runs, **corner +//! proposals** where the fourth difference of consecutive windows fires (B3.3). And the +//! **renderer floor** (A3): per window, and the offset shared by the windows of an edge that +//! runs along an axis or a diagonal. +//! +//! # Where it sits +//! +//! [`build`] reads the planar map after stage 07 (its topology, and its geometry only to say +//! which edge owns a pixel and which way it runs), the composited image and each face's fill. +//! It changes nothing in the trace; the fitter consumes it through +//! [`BoundaryLikelihood`]. Edges with a gradient on either side, or the image's frame on one +//! side, have no run windows yet (their windows would need the moment term of B1.4). +//! +//! Method from: the column-sum (partial-area) identity of volume-of-fluid reconstruction and +//! sub-pixel edge detection (E. G. Puckett (2010), CAMCoS 5(1); A. Trujillo-Pino et al. +//! (2013), Image and Vision Computing 31(1), ). +//! Not from the literature: the window partition, its use as the likelihood of arbitrary +//! descriptions, and the renderer-floor model (measured in `bench/theory/renderer_floor.py`). + +use inkvec_core::likelihood::{ + BoundaryLikelihood, Chi2, CornerProposal, Floor, JunctionReport, Owner, Piece, RenderModel, + RunObs, StrokeBand, +}; +use inkvec_core::noise::NoiseModel; + +use crate::gradient::FillModel; +use crate::planar::{Edge, PlanarMap}; + +pub mod checks; +mod local; +pub mod noise; +mod reports; +mod windows; + +use inkvec_core::Point; +use local::{CornerPixel, Local, LocalPixel, StripPixel}; +use windows::{Axis2, RunPixel}; + +/// Record a corner term (the pixels of windows the starting geometry does not cross) and its +/// proposal, placed before run window `index` of edge `edge`. +fn push_corner( + corners: &mut Vec, + terms: &mut Vec>, + edge: usize, + index: usize, + pixels: Vec, +) { + let n = pixels.len().max(1) as f64; + let at = pixels.iter().fold(Point::new(0.0, 0.0), |a, p| { + Point::new(a.x + p.x as f64 / n, a.y + p.y as f64 / n) + }); + corners.push(CornerProposal { + edge: edge as u32, + index, + z: f64::INFINITY, + at, + }); + terms.push(pixels); +} + +/// How the evidence is built. +#[derive(Debug, Clone, Copy)] +pub struct EvidenceOptions { + /// The renderer floor; `None` for the corpus intake's (resvg at 8× with 4 × 4 samples per + /// device pixel: a 32-sample lattice, [`Floor::lattice`]). + pub floor: Option, + /// How candidates are drawn (usvg's arc tolerance in px). + pub render: RenderModel, + /// A pixel within this distance (px) of an edge's starting geometry is that edge's. + pub reach: f64, + /// Pixels within this distance (px) of a junction belong to its local term. + pub local_radius: f64, + /// Corner proposals: smallest `|D|` in standard deviations. + pub corner_z: f64, + /// Junction continuations: largest angle difference in standard deviations. + pub continuation_z: f64, + /// The intake was lossy with subsampled chroma (a JPEG): weights are read from luma, the + /// channel kept at full resolution, wherever the two inks' lumas differ enough. + pub lossy: bool, + /// The intake's box-equivalent edge width (`softness::ramp_evidence`), px: 1 on a native + /// render. A blurred edge's ramp spans about this many pixels, and the reach widens to + /// cover it, so that each window holds the observed ramp whole. + pub ramp_width: f64, + /// Estimate each window's variance beyond rounding from the image's own fourth + /// differences ([`noise`]); off, the floor's `window_var` alone is added. + pub self_calibrate: bool, +} + +impl Default for EvidenceOptions { + fn default() -> Self { + Self { + floor: None, + render: RenderModel::default(), + reach: 1.6, + local_radius: 2.5, + corner_z: 3.0, + continuation_z: 3.0, + lossy: false, + ramp_width: 1.0, + self_calibrate: true, + } + } +} + +/// Pixels two edges both reach away from a junction (thin features), marked taken: their +/// positions, and the same in colour with their pair of edges (variance `var` per channel). +fn strip_terms( + claims: &[windows::Claim], + rgb: &[[f32; 3]], + w: usize, + reach: f64, + var: f64, + taken: &mut [bool], +) -> (Vec<(i32, i32)>, Vec) { + let (mut at, mut strips) = (Vec::new(), Vec::new()); + for (i, c) in claims.iter().enumerate() { + if c.edge != u32::MAX && c.dist <= reach && c.dist2 <= reach && !taken[i] { + taken[i] = true; + let (x, y) = ((i % w) as i32, (i / w) as i32); + at.push((x, y)); + let p = rgb[i]; + strips.push(StripPixel { + x, + y, + rgb: [p[0] as f64, p[1] as f64, p[2] as f64], + var, + pair: (c.edge.min(c.edge2), c.edge.max(c.edge2)), + }); + } + } + (at, strips) +} + +/// The two-ink axis an edge between inks `left` and `right` is read on, or `None` when they +/// are too close to unmix. Self-calibrating, a window's variance starts from rounding alone +/// and the image's own windows supply the rest ([`noise`]); the pixel noise still sets the +/// third-ink test. On a lossy intake, luma where the inks' lumas differ enough. +fn edge_axis( + left: [f32; 3], + right: [f32; 3], + sigma_noise: f64, + opts: &EvidenceOptions, +) -> Option { + let sigma_var = if opts.self_calibrate { + 0.0 + } else { + sigma_noise + }; + let axis = Axis2 { + third_tol2: (4.0 * sigma_noise.max(1.0 / 255.0)).powi(2), + ..Axis2::new(left, right, sigma_var) + }; + if axis.dd.sqrt() < (3.0 * sigma_noise).max(0.02) { + return None; + } + Some(if opts.lossy { + axis.luma_of(LUMA_MIN_CONTRAST, LOSSY_CHROMA_TOL) + .unwrap_or(Axis2 { + third_tol2: LOSSY_CHROMA_TOL * LOSSY_CHROMA_TOL, + ..axis + }) + } else { + axis + }) +} + +/// `|d|²` of an axis in the units its weights are read in (luma's contrast, squared, on a +/// luma axis). +fn axis_dd(a: Axis2) -> f64 { + match a.luma { + Some((_, dy)) => dy * dy, + None => a.dd, + } +} + +/// Box-equivalent edge width above which an intake is soft (resampled or blurred): its +/// windows then take every pixel of the edge's band on their line, not only those that read +/// as mixtures, since noise splits a blurred ramp's run of partial pixels. +const SOFT_RAMP_WIDTH: f64 = 1.2; +/// The shape of the per-pixel noise by distance from the nearest edge on a resized JPEG, +/// relative to the first band (luma, web tier: 9.4, 3.1, 2.3 and 1.7 levels within 1, 2, 3 +/// and 5 px; `bench/theory/noise_profile.py`). Scaled per image by the windows' own noise. +const EDGE_NOISE_SHAPE: [f64; 4] = [1.0, 0.33, 0.25, 0.18]; + +/// Least luma difference (sRGB units) between two inks for their windows to be read from +/// luma on a lossy intake: three times the noise measured within a pixel of a web-tier edge +/// (about nine levels). +const LUMA_MIN_CONTRAST: f64 = 0.1; +/// How far off the colour line a lossy intake's pixel may sit before it holds a third ink: +/// 4:2:0 chroma bleeds across every edge, at about 6.5 levels rms within a pixel of one on the +/// web tier, so four of those (in sRGB units). +const LOSSY_CHROMA_TOL: f64 = 26.0 / 255.0; +/// Plateau pixels for an edge's inks are taken this far beyond its reach, px. +const PLATEAU_BAND: f64 = 2.5; +/// Fewest plateau pixels on a side for their median to stand for that side's ink. +const PLATEAU_MIN: usize = 5; + +/// Per edge, the per-channel median colour of the pixels just beyond its reach on each side +/// (left, right): the inks a window's weights are read against, robust to noise, ringing and +/// a JPEG's block errors (a mean is not). Pixels that another edge also nearly reaches are +/// left out. `None` where a side has fewer than [`PLATEAU_MIN`] such pixels (a thin face). +fn plateau_inks( + claims: &[windows::Claim], + rgb: &[[f32; 3]], + reach: f64, + n_edges: usize, +) -> Vec<[Option<[f32; 3]>; 2]> { + let mut side: Vec<[Vec<[f32; 3]>; 2]> = + (0..n_edges).map(|_| [Vec::new(), Vec::new()]).collect(); + for (i, c) in claims.iter().enumerate() { + if c.edge == u32::MAX || c.dist <= reach || c.dist2 < c.dist + 1.0 { + continue; + } + side[c.edge as usize][usize::from(!c.left)].push(rgb[i]); + } + side.into_iter() + .map(|mut lr| { + let med = |v: &mut Vec<[f32; 3]>| -> Option<[f32; 3]> { + if v.len() < PLATEAU_MIN { + return None; + } + let mut out = [0f32; 3]; + for (ch, o) in out.iter_mut().enumerate() { + let mut c: Vec = v.iter().map(|p| p[ch]).collect(); + let k = c.len() / 2; + *o = *c.select_nth_unstable_by(k, f32::total_cmp).1; + } + Some(out) + }; + [med(&mut lr[0]), med(&mut lr[1])] + }) + .collect() +} + +/// The evidence of one image: see the module docs. +#[derive(Debug, Clone)] +pub struct Evidence { + width: usize, + height: usize, + runs: Vec>, + run_pixels: Vec>>, + lattice_edge: Vec, + lengths: Vec>, + locals: Vec, + junctions: Vec, + corners: Vec, + /// Per corner proposal, its per-pixel term (empty for a proposal inside a run). + corner_terms: Vec>, + /// Pixels shared by two edges away from a junction (thin features): scored only against a + /// stroke band ([`BoundaryLikelihood::chi2_band`]). + strip_pixels: Vec<(i32, i32)>, + /// The same pixels, in colour, with the pair of edges that reach them. + strips: Vec, + /// Pixels of an edge's own that hold a third ink: not scored. + third_pixels: Vec<(i32, i32)>, + floor: Floor, + render: RenderModel, + faces: Vec, + edge_faces: Vec<(u16, u16)>, + /// Per edge, the two-ink axis its pixels were unmixed on (`None`: no runs). + axes: Vec>, + /// Per edge and run window, the variance of its sum from quantisation (and measured + /// noise) alone, before the renderer floor. + quant_var: Vec>, + /// What the windows' fourth differences said about their error beyond rounding. + calibration: noise::Calibration, + /// The intake's noise, summarised for the representation chain. + noise: NoiseModel, + /// Per edge, the variance of the offset its windows share (A3). + offset_var: Vec, + /// Per edge and run window, the fractional index of its centre along the edge's points. + point_at: Vec>, +} + +/// The variance of one 8-bit level's rounding, per channel. +const Q2_12: f64 = 1.0 / (255.0 * 255.0 * 12.0); + +/// The local term of every junction: the pixels within `r` px of it that no earlier term +/// holds, each with its colour and variance `var` (marked taken). +fn junction_locals( + junctions: &[JunctionReport], + rgb: &[[f32; 3]], + (w, h): (usize, usize), + r: f64, + var: f64, + taken: &mut [bool], +) -> Vec { + let mut locals = Vec::with_capacity(junctions.len()); + for j in junctions { + let mut pixels = Vec::new(); + let (x0, x1) = ( + (j.at.x - r).floor().max(0.0) as usize, + ((j.at.x + r).ceil() as usize).min(w - 1), + ); + let (y0, y1) = ( + (j.at.y - r).floor().max(0.0) as usize, + ((j.at.y + r).ceil() as usize).min(h - 1), + ); + for y in y0..=y1 { + for x in x0..=x1 { + if (x as f64 - j.at.x).hypot(y as f64 - j.at.y) > r || taken[y * w + x] { + continue; + } + taken[y * w + x] = true; + let c = rgb[y * w + x]; + pixels.push(LocalPixel { + x: x as i32, + y: y as i32, + rgb: [c[0] as f64, c[1] as f64, c[2] as f64], + var, + }); + } + } + locals.push(Local { + node: j.node, + at: j.at, + arms: j + .arms + .iter() + .map(|a| (a.edge as usize, a.at_start)) + .collect(), + pixels, + }); + } + locals +} + +/// One edge's share of the evidence: its run windows (with their pixels), the corner terms +/// between them (each with the index of the run window it precedes), and its third-ink pixels. +#[derive(Default)] +struct EdgeEvidence { + runs: Vec, + run_pixels: Vec>, + corner_terms: Vec<(usize, Vec)>, + third: Vec<(i32, i32)>, +} + +/// What [`edge_evidence`] reads besides the edge. +struct Intake<'a> { + rgb: &'a [[f32; 3]], + alpha: Option<&'a [f32]>, + width: usize, + claims: &'a [windows::Claim], + /// Take every non-third pixel of the edge's band, not only those reading as mixtures. + band: bool, +} + +/// An edge's polyline indexed by arclength, so that a window's crossing test reads only the +/// stretch near it (`O(log n)` to find, instead of the whole edge per window). +struct NearPolyline<'a> { + points: &'a [Point], + closed: bool, + /// Cumulative arclength at each point (and, closed, back at the first). + s: Vec, +} + +impl<'a> NearPolyline<'a> { + fn new(points: &'a [Point], closed: bool) -> Self { + let n = points.len(); + let m = if closed && n > 0 { n + 1 } else { n }; + let mut s = Vec::with_capacity(m); + let mut acc = 0.0; + for k in 0..m { + if k > 0 { + acc += points[k % n].dist(points[(k - 1) % n]); + } + s.push(acc); + } + NearPolyline { points, closed, s } + } + + /// The points within `half` px of arclength of `at` (wrapping round a closed edge), with + /// one more point either side so the stretch reaches past them. + fn around(&self, at: f64, half: f64) -> Vec { + let n = self.points.len(); + if n == 0 { + return Vec::new(); + } + let total = *self.s.last().unwrap_or(&0.0); + if !self.closed { + let lo = self.s.partition_point(|&v| v < at - half).saturating_sub(1); + let hi = (self.s.partition_point(|&v| v <= at + half) + 1).min(n); + return self.points[lo..hi].to_vec(); + } + if total <= 2.0 * half + 2.0 { + let mut all = self.points.to_vec(); + all.push(self.points[0]); + return all; + } + // Closed: from the point before `at − half` round to the one after `at + half`. + let s0 = (at - half).rem_euclid(total); + let k0 = self.s.partition_point(|&v| v <= s0).saturating_sub(1) % n; + let mut out = vec![self.points[k0]]; + let mut walked = self.s[k0] - s0; + let mut k = k0; + while walked <= 2.0 * half && out.len() <= n { + let next = (k + 1) % n; + walked += self.points[next].dist(self.points[k]); + out.push(self.points[next]); + k = next; + } + // One more point past the end. + let next = (k + 1) % n; + out.push(self.points[next]); + out + } +} + +/// The run windows and corner terms of edge `e` between flat inks (`axis`), from its pixels +/// `mine` (indices into the image), marking the pixels it uses taken. +fn edge_evidence( + e: &Edge, + axis: &Axis2, + mine: &[usize], + at: &Intake, + taken: &mut [bool], +) -> EdgeEvidence { + let w = at.width; + let mut out = EdgeEvidence::default(); + let mut px = Vec::with_capacity(mine.len()); + let profile = at.band.then(|| windows::class_profile(&e.points, e.closed)); + for &i in mine { + let mut m = axis.unmix(at.rgb[i], at.alpha.map(|a| a[i])); + if m.third { + out.third.push(((i % w) as i32, (i / w) as i32)); + taken[i] = true; + continue; + } + if at.band && !m.partial { + m.partial = true; + m.var = axis.var_partial; + } + let c = at.claims[i]; + let column = match &profile { + Some(p) => windows::class_at(p, c.s), + None => c.t.0.abs() >= c.t.1.abs(), + }; + px.push(RunPixel { + x: (i % w) as i32, + y: (i / w) as i32, + m, + s: c.s, + t: c.t, + column, + }); + } + for p in &px { + if p.m.partial { + taken[(p.y as usize) * w + p.x as usize] = true; + } + } + // No pure flanks: a pixel that reads as one face's pure colour may hold up to half a + // level of the other's area and reads none of it, an error of one sign the rounding model + // does not describe (measured: chi2/M 1.85 with flanks, on 8-bit squares). The windows' + // areas need no flank to be exact (the clamp), so a window is its partial pixels only. + let mut flank = |_: i32, _: i32| None; + let grouped = windows::group(&px, &mut flank); + // A window the starting geometry does not cross once (a corner turns inside it, or the + // edge ends there) cannot be read as a run: its pixels go to a corner term, scored per + // pixel, and the place is proposed as a corner. + let near = NearPolyline::new(&e.points, e.closed); + let mut pending: Option> = None; + for (o, p) in grouped { + let piece = near.around(o.s, o.window.len() as f64 + 4.0); + if checks::polyline_left_area(&piece, &o.window).is_some() { + if let Some(pix) = pending.take() { + out.corner_terms.push((out.runs.len(), pix)); + } + out.runs.push(o); + out.run_pixels.push(p); + } else { + let term = pending.get_or_insert_with(Vec::new); + for (x, y) in p { + let i = y as usize * w + x as usize; + let m = axis.unmix(at.rgb[i], at.alpha.map(|a| a[i])); + term.push(CornerPixel { + x, + y, + a: m.a, + var: m.var, + }); + } + } + } + if let Some(pix) = pending.take() { + out.corner_terms.push((out.runs.len(), pix)); + } + out +} + +/// Build the evidence of `rgb` (row-major sRGB, the map's size) for `map`, whose faces have +/// fills `faces`; `sigma_noise` is [`crate::coverage::estimate_noise`]'s. `O(boundary pixels)`. +pub fn build( + map: &PlanarMap, + rgb: &[[f32; 3]], + faces: &[FillModel], + sigma_noise: f64, + opts: &EvidenceOptions, +) -> Evidence { + build_with_alpha(map, rgb, None, faces, sigma_noise, opts) +} + +/// [`build`], told the source's alpha (`rgb` is then the image composited onto white). Where +/// the source drew an ink partly over the clear ground the intake rounded the alpha, not the +/// colour, and the weight's variance is one level's whatever the ink's contrast with white. +pub fn build_with_alpha( + map: &PlanarMap, + rgb: &[[f32; 3]], + alpha: Option<&[f32]>, + faces: &[FillModel], + sigma_noise: f64, + opts: &EvidenceOptions, +) -> Evidence { + let alpha = alpha.filter(|a| a.len() == rgb.len()); + let (w, h) = (map.width, map.height); + let floor = opts.floor.unwrap_or_else(|| Floor::lattice(32)); + let reach = opts.reach.max(0.5 * opts.ramp_width + 1.1); + let claims = windows::claims(map, reach + PLATEAU_BAND); + let mut taken = vec![false; w * h]; + + // Junctions and their local pixels. + let junctions = reports::junctions(map, 6.0, 0.02, opts.continuation_z); + let extra = (sigma_noise * sigma_noise - 0.25 / (255.0 * 255.0)).max(0.0); + let locals = junction_locals( + &junctions, + rgb, + (w, h), + opts.local_radius, + Q2_12 + extra, + &mut taken, + ); + + // Pixels two edges reach away from a junction: thin features, kept out of runs. + let (strip_pixels, mut strips) = strip_terms(&claims, rgb, w, reach, Q2_12 + extra, &mut taken); + + let intake = Intake { + rgb, + alpha, + width: w, + claims: &claims, + band: opts.lossy || opts.ramp_width > SOFT_RAMP_WIDTH, + }; + let AllEdges { + mut runs, + run_pixels, + third_pixels, + mut corners, + mut corner_terms, + axes, + } = all_edges(map, faces, reach, &intake, sigma_noise, opts, &mut taken); + let edge_faces: Vec<(u16, u16)> = map.edges.iter().map(|e| (e.left, e.right)).collect(); + + let quant_var: Vec> = runs + .iter() + .map(|r| r.iter().map(|o| o.var).collect()) + .collect(); + let (calibration, noise, offset_var) = calibrate_runs( + &mut runs, + &quant_var, + &run_pixels, + &axes, + floor, + sigma_noise, + opts, + ); + let mut locals = locals; + if !noise.is_clean() { + let s2 = noise.sigma_edge_at(0.0).powi(2); + raise_local_noise( + s2, + &mut locals, + &mut strips, + &corners, + &mut corner_terms, + &axes, + ); + } + let RunReports { + point_at, + lattice_edge, + lengths, + corners: run_corners, + } = run_reports(map, &runs, floor, opts); + for c in run_corners { + corners.push(c); + corner_terms.push(Vec::new()); + } + Evidence { + width: w, + height: h, + runs, + run_pixels, + lattice_edge, + lengths, + locals, + junctions, + corners, + corner_terms, + strip_pixels, + strips, + third_pixels, + floor, + render: RenderModel { + psf_mu2: noise.psf_mu2, + ..opts.render + }, + faces: faces.to_vec(), + edge_faces, + axes, + quant_var, + calibration, + noise, + offset_var, + point_at, + } +} + +/// What each edge's runs report once their variances are known: where each window sits along +/// the edge's points, whether the edge runs along the floor's lattice, each window's +/// boundary length, and the corner proposals of the fourth difference. +struct RunReports { + point_at: Vec>, + lattice_edge: Vec, + lengths: Vec>, + corners: Vec, +} + +fn run_reports( + map: &PlanarMap, + runs: &[Vec], + floor: Floor, + opts: &EvidenceOptions, +) -> RunReports { + let n_edges = runs.len(); + let point_at: Vec> = runs + .iter() + .zip(&map.edges) + .map(|(r, e)| { + r.iter() + .map(|o| point_index(&e.points, e.closed, o.s)) + .collect() + }) + .collect(); + let mut out = RunReports { + point_at, + lattice_edge: vec![false; n_edges], + lengths: vec![Vec::new(); n_edges], + corners: Vec::new(), + }; + for k in 0..n_edges { + out.corners.extend(reports::corners( + k as u32, + &runs[k], + map.edges[k].closed, + opts.corner_z, + opts.lossy, + )); + out.lattice_edge[k] = reports::on_lattice(&runs[k], floor.lattice); + out.lengths[k] = reports::window_lengths(&runs[k]); + } + out +} + +/// Per-pixel terms take the noise within a pixel of an edge (`s2`, per channel): junctions, +/// thin strips, and corner terms (in their axis's weight units). +fn raise_local_noise( + s2: f64, + locals: &mut [Local], + strips: &mut [StripPixel], + corners: &[CornerProposal], + corner_terms: &mut [Vec], + axes: &[Option], +) { + for l in locals.iter_mut() { + for p in &mut l.pixels { + p.var = p.var.max(s2); + } + } + for p in strips.iter_mut() { + p.var = p.var.max(s2); + } + for (c, term) in corners.iter().zip(corner_terms.iter_mut()) { + let dd = axes[c.edge as usize].map_or(1.0, axis_dd); + for p in term.iter_mut() { + p.var = p.var.max(s2 / dd); + } + } +} + +/// Every edge's runs, corner terms and third-ink pixels, with the axis each was read on. +struct AllEdges { + runs: Vec>, + run_pixels: Vec>>, + third_pixels: Vec<(i32, i32)>, + corners: Vec, + corner_terms: Vec>, + axes: Vec>, +} + +/// Read every edge between two flat fills: its pixels within `reach` that nothing has taken, +/// unmixed against its plateau inks ([`plateau_inks`], else the faces' fills). +fn all_edges( + map: &PlanarMap, + faces: &[FillModel], + reach: f64, + intake: &Intake, + sigma_noise: f64, + opts: &EvidenceOptions, + taken: &mut [bool], +) -> AllEdges { + let n_edges = map.edges.len(); + let mut out = AllEdges { + runs: vec![Vec::new(); n_edges], + run_pixels: vec![Vec::new(); n_edges], + third_pixels: Vec::new(), + corners: Vec::new(), + corner_terms: Vec::new(), + axes: vec![None; n_edges], + }; + let mut by_edge: Vec> = vec![Vec::new(); n_edges]; + for (i, c) in intake.claims.iter().enumerate() { + if c.edge != u32::MAX && c.dist <= reach && !taken[i] { + by_edge[c.edge as usize].push(i); + } + } + let inks = plateau_inks(intake.claims, intake.rgb, reach, n_edges); + for (k, e) in map.edges.iter().enumerate() { + let (Some(FillModel::Flat(cl)), Some(FillModel::Flat(cr))) = + (faces.get(e.left as usize), faces.get(e.right as usize)) + else { + continue; + }; + let [il, ir] = inks[k]; + let Some(axis) = edge_axis(il.unwrap_or(*cl), ir.unwrap_or(*cr), sigma_noise, opts) else { + continue; + }; + let ev = edge_evidence(e, &axis, &by_edge[k], intake, taken); + out.axes[k] = Some(axis); + out.third_pixels.extend(ev.third); + for (index, pix) in ev.corner_terms { + push_corner(&mut out.corners, &mut out.corner_terms, k, index, pix); + } + out.runs[k] = ev.runs; + out.run_pixels[k] = ev.run_pixels; + } + out +} + +/// The fractional point index along `points` (closed: wrapping) at arclength `s`. +fn point_index(points: &[Point], closed: bool, s: f64) -> f64 { + let n = points.len(); + if n < 2 { + return 0.0; + } + let segs = if closed { n } else { n - 1 }; + let mut acc = 0.0; + for j in 0..segs { + let l = points[(j + 1) % n].dist(points[j]); + if s < acc + l || j + 1 == segs { + let f = if l > 0.0 { + ((s - acc) / l).clamp(0.0, 1.0) + } else { + 0.0 + }; + return j as f64 + f; + } + acc += l; + } + (segs - 1) as f64 +} + +/// Add each window's variance beyond rounding (the image's own estimate for the window's +/// class, at least the floor's `window_var`), deflate replica stretches to one measurement +/// each, and set each edge's offset variance: one window's variance under self-calibration +/// (the phase-locking argument of [`noise`]), else the floor's `edge_var` on edges along +/// the lattice. Returns the calibration, the noise model it summarises and the offsets. +#[allow(clippy::too_many_arguments)] +fn calibrate_runs( + runs: &mut [Vec], + quant_var: &[Vec], + run_pixels: &[Vec>], + axes: &[Option], + floor: Floor, + sigma_noise: f64, + opts: &EvidenceOptions, +) -> (noise::Calibration, NoiseModel, Vec) { + let classes: Vec)>> = + runs.iter().map(|r| noise::classify(r)).collect(); + let cal = if opts.self_calibrate { + let ds: Vec = runs + .iter() + .zip(quant_var) + .zip(&classes) + .flat_map(|((r, q), c)| noise::fourth_differences(r, q, c)) + .collect(); + noise::calibrate(&ds) + } else { + noise::Calibration::NONE + }; + let reps_all: Vec> = runs + .iter() + .map(|r| { + if opts.self_calibrate { + noise::replica_stretches(r) + } else { + vec![1; r.len()] + } + }) + .collect(); + let lattice = if opts.self_calibrate { + lattice_of(runs, &reps_all, run_pixels, quant_var) + } else { + None + }; + let sawtooth = lattice.map_or(0.0, |n| 1.0 / (12.0 * (n as f64).powi(2))); + let (mut v_q, mut v_all) = (0.0, 0.0); + let mut per_pixel: Vec = Vec::new(); + let mut offset_var = vec![0.0; runs.len()]; + for (k, r) in runs.iter_mut().enumerate() { + let dd = axes[k].map_or(1.0, axis_dd); + let reps = &reps_all[k]; + let mut single: Vec = Vec::with_capacity(r.len()); + for (i, o) in r.iter_mut().enumerate() { + let mut extra = cal.extra[classes[k][i].0 as usize].max(floor.window_var); + if reps[i] >= 2 { + extra += sawtooth; + } + let one = quant_var[k][i] + extra; + single.push(one); + o.var = one * reps[i] as f64; + o.share = 1.0 / reps[i] as f64; + // The noise summary reads the part independent between windows only: a + // renderer's lattice offset is systematic, not noise. + let rough = cal.extra[classes[k][i].0 as usize]; + v_q += quant_var[k][i]; + v_all += quant_var[k][i] + rough; + let n = run_pixels[k][i].len().max(1) as f64; + per_pixel.push(rough * dd / n); + } + offset_var[k] = if opts.self_calibrate && !single.is_empty() { + let m = single.len() / 2; + *single.select_nth_unstable_by(m, f64::total_cmp).1 + } else { + 0.0 + }; + } + let ramp = opts.ramp_width.max(1.0); + let noisy = v_all > v_q * 1.0001 || opts.lossy || ramp > SOFT_RAMP_WIDTH; + let noise = if !opts.self_calibrate || !noisy { + NoiseModel::clean() + } else { + let s_pix = if per_pixel.is_empty() { + 0.0 + } else { + let k = per_pixel.len() / 2; + per_pixel + .select_nth_unstable_by(k, f64::total_cmp) + .1 + .max(0.0) + .sqrt() + }; + noise_model(&cal, s_pix, sigma_noise, ramp, opts.lossy, (v_q, v_all)) + }; + (cal, noise, offset_var) +} + +/// A point-sampling renderer's lattice, from the single partial pixels of axis-aligned replica +/// stretches (one value per stretch of at least three): their windows then carry its +/// sawtooth. +fn lattice_of( + runs: &[Vec], + reps: &[Vec], + run_pixels: &[Vec>], + quant_var: &[Vec], +) -> Option { + let mut values: Vec<(f64, f64)> = Vec::new(); + for (k, r) in runs.iter().enumerate() { + let mut i = 0; + while i < r.len() { + let n = reps[k][i]; + if n >= 3 && run_pixels[k][i].len() == 1 { + values.push((r[i].sum, (3.0 * quant_var[k][i]).sqrt())); + } + i += n.max(1); + } + } + noise::detect_lattice(&values) +} + +/// The noise model a calibration summarises: per-pixel edge noise `s_pix` (colour units, the +/// windows' error spread over their pixels) shaped by distance, the blur from the ramp width, +/// and the window scale from the rounding and total variances `(v_q, v_all)`. +fn noise_model( + cal: &noise::Calibration, + s_pix: f64, + sigma_noise: f64, + ramp: f64, + lossy: bool, + (v_q, v_all): (f64, f64), +) -> NoiseModel { + let flat = sigma_noise.max(0.5 / 255.0); + NoiseModel { + sigma_flat: flat, + sigma_edge: EDGE_NOISE_SHAPE + .iter() + .map(|t| (flat * flat + (s_pix * t).powi(2)).sqrt()) + .collect(), + psf_radius: 0.5 * (ramp - 1.0), + psf_mu2: 0.25 * (ramp * ramp - 1.0), + nu: cal.nu, + lossy, + window_scale: if v_q > 0.0 { (v_all / v_q).sqrt() } else { 1.0 }, + } +} + +/// Edge noise (per channel, within a pixel of an edge) above which an intake's measured noise +/// is folded into the planar map's per-point uncertainties: three 8-bit levels. Clean renders +/// read at most about 1.3 (bench: `floor_selfcal.py`, exact, lattice and resvg renders at +/// 128 px), a resized quality-80 JPEG 4 to 27. +pub const FOLD_LEVEL: f64 = 3.0 / 255.0; + +/// Measure an intake's noise from its own edges, for an intake the colour path found soft or +/// lossy (its edges wider than a native render's, ringing, or a lossy container). Where the +/// edges' noise is under [`FOLD_LEVEL`] the model is [`NoiseModel::clean`], so that a clean +/// intake is traced exactly as before. +/// +/// With `INKVEC_NOISE_FOLD=1` it also folds the noise into `map`'s per-point uncertainties: +/// each point's `σ` grows by the windows' measured error beyond rounding, in quadrature, which +/// is what the fitter divides by. Off by default until the representation chain's fitter reads +/// it with its robust loss: with today's fitter it buys simpler fits at a cost in fidelity +/// (`quality-web`, 62 icons: turning −5.0 %, parameters −1.4 %, dE00 +2.8 %, geom +1.7 %). +pub fn measure_noise( + map: &mut PlanarMap, + rgb: &[[f32; 3]], + faces: &[FillModel], + sigma_noise: f64, + lossy: bool, +) -> NoiseModel { + let fold = inkvec_core::env::flag("INKVEC_NOISE_FOLD"); + measure_noise_with(map, rgb, faces, sigma_noise, lossy, fold) +} + +/// The colour path's last step: a soft or lossy intake's noise sits at its edges, where +/// flat-region estimates cannot see it, so it is measured there ([`measure_noise`]) into +/// [`ColorTrace::noise`](crate::ColorTrace::noise). A clean intake (`soft` false) is +/// returned as it came, without measuring anything. +pub(crate) fn with_noise( + mut ct: crate::ColorTrace, + rgb: &[[f32; 3]], + soft: bool, + lossy: bool, + sw: &mut crate::Stopwatch, +) -> crate::ColorTrace { + if soft { + let faces: Vec = ct.face_fill.iter().map(|f| f.model.clone()).collect(); + ct.noise = measure_noise(&mut ct.map, rgb, &faces, ct.sigma_noise, lossy); + sw.mark("noise"); + } + ct +} + +/// [`measure_noise`], with the fold into the per-point uncertainties chosen by the caller. +pub fn measure_noise_with( + map: &mut PlanarMap, + rgb: &[[f32; 3]], + faces: &[FillModel], + sigma_noise: f64, + lossy: bool, + fold: bool, +) -> NoiseModel { + let ramps = crate::softness::ramp_evidence(rgb, map.width, map.height); + let opts = EvidenceOptions { + lossy, + ramp_width: ramps.width.max(1.0), + ..EvidenceOptions::default() + }; + let ev = build(map, rgb, faces, sigma_noise, &opts); + let noise = ev.noise().clone(); + if noise.is_clean() || noise.sigma_edge_at(0.0) <= FOLD_LEVEL { + return NoiseModel::clean(); + } + if fold { + let extra = ev.calibration.extra[0].max(ev.calibration.extra[1]); + for e in &mut map.edges { + for s in &mut e.sigma { + *s = (*s * *s + extra).sqrt(); + } + } + } + noise +} + +impl Evidence { + /// Image size, px. + pub fn size(&self) -> (usize, usize) { + (self.width, self.height) + } + + /// The pixels of edge `e`'s run window `i`, in order along its line. + pub fn window_pixels(&self, e: usize, i: usize) -> &[(i32, i32)] { + &self.run_pixels[e][i] + } + + /// The pixels of a junction's local term, by node id. + pub fn local_pixels(&self, node: u32) -> Vec<(i32, i32)> { + self.locals + .iter() + .find(|l| l.node == node) + .map(|l| l.pixels.iter().map(|p| (p.x, p.y)).collect()) + .unwrap_or_default() + } + + /// The pixels of corner proposal `i`'s per-pixel term (empty for a proposal inside a run). + pub fn corner_pixels(&self, i: usize) -> Vec<(i32, i32)> { + self.corner_terms[i].iter().map(|p| (p.x, p.y)).collect() + } + + /// Pixels two edges share away from a junction (thin features; not scored yet). + pub fn strip_pixels(&self) -> &[(i32, i32)] { + &self.strip_pixels + } + + /// Pixels on an edge holding a third ink (not scored). + pub fn third_pixels(&self) -> &[(i32, i32)] { + &self.third_pixels + } + + /// Per run window of edge `e`, the variance of its sum from quantisation (and measured + /// noise) alone, before the renderer floor. + pub fn quantisation_var(&self, e: usize) -> &[f64] { + &self.quant_var[e] + } + + /// What the windows' fourth differences said about their error beyond rounding. + pub fn calibration(&self) -> &noise::Calibration { + &self.calibration + } + + /// The intake's noise as the windows measured it ([`NoiseModel::clean`] when nothing + /// beyond rounding was found on a native, lossless intake). + pub fn noise(&self) -> &NoiseModel { + &self.noise + } + + /// The sums edge `e`'s run windows read on another image of the same size (row-major, + /// composited onto white): the same pixels unmixed on the same two inks. Scoring a known + /// truth this way gives each window's error, `sum − truth`. + pub fn window_sums_of(&self, e: usize, rgb: &[[f32; 3]]) -> Vec { + let Some(axis) = self.axes[e] else { + return Vec::new(); + }; + self.run_pixels[e] + .iter() + .map(|pix| { + pix.iter() + .map(|&(x, y)| { + axis.unmix(rgb[y as usize * self.width + x as usize], None) + .a + }) + .sum() + }) + .collect() + } +} + +impl BoundaryLikelihood for Evidence { + fn edge_count(&self) -> usize { + self.runs.len() + } + + fn runs(&self, e: usize) -> &[RunObs] { + &self.runs[e] + } + + fn render_model(&self) -> RenderModel { + self.render + } + + fn floor(&self) -> Floor { + self.floor + } + + fn edge_on_lattice(&self, e: usize) -> bool { + self.lattice_edge[e] + } + + fn edge_offset_var(&self, e: usize) -> f64 { + let lattice = if self.lattice_edge[e] { + self.floor.edge_var + } else { + 0.0 + }; + self.offset_var[e].max(lattice) + } + + fn tail_nu(&self) -> f64 { + self.noise.nu + } + + fn window_point_index(&self, e: usize) -> Vec { + self.point_at[e].clone() + } + + fn chi2_band(&self, pair: (usize, usize), band: &StrokeBand, inks: [[f32; 3]; 3]) -> Chi2 { + let (a, b) = (pair.0.min(pair.1) as u32, pair.0.max(pair.1) as u32); + local::chi2_band(&self.strips, (a, b), band, inks) + } + + fn chi2_local_layers( + &self, + node: u32, + layers: &[(&[Piece], [f32; 3])], + ground: [f32; 3], + ) -> Chi2 { + match self.locals.iter().find(|l| l.node == node) { + Some(term) => local::chi2_layers(term, &self.render, layers, ground), + None => Chi2::default(), + } + } + + fn chi2_local(&self, owner: Owner, curves: &[(usize, &[Piece])]) -> Chi2 { + match owner { + Owner::Junction(node) => { + let Some(term) = self.locals.iter().find(|l| l.node == node) else { + return Chi2::default(); + }; + // Order the candidates as the term's arms. + let mut ordered: Vec<&[Piece]> = Vec::with_capacity(term.arms.len()); + for &(e, _) in &term.arms { + match curves.iter().find(|(ce, _)| *ce == e) { + Some((_, c)) => ordered.push(c), + None => return Chi2::default(), + } + } + let colour = |e: usize, left: bool, x: i32, y: i32| -> [f64; 3] { + let (l, r) = self.edge_faces[e]; + let f = if left { l } else { r }; + let c = self + .faces + .get(f as usize) + .map_or([0.0; 3], |m| m.color_at(x as f64, y as f64)); + [c[0] as f64, c[1] as f64, c[2] as f64] + }; + local::chi2(term, &self.render, &ordered, &colour).unwrap_or_default() + } + Owner::Corner(i) => { + // Only the corner's own pixels: the run windows round it are the runs'. + let Some(c) = self.corners.get(i as usize) else { + return Chi2::default(); + }; + match curves.iter().find(|(ce, _)| *ce == c.edge as usize) { + Some((_, cv)) => { + local::chi2_corner(&self.corner_terms[i as usize], &self.render, cv) + } + None => Chi2::default(), + } + } + } + } + + fn junctions(&self) -> &[JunctionReport] { + &self.junctions + } + + fn corners(&self) -> &[CornerProposal] { + &self.corners + } + + fn density(&self, e: usize) -> Vec<(f64, f64)> { + self.runs[e] + .iter() + .zip(&self.lengths[e]) + .map(|(o, l)| (o.s, l / o.var.max(1e-300))) + .collect() + } +} + +#[cfg(test)] +#[path = "evidence_tests.rs"] +mod tests; diff --git a/crates/inkvec-trace/src/evidence/checks.rs b/crates/inkvec-trace/src/evidence/checks.rs new file mode 100644 index 00000000..307f8b46 --- /dev/null +++ b/crates/inkvec-trace/src/evidence/checks.rs @@ -0,0 +1,237 @@ +//! Checker call sites: where a result a theorem speaks about is accepted only if a checker +//! generated from Lean agrees (`docs/theory/verification.md`). +//! +//! * [`certify_run_chi2_polyline`]: the `χ²` of a polyline candidate on a set of run windows. +//! The candidate is cut, per window, at the window's strip and ends (the certificate: the +//! straight pieces and the clamped height of each); every piece's area is the generated +//! `trapezoid_iv` (`Inkvec.Gen.trapezoidK_integral`: the integral of the piece's height above +//! the window's end), each window's term the generated `window_term_iv`, and the sum an +//! outward-rounded enclosure. The window identity (`Inkvec.window_sum_eq_area`) is what +//! makes the measured sums areas at all. +//! * [`certify_corner`]: a corner proposal's fourth difference is at least `z` of its standard +//! deviations (`corner_excess_iv`, `Inkvec.Gen.cornerExcessK_eq`; `fourthDiff_cubic` says a +//! smooth run reads zero there). +//! +//! What is trusted beyond the generated kernels: the cutting (where each piece meets the +//! strip's sides and the window's ends, computed in `f64`; a cut a rounding away from the +//! exact one moves the area by the same rounding), and the combination of the per-piece sums +//! into the left face's area by the runtime's interval operations. + +use inkvec_core::likelihood::{Axis, RunObs, Window}; +use inkvec_core::Point; +use inkvec_verified::generated::evidence::{corner_excess_iv, trapezoid_iv, window_term_iv}; +use inkvec_verified::iv::{self, Iv}; + +/// Why a checker refused a result. +#[derive(Debug, Clone, PartialEq)] +pub enum Refused { + /// The candidate did not cross a window's strip exactly once. + NotACrossing { + /// Index of the window in the range. + window: usize, + }, + /// The enclosure could not be formed (a non-finite input, an overflow). + Arithmetic, + /// The claimed value lies outside the certified enclosure. + Mismatch { + /// The solver's value. + claimed: f64, + /// The certified enclosure. + lo: f64, + /// The certified enclosure. + hi: f64, + }, +} + +/// The straight pieces of segment `a → b` (strip coordinates `(u, v)`) inside the strip +/// `u ∈ [u0, u1]`, cut where `v` crosses `vlo` and `vhi`, with each piece's heights clamped to +/// `[vlo, vhi]`: the certificate `trapezoid` is evaluated on. +fn pieces(a: (f64, f64), b: (f64, f64), u0: f64, u1: f64, vlo: f64, vhi: f64) -> Vec<[f64; 4]> { + let (du, dv) = (b.0 - a.0, b.1 - a.1); + if du == 0.0 { + return Vec::new(); + } + let (ta, tb) = { + let t0 = (u0 - a.0) / du; + let t1 = (u1 - a.0) / du; + (t0.min(t1).max(0.0), t0.max(t1).min(1.0)) + }; + if tb <= ta { + return Vec::new(); + } + let mut ts = vec![ta, tb]; + if dv != 0.0 { + for lv in [vlo, vhi] { + let t = (lv - a.1) / dv; + if t > ta && t < tb { + ts.push(t); + } + } + } + ts.sort_by(f64::total_cmp); + ts.windows(2) + .map(|w| { + let (t0, t1) = (w[0], w[1]); + let clamp = |v: f64| v.clamp(vlo, vhi); + [ + a.0 + t0 * du, + clamp(a.1 + t0 * dv), + a.0 + t1 * du, + clamp(a.1 + t1 * dv), + ] + }) + .collect() +} + +/// A certified enclosure of the area polyline `pts` gives its left face in window `w`, from +/// its passes through the strip that come within a pixel of the window; `Err` when those do +/// not advance one strip width in all, either way, or the arithmetic refuses. +pub fn certified_left_area(pts: &[Point], w: &Window) -> Result { + let (u0, u1) = (w.line as f64 - 0.5, w.line as f64 + 0.5); + let (vlo, vhi) = (w.lo as f64 - 0.5, w.hi as f64 + 0.5); + let uv = |p: Point| match w.axis { + Axis::Column => (p.x, p.y), + Axis::Row => (p.y, p.x), + }; + let inside = |u: f64| u >= u0 && u <= u1; + // Passes: runs of consecutive segments that stay in the strip from one to the next. + struct Pass { + area: Iv, + adv: f64, + vmin: f64, + vmax: f64, + } + let zero = Iv::point(0.0).ok_or(Refused::Arithmetic)?; + let mut passes: Vec = Vec::new(); + let mut open = false; + for s in pts.windows(2) { + let (a, b) = (uv(s[0]), uv(s[1])); + let ps = pieces(a, b, u0, u1, vlo, vhi); + if ps.is_empty() { + open = false; + continue; + } + let mut area = zero; + let mut adv = 0.0; + // The segment's unclamped heights where it is inside the strip decide nearness, as + // in the evaluator. + let (vmin, vmax) = { + let du = b.0 - a.0; + let (p, q) = ((u0 - a.0) / du, (u1 - a.0) / du); + let (ta, tb) = (p.min(q).max(0.0), p.max(q).min(1.0)); + let (va, vb) = (a.1 + ta * (b.1 - a.1), a.1 + tb * (b.1 - a.1)); + (va.min(vb), va.max(vb)) + }; + for p in &ps { + let x = [p[0], p[1], p[2], p[3], vlo].map(Iv::point); + let x = [ + x[0].ok_or(Refused::Arithmetic)?, + x[1].ok_or(Refused::Arithmetic)?, + x[2].ok_or(Refused::Arithmetic)?, + x[3].ok_or(Refused::Arithmetic)?, + x[4].ok_or(Refused::Arithmetic)?, + ]; + let [t] = trapezoid_iv(&x).ok_or(Refused::Arithmetic)?; + area = iv::add(area, t).ok_or(Refused::Arithmetic)?; + adv += p[2] - p[0]; + } + match passes.last_mut() { + Some(p) if open && inside(a.0) => { + p.area = iv::add(p.area, area).ok_or(Refused::Arithmetic)?; + p.adv += adv; + p.vmin = p.vmin.min(vmin); + p.vmax = p.vmax.max(vmax); + } + _ => passes.push(Pass { + area, + adv, + vmin, + vmax, + }), + } + open = inside(b.0); + } + let (mut i, mut adv) = (zero, 0.0); + for p in passes + .iter() + .filter(|p| p.vmax >= vlo - 1.0 && p.vmin <= vhi + 1.0) + { + i = iv::add(i, p.area).ok_or(Refused::Arithmetic)?; + adv += p.adv; + } + let dir = if (adv - 1.0).abs() < 1e-9 { + 1.0 + } else if (adv + 1.0).abs() < 1e-9 { + -1.0 + } else { + return Err(Refused::NotACrossing { window: 0 }); + }; + let h = Iv::point(vhi - vlo).ok_or(Refused::Arithmetic)?; + // Column: I + h(1 − Δ)/2; row: −I + h(1 + Δ)/2, with Δ = ±1 exactly. + let a = match w.axis { + Axis::Column if dir > 0.0 => Some(i), + Axis::Column => iv::add(i, h), + Axis::Row if dir > 0.0 => iv::sub(h, i), + Axis::Row => iv::neg(i), + } + .ok_or(Refused::Arithmetic)?; + Ok(a) +} + +/// The area of the left face of polyline `pts` in window `w` (the midpoint of the certified +/// enclosure), or `None` when the checker refuses. +pub fn polyline_left_area(pts: &[Point], w: &Window) -> Option { + certified_left_area(pts, w) + .ok() + .map(|a| 0.5 * (a.lo + a.hi)) +} + +/// Certify a solver's `χ²` of a polyline candidate on run windows: the generated kernels' +/// enclosure must contain it, widened by `tol` relative to `1 + χ²` (the cut points are +/// computed in `f64`). Returns the enclosure's midpoint. +pub fn certify_run_chi2_polyline( + obs: &[RunObs], + pts: &[Point], + claimed: f64, + tol: f64, +) -> Result { + let mut chi = Iv::point(0.0).ok_or(Refused::Arithmetic)?; + for (k, o) in obs.iter().enumerate() { + let a = certified_left_area(pts, &o.window).map_err(|e| match e { + Refused::NotACrossing { .. } => Refused::NotACrossing { window: k }, + other => other, + })?; + let s = Iv::point(o.sum).ok_or(Refused::Arithmetic)?; + let v = Iv::point(o.var).ok_or(Refused::Arithmetic)?; + let [term, _] = window_term_iv(&[s, a, v]).ok_or(Refused::Arithmetic)?; + chi = iv::add(chi, term).ok_or(Refused::Arithmetic)?; + } + let slack = tol * (1.0 + chi.hi.abs()); + if claimed < chi.lo - slack || claimed > chi.hi + slack { + return Err(Refused::Mismatch { + claimed, + lo: chi.lo, + hi: chi.hi, + }); + } + Ok(0.5 * (chi.lo + chi.hi)) +} + +/// Certify a corner proposal: the fourth difference of five consecutive window means `h` with +/// variances `v` is at least `z` of its standard deviations (`corner_excess_iv` non-negative). +/// A refusal drops the proposal, which only costs information (the windows stay a run). +pub fn certify_corner(h: [f64; 5], v: [f64; 5], z: f64) -> bool { + let mut x = [Iv { lo: 0.0, hi: 0.0 }; 11]; + for k in 0..5 { + let (Some(a), Some(b)) = (Iv::point(h[k]), Iv::point(v[k])) else { + return false; + }; + x[k] = a; + x[5 + k] = b; + } + let Some(z2) = Iv::point(z * z) else { + return false; + }; + x[10] = z2; + corner_excess_iv(&x).is_some_and(|[e]| e.is_nonneg()) +} diff --git a/crates/inkvec-trace/src/evidence/local.rs b/crates/inkvec-trace/src/evidence/local.rs new file mode 100644 index 00000000..11096b59 --- /dev/null +++ b/crates/inkvec-trace/src/evidence/local.rs @@ -0,0 +1,498 @@ +//! The per-pixel term of a junction: its pixels' colours against the mixture the candidate +//! curves draw there (`docs/theory/chain-boundary.md`, B1.3, B3.2). A junction pixel holds +//! three or more inks, so it is scored in colour, not unmixed: each face's area in the pixel +//! comes from the sector its two arms cut out of a disc around the vertex. + +use inkvec_core::likelihood::{Chi2, Piece, RenderModel}; +use inkvec_core::Point; + +/// One pixel of a local term. +#[derive(Debug, Clone, Copy)] +pub(super) struct LocalPixel { + pub(super) x: i32, + pub(super) y: i32, + /// Its colour, sRGB. + pub(super) rgb: [f64; 3], + /// Variance per channel. + pub(super) var: f64, +} + +/// A junction's local term: its arms (edge, whether the edge starts here), and its pixels. +#[derive(Debug, Clone)] +pub(super) struct Local { + pub(super) node: u32, + pub(super) at: Point, + pub(super) arms: Vec<(usize, bool)>, + pub(super) pixels: Vec, +} + +/// Points along a curve, flattened finely (the local term is a few pixels; `1e-3` px). +fn flatten(rm: &RenderModel, pieces: &[Piece]) -> Vec { + // Arcs the model draws exactly are followed through fine cubics. + let drawn: Vec = rm + .as_rendered(pieces) + .into_iter() + .flat_map(|p| match p { + Piece::Arc(a) => a.to_cubics(1e-4), + other => vec![other], + }) + .collect(); + let mut out: Vec = Vec::new(); + for p in &drawn { + let (pts, n): (Vec, usize) = match p { + Piece::Line([a, b]) => (vec![*a, *b], 1), + Piece::Quad(q) => (q.to_vec(), 24), + Piece::Cubic(q) => (q.to_vec(), 32), + Piece::Arc(_) => continue, + }; + if out.is_empty() { + out.push(pts[0]); + } + for k in 1..=n { + let t = k as f64 / n as f64; + let q = match pts.len() { + 2 => Point::new( + pts[0].x + t * (pts[1].x - pts[0].x), + pts[0].y + t * (pts[1].y - pts[0].y), + ), + 3 => { + let m = 1.0 - t; + Point::new( + m * m * pts[0].x + 2.0 * m * t * pts[1].x + t * t * pts[2].x, + m * m * pts[0].y + 2.0 * m * t * pts[1].y + t * t * pts[2].y, + ) + } + _ => { + let m = 1.0 - t; + let (a, b, c, d) = (m * m * m, 3.0 * m * m * t, 3.0 * m * t * t, t * t * t); + Point::new( + a * pts[0].x + b * pts[1].x + c * pts[2].x + d * pts[3].x, + a * pts[0].y + b * pts[1].y + c * pts[2].y + d * pts[3].y, + ) + } + }; + out.push(q); + } + } + out +} + +/// Area of a (possibly non-convex) polygon inside the pixel square centred at `(x, y)`: +/// Sutherland–Hodgman against the square's four sides, then the shoelace formula. +pub(super) fn area_in_pixel(poly: &[Point], x: i32, y: i32) -> f64 { + let (x0, x1, y0, y1) = ( + x as f64 - 0.5, + x as f64 + 0.5, + y as f64 - 0.5, + y as f64 + 0.5, + ); + let mut cur: Vec = poly.to_vec(); + let sides: [&dyn Fn(Point) -> f64; 4] = [ + &|p: Point| p.x - x0, + &|p: Point| x1 - p.x, + &|p: Point| p.y - y0, + &|p: Point| y1 - p.y, + ]; + for f in sides { + if cur.is_empty() { + return 0.0; + } + let mut next = Vec::with_capacity(cur.len() + 4); + for i in 0..cur.len() { + let (a, b) = (cur[i], cur[(i + 1) % cur.len()]); + let (fa, fb) = (f(a), f(b)); + if fa >= 0.0 { + next.push(a); + } + if (fa >= 0.0) != (fb >= 0.0) { + let t = fa / (fa - fb); + next.push(Point::new(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y))); + } + } + cur = next; + } + let n = cur.len(); + let mut s = 0.0; + for i in 0..n { + let (a, b) = (cur[i], cur[(i + 1) % n]); + s += a.x * b.y - b.x * a.y; + } + (0.5 * s).abs() +} + +/// One pixel of a corner term: its unmixed weight of the edge's left face. +#[derive(Debug, Clone, Copy)] +pub(super) struct CornerPixel { + pub(super) x: i32, + pub(super) y: i32, + pub(super) a: f64, + pub(super) var: f64, +} + +/// The part of segment `a → b` inside the box `[x0, x1] × [y0, y1]` (Liang–Barsky), as +/// parameters `(t0, t1)`, or `None`. +fn clip_segment(a: Point, b: Point, x0: f64, x1: f64, y0: f64, y1: f64) -> Option<(f64, f64)> { + let (dx, dy) = (b.x - a.x, b.y - a.y); + let (mut t0, mut t1) = (0.0f64, 1.0f64); + for (p, q) in [ + (-dx, a.x - x0), + (dx, x1 - a.x), + (-dy, a.y - y0), + (dy, y1 - a.y), + ] { + if p == 0.0 { + if q < 0.0 { + return None; + } + continue; + } + let r = q / p; + if p < 0.0 { + t0 = t0.max(r); + } else { + t1 = t1.min(r); + } + if t0 > t1 { + return None; + } + } + Some((t0, t1)) +} + +/// Position of a point on the box's boundary as a perimeter coordinate, walking +/// `(x0, y0) → (x1, y0) → (x1, y1) → (x0, y1)`. +fn perimeter(p: Point, x0: f64, x1: f64, y0: f64, y1: f64) -> f64 { + let (w, h) = (x1 - x0, y1 - y0); + let e = 1e-9 * (w + h); + if (p.y - y0).abs() <= e { + p.x - x0 + } else if (p.x - x1).abs() <= e { + w + (p.y - y0) + } else if (p.y - y1).abs() <= e { + w + h + (x1 - p.x) + } else { + 2.0 * w + h + (y1 - p.y) + } +} + +fn point_in(poly: &[Point], q: Point) -> bool { + let mut inside = false; + let n = poly.len(); + for i in 0..n { + let (a, b) = (poly[i], poly[(i + 1) % n]); + if (a.y > q.y) != (b.y > q.y) && q.x < a.x + (q.y - a.y) / (b.y - a.y) * (b.x - a.x) { + inside = !inside; + } + } + inside +} + +/// The area the polyline `curve` gives its left face in pixel `(x, y)`: the pass of the +/// curve through a box of half-size `reach` around the pixel that comes nearest its centre, +/// closed along the box's boundary on the curve's left, clipped to the pixel. Exact for a +/// polyline that passes through the box once; `None` when the curve ends inside the box. +pub(super) fn left_area_pixel(curve: &[Point], x: i32, y: i32, reach: f64) -> Option { + let (x0, x1, y0, y1) = ( + x as f64 - reach, + x as f64 + reach, + y as f64 - reach, + y as f64 + reach, + ); + let c = Point::new(x as f64, y as f64); + // Passes: maximal runs of consecutive clipped segments. + let mut passes: Vec> = Vec::new(); + let mut open = false; + for s in curve.windows(2) { + let Some((t0, t1)) = clip_segment(s[0], s[1], x0, x1, y0, y1) else { + open = false; + continue; + }; + let at = |t: f64| { + Point::new( + s[0].x + t * (s[1].x - s[0].x), + s[0].y + t * (s[1].y - s[0].y), + ) + }; + if open && t0 == 0.0 { + passes.last_mut().expect("open pass").push(at(t1)); + } else { + passes.push(vec![at(t0), at(t1)]); + } + open = t1 == 1.0; + } + let dist = |p: &Vec| p.iter().map(|q| q.dist(c)).fold(f64::INFINITY, f64::min); + let pass = passes + .into_iter() + .min_by(|a, b| dist(a).total_cmp(&dist(b)))?; + let (s, e) = (pass[0], *pass.last().expect("two points")); + let on_box = |p: Point| { + let tol = 1e-9 * reach; + (p.x - x0).abs() <= tol + || (p.x - x1).abs() <= tol + || (p.y - y0).abs() <= tol + || (p.y - y1).abs() <= tol + }; + if !on_box(s) || !on_box(e) { + return None; + } + // The two ways round the box from the exit back to the entry. + let per = 4.0 * 2.0 * reach; + let (pe, ps) = (perimeter(e, x0, x1, y0, y1), perimeter(s, x0, x1, y0, y1)); + let corners = [ + (0.0, Point::new(x0, y0)), + (2.0 * reach, Point::new(x1, y0)), + (4.0 * reach, Point::new(x1, y1)), + (6.0 * reach, Point::new(x0, y1)), + ]; + let walk = |forward: bool| -> Vec { + let mut out = Vec::new(); + let span = if forward { + (ps - pe).rem_euclid(per) + } else { + (pe - ps).rem_euclid(per) + }; + let mut cs: Vec<(f64, Point)> = corners + .iter() + .map(|&(p, q)| { + ( + if forward { + (p - pe).rem_euclid(per) + } else { + (pe - p).rem_euclid(per) + }, + q, + ) + }) + .filter(|(d, _)| *d > 0.0 && *d < span) + .collect(); + cs.sort_by(|a, b| a.0.total_cmp(&b.0)); + out.extend(cs.into_iter().map(|(_, q)| q)); + out + }; + // A point just left of the pass's middle: left of direction d is (d.y, -d.x). + let k = pass.len() / 2; + let (a, b) = (pass[k.saturating_sub(1)], pass[k.min(pass.len() - 1)]); + let (dx, dy) = (b.x - a.x, b.y - a.y); + let l = dx.hypot(dy).max(1e-12); + let probe = Point::new( + 0.5 * (a.x + b.x) + 1e-6 * dy / l, + 0.5 * (a.y + b.y) - 1e-6 * dx / l, + ); + for forward in [true, false] { + let mut poly = pass.clone(); + poly.extend(walk(forward)); + if point_in(&poly, probe) { + return Some(area_in_pixel(&poly, x, y)); + } + } + None +} + +/// `χ²` of a corner term's pixels against a candidate curve (pieces, oriented as the edge). +pub(super) fn chi2_corner(pixels: &[CornerPixel], rm: &RenderModel, curve: &[Piece]) -> Chi2 { + let pts = flatten(rm, curve); + let mut out = Chi2::default(); + for p in pixels { + let Some(a) = left_area_pixel(&pts, p.x, p.y, 4.0) else { + continue; + }; + let r = p.a - a; + out.chi2 += r * r / p.var.max(1e-300); + out.m += 1; + } + out.chi2_floor = out.chi2; + out.dof = out.m as f64; + out.cost = out.chi2; + out +} + +/// `χ²` of a junction's pixels against candidate curves for its arms. `curves[k]` is the +/// candidate for arm `k` (in the term's arm order), oriented as its edge; `faces(e, left)` is +/// the colour of edge `e`'s left (or right) face at a pixel. The arms are flattened, followed +/// outwards from the junction, extended radially to a disc well beyond the term's pixels, and +/// sorted by direction; the face between two consecutive arms is the right face of the first +/// walked outwards, and its sector (vertex, first arm, the disc's rim, second arm) clipped to +/// each pixel is its area there. +pub(super) fn chi2( + term: &Local, + rm: &RenderModel, + curves: &[&[Piece]], + colour: &dyn Fn(usize, bool, i32, i32) -> [f64; 3], +) -> Option { + if curves.len() != term.arms.len() || curves.len() < 2 { + return None; + } + let rim = term + .pixels + .iter() + .map(|p| (p.x as f64 - term.at.x).hypot(p.y as f64 - term.at.y)) + .fold(0.0f64, f64::max) + + 3.0; + // Outward polylines. + let mut arms: Vec<(Vec, usize, bool)> = Vec::new(); + for (k, &(e, at_start)) in term.arms.iter().enumerate() { + let mut pts = flatten(rm, curves[k]); + if pts.len() < 2 { + return None; + } + if !at_start { + pts.reverse(); + } + arms.push((pts, e, at_start)); + } + let vertex = { + let n = arms.len() as f64; + arms.iter().fold(Point::new(0.0, 0.0), |a, (p, _, _)| { + Point::new(a.x + p[0].x / n, a.y + p[0].y / n) + }) + }; + let mut rays: Vec<(f64, Vec, usize, bool)> = Vec::new(); + for (pts, e, at_start) in arms { + let mut q: Vec = vec![vertex]; + for p in pts.iter().skip(1) { + if p.dist(vertex) >= rim { + break; + } + q.push(*p); + } + let last = *q.last().expect("vertex"); + let prev = if q.len() >= 2 { q[q.len() - 2] } else { vertex }; + let (mut dx, mut dy) = (last.x - prev.x, last.y - prev.y); + if dx.hypot(dy) < 1e-9 { + let p1 = pts[1]; + dx = p1.x - vertex.x; + dy = p1.y - vertex.y; + } + let l = dx.hypot(dy).max(1e-12); + q.push(Point::new( + last.x + dx / l * 2.0 * rim, + last.y + dy / l * 2.0 * rim, + )); + let tip = *q.last().expect("tip"); + rays.push(((tip.y - vertex.y).atan2(tip.x - vertex.x), q, e, at_start)); + } + rays.sort_by(|a, b| a.0.total_cmp(&b.0)); + let n = rays.len(); + let mut model: Vec<[f64; 3]> = vec![[0.0; 3]; term.pixels.len()]; + for k in 0..n { + let (a0, ref r0, e0, s0) = rays[k]; + let (mut a1, ref r1, _, _) = rays[(k + 1) % n]; + if a1 <= a0 { + a1 += 2.0 * std::f64::consts::PI; + } + let mut poly: Vec = r0.clone(); + let steps = (((a1 - a0) / 0.05).ceil() as usize).max(1); + for i in 1..steps { + let a = a0 + (a1 - a0) * i as f64 / steps as f64; + poly.push(Point::new( + vertex.x + 3.0 * rim * a.cos(), + vertex.y + 3.0 * rim * a.sin(), + )); + } + poly.extend(r1.iter().rev()); + // Walking out along arm k (direction θ), its left face lies at θ − 90° and its right + // face at θ + 90°, inside this sector. Walked outwards an edge that starts here keeps + // its faces; one that ends here has them swapped: the sector's face is the edge's + // right face, or its left face when the edge ends at the junction. + let edge_left = !s0; + for (pi, px) in term.pixels.iter().enumerate() { + let a = area_in_pixel(&poly, px.x, px.y); + if a <= 0.0 { + continue; + } + let c = colour(e0, edge_left, px.x, px.y); + for ch in 0..3 { + model[pi][ch] += a * c[ch]; + } + } + } + Some(colour_score( + term.pixels + .iter() + .zip(&model) + .map(|(px, m)| (px.rgb, *m, px.var)), + )) +} + +/// A pixel two edges both reach away from a junction (a thin feature), in colour. +#[derive(Debug, Clone, Copy)] +pub(super) struct StripPixel { + pub(super) x: i32, + pub(super) y: i32, + pub(super) rgb: [f64; 3], + /// Per-channel variance. + pub(super) var: f64, + /// The two edges, the lower index first. + pub(super) pair: (u32, u32), +} + +/// Sum per-pixel colour residuals into a score. +fn colour_score(pixels: impl Iterator) -> Chi2 { + let mut out = Chi2::default(); + for (obs, model, var) in pixels { + for ch in 0..3 { + let r = obs[ch] - model[ch]; + out.chi2 += r * r / var.max(1e-300); + } + out.m += 3; + } + out.chi2_floor = out.chi2; + out.dof = out.m as f64; + out.cost = out.chi2; + out +} + +/// A2: a stroke band against the strip pixels of its two edges: each pixel is the left +/// side's ink where it is left of the band's left side, the band's within the band, and the +/// right side's elsewhere. +pub(super) fn chi2_band( + pixels: &[StripPixel], + pair: (u32, u32), + band: &inkvec_core::likelihood::StrokeBand, + inks: [[f32; 3]; 3], +) -> Chi2 { + let (left, right) = band.sides(0.05); + if left.len() < 2 { + return Chi2::default(); + } + let mut poly = left.clone(); + poly.extend(right.iter().rev()); + let ink = |k: usize| [inks[k][0] as f64, inks[k][1] as f64, inks[k][2] as f64]; + let (il, ib, ir) = (ink(0), ink(1), ink(2)); + colour_score(pixels.iter().filter(|p| p.pair == pair).filter_map(|p| { + let b = area_in_pixel(&poly, p.x, p.y).clamp(0.0, 1.0); + let l = left_area_pixel(&left, p.x, p.y, 4.0)?.clamp(0.0, 1.0 - b); + let r = (1.0 - b - l).max(0.0); + let model: [f64; 3] = std::array::from_fn(|c| l * il[c] + b * ib[c] + r * ir[c]); + Some((p.rgb, model, p.var)) + })) +} + +/// A2: a junction's pixels under per-layer compositing: each layer's whole shape covers its +/// area of a pixel and is painted over what lies beneath, in order, over `ground`. +pub(super) fn chi2_layers( + term: &Local, + rm: &RenderModel, + layers: &[(&[Piece], [f32; 3])], + ground: [f32; 3], +) -> Chi2 { + let shapes: Vec<(Vec, [f64; 3])> = layers + .iter() + .map(|(b, c)| (flatten(rm, b), [c[0] as f64, c[1] as f64, c[2] as f64])) + .collect(); + let g = [ground[0] as f64, ground[1] as f64, ground[2] as f64]; + colour_score(term.pixels.iter().map(|p| { + let mut c = g; + for (poly, col) in &shapes { + let a = if poly.len() >= 3 { + area_in_pixel(poly, p.x, p.y).clamp(0.0, 1.0) + } else { + 0.0 + }; + for ch in 0..3 { + c[ch] = a * col[ch] + (1.0 - a) * c[ch]; + } + } + (p.rgb, c, p.var) + })) +} diff --git a/crates/inkvec-trace/src/evidence/noise.rs b/crates/inkvec-trace/src/evidence/noise.rs new file mode 100644 index 00000000..777e0949 --- /dev/null +++ b/crates/inkvec-trace/src/evidence/noise.rs @@ -0,0 +1,394 @@ +//! The window variance of one image, estimated from the image's own edges +//! (`docs/theory/chain-boundary.md`, "Noise: the window variance from the edges"). +//! +//! Every window's sum is the area its face holds there, plus an error: 8-bit rounding, which +//! the variance model of [`super::windows`] knows exactly, and whatever else the intake's +//! history added (a renderer's sampling lattice and curve flattening, a resampler's phase +//! ripple, a JPEG's blocks and ringing). That error is a function of the edge's local +//! sub-pixel phase and of what lies near it, so it has three parts, each measured or bounded +//! here from the image alone: +//! +//! * **Replicas.** Consecutive windows whose mean positions differ by a whole number of +//! pixels see the edge at the same phase: on an axis or a diagonal every window is the same +//! measurement repeated, with the same error (bench: correlation 0.84 to 0.95 between such +//! neighbours, whatever the input). A stretch of `k` replicas counts as one measurement: +//! each gets `k` times the variance ([`replica_stretches`]). +//! * **The rough part**, independent between windows at different phases: the fourth +//! differences `D` of consecutive windows' mean positions see it whole, since `D` +//! annihilates every cubic, so a smooth boundary contributes nothing. `D` is the residual +//! of the local cubic through five windows: the fitted model's residual, with no fit to +//! iterate. Its variance is `Σ wᵢ² (Vᵢ + s²)`, `Vᵢ` the known rounding variances and `s²` +//! the extra, solved per class of window from a winsorised second moment (exact for normal +//! errors, within 2 % for the bounded errors of rounding, and not carried away by a JPEG's +//! heavy tails). Only stencils with no replica step, no phase step under 0.06 px (where +//! rounding errors anticorrelate) and a local second derivative under 0.08 px⁻¹ count: on +//! tighter curves the geometry's own fourth difference leaks into `D` (bench: the `D` of the +//! measured positions and of the truth's errors agree below 0.08 and part above it). +//! * **The smooth part**, shared along a run: an offset no difference sees, the same as +//! moving the edge, so it cannot be measured from one image. Its variance is set by the +//! phase-locking argument above: an axis-aligned edge's constant error *is* one window's +//! error, replicated, so each edge gets an offset of the variance of one of its windows +//! (the trait's `chi2_floor`). A fitted candidate absorbs it in its own position. +//! +//! Never from flat regions: on the web tier the noise within 3 px of an edge is 5 to 9 times +//! the interiors', where `coverage::estimate_noise` reads (`docs/theory/noise.md`). +//! +//! The tail is read from the same `D`s: the ratio of the 90th to the 50th percentile of `|z|` +//! is 2.44 for a normal and grows as the tail thickens; matched to Student-t's, then diluted +//! back to one window's (a `D` mixes five windows, which keeps `Σw⁴/(Σw²)² = 0.37` of their +//! excess kurtosis). + +use inkvec_core::likelihood::RunObs; + +/// Weights of the fourth difference. +const W4: [f64; 5] = [1.0, -4.0, 6.0, -4.0, 1.0]; +/// `Σ wᵢ²`. +const W4_SQ: f64 = 70.0; +/// Winsorisation of the standardised `D²`, and its expectation for a standard normal +/// (`E min(z², c²)` at `c = 2.5`). +const WINSOR: f64 = 2.5; +const WINSOR_NORMAL: f64 = 0.977_6; +/// A window whose local second derivative (of the boundary's position along the strip, per +/// window) is below this is on a straight stretch. +const STRAIGHT_CURVATURE: f64 = 0.02; +/// At or above this the geometry's fourth difference leaks into `D`: such stencils are not +/// used for the estimate. +const LEAK_CURVATURE: f64 = 0.08; +/// A phase step below this between neighbouring windows (and not a replica) makes their +/// rounding errors anticorrelate: such stencils are not used. +const MIN_PHASE_STEP: f64 = 0.06; +/// Two windows' positions differing by a whole number of pixels to within this are replicas. +const REPLICA_TOL: f64 = 1e-6; +/// Fewest `D`s for a class's own estimate; fewer and the pooled estimate stands in. +const MIN_D: usize = 12; + +/// Window classes the variance is estimated for separately. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Class { + /// A locally straight boundary. + Straight = 0, + /// A curved one. + Curved = 1, +} + +/// What one image's windows say about their error beyond rounding. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Calibration { + /// Per class, the variance each window's sum has beyond the rounding model, px². + pub extra: [f64; 2], + /// Per class, how many fourth differences the estimate rests on. + pub count: [usize; 2], + /// Student-t degrees of freedom of the windows' standardised errors; infinite when they + /// are no heavier-tailed than a normal's. + pub nu: f64, +} + +impl Calibration { + /// Nothing beyond rounding. + pub const NONE: Calibration = Calibration { + extra: [0.0; 2], + count: [0; 2], + nu: f64::INFINITY, + }; +} + +/// Whether windows `a` and `b` (in order) are neighbours: one axis, consecutive lines. +fn neighbours(a: &RunObs, b: &RunObs) -> bool { + a.window.axis == b.window.axis && (b.window.line - a.window.line).abs() == 1 +} + +/// The phase step between neighbouring windows: how far their mean positions differ from a +/// whole number of pixels, in `[0, ½]`. +fn phase_step(a: &RunObs, b: &RunObs) -> f64 { + let d = (b.mean_position() - a.mean_position()).abs().fract(); + d.min(1.0 - d) +} + +/// Per window, the size of the replica stretch it belongs to (1 for a window seen at a phase +/// of its own): maximal runs of neighbours whose phase step is zero. +pub fn replica_stretches(obs: &[RunObs]) -> Vec { + let n = obs.len(); + let mut out = vec![1usize; n]; + let mut i = 0; + while i < n { + let mut j = i; + while j + 1 < n + && neighbours(&obs[j], &obs[j + 1]) + && phase_step(&obs[j], &obs[j + 1]) < REPLICA_TOL + { + j += 1; + } + for o in &mut out[i..=j] { + *o = j - i + 1; + } + i = j + 1; + } + out +} + +/// Per window, its class and its local second derivative (`None` where too few neighbours): +/// a least-squares quadratic through up to three windows either side, along one axis. +pub fn classify(obs: &[RunObs]) -> Vec<(Class, Option)> { + let n = obs.len(); + (0..n) + .map(|i| { + let mut lo = i; + while lo > 0 && i - lo < 3 && neighbours(&obs[lo - 1], &obs[lo]) { + lo -= 1; + } + let mut hi = i; + while hi + 1 < n && hi - i < 3 && neighbours(&obs[hi], &obs[hi + 1]) { + hi += 1; + } + if hi - lo < 4 { + return (Class::Curved, None); + } + let u0 = obs[i].window.line as f64; + let pts: Vec<(f64, f64)> = (lo..=hi) + .map(|k| (obs[k].window.line as f64 - u0, obs[k].mean_position())) + .collect(); + let k = (2.0 * quadratic_coefficient(&pts)).abs(); + let class = if k < STRAIGHT_CURVATURE { + Class::Straight + } else { + Class::Curved + }; + (class, Some(k)) + }) + .collect() +} + +/// The `u²` coefficient of the least-squares quadratic through `pts`. +fn quadratic_coefficient(pts: &[(f64, f64)]) -> f64 { + let n = pts.len() as f64; + let mean = |f: &dyn Fn(f64, f64) -> f64| pts.iter().map(|&(u, v)| f(u, v)).sum::() / n; + let (mu, mu2, mv) = (mean(&|u, _| u), mean(&|u, _| u * u), mean(&|_, v| v)); + let suu = mean(&|u, _| (u - mu) * (u - mu)); + let su2u = mean(&|u, _| (u * u - mu2) * (u - mu)); + let su2u2 = mean(&|u, _| (u * u - mu2) * (u * u - mu2)); + let svu = mean(&|u, v| (v - mv) * (u - mu)); + let svu2 = mean(&|u, v| (v - mv) * (u * u - mu2)); + let det = suu * su2u2 - su2u * su2u; + if det.abs() < 1e-12 { + return 0.0; + } + (suu * svu2 - su2u * svu) / det +} + +/// One five-window stencil for the rough part: the centre's class, the largest local second +/// difference of positions inside it (a corner or a tight curve shows there), `D`, and +/// `Σ wᵢ² Vᵢ`. +#[derive(Debug, Clone, Copy)] +pub struct Stencil { + class: Class, + bend: f64, + d: f64, + v: f64, +} + +/// The fourth-difference stencils of an edge's windows that can see its rough error: five +/// consecutive windows (one axis, consecutive lines, one direction) with no replica or small +/// phase step among them. Which of them are free of the geometry is decided in [`calibrate`], +/// against the noise. `quant` holds the windows' rounding variances. +pub fn fourth_differences( + obs: &[RunObs], + quant: &[f64], + classes: &[(Class, Option)], +) -> Vec { + let mut out = Vec::new(); + if obs.len() < 5 { + return out; + } + for i in 2..obs.len() - 2 { + let five = &obs[i - 2..=i + 2]; + let step = five[1].window.line - five[0].window.line; + let ok = five.windows(2).all(|p| { + neighbours(&p[0], &p[1]) + && p[1].window.line - p[0].window.line == step + && phase_step(&p[0], &p[1]) >= MIN_PHASE_STEP + }); + if !ok { + continue; + } + let h: Vec = five.iter().map(|o| o.mean_position()).collect(); + let bend = (1..4) + .map(|j| (h[j - 1] - 2.0 * h[j] + h[j + 1]).abs()) + .fold(0.0, f64::max); + let d: f64 = h.iter().zip(W4).map(|(h, w)| w * h).sum(); + let v: f64 = (0..5).map(|j| W4[j] * W4[j] * quant[i - 2 + j]).sum(); + out.push(Stencil { + class: classes[i].0, + bend, + d, + v, + }); + } + out +} + +/// The extra variance `s²` whose winsorised second moment of `D/√(V + 70 s²)` is a normal's, +/// or 0 when the rounding model already explains the `D`s to within three standard errors of +/// that moment (`√(1.5/n)`: the variance of `min(z², c²)` is about 1.5): a few `D`s that a +/// tight curve's geometry or a corner leaks into must not raise every window's variance. +fn solve_extra(ds: &[(f64, f64)]) -> f64 { + let moment = |s2: f64| -> f64 { + ds.iter() + .map(|&(d, v)| (d * d / (v + W4_SQ * s2).max(1e-300)).min(WINSOR * WINSOR)) + .sum::() + / ds.len() as f64 + }; + let se = (1.5 / ds.len().max(1) as f64).sqrt(); + if ds.is_empty() || moment(0.0) <= WINSOR_NORMAL + 3.0 * se { + return 0.0; + } + let mut hi = ds.iter().map(|&(d, _)| d * d).fold(0.0, f64::max) / W4_SQ; + let mut lo = 0.0; + for _ in 0..80 { + let mid = 0.5 * (lo + hi); + if moment(mid) > WINSOR_NORMAL { + lo = mid; + } else { + hi = mid; + } + } + 0.5 * (lo + hi) +} + +/// Student-t's `q90/q50` of `|t|` (`t₀.₉₅/t₀.₇₅`), for `ν` from 3 up; the normal's is 2.4387. +const T_TAIL: [(f64, f64); 9] = [ + (3.0, 3.0767), + (4.0, 2.8782), + (5.0, 2.7729), + (6.0, 2.7080), + (8.0, 2.6325), + (10.0, 2.5899), + (20.0, 2.5107), + (40.0, 2.4738), + (f64::INFINITY, 2.4387), +]; + +/// Degrees of freedom of a `D`'s tail from its `q90/q50` ratio, then one window's: a `D` +/// keeps 0.37 of its windows' excess kurtosis (`6/(ν − 4)` for Student-t), so +/// `ν_window = 4 + 0.37 (ν_D − 4)`, at least 3. +fn tail_nu(z: &mut [f64]) -> f64 { + if z.len() < 4 * MIN_D { + return f64::INFINITY; + } + for v in z.iter_mut() { + *v = v.abs(); + } + let q = |z: &mut [f64], p: f64| { + let k = ((z.len() - 1) as f64 * p).round() as usize; + *z.select_nth_unstable_by(k, f64::total_cmp).1 + }; + let ratio = q(z, 0.9) / q(z, 0.5).max(1e-300); + // A standard error of about 0.1 on the ratio for a few hundred Ds: within it, normal. + if ratio <= T_TAIL[T_TAIL.len() - 1].1 + 0.1 { + return f64::INFINITY; + } + let mut nu_d = 3.0; + for p in T_TAIL.windows(2) { + let ((n0, r0), (n1, r1)) = (p[0], p[1]); + if ratio <= r0 && ratio > r1 { + nu_d = if n1.is_finite() { + n0 + (r0 - ratio) / (r0 - r1) * (n1 - n0) + } else { + n0 + }; + break; + } + } + (4.0 + 0.37 * (nu_d - 4.0)).max(3.0) +} + +/// Calibrate from every edge's stencils: per class `s²`, and the pooled tail. +/// +/// A stencil whose positions bend by more than [`LEAK_CURVATURE`] (a corner, a tight curve) +/// carries the geometry's own fourth difference, but on a noisy intake the noise bends every +/// stencil that much: so the gate is the larger of that and three standard deviations of a +/// second difference under the noise found so far, starting from all stencils and settling +/// in a few rounds. +pub fn calibrate(stencils: &[Stencil]) -> Calibration { + let pairs = |sel: &dyn Fn(&Stencil) -> bool| -> Vec<(f64, f64)> { + stencils + .iter() + .filter(|s| sel(s)) + .map(|s| (s.d, s.v)) + .collect() + }; + // A typical window's rounding variance: Σ wᵢ² Vᵢ / 70. + let mut vq: Vec = stencils.iter().map(|s| s.v / W4_SQ).collect(); + let v_typ = if vq.is_empty() { + 0.0 + } else { + let k = vq.len() / 2; + *vq.select_nth_unstable_by(k, f64::total_cmp).1 + }; + let mut s2 = solve_extra(&pairs(&|_| true)); + let mut gate = LEAK_CURVATURE; + for _ in 0..4 { + gate = LEAK_CURVATURE.max(6.0 * (6.0 * (v_typ + s2)).sqrt()); + s2 = solve_extra(&pairs(&|s| s.bend < gate)); + } + let all = s2; + let mut out = Calibration::NONE; + for c in [Class::Straight, Class::Curved] { + let mine = pairs(&|s| s.class == c && s.bend < gate); + out.count[c as usize] = mine.len(); + out.extra[c as usize] = if mine.len() >= MIN_D { + solve_extra(&mine) + } else { + all + }; + } + let mut z: Vec = stencils + .iter() + .filter(|s| s.bend < gate) + .map(|s| { + s.d / (s.v + W4_SQ * out.extra[s.class as usize]) + .max(1e-300) + .sqrt() + }) + .collect(); + out.nu = tail_nu(&mut z); + out +} + +/// Candidate sampling lattices, samples per pixel along each axis. +const LATTICES: [u32; 5] = [4, 8, 16, 32, 64]; + +/// The sampling lattice of a point-sampled renderer, read from the image: on an axis-aligned +/// edge (a replica stretch whose windows hold one partial pixel) such a renderer's coverage is +/// a multiple of `1/n`, then rounded to 8 bits. `values` are those coverages with the +/// half-width of their rounding. The smallest `n` that at least 90 % of them sit on, where a +/// random coverage would sit on it at most half the time; `None` for an exact-area renderer +/// (or too few informative stretches to tell, fewer than 8). +pub fn detect_lattice(values: &[(f64, f64)]) -> Option { + // A coverage of one half sits on every lattice, and drawings put edges on half pixels by + // design (a 64-unit icon at 128 px): such values say nothing about `n`, and an edge there + // has no lattice error anyway. + let values: Vec<(f64, f64)> = values + .iter() + .copied() + .filter(|&(c, half)| (c - 0.5).abs() > half + 1e-9) + .collect(); + if values.len() < 8 { + return None; + } + for n in LATTICES { + let nf = n as f64; + let (mut hits, mut chance) = (0usize, 0.0); + for &(c, half) in &values { + let d = (c * nf - (c * nf).round()).abs() / nf; + if d <= half + 1e-9 { + hits += 1; + } + chance += (2.0 * (half + 1e-9) * nf).min(1.0); + } + let k = values.len() as f64; + if hits as f64 >= 0.9 * k && chance <= 0.5 * k { + return Some(n); + } + } + None +} diff --git a/crates/inkvec-trace/src/evidence/reports.rs b/crates/inkvec-trace/src/evidence/reports.rs new file mode 100644 index 00000000..7a2ed983 --- /dev/null +++ b/crates/inkvec-trace/src/evidence/reports.rs @@ -0,0 +1,262 @@ +//! What the boundary chain reports where runs end: corner proposals along runs, junctions +//! with their arms in cyclic order and candidate continuations, and which edges share the +//! renderer floor's per-edge offset (`docs/theory/chain-boundary.md`, B3; amendments A3, A4). + +use std::f64::consts::PI; + +use inkvec_core::likelihood::{Arm, CornerProposal, JunctionReport, RunObs}; +use inkvec_core::Point; + +use crate::planar::PlanarMap; + +use super::windows::crossing; + +/// The fourth difference `h₋₂ − 4h₋₁ + 6h₀ − 4h₁ + h₂` of five consecutive windows' mean +/// positions annihilates every cubic (so it is zero on a smooth run to the quartic term) and +/// has variance `Σ wᵢ² Vᵢ`, `70 V` for equal variances; a slope change `Δs` at its centre gives +/// it `1.25 Δs` at most. `strip.rs`'s one-sided corner test is this divided by 12. A window +/// whose `|D|` is at least `z_min` standard deviations and a local maximum along the run is +/// proposed; a constant or linear bias shared by the windows (the renderer floor's per-edge +/// offset) cancels in `D`. +pub(super) fn corners( + edge: u32, + obs: &[RunObs], + closed: bool, + z_min: f64, + lossy: bool, +) -> Vec { + const W: [f64; 5] = [1.0, -4.0, 6.0, -4.0, 1.0]; + let n = obs.len(); + let mut z = vec![0.0f64; n]; + if n < 5 { + return Vec::new(); + } + // On a closed edge the stencil wraps round its seam. + let centres: Vec = if closed { + (0..n).collect() + } else { + (2..n - 2).collect() + }; + for i in centres { + let five: Vec = (0..5).map(|k| obs[(i + n + k - 2) % n]).collect(); + let five = &five[..]; + let a0 = five[0].window.axis; + let consecutive = five + .windows(2) + .all(|p| p[1].window.axis == a0 && (p[1].window.line - p[0].window.line).abs() == 1) + && five.iter().all(|o| o.window.axis == a0); + let monotone = (five[1].window.line - five[0].window.line) + == (five[4].window.line - five[3].window.line); + if !consecutive || !monotone { + continue; + } + let d: f64 = five.iter().zip(W).map(|(o, w)| w * o.mean_position()).sum(); + let v: f64 = five.iter().zip(W).map(|(o, w)| w * w * o.var).sum(); + z[i] = d.abs() / v.max(1e-300).sqrt(); + } + let mut out = Vec::new(); + for i in 0..n { + if z[i] < z_min { + continue; + } + let left = if i > 0 { + z[i - 1] + } else if closed { + z[n - 1] + } else { + 0.0 + }; + let right = if i + 1 < n { + z[i + 1] + } else if closed { + z[0] + } else { + 0.0 + }; + // The checker generated from `cornerExcessK` must agree that |D| ≥ z_min·σ_D. + let five: Vec<&RunObs> = (0..5).map(|k| &obs[(i + n + k - 2) % n]).collect(); + let h = [0, 1, 2, 3, 4].map(|k| five[k].mean_position()); + let v = [0, 1, 2, 3, 4].map(|k| five[k].var); + // On a JPEG an 8 × 8 block boundary steps the error between blocks: a proposal centred + // on a window by such a boundary must clear twice the threshold. + let block = lossy && matches!(obs[i].window.line.rem_euclid(8), 0 | 7); + let need = if block { 2.0 * z_min } else { z_min }; + if z[i] >= need && z[i] >= left && z[i] > right && super::checks::certify_corner(h, v, need) + { + out.push(CornerProposal { + edge, + index: i, + z: z[i], + at: crossing(&obs[i]), + }); + } + } + out +} + +/// Whether an edge's windows run within one lattice step of an axis or a diagonal (`n` +/// samples per pixel): there the renderer's per-sample-column rounding errors coincide and +/// add to one offset per edge. Decided by the majority of its windows, from the slope +/// between neighbouring windows' mean positions. +pub(super) fn on_lattice(obs: &[RunObs], n: u32) -> bool { + let step = 1.0 / n.max(1) as f64; + let (mut near, mut all) = (0usize, 0usize); + for p in obs.windows(2) { + let (a, b) = (&p[0], &p[1]); + if a.window.axis != b.window.axis || (b.window.line - a.window.line).abs() != 1 { + continue; + } + let t = (b.mean_position() - a.mean_position()).abs(); + all += 1; + if t < step || (t - 1.0).abs() < step { + near += 1; + } + } + all > 0 && 2 * near >= all +} + +/// One arm's outward direction and its standard deviation, from the edge's points within +/// `reach` px of the junction (a weighted least-squares line through them, its direction +/// pointing away from the node), or `None` when fewer than three points lie there. +fn arm( + map: &PlanarMap, + e: usize, + at_start: bool, + node: Point, + reach: f64, + sigma: f64, +) -> Option { + let pts = &map.edges[e].points; + let ordered: Vec = if at_start { + pts.to_vec() + } else { + pts.iter().rev().copied().collect() + }; + let near: Vec = ordered + .iter() + .skip(1) + .take_while(|p| p.dist(node) <= reach) + .copied() + .collect(); + if near.len() < 3 { + return None; + } + let n = near.len() as f64; + let (mx, my) = near + .iter() + .fold((0.0, 0.0), |(a, b), p| (a + p.x / n, b + p.y / n)); + let (mut sxx, mut syy, mut sxy) = (0.0, 0.0, 0.0); + for p in &near { + let (dx, dy) = (p.x - mx, p.y - my); + sxx += dx * dx; + syy += dy * dy; + sxy += dx * dy; + } + let th = 0.5 * (2.0 * sxy).atan2(sxx - syy); + let (mut ux, mut uy) = (th.cos(), th.sin()); + // Point away from the node. + if (mx - node.x) * ux + (my - node.y) * uy < 0.0 { + ux = -ux; + uy = -uy; + } + // Spread along the line and residual across it: the slope's standard error. + let along: f64 = near + .iter() + .map(|p| ((p.x - mx) * ux + (p.y - my) * uy).powi(2)) + .sum(); + let across: f64 = near + .iter() + .map(|p| ((p.x - mx) * -uy + (p.y - my) * ux).powi(2)) + .sum(); + let resid_var = (across / (n - 2.0).max(1.0)).max(sigma * sigma); + let sd = (resid_var / along.max(1e-12)).sqrt().max(1e-4); + Some(Arm { + edge: e as u32, + at_start, + direction: uy.atan2(ux), + direction_sd: sd, + }) +} + +/// Junction reports: every node where three or more edge ends meet, its arms in increasing +/// direction, and each pair of arms leaving in opposite directions to within `z_max` +/// standard deviations (a curve that may continue through the junction, R2.9). +pub(super) fn junctions( + map: &PlanarMap, + reach: f64, + sigma: f64, + z_max: f64, +) -> Vec { + use std::collections::BTreeMap; + let mut ends: BTreeMap> = BTreeMap::new(); + for (k, e) in map.edges.iter().enumerate() { + if e.closed || e.points.len() < 2 { + continue; + } + ends.entry(e.start_node).or_default().push((k, true)); + ends.entry(e.end_node).or_default().push((k, false)); + } + let mut out = Vec::new(); + for (node, list) in ends { + if list.len() < 3 { + continue; + } + let first = list[0]; + let e0 = &map.edges[first.0]; + let at = if first.1 { + e0.points[0] + } else { + *e0.points.last().expect("two points") + }; + let mut arms: Vec = list + .iter() + .filter_map(|&(e, s)| arm(map, e, s, at, reach, sigma)) + .collect(); + arms.sort_by(|a, b| a.direction.total_cmp(&b.direction)); + let mut cont = Vec::new(); + for i in 0..arms.len() { + for j in i + 1..arms.len() { + let mut d = arms[j].direction - arms[i].direction - PI; + d = (d + PI).rem_euclid(2.0 * PI) - PI; + let sd = arms[i].direction_sd.hypot(arms[j].direction_sd); + let z = d.abs() / sd; + if z <= z_max { + cont.push((i, j, z)); + } + } + } + out.push(JunctionReport { + node, + at, + arms, + continuations: cont, + }); + } + out +} + +/// Boundary length of the starting geometry inside a window, from its windows' slope: +/// `√(1 + t²)` for a slope `t` across the strip (B2.5). +pub(super) fn window_lengths(obs: &[RunObs]) -> Vec { + let n = obs.len(); + (0..n) + .map(|i| { + let slope = |a: &RunObs, b: &RunObs| { + if a.window.axis == b.window.axis && (b.window.line - a.window.line).abs() == 1 { + Some((b.mean_position() - a.mean_position()).abs()) + } else { + None + } + }; + let t = match ( + (i > 0).then(|| slope(&obs[i - 1], &obs[i])).flatten(), + (i + 1 < n).then(|| slope(&obs[i], &obs[i + 1])).flatten(), + ) { + (Some(a), Some(b)) => 0.5 * (a + b), + (Some(a), None) | (None, Some(a)) => a, + (None, None) => 0.0, + }; + (1.0 + t * t).sqrt() + }) + .collect() +} diff --git a/crates/inkvec-trace/src/evidence/windows.rs b/crates/inkvec-trace/src/evidence/windows.rs new file mode 100644 index 00000000..bd46dbc8 --- /dev/null +++ b/crates/inkvec-trace/src/evidence/windows.rs @@ -0,0 +1,430 @@ +//! The partition of an edge's partial pixels into column and row windows, and the +//! measurement each window makes (`docs/theory/chain-boundary.md`, B2.2). +//! +//! Every pixel within reach of the starting map is claimed by its nearest edge. A pixel +//! claimed within reach by two edges, or within the local radius of a junction node, belongs +//! to that junction's local term instead of a run. Of an edge's own pixels, those whose +//! unmixed weight is strictly between its two faces' (the partial pixels) are classed by the +//! edge's direction at their nearest point: column where it runs within 45° of horizontal, +//! row elsewhere. A window is a maximal run of one class's partial pixels along one column +//! (row), extended by the pure pixel at each end when that pixel is free. So every partial +//! pixel is in exactly one window, whatever the direction, including where the edge turns +//! through 45° (where a column's run ends a row's begins, and neither takes the other's +//! pixels); `windows_partition_every_partial_pixel` in the tests checks it. + +use inkvec_core::likelihood::{Axis, RunObs, Window}; +use inkvec_core::Point; + +use crate::planar::PlanarMap; + +/// What the nearest (and second nearest) edges say about one pixel. +#[derive(Debug, Clone, Copy)] +pub(super) struct Claim { + /// Nearest edge, or `u32::MAX`. + pub(super) edge: u32, + /// Its distance from the pixel centre, px. + pub(super) dist: f64, + /// Arclength of the nearest point along the edge, px. + pub(super) s: f64, + /// Unit tangent of the edge there. + pub(super) t: (f64, f64), + /// Second nearest edge (another edge), or `u32::MAX`. + pub(super) edge2: u32, + /// Its distance, px. + pub(super) dist2: f64, + /// Whether the pixel lies on the nearest edge's left (`(t.y, −t.x)` of its direction). + pub(super) left: bool, +} + +impl Default for Claim { + fn default() -> Self { + Claim { + edge: u32::MAX, + dist: f64::INFINITY, + s: 0.0, + t: (1.0, 0.0), + edge2: u32::MAX, + dist2: f64::INFINITY, + left: false, + } + } +} + +/// Per pixel (row-major), the nearest and second nearest edges within `reach` px of its +/// centre, by distance to each edge's polyline. `O(points × reach²)`. +pub(super) fn claims(map: &PlanarMap, reach: f64) -> Vec { + let (w, h) = (map.width as i64, map.height as i64); + let mut out = vec![Claim::default(); (w * h) as usize]; + for (k, e) in map.edges.iter().enumerate() { + let k = k as u32; + let pts = &e.points; + let n = pts.len(); + let segs = if e.closed { n } else { n.saturating_sub(1) }; + let mut s_acc = 0.0; + for i in 0..segs { + let (a, b) = (pts[i], pts[(i + 1) % n]); + let (dx, dy) = (b.x - a.x, b.y - a.y); + let len = dx.hypot(dy); + let t = if len > 1e-12 { + (dx / len, dy / len) + } else { + (1.0, 0.0) + }; + let x0 = (a.x.min(b.x) - reach).floor().max(0.0) as i64; + let x1 = (a.x.max(b.x) + reach).ceil().min((w - 1) as f64) as i64; + let y0 = (a.y.min(b.y) - reach).floor().max(0.0) as i64; + let y1 = (a.y.max(b.y) + reach).ceil().min((h - 1) as f64) as i64; + for y in y0..=y1 { + for x in x0..=x1 { + let (px, py) = (x as f64, y as f64); + let u = if len > 1e-12 { + (((px - a.x) * dx + (py - a.y) * dy) / (len * len)).clamp(0.0, 1.0) + } else { + 0.0 + }; + let (qx, qy) = (a.x + u * dx, a.y + u * dy); + let d = (px - qx).hypot(py - qy); + if d > reach { + continue; + } + let left = (px - qx) * t.1 - (py - qy) * t.0 > 0.0; + let c = &mut out[(y * w + x) as usize]; + if c.edge == k { + if d < c.dist { + c.dist = d; + c.s = s_acc + u * len; + c.t = t; + c.left = left; + } + } else if d < c.dist { + if c.edge != u32::MAX { + c.edge2 = c.edge; + c.dist2 = c.dist; + } + c.edge = k; + c.dist = d; + c.s = s_acc + u * len; + c.t = t; + c.left = left; + } else if c.edge2 == k { + c.dist2 = c.dist2.min(d); + } else if d < c.dist2 { + c.edge2 = k; + c.dist2 = d; + } + } + } + s_acc += len; + } + } + out +} + +/// One pixel's unmixed measurement against an edge's two faces. +#[derive(Debug, Clone, Copy)] +pub(super) struct Unmixed { + /// Weight of the left face, unclamped. + pub(super) a: f64, + /// Variance of `a` from quantisation (and measured noise above it). + pub(super) var: f64, + /// Whether the pixel is a mixture of the two faces (not pure, within half a level). + pub(super) partial: bool, + /// Whether the colour lies off the line through the two faces' colours (a third ink). + pub(super) third: bool, +} + +/// The two faces' colours an edge is unmixed against, and the per-pixel variance model. +#[derive(Debug, Clone, Copy)] +pub(super) struct Axis2 { + /// Right face's colour (weight 0). + pub(super) cr: [f64; 3], + /// `left − right`. + pub(super) d: [f64; 3], + /// `|d|²`. + pub(super) dd: f64, + /// Variance of the unmixed weight of a partial pixel. + pub(super) var_partial: f64, + /// Variance of a pure pixel's (measured noise beyond quantisation, usually 0). + pub(super) var_pure: f64, + /// Variance of the weight of a pixel the source drew partly over the clear ground: there + /// the intake rounds the alpha, not the colour, so the weight is the alpha to within + /// `Q²/12` whatever the contrast. + pub(super) var_alpha: f64, + /// Half a quantisation level, in weight units: a pixel this close to 0 or 1 is pure. + pub(super) pure_tol: f64, + /// Squared distance off the colour line beyond which a pixel holds a third ink. + pub(super) third_tol2: f64, + /// Unmix on luma alone (a lossy intake with subsampled chroma): `None` for full colour, + /// else the right face's luma and `luma(left) − luma(right)`. + pub(super) luma: Option<(f64, f64)>, +} + +/// JPEG's luma (ITU-R BT.601 weights on the encoded sRGB values): the one channel a 4:2:0 +/// file keeps at full resolution. +pub(super) fn jpeg_luma(c: [f64; 3]) -> f64 { + 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2] +} + +/// 8-bit quantisation step. +const Q: f64 = 1.0 / 255.0; + +impl Axis2 { + /// The axis from `right` (weight 0) to `left` (weight 1), with pixel noise `sigma_noise` + /// (sRGB units). Quantisation's variance per channel is `Q²/12`; channels whose two + /// colours agree to within a level round together (a grey axis rounds all three alike), + /// so their errors are summed before squaring: `var = Σ_groups (Σ_{c∈g} d_c)² Q²/12 / |d|⁴` + /// (`chain-boundary.md` B1.2). Noise measured above half a level adds `σ²/|d|²`. + pub(super) fn new(left: [f32; 3], right: [f32; 3], sigma_noise: f64) -> Self { + let cl = [left[0] as f64, left[1] as f64, left[2] as f64]; + let cr = [right[0] as f64, right[1] as f64, right[2] as f64]; + let d = [cl[0] - cr[0], cl[1] - cr[1], cl[2] - cr[2]]; + let dd = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).max(1e-300); + // Group channels whose (right, left) colours agree to within a level. + let mut grouped = [false; 3]; + let mut qsum = 0.0; + for i in 0..3 { + if grouped[i] { + continue; + } + let mut g = d[i]; + for j in i + 1..3 { + if !grouped[j] && (cr[i] - cr[j]).abs() < Q && (cl[i] - cl[j]).abs() < Q { + grouped[j] = true; + g += d[j]; + } + } + qsum += g * g; + } + let var_q = qsum * Q * Q / 12.0 / (dd * dd); + let extra = (sigma_noise * sigma_noise - 0.25 * Q * Q).max(0.0) / dd; + Axis2 { + cr, + d, + dd, + var_partial: var_q + extra, + var_pure: extra, + var_alpha: Q * Q / 12.0 + extra, + pure_tol: 0.5 * Q / dd.sqrt(), + third_tol2: (4.0 * sigma_noise.max(Q)).powi(2), + luma: None, + } + } + + /// The axis for a lossy intake whose chroma is subsampled (4:2:0): the weight is read from + /// luma, the channel kept at full resolution, as `(Y − Y_right)/(Y_left − Y_right)`, when + /// the two inks' lumas differ by at least `min_contrast`; otherwise `None` (a nearly + /// isoluminant pair, unmixed in full colour). Chroma bleeds a pixel or more across every + /// edge there, so the third-ink test allows `chroma_tol` off the colour line. + pub(super) fn luma_of(self, min_contrast: f64, chroma_tol: f64) -> Option { + let yr = jpeg_luma(self.cr); + let cl = [ + self.cr[0] + self.d[0], + self.cr[1] + self.d[1], + self.cr[2] + self.d[2], + ]; + let dy = jpeg_luma(cl) - yr; + if dy.abs() < min_contrast { + return None; + } + // Rounding of the three channels, through the luma weights. + let wq = 0.299f64.powi(2) + 0.587f64.powi(2) + 0.114f64.powi(2); + let var_q = wq * Q * Q / 12.0 / (dy * dy); + let extra = self.var_pure * self.dd / (dy * dy); + Some(Axis2 { + var_partial: var_q + extra, + var_pure: extra, + pure_tol: 0.5 * Q / dy.abs(), + third_tol2: chroma_tol * chroma_tol, + luma: Some((yr, dy)), + ..self + }) + } + + /// Unmix colour `p` (composited onto white); `alpha` is the source's alpha there when the + /// intake had one. A pixel the source drew partly over the clear ground (alpha strictly + /// between 0 and 1 by half a level) is partial whatever its contrast, with the alpha's + /// rounding as its variance. + pub(super) fn unmix(&self, p: [f32; 3], alpha: Option) -> Unmixed { + let q = [ + p[0] as f64 - self.cr[0], + p[1] as f64 - self.cr[1], + p[2] as f64 - self.cr[2], + ]; + let a = match self.luma { + Some((yr, dy)) => (jpeg_luma([p[0] as f64, p[1] as f64, p[2] as f64]) - yr) / dy, + None => (q[0] * self.d[0] + q[1] * self.d[1] + q[2] * self.d[2]) / self.dd, + }; + let r2: f64 = (0..3).map(|c| (q[c] - a * self.d[c]).powi(2)).sum(); + let clear = alpha + .map(|v| v as f64) + .filter(|&v| v > 0.5 * Q && v < 1.0 - 0.5 * Q); + let (partial, var) = match clear { + Some(_) => (true, self.var_alpha), + None if a > self.pure_tol && a < 1.0 - self.pure_tol => (true, self.var_partial), + None => (false, self.var_pure), + }; + Unmixed { + a, + var, + partial, + third: r2 > self.third_tol2, + } + } +} + +/// A pixel taking part in an edge's runs. +#[derive(Debug, Clone, Copy)] +pub(super) struct RunPixel { + pub(super) x: i32, + pub(super) y: i32, + pub(super) m: Unmixed, + pub(super) s: f64, + pub(super) t: (f64, f64), + /// Whether the pixel goes to a column window (else a row window). + pub(super) column: bool, +} + +/// Along an edge, which stretches are read by column windows and which by row windows on a +/// soft intake: the direction smoothed over `±SMOOTH` px of arclength, with a hysteresis of +/// `HYSTERESIS` either side of 45°, so that a noisy polyline near a diagonal does not cut the +/// blurred ramp into alternating fragments (each of which would lose mass to the next). +/// Returns breakpoints `(s, column)`: from `s` on, until the next, the class is `column`. +pub(super) fn class_profile(points: &[Point], closed: bool) -> Vec<(f64, bool)> { + const SMOOTH: f64 = 2.0; + const HYSTERESIS: f64 = 0.15; // radians, about 8.6 degrees + let n = points.len(); + if n < 2 { + return vec![(0.0, true)]; + } + let m = if closed { n + 1 } else { n }; + let at = |k: usize| points[k % n]; + let mut s = vec![0.0; m]; + for k in 1..m { + s[k] = s[k - 1] + at(k).dist(at(k - 1)); + } + let total = s[m - 1]; + // The point at arclength `u` (clamped on an open edge, wrapped on a closed one). + let point_at = |u: f64| -> Point { + let u = if closed && total > 0.0 { + u.rem_euclid(total) + } else { + u.clamp(0.0, total) + }; + let k = s.partition_point(|&v| v <= u).clamp(1, m - 1); + let (a, b) = (at(k - 1), at(k)); + let l = s[k] - s[k - 1]; + let f = if l > 0.0 { (u - s[k - 1]) / l } else { 0.0 }; + Point::new(a.x + f * (b.x - a.x), a.y + f * (b.y - a.y)) + }; + let mut out: Vec<(f64, bool)> = Vec::new(); + let mut cur: Option = None; + for &u in s.iter().take(n) { + let (a, b) = (point_at(u - SMOOTH), point_at(u + SMOOTH)); + let ang = (b.y - a.y).abs().atan2((b.x - a.x).abs()); // 0: horizontal, π/2: vertical + let want = match cur { + None => ang <= std::f64::consts::FRAC_PI_4, + Some(true) => ang <= std::f64::consts::FRAC_PI_4 + HYSTERESIS, + Some(false) => ang < std::f64::consts::FRAC_PI_4 - HYSTERESIS, + }; + if cur != Some(want) { + out.push((u, want)); + cur = Some(want); + } + } + out +} + +/// The class `profile` gives arclength `s`. +pub(super) fn class_at(profile: &[(f64, bool)], s: f64) -> bool { + let k = profile.partition_point(|&(u, _)| u <= s); + profile[k.saturating_sub(1)].1 +} + +/// Group an edge's partial pixels into windows; `free(x, y)` says whether a pixel may be taken +/// as a pure flank (and marks it taken). Returns the run observations in order of `s`, each +/// with the variance of its sum from quantisation alone, and for each the pixels it holds. +pub(super) fn group( + px: &[RunPixel], + flank: &mut dyn FnMut(i32, i32) -> Option, +) -> Vec<(RunObs, Vec<(i32, i32)>)> { + let mut out: Vec<(RunObs, Vec<(i32, i32)>)> = Vec::new(); + for axis in [Axis::Column, Axis::Row] { + let mut mine: Vec<&RunPixel> = px + .iter() + .filter(|p| p.m.partial && p.column == (axis == Axis::Column)) + .collect(); + // Sort by line, then position along it. + mine.sort_by_key(|p| match axis { + Axis::Column => (p.x, p.y), + Axis::Row => (p.y, p.x), + }); + let line_pos = |p: &RunPixel| match axis { + Axis::Column => (p.x, p.y), + Axis::Row => (p.y, p.x), + }; + let mut i = 0; + while i < mine.len() { + let (line, start) = line_pos(mine[i]); + let mut j = i; + while j + 1 < mine.len() && line_pos(mine[j + 1]) == (line, line_pos(mine[j]).1 + 1) { + j += 1; + } + let run = &mine[i..=j]; + let (mut lo, mut hi) = (start, start + (j - i) as i32); + let mut sum: f64 = run.iter().map(|p| p.m.a).sum(); + let mut var: f64 = run.iter().map(|p| p.m.var).sum(); + let mut pix: Vec<(i32, i32)> = run.iter().map(|p| (p.x, p.y)).collect(); + let at = |k: i32| match axis { + Axis::Column => (line, k), + Axis::Row => (k, line), + }; + if let Some(m) = flank(at(lo - 1).0, at(lo - 1).1) { + lo -= 1; + sum += m.a; + var += m.var; + pix.insert(0, at(lo)); + } + if let Some(m) = flank(at(hi + 1).0, at(hi + 1).1) { + hi += 1; + sum += m.a; + var += m.var; + pix.push(at(hi)); + } + let n = run.len() as f64; + let s = run.iter().map(|p| p.s).sum::() / n; + let (tx, ty) = run + .iter() + .fold((0.0, 0.0), |(a, b), p| (a + p.t.0, b + p.t.1)); + // The left face lies on (t.y, -t.x): above a column when walking +x; west of a + // row when walking -y. + let left_low = match axis { + Axis::Column => tx > 0.0, + Axis::Row => ty < 0.0, + }; + out.push(( + RunObs { + window: Window { axis, line, lo, hi }, + s, + sum, + var, + left_low, + share: 1.0, + }, + pix, + )); + i = j + 1; + } + } + out.sort_by(|a, b| a.0.s.total_cmp(&b.0.s)); + out +} + +/// The point where window `o` meets the starting geometry: its line and its measured mean +/// position. +pub(super) fn crossing(o: &RunObs) -> Point { + let m = o.mean_position(); + match o.window.axis { + Axis::Column => Point::new(o.window.line as f64, m), + Axis::Row => Point::new(m, o.window.line as f64), + } +} diff --git a/crates/inkvec-trace/src/evidence_tests.rs b/crates/inkvec-trace/src/evidence_tests.rs new file mode 100644 index 00000000..a87a4828 --- /dev/null +++ b/crates/inkvec-trace/src/evidence_tests.rs @@ -0,0 +1,969 @@ +use super::*; +use crate::planar; +use inkvec_core::likelihood::{left_area, Axis}; +use inkvec_core::Point; +use std::f64::consts::PI; + +/// Exact area coverage of each layer (simple polygons, pairwise disjoint: they may abut but +/// not overlap) per pixel, composited over `bg`, optionally rounded to 8 bits; the label of +/// each pixel is its largest face; faces are `bg` then the layers. +struct Scene { + w: usize, + h: usize, + rgb: Vec<[f32; 3]>, + cov: Vec>, // per layer, the visible coverage + labels: Vec, + faces: Vec, +} + +fn render( + w: usize, + h: usize, + bg: [f32; 3], + layers: &[(Vec, [f32; 3])], + quantise: bool, +) -> Scene { + let n = layers.len(); + let mut raw: Vec> = vec![vec![0.0; w * h]; n]; + for (k, (poly, _)) in layers.iter().enumerate() { + let (x0, x1) = poly + .iter() + .fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), p| { + (a.min(p.x), b.max(p.x)) + }); + let (y0, y1) = poly + .iter() + .fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), p| { + (a.min(p.y), b.max(p.y)) + }); + for y in (y0.floor().max(0.0) as usize)..=(y1.ceil() as usize).min(h - 1) { + for x in (x0.floor().max(0.0) as usize)..=(x1.ceil() as usize).min(w - 1) { + raw[k][y * w + x] = local::area_in_pixel(poly, x as i32, y as i32); + } + } + } + let cov = raw; + for i in 0..w * h { + assert!( + cov.iter().map(|l| l[i]).sum::() <= 1.0 + 1e-9, + "layers overlap" + ); + } + let mut rgb = vec![[0f32; 3]; w * h]; + let mut labels = vec![0u16; w * h]; + for i in 0..w * h { + let mut c = [0f64; 3]; + let mut used = 0.0; + let mut best = (1.0 - cov.iter().map(|l| l[i]).sum::(), 0u16); + for (k, (_, col)) in layers.iter().enumerate() { + for ch in 0..3 { + c[ch] += cov[k][i] * col[ch] as f64; + } + used += cov[k][i]; + if cov[k][i] > best.0 { + best = (cov[k][i], k as u16 + 1); + } + } + for ch in 0..3 { + c[ch] += (1.0 - used) * bg[ch] as f64; + if quantise { + c[ch] = (c[ch] * 255.0).round() / 255.0; + } + rgb[i][ch] = c[ch] as f32; + } + labels[i] = best.1; + } + let mut faces = vec![FillModel::Flat(bg)]; + faces.extend(layers.iter().map(|(_, c)| FillModel::Flat(*c))); + Scene { + w, + h, + rgb, + cov, + labels, + faces, + } +} + +fn map_of(s: &Scene) -> PlanarMap { + let mut map = planar::build(&s.labels, s.w, s.h, s.faces.len()); + planar::refine_subpixel(&mut map, &s.rgb, &s.faces, 0.5 / 255.0, false); + map +} + +fn disc(cx: f64, cy: f64, r: f64, n: usize) -> Vec { + // Area-matched polygon, as `bench/theory/exact_raster.py` draws discs. + let rr = r * ((2.0 * PI / n as f64) / (2.0 * PI / n as f64).sin()).sqrt(); + (0..n) + .map(|k| { + let t = 2.0 * PI * k as f64 / n as f64; + Point::new(cx + rr * t.cos(), cy + rr * t.sin()) + }) + .collect() +} + +fn square(cx: f64, cy: f64, half: f64, rot: f64) -> Vec { + (0..4) + .map(|k| { + let t = rot + PI / 4.0 + k as f64 * PI / 2.0; + Point::new( + cx + half * 2f64.sqrt() * t.cos(), + cy + half * 2f64.sqrt() * t.sin(), + ) + }) + .collect() +} + +/// The polygon as line pieces, closed, in its own order or reversed. +fn pieces(poly: &[Point], reverse: bool) -> Vec { + let mut p: Vec = poly.to_vec(); + if reverse { + p.reverse(); + } + let n = p.len(); + (0..n) + .map(|k| Piece::Line([p[k], p[(k + 1) % n]])) + .collect() +} + +fn exact_floor() -> EvidenceOptions { + EvidenceOptions { + floor: Some(Floor { + lattice: 1_000_000, + window_var: 0.0, + edge_var: 0.0, + }), + ..EvidenceOptions::default() + } +} + +const B: [f32; 3] = [0.0, 0.0, 0.0]; +const WHITE: [f32; 3] = [1.0, 1.0, 1.0]; + +/// Every partial pixel is in exactly one run window, local term, thin strip or third-ink +/// list; no pixel is in two windows. Discs and rotated squares cover every direction, +/// including the switches between columns and rows at 45°. +#[test] +fn windows_partition_every_partial_pixel() { + let shapes: Vec> = vec![ + disc(31.4, 30.2, 17.3, 720), + disc(32.0, 32.0, 9.6, 720), + square(31.7, 32.2, 13.0, 0.3), + square(30.9, 31.4, 15.0, PI / 4.0 + 0.01), + ]; + for poly in shapes { + let s = render(64, 64, WHITE, &[(poly, B)], false); + let map = map_of(&s); + let ev = build(&map, &s.rgb, &s.faces, 0.5 / 255.0, &exact_floor()); + let mut count = vec![0u32; s.w * s.h]; + let mut in_windows = vec![0u32; s.w * s.h]; + for e in 0..ev.edge_count() { + for i in 0..ev.runs(e).len() { + for &(x, y) in ev.window_pixels(e, i) { + count[y as usize * s.w + x as usize] += 1; + in_windows[y as usize * s.w + x as usize] += 1; + } + } + } + for j in ev.junctions() { + for (x, y) in ev.local_pixels(j.node) { + count[y as usize * s.w + x as usize] += 1; + } + } + for i in 0..ev.corners().len() { + for (x, y) in ev.corner_pixels(i) { + count[y as usize * s.w + x as usize] += 1; + } + } + for &(x, y) in ev.strip_pixels().iter().chain(ev.third_pixels()) { + count[y as usize * s.w + x as usize] += 1; + } + let tol = 0.5 / 255.0 / 3f64.sqrt(); + let mut partial = 0; + for i in 0..s.w * s.h { + assert!( + in_windows[i] <= 1, + "pixel {} in {} windows", + i, + in_windows[i] + ); + let c = s.cov[0][i]; + if c > tol && c < 1.0 - tol { + partial += 1; + assert_eq!( + count[i], + 1, + "partial pixel ({}, {}) cov {c:.4} counted {}", + i % s.w, + i / s.w, + count[i] + ); + } + } + assert!(partial > 50); + } +} + +/// On an exact render, every run window's sum is the area the true curve gives the edge's +/// left face there (the window identity), to rounding: sums of exact coverages against the +/// evaluator's closed-form integrals. +#[test] +fn window_sums_are_exact_areas() { + for (poly, ink) in [ + (disc(31.4, 30.2, 17.3, 720), B), + (square(31.7, 32.2, 13.0, 0.3), B), + (square(31.7, 32.2, 13.0, 0.3), [0.9, 0.3, 0.1]), + ] { + let s = render(64, 64, WHITE, &[(poly.clone(), ink)], false); + let map = map_of(&s); + let ev = build(&map, &s.rgb, &s.faces, 0.5 / 255.0, &exact_floor()); + let mut checked = 0; + for e in 0..ev.edge_count() { + let obs = ev.runs(e); + if obs.is_empty() { + continue; + } + // The orientation that gives the edge's left face: the one matching window 0. + let fwd = pieces(&poly, false); + let rev = pieces(&poly, true); + let curve = if (left_area(&fwd, &obs[0].window) - obs[0].sum).abs() + < (left_area(&rev, &obs[0].window) - obs[0].sum).abs() + { + fwd + } else { + rev + }; + for o in obs { + let a = left_area(&curve, &o.window); + // The image holds f32: each pixel is rounded to a part in 1e7. + assert!( + (a - o.sum).abs() < 1e-6, + "window {:?}: area {a} sum {}", + o.window, + o.sum + ); + checked += 1; + } + } + assert!(checked > 40, "{checked}"); + } +} + +/// At the truth, with 8-bit quantisation and the variances of B1.2, `χ²/M` is near 1; the +/// certified χ² (the straight-line checker kernel) agrees with the evaluator's. +#[test] +fn the_truth_is_calibrated_and_certified() { + let mut chi = Chi2::default(); + for (k, poly) in [ + disc(31.4, 30.2, 17.3, 720), + disc(30.7, 33.1, 21.9, 720), + square(31.7, 32.2, 13.0, 0.3), + square(32.3, 31.1, 17.0, 1.1), + ] + .into_iter() + .enumerate() + { + // Inks on the 8-bit lattice, as a palette read off pure pixels is: an ink half a level + // off scales every weight by (1 - 0.0025) and shows as a -3σ bias per window. + let l = |v: f32| v / 255.0; + let ink = [ + [l(26.0), l(51.0), l(179.0)], + B, + [l(230.0), l(77.0), l(26.0)], + [0.0, l(128.0), l(128.0)], + ][k]; + let s = render(64, 64, WHITE, &[(poly.clone(), ink)], true); + let map = map_of(&s); + let ev = build(&map, &s.rgb, &s.faces, 0.5 / 255.0, &exact_floor()); + for e in 0..ev.edge_count() { + let obs = ev.runs(e); + if obs.is_empty() { + continue; + } + let fwd = pieces(&poly, false); + let rev = pieces(&poly, true); + let c1 = ev.chi2_run(e, 0..obs.len(), &fwd); + let c2 = ev.chi2_run(e, 0..obs.len(), &rev); + let (best, curve) = if c1.chi2 < c2.chi2 { + (c1, fwd) + } else { + (c2, rev) + }; + chi = chi + best; + let mut closed: Vec = curve + .iter() + .map(|p| match p { + Piece::Line([a, _]) => *a, + _ => unreachable!(), + }) + .collect(); + closed.push(closed[0]); + let cert = checks::certify_run_chi2_polyline(obs, &closed, best.chi2, 1e-9); + assert!(cert.is_ok(), "{cert:?}"); + } + } + let ratio = chi.chi2 / chi.m as f64; + // Measured 0.97 over 442 windows (1.14, 1.03, 0.84, 0.86 by shape; σ of χ²/M ≈ 0.07). + assert!( + chi.m > 300 && (0.8..1.2).contains(&ratio), + "chi2/M = {ratio:.3} over {}", + chi.m + ); +} + +/// A T: a black band over white with a red stem below it. Where the stem meets the band, two +/// junctions; at each, the band's two arms continue one another (A4), and the local term of +/// the true lines is calibrated. +#[test] +fn a_t_junction_reports_its_continuation() { + let (yb, xl, xr) = (30.3, 28.6, 35.2); + let band = vec![ + Point::new(-1.0, -1.0), + Point::new(65.0, -1.0), + Point::new(65.0, yb), + Point::new(-1.0, yb), + ]; + let stem = vec![ + Point::new(xl, yb), + Point::new(xr, yb), + Point::new(xr, 65.0), + Point::new(xl, 65.0), + ]; + let s = render(64, 64, WHITE, &[(band, B), (stem, [0.9, 0.1, 0.1])], true); + let map = map_of(&s); + let ev = build(&map, &s.rgb, &s.faces, 0.5 / 255.0, &exact_floor()); + let js: Vec<&JunctionReport> = ev + .junctions() + .iter() + .filter(|j| { + (j.at.y - yb).abs() < 2.0 && ((j.at.x - xl).abs() < 2.0 || (j.at.x - xr).abs() < 2.0) + }) + .collect(); + assert_eq!( + js.len(), + 2, + "{:?}", + ev.junctions().iter().map(|j| j.at).collect::>() + ); + for j in js { + assert_eq!(j.arms.len(), 3); + // The horizontal pair continues; the stem does not continue either. + let horiz: Vec = (0..3) + .filter(|&k| j.arms[k].direction.sin().abs() < 0.2) + .collect(); + assert_eq!(horiz.len(), 2, "{:?}", j.arms); + assert!( + j.continuations + .iter() + .any(|&(a, b, _)| horiz.contains(&a) && horiz.contains(&b)), + "{:?}", + j.continuations + ); + assert_eq!(j.continuations.len(), 1, "{:?}", j.continuations); + // The local term against the true lines, each oriented as its edge. + let x_j = if (j.at.x - xl).abs() < 2.0 { xl } else { xr }; + let mut curves: Vec<(usize, Vec)> = Vec::new(); + for a in &j.arms { + let e = &map.edges[a.edge as usize]; + let (p0, p1) = (e.points[0], *e.points.last().unwrap()); + let proj = |p: Point| { + if a.direction.sin().abs() < 0.2 { + Point::new(p.x, yb) + } else { + Point::new(x_j, p.y) + } + }; + let (mut q0, mut q1) = (proj(p0), proj(p1)); + if a.at_start { + q0 = Point::new(x_j, yb); + } else { + q1 = Point::new(x_j, yb); + } + curves.push((a.edge as usize, vec![Piece::Line([q0, q1])])); + } + let refs: Vec<(usize, &[Piece])> = curves.iter().map(|(e, c)| (*e, c.as_slice())).collect(); + let c = ev.chi2_local(Owner::Junction(j.node), &refs); + assert!(c.m > 30, "{c:?}"); + let ratio = c.chi2 / c.m as f64; + assert!(ratio < 2.0, "local chi2/M = {ratio:.3} ({c:?})"); + // A vertex one pixel off is many standard deviations worse. + let moved: Vec<(usize, Vec)> = curves + .iter() + .map(|(e, c)| { + let Piece::Line([a, b]) = c[0] else { + unreachable!() + }; + let sh = |p: Point| { + if (p.x - x_j).abs() < 1e-9 && (p.y - yb).abs() < 1e-9 { + Point::new(p.x + 1.0, p.y) + } else { + p + } + }; + (*e, vec![Piece::Line([sh(a), sh(b)])]) + }) + .collect(); + let refs2: Vec<(usize, &[Piece])> = moved.iter().map(|(e, c)| (*e, c.as_slice())).collect(); + let c2 = ev.chi2_local(Owner::Junction(j.node), &refs2); + assert!(c2.chi2 > c.chi2 + 100.0, "{c2:?} vs {c:?}"); + } +} + +/// A square rotated 10°: corner proposals near its four vertices, and few elsewhere. +#[test] +fn corner_proposals_find_the_corners() { + let poly = square(31.7, 32.2, 15.0, 10f64.to_radians()); + let s = render(64, 64, WHITE, &[(poly.clone(), B)], true); + let map = map_of(&s); + let ev = build(&map, &s.rgb, &s.faces, 0.5 / 255.0, &exact_floor()); + let props = ev.corners(); + for v in &poly { + assert!( + props.iter().any(|c| c.at.dist(*v) < 2.5), + "no proposal near {v:?}: {:?}", + props.iter().map(|c| (c.at, c.z)).collect::>() + ); + } + let windows: usize = (0..ev.edge_count()).map(|e| ev.runs(e).len()).sum(); + let false_props = props + .iter() + .filter(|c| poly.iter().all(|v| c.at.dist(*v) >= 2.5)) + .count(); + assert!( + false_props * 10 <= windows, + "{false_props} false proposals over {windows} windows" + ); + // Edges at 10° are not on the lattice; the evidence says so. + assert!((0..ev.edge_count()).all(|e| ev.runs(e).is_empty() || !ev.edge_on_lattice(e))); + // The corner terms, scored against the true square in the edge's direction, are + // calibrated, and a corner cut by a 1 px chamfer is many standard deviations worse + // (pooled over several rotations: most corners lie inside windows the curve crosses, + // and only a few pixels per square go to corner terms). + let mut chi = Chi2::default(); + let mut cut = Chi2::default(); + for deg in [10.0f64, 23.0, 37.0, 52.0, 66.0, 79.0] { + let poly = square(31.7, 32.2, 15.0, deg.to_radians()); + let s = render(64, 64, WHITE, &[(poly.clone(), B)], true); + let map = map_of(&s); + let ev = build(&map, &s.rgb, &s.faces, 0.5 / 255.0, &exact_floor()); + corner_terms_against(&ev, &poly, &mut chi, &mut cut); + } + assert!(chi.m >= 4, "{chi:?}"); + let ratio = chi.chi2 / chi.m as f64; + assert!(ratio < 2.5, "corner chi2/M = {ratio:.3} ({chi:?})"); + assert!(cut.chi2 > chi.chi2 + 100.0, "{cut:?} vs {chi:?}"); + let _ = Axis::Row; +} + +/// Score `ev`'s corner terms against the polygon `poly` (into `chi`) and against it with the +/// nearest vertex chamfered by 1 px (into `cut`). +fn corner_terms_against(ev: &Evidence, poly: &[Point], chi: &mut Chi2, cut: &mut Chi2) { + let props = ev.corners(); + for (i, c) in props.iter().enumerate() { + if ev.corner_pixels(i).is_empty() { + continue; + } + let e = c.edge as usize; + let (f, r) = (pieces(poly, false), pieces(poly, true)); + let cf = ev.chi2_local(Owner::Corner(i as u32), &[(e, &f)]); + let cr = ev.chi2_local(Owner::Corner(i as u32), &[(e, &r)]); + let (best, rev) = if cf.chi2 <= cr.chi2 { + (cf, false) + } else { + (cr, true) + }; + *chi = *chi + best; + // Chamfer the nearest vertex. + let k = (0..4) + .min_by(|&a, &b| poly[a].dist(c.at).total_cmp(&poly[b].dist(c.at))) + .unwrap(); + let (vp, v, vn) = (poly[(k + 3) % 4], poly[k], poly[(k + 1) % 4]); + let towards = |a: Point, b: Point| { + let l = a.dist(b); + Point::new(a.x + (b.x - a.x) / l, a.y + (b.y - a.y) / l) + }; + let mut chamfered: Vec = Vec::new(); + for (j, q) in poly.iter().enumerate() { + if j == k { + chamfered.push(towards(v, vp)); + chamfered.push(towards(v, vn)); + } else { + chamfered.push(*q); + } + } + *cut = *cut + ev.chi2_local(Owner::Corner(i as u32), &[(e, &pieces(&chamfered, rev))]); + } +} + +/// What the evidence sets aside, and how it answers requests it cannot score: a thin line's +/// pixels (both of its edges reach them) are a strip, pixels holding a third ink are listed, +/// an edge between inks too close to unmix has no windows, and a local term asked for an +/// unknown owner, or without the curves it needs, scores nothing. +#[test] +fn thin_features_third_inks_and_refusals() { + let pt = Point::new; + // A 1.2 px line between two blue blocks: its two long edges end at junctions there. + let line = vec![pt(4.0, 20.3), pt(30.3, 20.3), pt(30.3, 21.5), pt(4.0, 21.5)]; + let block = vec![ + pt(30.3, 10.0), + pt(50.0, 10.0), + pt(50.0, 30.0), + pt(30.3, 30.0), + ]; + let post = vec![pt(1.0, 12.0), pt(4.0, 12.0), pt(4.0, 30.0), pt(1.0, 30.0)]; + // A black square with a 0.4 px red sliver along part of its top edge. + let sq = vec![ + pt(10.3, 40.6), + pt(50.2, 40.6), + pt(50.2, 58.4), + pt(10.3, 58.4), + ]; + let sliver = vec![ + pt(20.0, 40.2), + pt(40.0, 40.2), + pt(40.0, 40.6), + pt(20.0, 40.6), + ]; + // A square too faint against the page to unmix. + let faint = vec![pt(2.0, 2.0), pt(8.0, 2.0), pt(8.0, 8.0), pt(2.0, 8.0)]; + let s = render( + 64, + 64, + WHITE, + &[ + (line, B), + (block, [0.1, 0.2, 0.8]), + (post, [0.1, 0.2, 0.8]), + (sq, B), + (sliver, [0.9, 0.1, 0.1]), + (faint, [0.99, 0.99, 0.99]), + ], + true, + ); + let map = map_of(&s); + let ev = build( + &map, + &s.rgb, + &s.faces, + 0.5 / 255.0, + &EvidenceOptions::default(), + ); + assert_eq!(ev.size(), (64, 64)); + assert_eq!(ev.floor(), Floor::lattice(32)); + assert!( + ev.strip_pixels() + .iter() + .any(|&(x, y)| (10..25).contains(&x) && (19..=22).contains(&y)), + "{:?}", + ev.strip_pixels() + ); + assert!( + ev.third_pixels() + .iter() + .any(|&(x, y)| (21..40).contains(&x) && (39..=41).contains(&y)), + "{:?}", + ev.third_pixels() + ); + // No window lies on the faint square's edge. + for e in 0..ev.edge_count() { + for i in 0..ev.runs(e).len() { + assert!(ev.window_pixels(e, i).iter().all(|&(x, y)| x > 9 || y > 9)); + } + } + // The information density is positive and finite wherever an edge has windows. + let e = (0..ev.edge_count()) + .find(|&e| !ev.runs(e).is_empty()) + .expect("runs"); + let d = ev.density(e); + assert_eq!(d.len(), ev.runs(e).len()); + assert!(d.iter().all(|&(_, r)| r > 0.0 && r.is_finite())); + // Refusals. + let none = Chi2::default(); + assert!(ev.local_pixels(u32::MAX).is_empty()); + assert_eq!(ev.chi2_local(Owner::Junction(u32::MAX), &[]), none); + assert_eq!(ev.chi2_local(Owner::Corner(u32::MAX), &[]), none); + let j = ev.junctions().first().expect("the line meets the block"); + assert_eq!(ev.chi2_local(Owner::Junction(j.node), &[]), none); + assert!(!ev.corners().is_empty()); + assert_eq!(ev.chi2_local(Owner::Corner(0), &[]), none); +} + +/// A deterministic standard normal stream (an LCG through Box–Muller). +struct Normal(u64); + +impl Normal { + fn uniform(&mut self) -> f64 { + self.0 = self + .0 + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + ((self.0 >> 11) as f64 + 0.5) / (1u64 << 53) as f64 + } + fn next(&mut self) -> f64 { + let (u, v) = (self.uniform(), self.uniform()); + (-2.0 * u.ln()).sqrt() * (2.0 * PI * v).cos() + } +} + +/// The truth's score on every edge: each window's sum against the exact area the truth +/// image gives it, through the evaluator's own `score`. +fn truth_score(ev: &Evidence, truth: &[[f32; 3]]) -> Chi2 { + let mut total = Chi2::default(); + for e in 0..ev.edge_count() { + let obs = ev.runs(e); + if obs.is_empty() { + continue; + } + let t = ev.window_sums_of(e, truth); + let r: Vec = obs.iter().zip(&t).map(|(o, t)| o.sum - t).collect(); + let v: Vec = obs.iter().map(|o| o.var).collect(); + let sh: Vec = obs.iter().map(|o| o.share).collect(); + total = total + + inkvec_core::likelihood::score( + &r, + &v, + &sh, + ev.edge_offset_var(e), + inkvec_core::noise::huber_kappa(ev.tail_nu()), + ); + } + total +} + +/// Noise added within a few pixels of the edges is found from the windows alone: the noise +/// model is no longer clean, the windows' variance grows to match, and the truth scores +/// near one per independent measurement again. Without it, the truth reads many times that. +#[test] +fn noise_at_the_edges_is_read_from_the_windows() { + let shapes = [ + disc(31.4, 30.2, 17.3, 720), + square(31.7, 32.2, 13.0, 0.3), + disc(32.6, 31.1, 21.9, 720), + ]; + let (mut chi, mut plain) = (Chi2::default(), Chi2::default()); + let mut scales = Vec::new(); + for (k, poly) in shapes.into_iter().enumerate() { + let s = render(64, 64, WHITE, &[(poly, B)], true); + let mut noisy = s.rgb.clone(); + let mut g = Normal(17 + k as u64); + for (i, p) in noisy.iter_mut().enumerate() { + let c = s.cov[0][i]; + // Noise where the image changes: within the edge's pixels and their neighbours. + let near = (1..=2).any(|d| { + let (x, y) = ((i % 64) as i64, (i / 64) as i64); + [(d, 0), (-d, 0), (0, d), (0, -d)].iter().any(|&(dx, dy)| { + let (u, v) = (x + dx, y + dy); + (0..64).contains(&u) && (0..64).contains(&v) && { + let c2 = s.cov[0][(v * 64 + u) as usize]; + (c2 - c).abs() > 1e-6 + } + }) + }); + if near { + let n = (6.0 / 255.0) * g.next(); + for ch in p.iter_mut() { + *ch = (*ch as f64 + n).clamp(0.0, 1.0) as f32; + } + } + } + let map = map_of(&s); + let opts = EvidenceOptions { + floor: Some(Floor { + lattice: 1_000_000, + window_var: 0.0, + edge_var: 0.0, + }), + ..EvidenceOptions::default() + }; + let ev = build(&map, &noisy, &s.faces, 0.5 / 255.0, &opts); + assert!(!ev.noise().is_clean(), "{:?}", ev.noise()); + scales.push(ev.noise().window_scale); + chi = chi + truth_score(&ev, &s.rgb); + let off = build( + &map, + &noisy, + &s.faces, + 0.5 / 255.0, + &EvidenceOptions { + self_calibrate: false, + ..opts + }, + ); + plain = plain + truth_score(&off, &s.rgb); + } + let r = chi.chi2_floor / chi.dof; + let r0 = plain.chi2_floor / plain.dof; + assert!( + (0.5..2.0).contains(&r), + "calibrated chi2/dof {r:.2} ({chi:?})" + ); + assert!(r0 > 4.0 * r, "uncalibrated {r0:.2} vs {r:.2}"); + assert!(scales.iter().all(|&w| w > 2.0), "{scales:?}"); +} + +/// A clean render measures clean, and its planar map leaves the measurement untouched. +#[test] +fn a_clean_render_is_left_alone() { + let s = render(64, 64, WHITE, &[(square(31.7, 32.2, 13.0, 0.3), B)], true); + let mut map = map_of(&s); + let before: Vec> = map.edges.iter().map(|e| e.sigma.clone()).collect(); + // Even asked to fold, a clean render's measurement folds nothing. + let n = measure_noise_with(&mut map, &s.rgb, &s.faces, 0.5 / 255.0, false, true); + assert!(n.is_clean(), "{n:?}"); + let after: Vec> = map.edges.iter().map(|e| e.sigma.clone()).collect(); + assert_eq!(before, after); +} + +/// A noisy intake's measurement is reported; folded, every point's uncertainty grows by the +/// windows' measured error, and unfolded the map is untouched. +#[test] +fn a_noisy_render_folds_when_asked() { + let s = render(64, 64, WHITE, &[(disc(31.4, 30.2, 17.3, 720), B)], true); + let mut g = Normal(5); + let noisy: Vec<[f32; 3]> = s + .rgb + .iter() + .map(|p| { + let n = (12.0 / 255.0) * g.next(); + p.map(|c| (c as f64 + n).clamp(0.0, 1.0) as f32) + }) + .collect(); + let mut map = map_of(&s); + let before: Vec> = map.edges.iter().map(|e| e.sigma.clone()).collect(); + let kept = measure_noise_with(&mut map, &noisy, &s.faces, 12.0 / 255.0, false, false); + assert!( + !kept.is_clean() && kept.sigma_edge_at(0.0) > FOLD_LEVEL, + "{kept:?}" + ); + let unfolded: Vec> = map.edges.iter().map(|e| e.sigma.clone()).collect(); + assert_eq!(before, unfolded); + let folded = measure_noise_with(&mut map, &noisy, &s.faces, 12.0 / 255.0, false, true); + assert_eq!(folded, kept); + for (b, e) in before.iter().zip(&map.edges) { + assert!( + b.iter().zip(&e.sigma).all(|(b, a)| a > b), + "{b:?} vs {:?}", + e.sigma + ); + } +} + +/// On an axis-aligned square every window of a side repeats one measurement: the stretch +/// counts once. +#[test] +fn replicas_count_once() { + // Off the 8-bit rounding's ties (a coverage of 0.7 over white reads 76.5 levels, which + // float error rounds either way). + let sq = vec![ + Point::new(12.31, 14.63), + Point::new(50.27, 14.63), + Point::new(50.27, 49.23), + Point::new(12.31, 49.23), + ]; + let s = render(64, 64, WHITE, &[(sq, B)], true); + let ev = build(&map_of(&s), &s.rgb, &s.faces, 0.5 / 255.0, &exact_floor()); + let (mut m, mut dof) = (0usize, 0.0); + for e in 0..ev.edge_count() { + for o in ev.runs(e) { + m += 1; + dof += o.share; + } + } + assert!(m > 100, "{m}"); + // Four sides, each a few stretches between its corners. + assert!(dof < 0.2 * m as f64, "{dof} of {m}"); +} + +/// A point-sampling lattice is read from the coverages of axis-aligned edges; half pixels and +/// arbitrary coverages say nothing. +#[test] +fn a_sampling_lattice_is_read_from_the_image() { + let half = 0.5 / 255.0; + let round = |c: f64| (c * 255.0).round() / 255.0; + let on32: Vec<(f64, f64)> = (1..32) + .filter(|&k| k != 16) + .map(|k| (round(k as f64 / 32.0), half)) + .collect(); + assert_eq!(noise::detect_lattice(&on32), Some(32)); + let on8: Vec<(f64, f64)> = [1, 2, 3, 5, 6, 7, 1, 3, 5, 7] + .iter() + .map(|&k| (round(k as f64 / 8.0), half)) + .collect(); + assert_eq!(noise::detect_lattice(&on8), Some(8)); + let halves = vec![(0.5, half); 20]; + assert_eq!(noise::detect_lattice(&halves), None); + let thirds: Vec<(f64, f64)> = (0..20) + .map(|k| (round([1.0 / 3.0, 2.0 / 3.0][k % 2]), half)) + .collect(); + assert_eq!(noise::detect_lattice(&thirds), None); +} + +/// On a lossy intake the weight comes from luma, which 4:2:0 keeps at full resolution: a +/// pixel whose chroma has bled still reads its coverage. An isoluminant pair has no luma +/// axis. +#[test] +fn luma_reads_through_chroma_bleed() { + let (blue, yellow) = ([0.1f32, 0.2, 0.9], [0.95f32, 0.9, 0.1]); + let axis = Axis2::new(blue, yellow, 0.5 / 255.0); + let luma = axis.luma_of(0.1, 26.0 / 255.0).expect("lumas differ"); + // 30 % blue, then the chroma pulled a tenth of the way to grey while luma stays (about + // ten levels, the bleed measured within a pixel of a web-tier edge). + let mix: [f32; 3] = std::array::from_fn(|c| 0.3 * blue[c] + 0.7 * yellow[c]); + let y = windows::jpeg_luma(mix.map(|v| v as f64)) as f32; + let bled: [f32; 3] = std::array::from_fn(|c| 0.9 * mix[c] + 0.1 * y); + let m = luma.unmix(bled, None); + assert!((m.a - 0.3).abs() < 1e-3, "{}", m.a); + assert!(!m.third); + let grey = [0.5f32, 0.5, 0.5]; + let iso = [0.5 + 0.1 / 0.299 * 0.587 * 0.5, 0.5 - 0.1, 0.5]; + let iso = iso.map(|v| v as f32); + let flat = Axis2::new(grey, iso, 0.5 / 255.0); + assert!(flat.luma_of(0.1, 26.0 / 255.0).is_none()); +} + +/// A2: a thin stroke's strip pixels, which no run window takes, are scored against a stroke +/// band: its true centreline and width are calibrated there, and the band moved by 0.3 px or +/// drawn 0.3 px too wide is many standard deviations worse. +#[test] +fn a_stroke_band_scores_its_strip() { + // A 1.4 px dark band at 20 degrees across the image, between two white sides. + let (a, b, wdt) = (Point::new(4.0, 18.3), Point::new(60.0, 38.68), 1.4); + let (dx, dy) = (b.x - a.x, b.y - a.y); + let l = dx.hypot(dy); + let (nx, ny) = (dy / l * wdt / 2.0, -dx / l * wdt / 2.0); + let band_poly = vec![ + Point::new(a.x + nx, a.y + ny), + Point::new(b.x + nx, b.y + ny), + Point::new(b.x - nx, b.y - ny), + Point::new(a.x - nx, a.y - ny), + ]; + // Two blocks the band runs between, so that its two long sides are separate edges. + let left_block = vec![ + Point::new(0.0, 10.0), + Point::new(4.0, 10.0), + Point::new(4.0, 30.0), + Point::new(0.0, 30.0), + ]; + let right_block = vec![ + Point::new(60.0, 30.0), + Point::new(64.0, 30.0), + Point::new(64.0, 50.0), + Point::new(60.0, 50.0), + ]; + let ink = [0.1f32, 0.2, 0.6]; + let s = render( + 64, + 64, + WHITE, + &[ + (band_poly, ink), + (left_block, [0.9, 0.3, 0.1]), + (right_block, [0.9, 0.3, 0.1]), + ], + true, + ); + let ev = build(&map_of(&s), &s.rgb, &s.faces, 0.5 / 255.0, &exact_floor()); + // The pair of edges with the most strip pixels is the band's. + let mut counts: std::collections::BTreeMap<(u32, u32), usize> = Default::default(); + for p in &ev.strips { + *counts.entry(p.pair).or_default() += 1; + } + let (&pair, &n) = counts.iter().max_by_key(|(_, &c)| c).expect("strip pixels"); + assert!(n > 40, "{counts:?}"); + let pair = (pair.0 as usize, pair.1 as usize); + let band = |off: f64, w: f64| StrokeBand { + centre: vec![Piece::Line([ + Point::new( + a.x - 2.0 + off * dy / l, + a.y - 2.0 * dy / dx + off * -dx / l, + ), + Point::new( + b.x + 2.0 + off * dy / l, + b.y + 2.0 * dy / dx + off * -dx / l, + ), + ])], + width: w, + }; + let sides = [WHITE, ink, WHITE]; + let truth = ev.chi2_band(pair, &band(0.0, wdt), sides); + assert!(truth.m > 60, "{truth:?}"); + let ratio = truth.chi2 / truth.m as f64; + assert!(ratio < 2.0, "band chi2/M {ratio:.2} ({truth:?})"); + let moved = ev.chi2_band(pair, &band(0.3, wdt), sides); + let wide = ev.chi2_band(pair, &band(0.0, wdt + 0.3), sides); + assert!(moved.chi2 > truth.chi2 + 100.0, "{moved:?} vs {truth:?}"); + assert!(wide.chi2 > truth.chi2 + 100.0, "{wide:?} vs {truth:?}"); +} + +/// Exact per-layer "over" compositing, as a renderer draws overlapping shapes, rounded to 8 +/// bits; each pixel labelled by its largest contribution. Faces: `bg`, then the layers. +fn render_over(w: usize, h: usize, bg: [f32; 3], layers: &[(Vec, [f32; 3])]) -> Scene { + let n = layers.len(); + let mut cov = vec![vec![0.0; w * h]; n]; + let mut rgb = vec![[0f32; 3]; w * h]; + let mut labels = vec![0u16; w * h]; + for i in 0..w * h { + let (x, y) = ((i % w) as i32, (i / w) as i32); + let mut c = [bg[0] as f64, bg[1] as f64, bg[2] as f64]; + for (k, (poly, col)) in layers.iter().enumerate() { + let a = local::area_in_pixel(poly, x, y).clamp(0.0, 1.0); + cov[k][i] = a; + for ch in 0..3 { + c[ch] = a * col[ch] as f64 + (1.0 - a) * c[ch]; + } + } + // Each layer's share is its own area times what the layers above it leave. + let left_by = |from: usize| (from..n).map(|j| 1.0 - cov[j][i]).product::(); + let mut best = (0usize, left_by(0)); + for k in 1..=n { + let share = cov[k - 1][i] * left_by(k); + if share > best.1 { + best = (k, share); + } + } + labels[i] = best.0 as u16; + rgb[i] = c.map(|v| ((v * 255.0).round() / 255.0) as f32); + } + let mut faces = vec![FillModel::Flat(bg)]; + faces.extend(layers.iter().map(|(_, c)| FillModel::Flat(*c))); + Scene { + w, + h, + rgb, + cov, + labels, + faces, + } +} + +/// A2: where one shape overlaps another, a renderer composites each over what lies beneath, +/// which the visible partition does not reproduce at the junctions. Scored by per-layer +/// compositing, the true shapes are calibrated there; moved by half a pixel they are not. +#[test] +fn junctions_composite_per_layer() { + let bottom = square(26.3, 27.1, 12.0, 0.2); + let top = square(37.6, 38.2, 11.0, -0.3); + let (red, blue) = ([0.85f32, 0.2, 0.15], [0.1f32, 0.35, 0.85]); + let s = render_over(64, 64, WHITE, &[(bottom.clone(), red), (top.clone(), blue)]); + let ev = build(&map_of(&s), &s.rgb, &s.faces, 0.5 / 255.0, &exact_floor()); + let closed = |p: &[Point]| pieces(p, false); + let (b, t) = (closed(&bottom), closed(&top)); + let mut chi = Chi2::default(); + let mut moved = Chi2::default(); + let shifted: Vec = top.iter().map(|p| Point::new(p.x + 0.5, p.y)).collect(); + let ts = closed(&shifted); + let mut n_junctions = 0; + for j in ev.junctions() { + let c = ev.chi2_local_layers(j.node, &[(&b, red), (&t, blue)], WHITE); + if c.m == 0 { + continue; + } + n_junctions += 1; + chi = chi + c; + moved = moved + ev.chi2_local_layers(j.node, &[(&b, red), (&ts, blue)], WHITE); + } + assert!(n_junctions >= 2, "{n_junctions}"); + let ratio = chi.chi2 / chi.m as f64; + assert!(ratio < 2.0, "layers chi2/M {ratio:.2} ({chi:?})"); + assert!(moved.chi2 > chi.chi2 + 100.0, "{moved:?} vs {chi:?}"); +} diff --git a/crates/inkvec-trace/src/fast/codec.rs b/crates/inkvec-trace/src/fast/codec.rs new file mode 100644 index 00000000..a57e6039 --- /dev/null +++ b/crates/inkvec-trace/src/fast/codec.rs @@ -0,0 +1,141 @@ +//! A lossy intake's codec damage taken out of a palette label image: Quality mode's use of +//! Fast's halo pass ([`super::faces`]), with one test of its own. Called from +//! [`crate::trace_color_full_with_alpha`] after the labels are despeckled and before blend +//! absorption, on an opaque lossy intake only, and not on an image that came out of the +//! restorer (`ColorOptions::restored`): the restorer took the codec's damage out, and on the +//! restored path (`quality-web`, `--restore on`, the gate's 0.3 sample) the clean-up read dE00 +//! +0.24 %, `openmoji/E30B`'s brown border strip, a real ink, going to the black outline. +//! +//! # The problem +//! +//! Quality's palette (the MDL walk, `color/mdl.rs`) admits what the codec made: on +//! `openmoji/E056` (`web` tier) it keeps three tinted blacks, `#000109`, `#080100` and +//! `#030801`, beside `#000000`, and the trace came back with 674 faces, 41 colours and 250 +//! subpaths where the artist drew four colours. A JPEG stores chroma at half resolution, so +//! a black stroke beside a blue fill takes a blue tint over its whole width without moving +//! its luma, and the walk sees a colour with thousands of interior pixels, more than 5 dE00 +//! from black when it is weighed (`#00010f`); its mean then settles nearer black. Along every +//! edge the codec also leaves the halos Fast's pass was written for. +//! +//! # The clean-up +//! +//! 1. **Codec variants** ([`variant_map`]): an ink whose colour lies within +//! [`CODEC_VARIANT_LEVELS`] of a heavier ink in luma-weighted YCbCr (each chroma channel +//! at a quarter of luma's weight on squares, `faces::halos::coverage`'s metric: the +//! chroma is at half resolution and bleeds), and within the soft floor +//! (`color::SOFT_SAME_INK_DE00`), is that ink, everywhere. The tinted blacks above lie 2.7 +//! to 5.9 levels from black; the mosaic's neighbouring fills differ in luma and lie +//! farther (`synthetic/mosaic_grid6` is unchanged by the clean-up). +//! 2. **Halos**: [`super::faces::RunLabels::absorb_halos_held`] with every thin component +//! held to the strip rule and the segment test (`strict`), not only one of an ink that +//! owns an area elsewhere as in Fast. Quality's palette admits a thin ink on evidence, and +//! a real strip can lie on the segment between its neighbours: `noto-emoji/emoji_u1f9ed`'s +//! needle shadow, a strip three to four pixels wide between the teal needle and the white +//! dial, went with the hull test alone. +//! 3. **Thin variants**: [`super::faces::RunLabels::merge_same_inks`] at the soft floor for +//! thin components, as in Fast. +//! +//! The labels come back as palette indices; the palette itself is not changed, so an ink +//! nothing is labelled with any more simply draws no face. +//! +//! # Literature +//! +//! - Method from: ITU-R BT.601 (JPEG's colour space) and ITU-T T.81's 4:2:0 subsampling, as +//! in the halo pass. +//! - Not from the literature: the luma-weighted variant test and its reach. + +use super::faces::{self, Pixels, RunLabels}; +use crate::Palette; + +/// How far (8-bit levels, luma-weighted YCbCr) an ink may lie from a heavier one and still be +/// the codec's variant of it ([`variant_map`]): the tinted blacks of `openmoji/E056` lie +/// 2.7-5.9 levels from black. The clean-up as a whole was measured on `quality-web` against +/// the build before it (246 icons, 2026-10-11, the gate's distance axes): dE00 −6.83 %, +/// `turning_gap` −36.57 %, `ratio_gap` −11.89 %, geom −3.73 %. No sweep of this value. +pub(crate) const CODEC_VARIANT_LEVELS: f32 = 8.0; + +/// Take the codec's variants, halos and thin variants out of the palette labels `labels` of +/// `img` (only its size is read), `rgb` being the image over white and `pal` the palette they index; nothing when +/// `alpha` (the source's, when known) holds a pixel below [`crate::native::OPAQUE`], as the +/// tests read JPEG's colour space, which has no opacity. See the module documentation. Says +/// what it did under `INKVEC_DIAG`. +pub(crate) fn clean_labels( + labels: &mut [u16], + img: &crate::Rgba, + rgb: &[[f32; 3]], + pal: &Palette, + alpha: Option<&[f32]>, +) { + if alpha.is_some_and(|a| a.iter().any(|&v| v < crate::native::OPAQUE)) { + return; + } + let (w, h) = (img.width, img.height); + let to = variant_map(pal); + let variants = to + .iter() + .enumerate() + .filter(|&(i, &t)| t as usize != i) + .count(); + if variants > 0 { + for l in labels.iter_mut() { + if let Some(&t) = to.get(*l as usize) { + *l = t; + } + } + } + let inks: Vec<[f32; 4]> = pal.rgb.iter().map(|c| [c[0], c[1], c[2], 1.0]).collect(); + let mut runs = RunLabels::new(labels, w, h); + let px = Pixels { rgb, alpha: None }; + let halos = runs.absorb_halos_held(px, &inks, true); + runs.merge_same_inks(&inks, Some(crate::color::SOFT_SAME_INK_DE00)); + let face_color = runs.write_faces(labels); + for l in labels.iter_mut() { + *l = face_color[*l as usize] as u16; + } + crate::diag!( + "slivers", + "lossy intake: {variants} codec variants, {} halos and {} halo specks given back", + halos.0, + halos.1 + ); +} + +/// For each ink of `pal`, the ink it is ([`CODEC_VARIANT_LEVELS`], module docs, step 1): +/// itself, or the heaviest ink before it (by weight, ties to the lower index) that is not a +/// variant itself and lies within reach. One pass in descending weight, so a chain of +/// variants maps to its heaviest member, never through a variant. +pub(crate) fn variant_map(pal: &Palette) -> Vec { + let n = pal.rgb.len(); + let ycc = |c: [f32; 3]| faces::halos_ycc([c[0], c[1], c[2], 1.0]); + let reach = CODEC_VARIANT_LEVELS / 255.0; + let mut order: Vec = (0..n).collect(); + order.sort_by(|&a, &b| { + let (wa, wb) = ( + pal.weight.get(a).copied().unwrap_or(0.0), + pal.weight.get(b).copied().unwrap_or(0.0), + ); + wb.total_cmp(&wa).then(a.cmp(&b)) + }); + let mut to: Vec = (0..n as u16).collect(); + for (i, &v) in order.iter().enumerate() { + let cv = ycc(pal.rgb[v]); + for &a in &order[..i] { + if to[a] as usize != a { + continue; + } + let ca = ycc(pal.rgb[a]); + let d2 = (cv[0] - ca[0]).powi(2) + + 0.25 * ((cv[1] - ca[1]).powi(2) + (cv[2] - ca[2]).powi(2)); + if d2 <= reach * reach + && crate::color::de00(pal.rgb[v], pal.rgb[a]) < crate::color::SOFT_SAME_INK_DE00 + { + to[v] = a as u16; + break; + } + } + } + to +} + +#[cfg(test)] +mod tests; diff --git a/crates/inkvec-trace/src/fast/codec/tests.rs b/crates/inkvec-trace/src/fast/codec/tests.rs new file mode 100644 index 00000000..1ac13fa2 --- /dev/null +++ b/crates/inkvec-trace/src/fast/codec/tests.rs @@ -0,0 +1,89 @@ +use super::*; + +/// A palette of the given sRGB inks and weights. +fn palette(inks: &[[f32; 3]], weight: &[f32]) -> Palette { + Palette { + colors: inks + .iter() + .map(|&c| crate::color::rgb_to_oklab(c)) + .collect(), + rgb: inks.to_vec(), + weight: weight.to_vec(), + alpha: vec![1.0; inks.len()], + } +} + +const fn hex(r: u8, g: u8, b: u8) -> [f32; 3] { + [r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0] +} + +#[test] +fn the_codec_tinted_blacks_are_black_and_a_mosaic_neighbour_is_not() { + // `openmoji/E056` on the web tier: black, three tinted blacks, the blue and the yellow + // fills; and two neighbouring fills of `synthetic/mosaic_grid6`, which differ in luma. + let inks = [ + hex(0, 0, 0), + hex(0x00, 0x01, 0x09), + hex(0x08, 0x01, 0x00), + hex(0x03, 0x08, 0x01), + hex(0x61, 0xb2, 0xe4), + hex(0xfa, 0xeb, 0x37), + hex(0xd3, 0x45, 0x45), + hex(0xd3, 0x5c, 0x45), + ]; + let weight = [0.05, 0.04, 0.03, 0.01, 0.1, 0.02, 0.2, 0.2]; + let to = variant_map(&palette(&inks, &weight)); + // Black, the heaviest of the four, takes the three tints (2.7 to 5.9 levels from it). + assert_eq!(&to[..4], &[0, 0, 0, 0]); + for i in 4..inks.len() { + assert_eq!(to[i] as usize, i, "ink {i} keeps its own"); + } +} + +#[test] +fn a_variant_maps_to_the_heaviest_ink_never_through_another_variant() { + // b is a variant of a, c of b only (more than the reach from a): c keeps itself, as b + // is a variant and no target. + let a = hex(0x40, 0x40, 0x40); + let b = hex(0x46, 0x46, 0x46); + let c = hex(0x4c, 0x4c, 0x4c); + let to = variant_map(&palette(&[a, b, c], &[0.5, 0.3, 0.2])); + assert_eq!(to, vec![0, 0, 2]); +} + +/// Columns of labels: blue, a band of label `band` `width` pixels wide, white. +fn strip_image(width: usize, band: u16) -> (Vec, usize, usize) { + let (w, h) = (16 + width, 12); + let labels = (0..w * h) + .map(|p| match p % w { + x if x < 8 => 0, + x if x < 8 + width => band, + _ => 1, + }) + .collect(); + (labels, w, h) +} + +#[test] +fn a_halo_goes_and_a_strip_of_ink_between_the_same_two_inks_stays() { + // Blue and white, and between them a colour on their segment: two pixels wide it is the + // codec's halo, four wide (an interior at radius one) a strip the artist drew. + let inks = [ + hex(0x2e, 0x78, 0x89), + hex(0xff, 0xff, 0xff), + hex(0x96, 0xbb, 0xc4), + ]; + let pal = palette(&inks, &[0.4, 0.5, 0.1]); + for (width, kept) in [(2, false), (4, true)] { + let (mut labels, w, h) = strip_image(width, 2); + let rgb: Vec<[f32; 3]> = labels.iter().map(|&l| inks[l as usize]).collect(); + let img = crate::Rgba { + width: w, + height: h, + data: vec![1.0; 4 * w * h], + }; + clean_labels(&mut labels, &img, &rgb, &pal, None); + let band = labels.iter().filter(|&&l| l == 2).count(); + assert_eq!(band > 0, kept, "width {width}"); + } +} diff --git a/crates/inkvec-trace/src/fast/faces.rs b/crates/inkvec-trace/src/fast/faces.rs index 7caf9976..ba9473f5 100644 --- a/crates/inkvec-trace/src/fast/faces.rs +++ b/crates/inkvec-trace/src/fast/faces.rs @@ -17,12 +17,17 @@ //! 2. [`RunLabels::absorb_rims`] (`slivers`): strips whose own ink is a blend of two inks //! they border are anti-aliased rims; each of their pixels goes to the side it covers //! more of. -//! 3. [`RunLabels::merge_same_inks`] (`slivers`): a component takes the ink of a larger -//! neighbour whose ink the eye cannot tell from its own (region merging on the graph). -//! 4. [`RunLabels::despeckle`] (`despeckle`): components under the speckle floor take the +//! 3. [`RunLabels::absorb_halos`] (`slivers`), on a lossy intake only: thin components +//! whose colour lies between two inks around them in JPEG's colour space are the +//! codec's halos, and each of their pixels goes to the ink it covers more of +//! ([`halos`]). +//! 4. [`RunLabels::merge_same_inks`] (`slivers`): a component takes the ink of a larger +//! neighbour whose ink the eye cannot tell from its own (region merging on the graph); +//! on a lossy intake a thin one takes one up to the soft floor. +//! 5. [`RunLabels::despeckle`] (`despeckle`): components under the speckle floor take the //! label they share the longest border with (an area filter on flat zones, a //! connected operator). -//! 5. [`RunLabels::write_faces`] (`split`): the components of the result are the faces; +//! 6. [`RunLabels::write_faces`] (`split`): the components of the result are the faces; //! their ids are written over the label buffer. //! //! In: one ink label per pixel, each pixel's colour ([`Pixels`], sRGB 0..1 plus opacity) @@ -111,6 +116,8 @@ //! milliseconds, about half of it the one read of the labels and the one write of the //! faces, which are bound by memory bandwidth rather than by one core. +mod halos; +pub(crate) use halos::ycc as halos_ycc; mod runs; use runs::Run; @@ -277,15 +284,14 @@ fn dedup_sorted(v: &mut [u16]) -> usize { /// indices, opacities within [`SAME_ALPHA`], and CIEDE2000 (on sRGB, ignoring opacity) /// below [`crate::color::SAME_INK_DE00`]. `n²` colour differences; the palette has tens /// of inks. Computed for both orders, as CIEDE2000 is evaluated with `a` first. -fn same_ink_table(inks: &[[f32; 4]]) -> Vec { +fn same_ink_table(inks: &[[f32; 4]], de00: f32) -> Vec { let n_inks = inks.len(); (0..n_inks * n_inks) .map(|k| { let (ia, ib) = (inks[k / n_inks], inks[k % n_inks]); k / n_inks != k % n_inks && (ia[3] - ib[3]).abs() < SAME_ALPHA - && crate::color::de00([ia[0], ia[1], ia[2]], [ib[0], ib[1], ib[2]]) - < crate::color::SAME_INK_DE00 + && crate::color::de00([ia[0], ia[1], ia[2]], [ib[0], ib[1], ib[2]]) < de00 }) .collect() } @@ -517,6 +523,17 @@ impl RunLabels { /// higher rank on a tie). Returns early, unchanged, when no two inks are the same or /// no such pair of components touches. /// + /// **Thin components on a lossy intake** (`thin_de00`, `None` otherwise). A JPEG splits + /// one ink into several a few dE00 apart wherever its blocks and its half-resolution + /// chroma shift the colour (a black outline came back as #010101, #010009 and #080000 + /// on `openmoji/1F9D1`, `web` tier), and the variants tile the ink into fragments, none + /// of which has an interior. A component with no pixel whose window of radius + /// [`halos::HALO_REACH`] is all its own ([`RunLabels::deep_components`]) then counts an + /// ink within `thin_de00` (CIEDE2000; [`crate::color::SOFT_SAME_INK_DE00`], the soft + /// floor Quality's palette uses on such an intake) as its own; a component with an + /// interior keeps the clean threshold, so two flat inks a few dE00 apart stay two. + /// With `None` the decisions are exactly the clean ones. + /// /// **On runs.** The border lengths are summed over run contacts /// ([`RunLabels::for_each_contact`], equal to the per-pixel count), oriented as the /// per-pixel code met them (left or upper component first, which decides the order @@ -527,13 +544,22 @@ impl RunLabels { /// /// Method from: Salembier & Serra (1995), -- a /// connected operator: flat zones are merged whole, never split. - pub(crate) fn merge_same_inks(&mut self, inks: &[[f32; 4]]) { + pub(crate) fn merge_same_inks(&mut self, inks: &[[f32; 4]], thin_de00: Option) { let n_inks = inks.len(); - let same = same_ink_table(inks); - if !same.contains(&true) { + let same = same_ink_table(inks, crate::color::SAME_INK_DE00); + let thin_same = thin_de00.map(|de00| same_ink_table(inks, de00)); + if !same.contains(&true) && !thin_same.as_ref().is_some_and(|t| t.contains(&true)) { return; } self.components(); + let deep = thin_de00.map(|_| self.deep_components(halos::HALO_REACH)); + // Whether component `k`, of ink `a`, may take ink `b`. + let same_for = |k: usize, a: usize, b: usize| -> bool { + match (&thin_same, &deep) { + (Some(t), Some(d)) if !d[k] => t[a * n_inks + b], + _ => same[a * n_inks + b], + } + }; let n = self.size.len(); // Border shared by each pair of components whose inks are one ink to the eye. let mut touching: Vec<(u32, u32, u32)> = Vec::new(); @@ -543,7 +569,13 @@ impl RunLabels { self.label[a as usize] as usize, self.label[b as usize] as usize, ); - if a != b && la < n_inks && lb < n_inks && same[la * n_inks + lb] { + if a != b + && la < n_inks + && lb < n_inks + && (same[la * n_inks + lb] + || (thin_de00.is_some() + && (same_for(a as usize, la, lb) || same_for(b as usize, lb, la)))) + { touching.push((a.min(b), a.max(b), len)); } }); @@ -577,7 +609,7 @@ impl RunLabels { .filter(|&&(o, _)| rank[o as usize] < rank[k as usize]) .filter(|&&(o, _)| { let t = to[o as usize] as usize; - t != own && t < n_inks && same[own * n_inks + t] + t != own && t < n_inks && same_for(k as usize, own, t) }) .max_by_key(|&&(o, len)| (len, std::cmp::Reverse(rank[o as usize]))); if let Some(&(o, _)) = best { diff --git a/crates/inkvec-trace/src/fast/faces/halos.rs b/crates/inkvec-trace/src/fast/faces/halos.rs new file mode 100644 index 00000000..07989132 --- /dev/null +++ b/crates/inkvec-trace/src/fast/faces/halos.rs @@ -0,0 +1,484 @@ +//! Codec halos: thin bands of colour that a lossy codec leaves along an edge, put back into +//! the two inks of the edge. Fast mode's clean-up pass for a lossy intake ([`super`], +//! [`RunLabels::absorb_halos`]). +//! +//! # The problem +//! +//! A JPEG stores colour at half resolution (4:2:0) and quantises every 8 × 8 block, so an +//! edge between two inks comes back with a band two or three pixels wide on each side whose +//! luma overshoots or rings and whose chroma has bled a pixel or two across, independently of +//! the luma. Such a band has flat pixels, so Fast's histogram palette founds it as an ink of +//! its own, and its pixels are no blend of the two inks in sRGB: the chroma moved where the +//! luma did not, which puts them 0.08-0.09 sRGB off the line between the inks +//! (`twemoji/1f1fa` on the `web` tier, twice [`super::BLEND_TOL`]), so neither +//! [`RunLabels::absorb_slivers`] nor [`RunLabels::absorb_rims`] recognises them. A +//! two-colour flag came back with four inks and 215 faces. +//! +//! # The test +//! +//! In JPEG's own colour space (BT.601 full-range YCbCr, [`ycc`]) the halo is easy to state: +//! each channel of its colour lies between the two inks' values in that channel, or a little +//! beyond them (overshoot), but the three channels need not agree on *where* between them. +//! A component of the label image is a halo of the inks `a` and `b` when +//! +//! 1. it is **thin**: no pixel of it has a window of radius [`HALO_REACH`] holding only its +//! own label (a JPEG halo reaches about three pixels from the edge; the "no interior +//! pixel" rule of the other passes, radius one, misses the wider ones); +//! 2. `a` and `b` are inks of **thick** components near it: bordering it, or bordering a +//! thin component that borders it (the band between blue and white is a dark halo next +//! to the blue and a light one next to the white, each touching one of the two inks); +//! 3. the **mean colour** of its pixels lies, channel by channel, in the hull +//! `[min − τ·|Δ|, max + τ·|Δ|]` of the two inks' values, `τ` = [`HALO_OVERSHOOT`], widened +//! by [`HALO_SLACK`] for a channel in which the inks barely differ ([`in_hull`]). +//! +//! That is the whole test for a component whose ink has no thick component anywhere in the +//! image: a colour the codec made, which owns no area of its own. A thin component of an ink +//! that does own an area somewhere is held to more: it must be a strip (no pixel whose four +//! neighbours share its label, [`STRIP_REACH`]) and its mean must lie within +//! [`HALO_LINE_TOL`] of the segment between the two inks ([`coverage`]'s distance). The +//! hull alone is a box, wide wherever the two inks differ in a channel, and a real ink can +//! sit in it: `twemoji/1faa3`'s #55ACEE rim, a band four pixels wide between a navy and a +//! blue, lies in the box of either pair around it and 0.054 from the nearer segment, where +//! the codec's halos lie 0.009-0.035 from theirs (`twemoji/1f1fa`, `openmoji/1F1FF-1F1F2`). +//! +//! Of the pairs that pass, the one whose segment the mean lies nearest is taken +//! ([`halo_pair`]). Each pixel then goes to `b` when its coverage `t` of `b` is at least +//! one half and to `a` otherwise, `t` read mostly from luma ([`coverage`]): the chroma is at +//! half resolution and bleeds, the luma carries the edge. Assigning by `t ≥ ½` keeps each +//! ink's area, as a pixel's coverage is the share of it each ink covers. +//! +//! A halo ink usually also leaves specks inside one of the two inks, a pixel or two from +//! the edge, with a single side and no pair. After the first pass, an ink some of whose +//! components were halos and that has no thick component left is a halo ink, and each of +//! its remaining components that borders a single other ink takes that ink. One bordering +//! two or more is left as it is: a ring of it around an eye goes neither to the eye nor to +//! the face around it whole. +//! +//! # When +//! +//! Only on a lossy intake (`ColorOptions::lossy_intake`, which reads the container) and only +//! for an opaque image: a clean render's edges carry no halos, its thin bands are artwork, +//! and its output stays byte-identical. Even then a component is touched only on the +//! evidence of its own pixels: thin, between two inks, and coloured as a halo of them; a +//! raster with no halos (one the trained restorer has cleaned) keeps its components. +//! Cost: one pass over the runs for the thick components at each radius, one over the +//! contacts for the neighbours, and a colour read per pixel of a thin component; O(pixels) +//! at worst, O(runs + thin pixels) in practice. +//! +//! # Literature +//! +//! - Method from: ITU-R BT.601 (and JFIF, which stores JPEG's colour in its full-range +//! form) for the luma-chroma transform, and the JPEG standard's 4:2:0 chroma subsampling +//! (ITU-T T.81), which is why chroma is read at half the weight of luma. +//! - See also: Zhang, Liang, Van Gool & Timofte (2021), "Designing a practical degradation +//! model for deep blind image super-resolution", ICCV, , +//! for resizing then JPEG as the degradation real inputs carry; and Bioucas-Dias et al. +//! (2012), , for the two-endmember unmixing the +//! reassignment is (as in [`super::blend_of`]). +//! - Not from the literature: the per-channel hull with overshoot as the test of a halo, the +//! thinness by window radius, the two-hop sides, and the stricter test for an ink that +//! owns an area elsewhere. + +use super::runs::Run; +use super::{Pixels, RunLabels}; + +/// How far (in pixels, a window of radius this) a pixel must be from every pixel of another +/// label for its component to count as thick. A JPEG halo reaches about three pixels from +/// the edge (`docs/theory/noise.md`: luma RMS 4.5, 3.1, 2.3 levels at under 1, 1-2 and 2-3 px +/// from an edge, against 0.2 in the interiors), so a band up to four pixels wide, whose +/// middle is two pixels from either side, is thin. +pub(crate) const HALO_REACH: u32 = 2; + +/// How far beyond either ink a halo's channel may lie, as a share of the inks' difference in +/// that channel: ringing overshoots the step it rings around. +pub(crate) const HALO_OVERSHOOT: f32 = 0.2; + +/// An absolute slack on every channel of the hull (YCbCr, 0..1 units), so a channel in which +/// the two inks barely differ still lets the codec's noise through: about five 8-bit levels. +pub(crate) const HALO_SLACK: f32 = 0.02; + +/// The radius at which a thin component of an ink that owns an area elsewhere must have no +/// deep pixel: one, the strip rule of [`RunLabels::absorb_rims`] (no pixel whose four +/// neighbours share its label, here with the eight diagonal ones too). A band of a real ink +/// three or four pixels wide keeps its interior at this radius. +pub(crate) const STRIP_REACH: u32 = 1; + +/// How far (YCbCr, [`coverage`]'s weighted distance) from the segment between the two inks +/// the mean of a thin component of an ink that owns an area elsewhere may lie and still be +/// their halo. The codec's halos measured 0.009-0.035 from theirs (`twemoji/1f1fa`, +/// `openmoji/1F1FF-1F1F2`, `web` tier); the real #55ACEE rim of `twemoji/1faa3`, 0.054. +pub(crate) const HALO_LINE_TOL: f32 = 0.04; + +/// The weight of each chroma channel against luma's in [`coverage`], on squared differences +/// (half the amplitude): 4:2:0 stores chroma at half resolution, so where luma and chroma +/// disagree about an edge the luma is the better reading of how much of each ink a pixel +/// holds. Two inks that differ only in chroma are still told apart by it. +const CHROMA_WEIGHT: f32 = 0.25; + +/// BT.601 full-range YCbCr (JPEG's, as JFIF stores it) of an sRGB 0..1 colour, chroma +/// centred on zero: `Y = 0.299 R + 0.587 G + 0.114 B`, +/// `Cb = −0.168736 R − 0.331264 G + 0.5 B`, `Cr = 0.5 R − 0.418688 G − 0.081312 B`. +pub(crate) fn ycc(c: [f32; 4]) -> [f32; 3] { + let [r, g, b, _] = c; + [ + 0.299 * r + 0.587 * g + 0.114 * b, + -0.168_736 * r - 0.331_264 * g + 0.5 * b, + 0.5 * r - 0.418_688 * g - 0.081_312 * b, + ] +} + +/// Whether `c` lies in the hull of `a` and `b` channel by channel: each channel within +/// `[min − τ·|Δ| − ε, max + τ·|Δ| + ε]` of the two inks' values, `τ` = [`HALO_OVERSHOOT`], +/// `ε` = [`HALO_SLACK`]. The channels are tested independently: a halo's luma and chroma +/// need not sit at the same place between the inks. +pub(crate) fn in_hull(c: [f32; 3], a: [f32; 3], b: [f32; 3]) -> bool { + (0..3).all(|k| { + let span = (b[k] - a[k]).abs(); + let lo = a[k].min(b[k]) - HALO_OVERSHOOT * span - HALO_SLACK; + let hi = a[k].max(b[k]) + HALO_OVERSHOOT * span + HALO_SLACK; + (lo..=hi).contains(&c[k]) + }) +} + +/// `c`'s coverage `t` of `b` on the segment from `a` to `b` in YCbCr, chroma weighted by +/// [`CHROMA_WEIGHT`], and its weighted squared distance from the segment (`t` clamped to +/// 0..1 for the distance only). `None` when the two inks are one colour. +pub(crate) fn coverage(c: [f32; 3], a: [f32; 3], b: [f32; 3]) -> Option<(f32, f32)> { + let wt = [1.0, CHROMA_WEIGHT, CHROMA_WEIGHT]; + let ab: [f32; 3] = std::array::from_fn(|k| b[k] - a[k]); + let l2: f32 = (0..3).map(|k| wt[k] * ab[k] * ab[k]).sum(); + if l2 < 1e-9 { + return None; + } + let t = (0..3).map(|k| wt[k] * (c[k] - a[k]) * ab[k]).sum::() / l2; + let tc = t.clamp(0.0, 1.0); + let d = (0..3) + .map(|k| wt[k] * (c[k] - (a[k] + tc * ab[k])).powi(2)) + .sum::(); + Some((t, d)) +} + +/// The pair of inks `(lo, hi)`, `lo < hi`, from the sorted distinct labels `sides`, whose +/// hull holds `mean` ([`in_hull`]) and whose segment it lies nearest ([`coverage`]'s +/// distance), the smaller pair on a tie; `None` when no pair holds it. `inks` are YCbCr. +pub(crate) fn halo_pair(mean: [f32; 3], sides: &[u16], inks: &[[f32; 3]]) -> Option<(u16, u16)> { + let mut best: Option<(f32, u16, u16)> = None; + for (i, &lo) in sides.iter().enumerate() { + for &hi in &sides[i + 1..] { + let (a, b) = (inks[lo as usize], inks[hi as usize]); + if !in_hull(mean, a, b) { + continue; + } + let Some((_, d)) = coverage(mean, a, b) else { + continue; + }; + if best.is_none_or(|(e, l0, h0)| d < e || (d == e && (lo, hi) < (l0, h0))) { + best = Some((d, lo, hi)); + } + } + } + best.map(|(_, a, b)| (a, b)) +} + +/// A list of lists in one buffer: `items[start[i]..start[i + 1]]` is list `i`. +struct Lists { + start: Vec, + items: Vec, +} + +impl Lists { + /// Group `pairs` (list index, item) into sorted, deduplicated lists for `n` indices. + fn of(n: usize, mut pairs: Vec<(u32, T)>) -> Self { + pairs.sort_unstable(); + pairs.dedup(); + let mut start = vec![0usize; n + 1]; + for &(i, _) in &pairs { + start[i as usize + 1] += 1; + } + for i in 0..n { + start[i + 1] += start[i]; + } + Lists { + start, + items: pairs.into_iter().map(|(_, t)| t).collect(), + } + } + + fn get(&self, i: usize) -> &[T] { + &self.items[self.start[i]..self.start[i + 1]] + } +} + +impl RunLabels { + /// Which components have a *deep* pixel: one whose window of radius `reach` (a square of + /// side `2·reach + 1`) holds only its own label, the outside of the image counting as + /// its own label. Needs fresh components. + /// + /// **On runs.** Pixel `x` of a run `x0..x1` has its own label across its window's row + /// when `x − reach .. x + reach` lies in the run or off the image: the stretch + /// [`deep_span`] of the run. The pixel is deep when that holds in every row of the + /// window, each time in a run of its label. So a run's deep pixels are its span cut, row + /// by row, with the spans of the overlapping runs of its label in the `2·reach` rows + /// around it; the run holds a deep pixel when anything is left. The window is one block + /// of the label containing the pixel, so every run met is in the pixel's component. A + /// component already known to be deep is skipped. Cost: per run, the overlapping runs of + /// `2·reach` rows; O(R · reach) on images whose runs overlap a few others. + pub(super) fn deep_components(&self, reach: u32) -> Vec { + debug_assert!(reach >= 1); + let (runs, rs, w, h) = (&self.runs, &self.row_start, self.w as u32, self.h); + let span = |r: &Run| deep_span(r, w, reach); + let mut deep = vec![false; self.size.len()]; + let mut cur: Vec<(u32, u32)> = Vec::new(); + let mut next: Vec<(u32, u32)> = Vec::new(); + for y in 0..h { + for r in rs[y]..rs[y + 1] { + let run = runs[r]; + let c = self.run_comp[r] as usize; + let (s, e) = span(&run); + if deep[c] || s >= e { + continue; + } + cur.clear(); + cur.push((s, e)); + let (y0, y1) = ( + y.saturating_sub(reach as usize), + (y + reach as usize).min(h - 1), + ); + for yy in (y0..=y1).filter(|&yy| yy != y) { + next.clear(); + let row = &runs[rs[yy]..rs[yy + 1]]; + for &(a, b) in &cur { + let mut k = row.partition_point(|q| q.x1 <= a); + while k < row.len() && row[k].x0 < b { + if row[k].label == run.label { + let (s2, e2) = span(&row[k]); + let (s3, e3) = (a.max(s2), b.min(e2)); + if s3 < e3 { + next.push((s3, e3)); + } + } + k += 1; + } + } + std::mem::swap(&mut cur, &mut next); + if cur.is_empty() { + break; + } + } + deep[c] = !cur.is_empty(); + } + } + deep + } + + /// Each component's neighbouring components (sharing a pixel edge), sorted. Needs fresh + /// components. O(E log E) for the E contacts. + fn neighbours(&self) -> Lists { + let mut pairs: Vec<(u32, u32)> = Vec::new(); + self.for_each_contact(|i, j, _| { + let (a, b) = (self.run_comp[i], self.run_comp[j]); + if a != b { + pairs.push((a, b)); + pairs.push((b, a)); + } + }); + Lists::of(self.size.len(), pairs) + } + + /// Give the codec's halos back to the inks of the edge they lie along: see the module + /// documentation for the test, the reassignment and the second pass. `px` must be + /// opaque (no opacity channel) and `inks` sRGB 0..1; every label must index into them. + /// Returns the number of components given back in each of the two passes. + pub(crate) fn absorb_halos(&mut self, px: Pixels<'_>, inks: &[[f32; 4]]) -> (usize, usize) { + self.absorb_halos_held(px, inks, false) + } + + /// [`RunLabels::absorb_halos`], with `strict` holding every thin component to the strip + /// rule ([`STRIP_REACH`]) and the segment test ([`HALO_LINE_TOL`]), not only one of an ink + /// that owns an area elsewhere. Quality mode's use (`super::super::codec`): its palette + /// admits a thin ink on evidence, and a real strip can lie on the segment between its + /// neighbours. Fast passes `false`. + pub(crate) fn absorb_halos_held( + &mut self, + px: Pixels<'_>, + inks: &[[f32; 4]], + strict: bool, + ) -> (usize, usize) { + self.components(); + let inks_ycc: Vec<[f32; 3]> = inks.iter().map(|&c| ycc(c)).collect(); + let pair = self.halo_pairs(px, &inks_ycc, strict); + let first = pair.iter().filter(|p| p.is_some()).count(); + if first == 0 { + return (0, 0); + } + let mut was_halo = vec![false; inks.len()]; + for (c, p) in pair.iter().enumerate() { + if p.is_some() { + was_halo[self.label[c] as usize] = true; + } + } + // Every pixel of a halo goes to the ink it covers more of. Decided for every pixel + // before any is written, in scan order, as `apply_pixel_edits` needs. + let mut edits = Vec::new(); + for y in 0..self.h { + for r in self.row_start[y]..self.row_start[y + 1] { + let Some((a, b)) = pair[self.run_comp[r] as usize] else { + continue; + }; + let (ya, yb) = (inks_ycc[a as usize], inks_ycc[b as usize]); + let Run { x0, x1, .. } = self.runs[r]; + for x in x0..x1 { + let v = ycc(px.get(y * self.w + x as usize)); + let to = match coverage(v, ya, yb) { + Some((t, _)) if t >= 0.5 => b, + _ => a, + }; + edits.push((r as u32, x, to)); + } + } + } + self.apply_pixel_edits(&edits); + let second = self.absorb_halo_specks(&was_halo); + (first, second) + } + + /// The pair of inks each component is a halo of ([`RunLabels::absorb_halos`]'s first + /// pass), `None` for one that is not a halo; one entry per component. Needs fresh + /// components. `inks` are YCbCr ([`ycc`]); labels outside them are never halos. + fn halo_pairs( + &self, + px: Pixels<'_>, + inks: &[[f32; 3]], + strict: bool, + ) -> Vec> { + let n_inks = inks.len(); + let n = self.size.len(); + let deep = self.deep_components(HALO_REACH); + let strip_deep = self.deep_components(STRIP_REACH); + let nbrs = self.neighbours(); + let in_palette = |c: usize| (self.label[c] as usize) < n_inks; + // Inks with an area of their own somewhere: a thin component of one is held to the + // stricter test. + let mut has_area = vec![false; n_inks]; + for c in (0..n).filter(|&c| deep[c] && in_palette(c)) { + has_area[self.label[c] as usize] = true; + } + let candidate = |c: usize| { + !deep[c] + && in_palette(c) + && !((has_area[self.label[c] as usize] || strict) && strip_deep[c]) + }; + // The inks of each component's thick neighbours. + let thick_sides = Lists::of( + n, + (0..n) + .flat_map(|c| nbrs.get(c).iter().map(move |&o| (c as u32, o))) + .filter(|&(_, o)| deep[o as usize]) + .map(|(c, o)| (c, self.label[o as usize])) + .filter(|&(_, l)| (l as usize) < n_inks) + .collect(), + ); + // The mean YCbCr of every candidate, in one pass over the runs. + let mut sum = vec![[0.0f64; 3]; n]; + for y in 0..self.h { + for r in self.row_start[y]..self.row_start[y + 1] { + let c = self.run_comp[r] as usize; + if !candidate(c) { + continue; + } + let Run { x0, x1, .. } = self.runs[r]; + for x in x0..x1 { + let v = ycc(px.get(y * self.w + x as usize)); + for k in 0..3 { + sum[c][k] += v[k] as f64; + } + } + } + } + let mut pair: Vec> = vec![None; n]; + let mut sides: Vec = Vec::new(); + for c in (0..n).filter(|&c| candidate(c)) { + sides.clear(); + sides.extend_from_slice(thick_sides.get(c)); + for &o in nbrs.get(c).iter().filter(|&&o| !deep[o as usize]) { + sides.extend_from_slice(thick_sides.get(o as usize)); + } + sides.sort_unstable(); + sides.dedup(); + sides.retain(|&l| l != self.label[c]); + if sides.len() < 2 { + continue; + } + let mean = sum[c].map(|v| (v / self.size[c] as f64) as f32); + pair[c] = halo_pair(mean, &sides, inks).filter(|&(a, b)| { + (!has_area[self.label[c] as usize] && !strict) + || coverage(mean, inks[a as usize], inks[b as usize]) + .is_some_and(|(_, d)| d <= HALO_LINE_TOL * HALO_LINE_TOL) + }); + } + pair + } + + /// The second pass of [`RunLabels::absorb_halos`]: an ink some of whose components were + /// halos (`was_halo`, per ink) and that has no thick component left is a halo ink, and + /// each of its components that borders exactly one ink that is not a halo ink takes that + /// ink; one bordering two or more, or none, stays. Labels are read as they were before + /// the pass. Returns how many components were relabelled. + fn absorb_halo_specks(&mut self, was_halo: &[bool]) -> usize { + self.components(); + let deep = self.deep_components(HALO_REACH); + let mut halo_ink = was_halo.to_vec(); + for (c, &d) in deep.iter().enumerate() { + let l = self.label[c] as usize; + if d && l < halo_ink.len() { + halo_ink[l] = false; + } + } + if !halo_ink.contains(&true) { + return 0; + } + let is_halo = |l: u16| halo_ink.get(l as usize).copied().unwrap_or(false); + // (halo component, the label across the border). + let mut sides: Vec<(u32, u16)> = Vec::new(); + self.for_each_contact(|i, j, _| { + let (ci, cj) = (self.run_comp[i], self.run_comp[j]); + let (li, lj) = (self.runs[i].label, self.runs[j].label); + if ci != cj && is_halo(li) && !is_halo(lj) { + sides.push((ci, lj)); + } + if ci != cj && is_halo(lj) && !is_halo(li) { + sides.push((cj, li)); + } + }); + sides.sort_unstable(); + sides.dedup(); + let mut to = self.label.clone(); + let mut moved = 0; + for group in sides.chunk_by(|a, b| a.0 == b.0) { + if let [(c, l)] = group { + to[*c as usize] = *l; + moved += 1; + } + } + if moved > 0 { + self.relabel_components(&to); + } + moved + } +} + +/// The stretch `s..e` of run `r` whose pixels have their own label for `reach` pixels on +/// either side within the row (the image's edge counting as their own); empty (`s ≥ e`) +/// when the run is too short. `w` is the image width. +fn deep_span(r: &Run, w: u32, reach: u32) -> (u32, u32) { + let s = if r.x0 == 0 { 0 } else { r.x0 + reach }; + let e = if r.x1 == w { + w + } else { + r.x1.saturating_sub(reach) + }; + (s, e) +} + +#[cfg(test)] +mod tests; diff --git a/crates/inkvec-trace/src/fast/faces/halos/tests.rs b/crates/inkvec-trace/src/fast/faces/halos/tests.rs new file mode 100644 index 00000000..5b6339d5 --- /dev/null +++ b/crates/inkvec-trace/src/fast/faces/halos/tests.rs @@ -0,0 +1,275 @@ +use super::*; + +const BLUE: [f32; 4] = [0.235, 0.533, 0.761, 1.0]; +const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0]; +/// The two halo inks Fast founded on `twemoji/1f1fa` (web tier): #3f7eae and #bee1ff. +const DARK_HALO: [f32; 4] = [0.247, 0.494, 0.682, 1.0]; +const LIGHT_HALO: [f32; 4] = [0.745, 0.882, 1.0, 1.0]; +const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0]; + +/// Brute force: is any pixel of component `c` deep (its window of radius `reach` holds only +/// its label, the outside counting as its own)? +fn deep_by_pixels(labels: &[u16], w: usize, h: usize, reach: usize) -> Vec { + let mut runs = RunLabels::new(labels, w, h); + runs.components(); + let mut comp = vec![0u32; w * h]; + for y in 0..h { + for r in runs.row_start[y]..runs.row_start[y + 1] { + let Run { x0, x1, .. } = runs.runs[r]; + for x in x0..x1 { + comp[y * w + x as usize] = runs.run_comp[r]; + } + } + } + let mut deep = vec![false; runs.size.len()]; + for y in 0..h { + for x in 0..w { + let l = labels[y * w + x]; + let ok = (y.saturating_sub(reach)..(y + reach + 1).min(h)).all(|yy| { + (x.saturating_sub(reach)..(x + reach + 1).min(w)).all(|xx| labels[yy * w + xx] == l) + }); + if ok { + deep[comp[y * w + x] as usize] = true; + } + } + } + deep +} + +/// A small deterministic generator (xorshift), so the random images are the same every run. +fn xorshift(s: &mut u64) -> u64 { + *s ^= *s << 13; + *s ^= *s >> 7; + *s ^= *s << 17; + *s +} + +#[test] +fn deep_components_match_the_pixel_windows() { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + for case in 0..200 { + let (w, h) = (1 + case % 17, 1 + (case * 7) % 13); + let k = 2 + (case % 3) as u64; + // Blocky random labels, so some components are deep and some are not. + let labels: Vec = (0..w * h) + .map(|p| { + let (x, y) = (p % w, p / w); + let v = xorshift(&mut seed); + if v.is_multiple_of(4) { + (v % k) as u16 + } else { + (((x / 3) + (y / 4) * 2) as u64 % k) as u16 + } + }) + .collect(); + for reach in 1..=3u32 { + let mut runs = RunLabels::new(&labels, w, h); + runs.components(); + let got = runs.deep_components(reach); + assert_eq!( + got, + deep_by_pixels(&labels, w, h, reach as usize), + "case {case}, {w} x {h}, reach {reach}" + ); + } + } +} + +#[test] +fn ycc_is_jpegs_full_range_transform() { + let w = ycc(WHITE); + assert!((w[0] - 1.0).abs() < 1e-5 && w[1].abs() < 1e-5 && w[2].abs() < 1e-5); + assert_eq!(ycc(BLACK), [0.0, 0.0, 0.0]); + let red = ycc([1.0, 0.0, 0.0, 1.0]); + assert!((red[0] - 0.299).abs() < 1e-6 && (red[2] - 0.5).abs() < 1e-6); +} + +#[test] +fn a_halo_lies_in_the_hull_and_off_the_line() { + let (b, wh) = (ycc(BLUE), ycc(WHITE)); + for halo in [DARK_HALO, LIGHT_HALO] { + assert!(in_hull(ycc(halo), b, wh)); + // ... which the sRGB blend test does not see. + let (_, d) = super::super::blend_of(halo, BLUE, WHITE).unwrap(); + assert!(d > super::super::BLEND_TOL * super::super::BLEND_TOL); + } + // A black outline between them is no halo; nor is red between black and white. + assert!(!in_hull(ycc(BLACK), b, wh)); + assert!(!in_hull(ycc([0.85, 0.1, 0.1, 1.0]), ycc(BLACK), wh)); + assert_eq!(halo_pair(ycc(DARK_HALO), &[0, 1], &[b, wh]), Some((0, 1))); + assert_eq!(halo_pair(ycc(BLACK), &[0, 1], &[b, wh]), None); + assert_eq!(coverage(b, b, b), None); +} + +/// Columns: blue, a dark halo, a light halo, white -- the band a JPEG leaves -- and, +/// lower down, a black hairline between blue and white. `widths` are the column counts. +fn band_image(h: usize) -> (Vec, Vec<[f32; 3]>, usize) { + let cols: [(u16, usize); 4] = [(0, 8), (2, 2), (3, 2), (1, 8)]; + let w: usize = cols.iter().map(|c| c.1).sum(); + let inks = [BLUE, WHITE, DARK_HALO, LIGHT_HALO, BLACK]; + let mut labels = Vec::with_capacity(w * h); + for y in 0..h { + for &(l, n) in &cols { + let l = if y >= h / 2 && (l == 2 || l == 3) { + 4 + } else { + l + }; + labels.extend(std::iter::repeat_n(l, n)); + } + } + let rgb = labels + .iter() + .map(|&l| { + let c = inks[l as usize]; + [c[0], c[1], c[2]] + }) + .collect(); + (labels, rgb, w) +} + +#[test] +fn a_halo_band_goes_back_to_its_two_inks_and_a_hairline_stays() { + let h = 12; + let (labels, rgb, w) = band_image(h); + let inks = [BLUE, WHITE, DARK_HALO, LIGHT_HALO, BLACK]; + let mut runs = RunLabels::new(&labels, w, h); + let px = Pixels { + rgb: &rgb, + alpha: None, + }; + let (first, _) = runs.absorb_halos(px, &inks); + assert_eq!(first, 2, "the dark and the light halo"); + let out = runs.to_labels(); + for y in 0..h { + let row = &out[y * w..(y + 1) * w]; + if y < h / 2 { + // The dark halo's pixels are mostly blue (t < 1/2), the light one's mostly white. + assert_eq!(&row[8..10], &[0, 0], "row {y}"); + assert_eq!(&row[10..12], &[1, 1], "row {y}"); + } else { + assert_eq!( + &row[8..12], + &[4, 4, 4, 4], + "row {y}: the hairline is no halo" + ); + } + } + runs.assert_canonical(); +} + +#[test] +fn a_thick_band_is_no_halo() { + // The light halo's colour, but five pixels wide: an ink with an interior of radius 2. + let (w, h) = (20, 9); + let labels: Vec = (0..w * h) + .map(|p| match p % w { + 0..8 => 0, + 8..13 => 3, + _ => 1, + }) + .collect(); + let inks = [BLUE, WHITE, DARK_HALO, LIGHT_HALO]; + let rgb: Vec<[f32; 3]> = labels + .iter() + .map(|&l| { + [ + inks[l as usize][0], + inks[l as usize][1], + inks[l as usize][2], + ] + }) + .collect(); + let mut runs = RunLabels::new(&labels, w, h); + let px = Pixels { + rgb: &rgb, + alpha: None, + }; + assert_eq!(runs.absorb_halos(px, &inks), (0, 0)); + assert_eq!(runs.to_labels(), labels); +} + +#[test] +fn halo_specks_inside_one_ink_go_to_it() { + // A band (dark halo) along the blue-white edge, and two specks of the same ink inside + // the blue, away from the edge: with the band a halo, the specks follow it. + let (w, h) = (24, 12); + let mut labels: Vec = (0..w * h) + .map(|p| match p % w { + 0..10 => 0, + 10..12 => 2, + _ => 1, + }) + .collect(); + labels[3 * w + 3] = 2; + labels[8 * w + 5] = 2; + labels[8 * w + 6] = 2; + let inks = [BLUE, WHITE, DARK_HALO]; + let rgb: Vec<[f32; 3]> = labels + .iter() + .map(|&l| { + [ + inks[l as usize][0], + inks[l as usize][1], + inks[l as usize][2], + ] + }) + .collect(); + let mut runs = RunLabels::new(&labels, w, h); + let px = Pixels { + rgb: &rgb, + alpha: None, + }; + assert_eq!(runs.absorb_halos(px, &inks), (1, 2)); + let out = runs.to_labels(); + assert!(!out.contains(&2)); + assert_eq!(out[3 * w + 3], 0); +} + +/// A strip of a real ink -- one that owns an area elsewhere -- between two others whose +/// box it lies in but whose segment it is far from (`twemoji/1faa3`'s #55ACEE rim between +/// its navy and white, whose pixels the JPEG gives a mean of #62A9DD, 0.054 from the +/// segment) is no halo; a strip of an ink that owns no area is, at the same distance. +#[test] +fn a_strip_of_an_ink_with_an_area_must_lie_near_the_segment() { + const NAVY: [f32; 4] = [0.0, 0.29, 0.467, 1.0]; + const RIM: [f32; 4] = [0.384, 0.665, 0.868, 1.0]; + let (n, r, wh) = (ycc(NAVY), ycc(RIM), ycc(WHITE)); + assert!(in_hull(r, n, wh)); + let (_, d) = coverage(r, n, wh).unwrap(); + assert!(d.sqrt() > HALO_LINE_TOL, "{}", d.sqrt()); + // Navy | a two-pixel strip of the rim's ink | white, over rows 0..6; below, a block of + // the rim's ink with an interior (so the ink owns an area) when `area` is set. + let inks = [NAVY, WHITE, RIM]; + for area in [true, false] { + let (w, h) = (20, 12); + let labels: Vec = (0..w * h) + .map(|p| { + let (x, y) = (p % w, p / w); + match (x, y) { + (_, 6..) if area && (3..=14).contains(&x) => 2, + (0..8, _) => 0, + (8..10, 0..6) => 2, + _ => 1, + } + }) + .collect(); + let rgb: Vec<[f32; 3]> = labels + .iter() + .map(|&l| { + [ + inks[l as usize][0], + inks[l as usize][1], + inks[l as usize][2], + ] + }) + .collect(); + let mut runs = RunLabels::new(&labels, w, h); + let px = Pixels { + rgb: &rgb, + alpha: None, + }; + let (first, _) = runs.absorb_halos(px, &inks); + assert_eq!(first, usize::from(!area), "area {area}"); + } +} diff --git a/crates/inkvec-trace/src/fast/faces/tests.rs b/crates/inkvec-trace/src/fast/faces/tests.rs index 341cc33b..e1a31144 100644 --- a/crates/inkvec-trace/src/fast/faces/tests.rs +++ b/crates/inkvec-trace/src/fast/faces/tests.rs @@ -167,7 +167,7 @@ fn two_inks_one_eye_cannot_tell_apart_become_one_and_a_step_stays() { .map(|p| if p / w >= 7 { 2 } else { u16::from(p % w >= 5) }) .collect(); let mut runs = RunLabels::new(&labels, w, h); - runs.merge_same_inks(&inks); + runs.merge_same_inks(&inks, None); let labels = runs.to_labels(); // The larger of the two near-blacks (ink 1, 7 columns) takes the other. assert!(labels[..7 * w].iter().all(|&l| l == 1)); @@ -351,7 +351,7 @@ fn check_case(c: &Case, min_size: usize, what: &str) { runs.assert_canonical(); assert_eq!(runs.to_labels(), want, "{what}: rims"); reference::merge_same_inks(&mut want, &c.inks, w, h); - runs.merge_same_inks(&c.inks); + runs.merge_same_inks(&c.inks, None); runs.assert_canonical(); assert_eq!(runs.to_labels(), want, "{what}: same-ink merge"); reference::despeckle(&mut want, w, h, min_size); @@ -403,7 +403,7 @@ fn empty_images_have_no_runs_no_components_and_no_faces() { runs.assert_canonical(); runs.absorb_slivers(px, &inks); runs.absorb_rims(px, &inks); - runs.merge_same_inks(&inks); + runs.merge_same_inks(&inks, None); runs.despeckle(4); assert!(runs.write_faces(&mut []).is_empty(), "{w}x{h}"); } @@ -561,7 +561,7 @@ fn time_the_passes_on_the_research_dumps() { lap[1] = s.elapsed().as_secs_f64(); runs.absorb_rims(px, &c.inks); lap[2] = s.elapsed().as_secs_f64(); - runs.merge_same_inks(&c.inks); + runs.merge_same_inks(&c.inks, None); lap[3] = s.elapsed().as_secs_f64(); runs.despeckle(floor); lap[4] = s.elapsed().as_secs_f64(); @@ -596,3 +596,39 @@ fn time_the_passes_on_the_research_dumps() { ); } } + +/// On a lossy intake a thin fragment of an ink a few dE00 from its neighbour's is a variant +/// the codec made and takes the neighbour's ink; a block of the same ink with an interior is +/// an ink of its own and stays, as it does without the lossy threshold. +#[test] +fn thin_variants_of_an_ink_merge_on_a_lossy_intake_and_thick_ones_stay() { + let black = [0.0f32, 0.0, 0.0, 1.0]; + let variant = [0.004f32, 0.004, 0.035, 1.0]; + let white = [1.0f32, 1.0, 1.0, 1.0]; + let de00 = crate::color::de00([0.0, 0.0, 0.0], [0.004, 0.004, 0.035]); + assert!(de00 > crate::color::SAME_INK_DE00 && de00 < crate::color::SOFT_SAME_INK_DE00); + let inks = [black, variant, white]; + let (w, h) = (24, 12); + // A black block on white with a two-pixel sliver of the variant inside it, and a + // separate 6 x 6 block of the variant on the white. + let labels: Vec = (0..w * h) + .map(|p| { + let (x, y) = (p % w, p / w); + match (x, y) { + (1..=10, 1..=10) if x == 5 && (3..=8).contains(&y) => 1, + (1..=10, 1..=10) => 0, + (14..=19, 3..=8) => 1, + _ => 2, + } + }) + .collect(); + let mut clean = RunLabels::new(&labels, w, h); + clean.merge_same_inks(&inks, None); + assert_eq!(clean.to_labels(), labels, "the clean threshold keeps both"); + let mut lossy = RunLabels::new(&labels, w, h); + lossy.merge_same_inks(&inks, Some(crate::color::SOFT_SAME_INK_DE00)); + let out = lossy.to_labels(); + assert_eq!(out[5 * w + 5], 0, "the sliver joins the black around it"); + assert_eq!(out[5 * w + 16], 1, "the block with an interior stays"); + lossy.assert_canonical(); +} diff --git a/crates/inkvec-trace/src/fast/front.rs b/crates/inkvec-trace/src/fast/front.rs index 65faae5b..06c50a83 100644 --- a/crates/inkvec-trace/src/fast/front.rs +++ b/crates/inkvec-trace/src/fast/front.rs @@ -65,7 +65,8 @@ fn flat_fill(pal: &Palette, ink: usize) -> gradient::FillFit { /// stopwatch under its progress name: `palette` ([`super::palette::palette_and_labels`], /// then `color::split_alpha_inks` for `--cutout`); `slivers` (the labels read into row runs, /// [`super::faces::RunLabels::new`], then [`super::faces::RunLabels::absorb_slivers`], -/// [`super::faces::RunLabels::absorb_rims`] and [`super::faces::RunLabels::merge_same_inks`]); +/// [`super::faces::RunLabels::absorb_rims`], on a lossy intake +/// [`super::faces::RunLabels::absorb_halos`], and [`super::faces::RunLabels::merge_same_inks`]); /// `despeckle` ([`super::faces::RunLabels::despeckle`]); `split` /// ([`super::faces::RunLabels::write_faces`], the face ids written over the label buffer, /// the only per-pixel write of the clean-up); and `ramps` ([`super::bands::merge_ramps`], @@ -116,7 +117,19 @@ fn trace( // of large type were most of both on a textured masthead: 4,068 faces and 47,548 // coordinates, where these two passes leave 8,798 at a lower dE00. runs.absorb_rims(px, &inks); - runs.merge_same_inks(&inks); + // A lossy intake's edges carry the codec's halos, and its inks come back split + // into variants a few dE00 apart; both are handled only on a lossy intake, and only + // on an opaque one (the halo test reads JPEG's colour space, which has no + // opacity). A clean intake takes neither, and its output is unchanged. + let lossy = opts.lossy_intake && native.is_none(); + if lossy { + let (halos, specks) = runs.absorb_halos(px, &inks); + crate::diag!( + "slivers", + "lossy intake: {halos} halo components and {specks} halo specks given back" + ); + } + runs.merge_same_inks(&inks, lossy.then_some(crate::color::SOFT_SAME_INK_DE00)); } sw.mark("slivers"); inkvec_core::progress::begin("despeckle"); @@ -150,7 +163,10 @@ fn trace( .collect() }); // No noise measurement: the fast fitter reads no per-point uncertainty, and the - // refinement only needs a floor under its contrast test. + // refinement only needs a floor under its contrast test. For the same reason the strip + // reading's side test is not scaled with noise here (`soft_intake` false): with only the + // floor to scale by, it would move the threshold on faint edges by a constant rather than + // by anything measured (on `fast-web` it changed 12 icons, dE00 and geom no better). crate::finish_color_trace_alpha( img, opts, @@ -161,6 +177,7 @@ fn trace( face_color, n_faces, coverage::NOISE_FLOOR, + false, &mut sw, native, face_alpha, diff --git a/crates/inkvec-trace/src/fast/mod.rs b/crates/inkvec-trace/src/fast/mod.rs index 9d98798f..1b24b465 100644 --- a/crates/inkvec-trace/src/fast/mod.rs +++ b/crates/inkvec-trace/src/fast/mod.rs @@ -53,6 +53,7 @@ //! mode. mod bands; +mod codec; mod curve; mod faces; mod front; @@ -63,6 +64,7 @@ mod prims; mod replay; mod smooth; +pub(crate) use codec::clean_labels as clean_lossy_labels; pub(crate) use front::{trace_color, trace_color_native}; use crate::planar::Edge; diff --git a/crates/inkvec-trace/src/gradient/carve.rs b/crates/inkvec-trace/src/gradient/carve.rs index 1f33b9ac..46ee21ab 100644 --- a/crates/inkvec-trace/src/gradient/carve.rs +++ b/crates/inkvec-trace/src/gradient/carve.rs @@ -21,6 +21,31 @@ const CARVE_RESIDUAL: f64 = 0.06; /// Most features carved from one image, a guard against a textured region shattering. const CARVE_MAX: usize = 64; +/// On a lossy intake, how far from its region's edge a pixel must lie, in px, to be carved +/// ([`residual_mask`]): the codec's band, whose residual is the edge's damage, not a feature. +/// +/// A codec's error is not stationary: on the gate's `web` tier (resized, quality-80 JPEG) its +/// RMS is 4.5 levels of luma and 6.5 of chroma on the edge pixel, 3.1 and 2.7 one to two +/// pixels out, 2.3 and 1.6 at two to three, and 0.2 and 0.35 in the interiors +/// (`docs/theory/noise.md`), and its ringing is a pattern, not noise: a rim of residual just +/// inside every region, brighter or darker by turns. Carved, that rim became extra regions +/// along the edges, and where a gradient had explained it, a declined gradient's rim did too. +/// Measured on `quality-web` against the recorded baseline (246 icons, 2026-10-10, the gate's +/// distance axes; dE00, `turning_gap`, `ratio_gap`, geom): +/// +/// | band | icons changed | dE00 | `turning_gap` | `ratio_gap` | geom | +/// |---|---|---|---|---|---| +/// | 1 px | 17 | +0.21 % | −4.89 % | −0.58 % | −0.01 % | +/// | 2 px | 18 | −0.01 % | −5.38 % | −0.80 % | −0.10 % | +/// | 3 px | 20 | −0.03 % | −5.47 % | −0.82 % | +0.08 % | +/// +/// Two pixels is the one reach no axis reads worse at. +/// +/// Only on a lossy intake (`ColorOptions::lossy_intake`, a lossy container or a restored +/// image): a clean render has no codec band, and a seam two pixels from a clean edge is a +/// feature, so a clean trace is byte-identical. +pub const CODEC_BAND: usize = 2; + /// Give clustered residual pixels their own region. /// /// The palette sees colours, not features: a two-pixel white seam through a black shape, @@ -66,6 +91,7 @@ pub fn carve_residual_features( lambda, min_size, None, + 0, ) } @@ -77,6 +103,10 @@ pub fn carve_residual_features( /// edges, and a threshold set by edge noise would hide a faint stroke in the middle of a /// region. `None` is exactly [`carve_residual_features`]. /// +/// `codec_band`, when not 0, keeps every pixel within that many px of its region's edge out +/// of the carving: [`CODEC_BAND`] on a lossy intake, where that band's residual is the codec's +/// damage to the edge. 0 is exactly [`carve_residual_features`]. +/// /// The work runs in three stages: [`residual_mask`] marks the candidate pixels, /// [`mint_features`] turns their clusters into new flat regions, and [`refit_parents`] /// refits the regions they were cut from. The signature is kept flat rather than @@ -96,6 +126,7 @@ pub fn carve_residual_features_with_detail_noise( lambda: f64, min_size: usize, detail_sigma: Option, + codec_band: usize, ) -> usize { let n = w * h; if fills.is_empty() || n == 0 { @@ -108,6 +139,7 @@ pub fn carve_residual_features_with_detail_noise( pal, sigma_noise, lambda, + codec_band, }; let mask = residual_mask(&img, labels, fills, detail_sigma); let (minted, parents) = mint_features(&img, labels, fills, ink, &mask, min_size); @@ -134,6 +166,9 @@ struct CarveImage<'a> { sigma_noise: f64, /// Price of one editable number in the MDL cost. lambda: f64, + /// Residual within this many px of a region's edge is not carved: [`CODEC_BAND`] on a + /// lossy intake, 0 otherwise. + codec_band: usize, } impl CarveImage<'_> { @@ -152,6 +187,22 @@ impl CarveImage<'_> { } } +/// Whether every pixel within `r` px of `p` (its `(2r+1)²` window) lies in the picture and +/// carries `p`'s label: `p` is deeper inside its region than a codec band of `r` px. +fn beyond_band(labels: &[u16], w: usize, h: usize, p: usize, r: usize) -> bool { + let (x, y) = (p % w, p / w); + let l = labels[p]; + x >= r + && y >= r + && x + r < w + && y + r < h + && (y - r..=y + r).all(|yy| { + labels[yy * w + x - r..=yy * w + x + r] + .iter() + .all(|&m| m == l) + }) +} + /// Whether pixel `p` is strictly inside its label: not on the picture edge, and all four /// neighbours carry the same label. fn interior4(labels: &[u16], w: usize, h: usize, p: usize) -> bool { @@ -169,8 +220,9 @@ fn interior4(labels: &[u16], w: usize, h: usize, p: usize) -> bool { /// Stage 1: the pixels the chosen fill does not explain. /// -/// A pixel is marked when it is strictly interior to its label ([`interior4`]), pure -/// (not a blend of nearby inks, [`fill_evidence`]), its label has a reliable flat colour +/// A pixel is marked when it is strictly interior to its label ([`interior4`]), beyond the +/// codec's band on a lossy intake ([`beyond_band`] at [`CODEC_BAND`]), pure (not a blend of +/// nearby inks, [`fill_evidence`]), its label has a reliable flat colour /// ([`region_flat_colours`]), and its residual against the label's fill, /// `r = max_ch |c_ch − f_ch(x, y)|` in sRGB, exceeds `max(8σ, CARVE_RESIDUAL)`. Where /// `detail_sigma` is given and the pixel's 7x7 neighbourhood is all one label, `σ` is @@ -216,6 +268,9 @@ fn residual_mask( if !interior4(labels, w, h, p) || !pure0[p] { continue; } + if img.codec_band > 0 && !beyond_band(labels, w, h, p, img.codec_band) { + continue; + } let c = rgb[p]; let pred = f.model.color_at((p % w) as f64, (p / w) as f64); let r_fit = (0..3).map(|k| (c[k] - pred[k]).abs()).fold(0f32, f32::max); @@ -489,6 +544,7 @@ mod lossy_detail_tests { 1.0, 2, detail, + 0, ); labels }; @@ -497,4 +553,66 @@ mod lossy_detail_tests { assert_ne!(detailed[16 * w + 12], 0); assert_eq!(detailed[16 * w + 1], 0); } + + /// On a lossy intake the codec's band along a region's edge is not carved: a tinted + /// column one pixel inside the white ground, beside a black square, is carved without the + /// band and left to the ground with it, while a tinted dot deep in the ground is carved + /// either way. + #[test] + fn the_codec_band_along_an_edge_is_not_carved() { + let (w, h) = (32, 32); + let tint = [0.75, 1.0, 1.0]; + let mut rgb = vec![[1.0; 3]; w * h]; + let mut labels = vec![0u16; w * h]; + for y in 10..22 { + for x in 10..22 { + rgb[y * w + x] = [0.0; 3]; + labels[y * w + x] = 1; + } + } + for y in 12..20 { + rgb[y * w + 8] = tint; + rgb[y * w + 9] = tint; + } + for y in 25..27 { + for x in 25..27 { + rgb[y * w + x] = tint; + } + } + let pal = Palette { + rgb: vec![[1.0; 3], [0.0; 3]], + colors: vec![ + crate::color::rgb_to_oklab([1.0; 3]), + crate::color::rgb_to_oklab([0.0; 3]), + ], + weight: vec![1.0, 1.0], + alpha: vec![1.0, 1.0], + }; + let run = |band| { + let mut labels = labels.clone(); + let mut fills = vec![flat_only([1.0; 3], 1.0), flat_only([0.0; 3], 1.0)]; + let mut ink = vec![0, 1]; + carve_residual_features_with_detail_noise( + &mut labels, + &rgb, + w, + h, + &pal, + &mut fills, + &mut ink, + 0.5 / 255.0, + 1.0, + 2, + None, + band, + ); + labels + }; + let plain = run(0); + assert!(plain[16 * w + 8] > 1, "carved without the band"); + assert!(plain[25 * w + 25] > 1, "the dot is carved"); + let banded = run(CODEC_BAND); + assert_eq!(banded[16 * w + 8], 0, "the band is left to the ground"); + assert!(banded[25 * w + 25] > 1, "the dot is still carved"); + } } diff --git a/crates/inkvec-trace/src/lib.rs b/crates/inkvec-trace/src/lib.rs index d3a3c74f..ba1b6a01 100644 --- a/crates/inkvec-trace/src/lib.rs +++ b/crates/inkvec-trace/src/lib.rs @@ -81,6 +81,7 @@ pub mod coverage; #[cfg(feature = "research")] pub mod decode; pub mod diag; +pub mod evidence; pub mod fast; pub mod gradient; #[cfg(feature = "research")] @@ -92,8 +93,8 @@ pub mod planar; pub mod regions; pub mod regroup; pub mod regularize; -// Stroke-drawn faces as centrelines plus one width, behind `--detect-strokes` -// (`Options::detect_strokes`) in the CLI's colour pipeline. +// Stroke-drawn faces as centrelines plus one width, in the CLI's colour pipeline +// (`Options::detect_strokes`, on by default). pub mod ribbon; pub mod softness; pub mod symmetry; @@ -183,6 +184,9 @@ pub struct ColorOptions { /// The intake came out of a lossy codec, so the palette's noise guard must run even /// though the edges are sharp. See [`lossy_container`]. pub lossy_intake: bool, + /// The image came out of the restorer, which took the codec's damage out: Quality's codec + /// clean-up (`fast::codec`) does not run, though the intake stays lossy for the palette. + pub restored: bool, /// Carry transparency natively: inks with opacity, the clear ground as an ink, and /// alpha as a fourth channel wherever the tracer unmixes. See [`native`]. Only an image /// with transparency takes this path; an opaque one traces as it always has. @@ -215,6 +219,7 @@ impl Default for ColorOptions { deadline: None, boundary_ms: None, lossy_intake: false, + restored: false, min_region: 4, fast: false, absorb_blends: true, @@ -258,6 +263,8 @@ pub struct ColorTrace { /// Per face, when transparency was traced natively and the face is a fade: one colour /// at an opacity that varies across it. Empty on the classic path. pub face_fade: Vec>, + /// The intake's noise at its edges, on a soft colour-path intake (`evidence::with_noise`). + pub noise: inkvec_core::noise::NoiseModel, } /// Full colour front end, with alpha assumed opaque. See [`trace_color_full_with_alpha`]. @@ -280,7 +287,7 @@ pub fn trace_color_full(img: &Rgba, opts: &ColorOptions) -> ColorTrace { /// counterpart when `opts.fast`); /// * otherwise `opts.fast`: the Fast engine's front end ([`fast`]); /// * otherwise the Quality pipeline below, stages 1–9 of the crate overview, then -/// `finish_color_trace` for the geometry. +/// `finish_color_trace_alpha` for the geometry. /// /// # Inputs and outputs /// @@ -544,6 +551,9 @@ pub fn trace_color_full_with_alpha( progress::begin("despeckle"); despeckle(&mut labels, img.width, img.height, min_region); + if opts.lossy_intake && !opts.restored { + fast::clean_lossy_labels(&mut labels, img, &rgb, &pal, source_alpha); + } sw.mark("despeckle"); progress::begin("blend_absorb"); @@ -676,6 +686,7 @@ pub fn trace_color_full_with_alpha( gradient::bic_lambda(img.width * img.height), min_region.max(2), (opts.lossy_intake && research_lossy_regularize()).then_some(detail_sigma), + codec_band(opts), ); if carved > 0 && inkvec_core::env::flag("INKVEC_TIMING") { eprintln!(" [t] carved {carved} residual feature(s) into regions"); @@ -738,7 +749,7 @@ pub fn trace_color_full_with_alpha( ); crate::diag!("fills", "snapped to their ink's colour: {snapped}"); - finish_color_trace( + let ct = finish_color_trace_alpha( img, opts, &rgb, @@ -748,8 +759,12 @@ pub fn trace_color_full_with_alpha( face_color, n_faces, sigma_noise, + soft_intake, &mut sw, - ) + None, + None, + ); + evidence::with_noise(ct, &rgb, soft_intake, opts.lossy_intake, &mut sw) } /// Research entry: run the colour tracer from a caller-supplied label map. @@ -776,7 +791,7 @@ pub fn trace_color_full_with_alpha( /// per-face fit would re-shatter a gradient the merge stage had just reassembled; /// 5. `split_components`, then `face_fill` / `face_color` read off `fills_by_label` / /// `label_ink` exactly as above; -/// 6. `finish_color_trace`: saddles, planar map, sub-pixel and junction refinement, the +/// 6. `finish_color_trace_alpha`: saddles, planar map, sub-pixel and junction refinement, the /// global boundary solve, decoding and symmetry. /// /// What is *not* run: palette extraction (`extract_palette_mdl`), `label_image`, alpha-ink @@ -953,6 +968,7 @@ pub fn trace_color_from_labels( lambda, opts.min_region.max(2), None, + codec_band(opts), ); if carved > 0 && inkvec_core::env::flag("INKVEC_TIMING") { eprintln!(" [t] carved {carved} residual feature(s) into regions"); @@ -992,7 +1008,7 @@ pub fn trace_color_from_labels( .map(|&l| label_ink.get(l).copied().unwrap_or(l)) .collect(); - finish_color_trace( + finish_color_trace_alpha( img, opts, &rgb, @@ -1002,49 +1018,20 @@ pub fn trace_color_from_labels( face_color, n_faces, sigma_noise, + opts.lossy_intake, &mut sw, - ) -} - -/// Everything from saddle disambiguation onwards: the geometry stages, which do not care -/// how the labels were arrived at. -/// -/// Shared by [`trace_color_full_with_alpha`] and [`trace_color_from_labels`] so the -/// research entry cannot drift away from the shipped one. The opaque form of -/// [`finish_color_trace_alpha`], which documents the arguments. -#[allow(clippy::too_many_arguments)] -fn finish_color_trace( - img: &Rgba, - opts: &ColorOptions, - rgb: &[[f32; 3]], - pal: Palette, - labels: Vec, - face_fill: Vec, - face_color: Vec, - n_faces: usize, - sigma_noise: f64, - sw: &mut Stopwatch, -) -> ColorTrace { - finish_color_trace_alpha( - img, - opts, - rgb, - pal, - labels, - face_fill, - face_color, - n_faces, - sigma_noise, - sw, None, None, ) } -/// [`finish_color_trace`], told the source's alpha. The sub-pixel refinement and the -/// boundary solve then unmix in four channels, each face at its palette entry's opacity, so -/// an edge between white paint and the clear ground is found although over white it has no -/// contrast at all. With `None` this is exactly the classic function. +/// Everything from saddle disambiguation onwards: the geometry stages, which do not care +/// how the labels were arrived at. Shared by [`trace_color_full_with_alpha`], +/// [`trace_color_from_labels`] and [`native::trace_color`], so no entry can drift from +/// another. Told the source's alpha, the sub-pixel refinement and the boundary solve unmix in +/// four channels, each face at its palette entry's opacity, so an edge between white paint +/// and the clear ground is found although over white it has no contrast at all; the opaque +/// entries pass `None` twice. /// /// # Stages /// @@ -1063,6 +1050,7 @@ fn finish_color_trace( /// * `face_fill`, `face_color`: per face, its fitted fill and its palette index; /// * `sigma_noise`: per-channel noise in sRGB units, which sets how far the sub-pixel /// refinement trusts each pixel; +/// * `soft_intake`: the intake is soft or lossy (`planar::measure_subpixel`); /// * `sw`: the caller's stopwatch, so stage timings continue in one sequence; /// * `source_alpha`: the source's alpha per pixel, or `None` on the opaque path; /// * `face_alpha_override`: per face, the opacity at which it meets the ground (the @@ -1081,6 +1069,7 @@ pub(crate) fn finish_color_trace_alpha( face_color: Vec, n_faces: usize, sigma_noise: f64, + soft_intake: bool, sw: &mut Stopwatch, source_alpha: Option<&[f32]>, face_alpha_override: Option>, @@ -1143,6 +1132,7 @@ pub(crate) fn finish_color_trace_alpha( &face_model, sigma_noise, opts.simplify_faint, + soft_intake, alpha_pair, ) }; @@ -1212,6 +1202,17 @@ pub(crate) fn finish_color_trace_alpha( face_rgb, sigma_noise, face_fade: Vec::new(), + noise: inkvec_core::noise::NoiseModel::clean(), + } +} + +/// How far from a region's edge the carve stage ignores residual: the codec's band on a +/// lossy intake (`gradient::carve::CODEC_BAND`), nothing on a clean one. +pub(crate) fn codec_band(opts: &ColorOptions) -> usize { + if opts.lossy_intake { + gradient::carve::CODEC_BAND + } else { + 0 } } diff --git a/crates/inkvec-trace/src/native.rs b/crates/inkvec-trace/src/native.rs index 35b81f9b..55748115 100644 --- a/crates/inkvec-trace/src/native.rs +++ b/crates/inkvec-trace/src/native.rs @@ -1008,6 +1008,7 @@ pub fn trace_color(img: &Rgba, opts: &ColorOptions, alpha: &[f32]) -> ColorTrace gradient::bic_lambda(w * h), min_region.max(2), None, + crate::codec_band(opts), ); name_carved_paint(&labels, &rgb, alpha, &pal, &mut label_ink, carved_from); } @@ -1097,6 +1098,7 @@ pub fn trace_color(img: &Rgba, opts: &ColorOptions, alpha: &[f32]) -> ColorTrace face_color, n_faces, sigma_noise, + soft_intake, &mut sw, Some(alpha), Some(face_alpha), diff --git a/crates/inkvec-trace/src/planar.rs b/crates/inkvec-trace/src/planar.rs index 3329e205..959ffc2c 100644 --- a/crates/inkvec-trace/src/planar.rs +++ b/crates/inkvec-trace/src/planar.rs @@ -59,7 +59,7 @@ use std::collections::HashMap; -use inkvec_core::{Point, Polyline, Vec2}; +use inkvec_core::{Point, Polyline}; use crate::gradient::FillModel; @@ -117,9 +117,12 @@ pub struct PlanarMap { pub n_labels: usize, } +mod chord; mod cracks; pub(crate) mod junctions; pub(crate) mod runs; +mod strip; +use chord::probe_chord; use cracks::{dual_segments, Incidence, Seg}; pub use junctions::{node_position, refine_junctions}; @@ -413,16 +416,6 @@ fn walk_closed_loops( /// Smallest colour separation (sRGB, Euclidean) a vertex is unmixed across. const MIN_UNMIX_CONTRAST: f64 = 0.02; -/// Points each side of a vertex its tangent is taken over; see the comment where it is -/// used, in `probe_chord`, for the measurement that left it at one (it was -/// `INKVEC_SUBPX_WIN`, 1..=8). -const SUBPX_WIN: usize = 1; - -/// Cosine of the turning angle between a point's two chords above which the point is -/// treated as a corner by `refine_subpixel` (60 degrees). A staircase at any slope turns -/// by at most 45 degrees between chords two points long, so slanted edges stay smooth. -const CORNER_COS: f64 = 0.5; - /// Move every boundary vertex of `map` to its sub-pixel position, and record how well /// localized it is. /// @@ -473,7 +466,16 @@ pub fn refine_subpixel_alpha( simplify_faint: bool, src_alpha: Option<(&[f32], &[f32])>, ) { - measure_subpixel(map, rgb, face_fill, sigma_noise, simplify_faint, src_alpha).apply(map); + measure_subpixel( + map, + rgb, + face_fill, + sigma_noise, + simplify_faint, + false, + src_alpha, + ) + .apply(map); } /// The refined geometry of every edge of a map, measured but not yet written back: what @@ -526,7 +528,9 @@ pub(crate) fn refine_in_parallel(map: &PlanarMap) -> bool { } /// Measure the sub-pixel position and sigma of every vertex of `map` (the arguments are -/// [`refine_subpixel_alpha`]'s), without changing `map`. +/// [`refine_subpixel_alpha`]'s), without changing `map`. `soft` says the front end found the +/// intake soft or lossy (wide edges, ringing, or a lossy container): the strip reading's side +/// test then scales with the intake's noise (`strip::SIDE_Z`); on a clean intake it does not. /// /// # Schedule /// @@ -571,6 +575,7 @@ pub(crate) fn measure_subpixel( face_fill: &[FillModel], sigma_noise: f64, simplify_faint: bool, + soft: bool, src_alpha: Option<(&[f32], &[f32])>, ) -> Refined { use rayon::prelude::*; @@ -585,6 +590,7 @@ pub(crate) fn measure_subpixel( sigma_noise, min_contrast: (3.0 * sigma_noise).max(MIN_UNMIX_CONTRAST), simplify_faint, + soft, debug: inkvec_core::env::flag("INKVEC_SUBPXDBG"), dump: inkvec_core::env::path("INKVEC_DUMP_CONTOUR"), }; @@ -688,6 +694,8 @@ struct RefineCtx<'a> { /// Below this colour separation a vertex is not unmixed: `max(3·sigma_noise, 0.02)`. min_contrast: f64, simplify_faint: bool, + /// The front end found the intake soft or lossy; see [`measure_subpixel`]. + soft: bool, /// `INKVEC_SUBPXDBG`: print every vertex's probes to stderr. debug: bool, /// `INKVEC_DUMP_CONTOUR`: the file every refined edge is appended to. @@ -727,7 +735,7 @@ fn refine_edge( let n = e.points.len(); let par = par && n >= PAR_VERTICES; - let vertex = |k: usize| refine_vertex(ctx, fa, fb, e.left, e.right, &e.points, k); + let vertex = |k: usize| refine_vertex(ctx, fa, fb, e, k); let (moved, sigmas): (Vec, Vec) = if par { (0..n) .into_par_iter() @@ -784,7 +792,9 @@ fn dump_contour(path: &std::path::Path, points: &[Point], sigmas: &[f64], closed /// `right` (fill `fb`), and its positional sigma before the curvature correction. /// /// Steps: take the local normal ([`probe_chord`]); build the unmixing axis between the two -/// faces' colours at this point ([`unmix_axis`]); read the coverage at the pixel centres +/// faces' colours at this point ([`unmix_axis`]); between two flat fills, slide the vertex +/// onto the cubic its column sums describe ([`strip::strip_offset`]) and stop there unless +/// that declines; otherwise read the coverage at the pixel centres /// the normal passes through ([`probe_pixel_centres`]); if the profile is a clean step /// between two flat fills, invert it directly ([`invert_step`]), otherwise root-find the /// 0.5 level of the interpolated coverage ([`root_find_half`]). The shift along the normal @@ -794,13 +804,12 @@ fn refine_vertex( ctx: &RefineCtx, fa: &FillModel, fb: &FillModel, - left: u16, - right: u16, - points: &[Point], + e: &Edge, k: usize, ) -> (Point, f64) { + let (points, left, right) = (&e.points, e.left, e.right); let p = points[k]; - let (t, corner) = probe_chord(points, k); + let (t, corner) = probe_chord(points, k, e.closed && points.len() >= 3); let tl = t.norm(); let axis = unmix_axis(ctx, fa, fb, left, right, p); // Nothing to unmix across: the vertex stays on the grid at grid uncertainty. @@ -810,6 +819,12 @@ fn refine_vertex( let nx = -t.y / tl; let ny = t.x / tl; + // The strip reading first (exact column sums; `strip.rs`), the probes where it declines. + if let Some(t) = strip::strip_offset(ctx, &axis, fa, fb, corner, p, (nx, ny)) { + let moved = Point::new(p.x + nx * t, p.y + ny * t); + return (moved, vertex_sigma(ctx, &axis, p, nx, ny)); + } + let probes = probe_pixel_centres(ctx, &axis, p, nx, ny); // Which way alpha grows along the normal. let dir = match (probes.first(), probes.last()) { @@ -842,45 +857,6 @@ fn refine_vertex( (moved, vertex_sigma(ctx, &axis, p, nx, ny)) } -/// The chord whose perpendicular is taken as vertex `k`'s normal, and whether `k` is a -/// corner. -/// -/// The chord runs from the point `SUBPX_WIN` before `k` to the one `SUBPX_WIN` after -/// (clamped to the ends of the edge). With a wider window, a vertex whose two chords turn -/// by more than 60 degrees (`CORNER_COS`) is a corner and falls back to its immediate -/// neighbours. At the shipped window of 1 the corner test never fires. -fn probe_chord(points: &[Point], k: usize) -> (Vec2, bool) { - let n = points.len(); - let p = points[k]; - // Local tangent from neighbours, normal perpendicular to it. The window is - // `SUBPX_WIN` points each side. - // - // A wider `SUBPX_WIN` averages the tangent over more points. The - // marching-squares polyline is a staircase, so a tangent from the immediate - // neighbours is quantised to a few directions and on a slanted edge the probe - // line is off-axis. Two points each side averages that out and improves the - // colour error (620-icon subset: dE00 0.2663 -> 0.2534 against the root-find, - // where one point each side gives 0.2591) - but it costs DISTS (0.0418 -> - // 0.0435), because a wide tangent at a corner moves the vertex sideways, and - // it has a failure mode: on one openmoji juggler the body's boundary moved - // enough to change which face the emitter paints on top (dE00 0.23 -> 3.20). - // Corners keep the narrow tangent already, so the remaining harm is elsewhere. - // Default is one point each side until that is understood (LOG-43). - let win = SUBPX_WIN; - let (pa, pb) = (points[k.saturating_sub(win)], points[(k + win).min(n - 1)]); - let corner = win > 1 && { - let (c0, c1) = (p - pa, pb - p); - let (l0, l1) = (c0.norm(), c1.norm()); - l0 > 1e-9 && l1 > 1e-9 && (c0.x * c1.x + c0.y * c1.y) / (l0 * l1) < CORNER_COS - }; - let (pa, pb) = if corner { - (points[k.saturating_sub(1)], points[(k + 1).min(n - 1)]) - } else { - (pa, pb) - }; - (pb - pa, corner) -} - /// The axis a vertex's coverage is measured along: from the right face's colour /// (coverage 0) to the left face's (coverage 1), optionally with opacity as a fourth /// channel. diff --git a/crates/inkvec-trace/src/planar/chord.rs b/crates/inkvec-trace/src/planar/chord.rs new file mode 100644 index 00000000..80b0adaa --- /dev/null +++ b/crates/inkvec-trace/src/planar/chord.rs @@ -0,0 +1,71 @@ +//! The lattice normal of a boundary vertex: the chord between its neighbours, which +//! `refine_vertex` reads the image across. Split from `planar.rs`, unchanged but for the +//! wrap round a closed edge's seam. + +use inkvec_core::{Point, Vec2}; + +/// Points each side of a vertex its tangent is taken over; see the comment where it is +/// used, in `probe_chord`, for the measurement that left it at one (it was +/// `INKVEC_SUBPX_WIN`, 1..=8). +const SUBPX_WIN: usize = 1; + +/// Cosine of the turning angle between a point's two chords above which the point is +/// treated as a corner by `refine_subpixel` (60 degrees). A staircase at any slope turns +/// by at most 45 degrees between chords two points long, so slanted edges stay smooth. +const CORNER_COS: f64 = 0.5; + +/// The chord whose perpendicular is taken as vertex `k`'s normal, and whether `k` is a +/// corner. +/// +/// The chord runs from the point `SUBPX_WIN` before `k` to the one `SUBPX_WIN` after, +/// clamped to the ends of an open edge and, with `wrap`, wrapped round a closed one (whose +/// first point is not repeated at its end; clamped, its seam took a one-sided chord, and on a +/// horizontal run a horizontal normal: 0.30 px off on an exact disc, in Fast mode). With a +/// wider window, a vertex whose two chords turn by more than 60 degrees (`CORNER_COS`) is a +/// corner and falls back to its immediate neighbours. At the shipped window of 1 the corner +/// test never fires. +pub(super) fn probe_chord(points: &[Point], k: usize, wrap: bool) -> (Vec2, bool) { + let n = points.len(); + let p = points[k]; + let before = |d: usize| { + if wrap { + (k + n - d % n) % n + } else { + k.saturating_sub(d) + } + }; + let after = |d: usize| { + if wrap { + (k + d) % n + } else { + (k + d).min(n - 1) + } + }; + // Local tangent from neighbours, normal perpendicular to it. The window is + // `SUBPX_WIN` points each side. + // + // A wider `SUBPX_WIN` averages the tangent over more points. The + // marching-squares polyline is a staircase, so a tangent from the immediate + // neighbours is quantised to a few directions and on a slanted edge the probe + // line is off-axis. Two points each side averages that out and improves the + // colour error (620-icon subset: dE00 0.2663 -> 0.2534 against the root-find, + // where one point each side gives 0.2591) - but it costs DISTS (0.0418 -> + // 0.0435), because a wide tangent at a corner moves the vertex sideways, and + // it has a failure mode: on one openmoji juggler the body's boundary moved + // enough to change which face the emitter paints on top (dE00 0.23 -> 3.20). + // Corners keep the narrow tangent already, so the remaining harm is elsewhere. + // Default is one point each side until that is understood (LOG-43). + let win = SUBPX_WIN; + let (pa, pb) = (points[before(win)], points[after(win)]); + let corner = win > 1 && { + let (c0, c1) = (p - pa, pb - p); + let (l0, l1) = (c0.norm(), c1.norm()); + l0 > 1e-9 && l1 > 1e-9 && (c0.x * c1.x + c0.y * c1.y) / (l0 * l1) < CORNER_COS + }; + let (pa, pb) = if corner { + (points[before(1)], points[after(1)]) + } else { + (pa, pb) + }; + (pb - pa, corner) +} diff --git a/crates/inkvec-trace/src/planar/refine_tests.rs b/crates/inkvec-trace/src/planar/refine_tests.rs index 5174cad4..05cced1f 100644 --- a/crates/inkvec-trace/src/planar/refine_tests.rs +++ b/crates/inkvec-trace/src/planar/refine_tests.rs @@ -26,6 +26,7 @@ fn refine_serial( sigma_noise, min_contrast: (3.0 * sigma_noise).max(MIN_UNMIX_CONTRAST), simplify_faint: false, + soft: false, debug: false, dump: None, }; @@ -40,7 +41,7 @@ fn refine_serial( continue; }; let (moved, sigmas): (Vec, Vec) = (0..e.points.len()) - .map(|k| refine_vertex(&ctx, fa, fb, e.left, e.right, &e.points, k)) + .map(|k| refine_vertex(&ctx, fa, fb, e, k)) .unzip(); let closed = e.closed; let sigmas: Vec = (0..moved.len()) diff --git a/crates/inkvec-trace/src/planar/strip.rs b/crates/inkvec-trace/src/planar/strip.rs new file mode 100644 index 00000000..7575e4f7 --- /dev/null +++ b/crates/inkvec-trace/src/planar/strip.rs @@ -0,0 +1,420 @@ +//! The strip reading of a boundary vertex: exact column sums, a histopolated cubic, and +//! the vertex slid along its normal onto that cubic. +//! +//! A pixel's coverage is the area of the shape inside it, so the coverages of a column of +//! pixels, summed from a pixel wholly on one side of a boundary to a pixel wholly on the +//! other, are *exactly* the column mean of the boundary's height, whatever its slope or +//! curvature (`column_sum_eq_average` in `formal/InkvecTheory/InkvecTheory/Coverage.lean`). +//! Four adjacent column means determine a unique cubic (`poly_eq_of_averages`, +//! `Identifiability.lean`: histopolation is unisolvent), and that cubic *is* the boundary +//! whenever the boundary is a cubic, so a vertex slid along its normal onto it lands on the +//! boundary with no normal-direction, threshold or interpolation error. Measured on circles, +//! ellipses, straight edges, rotated squares and regular polygons at 64 px +//! (`bench/theory/inkvec_compare.py`), stage 07's points, every vertex counted including +//! those this declines, lie 0.011 px from the true boundary on average against 0.073 px with +//! the per-vertex probes alone on exact area renders, and 0.016 px against 0.073 px on 8x8 +//! supersampled ones (the corpus's renderer). +//! +//! Method from: the partial area effect of A. Trujillo-Pino, K. Krissian, +//! M. Alemán-Flores, D. Santana-Cedrés (2013), *Accurate subpixel edge location based on +//! partial area effect*, Image and Vision Computing 31(1):72-90, +//! , which recovers a quadratic edge from +//! three column sums; and the cell-average reconstruction of finite-volume schemes +//! (e.g. P. McCorquodale, P. Colella (2011), *A high-order finite-volume method for +//! conservation laws on locally refined grids*, CAMCoS 6(1), +//! ). Adapted: the column window runs from a +//! saturated pixel of one face to a saturated pixel of the other (the flanks' own values +//! are summed, which keeps the sum unbiased under noise); the cubic is histopolated from +//! four columns and checked against two more, which is what refuses a corner; and the +//! vertex keeps its lattice normal and only chooses where along it to sit, so the edge +//! keeps its points. + +use inkvec_core::Point; +use inkvec_verified::generated::strip as generated; +use inkvec_verified::iv::Iv; + +use super::{RefineCtx, Source, UnmixAxis}; +use crate::gradient::FillModel; + +/// Pixels either side of the vertex searched along a column for the window's flanks. A +/// boundary within 45 degrees of the column's normal crosses at most two pixels of it, so +/// three reach both flanks from any vertex on it. +const REACH: isize = 3; + +/// Coverage within this of 0 or 1 makes a pixel a flank: wholly one face. +const SATURATED: f64 = 0.06; + +/// Largest disagreement, in px, at the vertex's pixel border between the cubic through the +/// four central columns and either one-sided cubic (columns -3..=0 or -1..=2). Every cubic +/// boundary makes all three agree exactly; a corner within reach does not. Each one-sided +/// difference carries 0.7 times the noise of one column mean, so on 8x8 supersampled +/// renders, whose column means scatter by a few hundredths of a pixel, the test still +/// passes a smooth boundary. +const SIDE_TOL: f64 = 0.05; + +/// The one-sided test in standard deviations of its own noise, on a soft intake only: +/// `|D|/12` exceeds `SIDE_Z·√(70 V)/12` (`fourthDiff_side`: the one-sided difference is the +/// fourth difference of the six column means over 12, whose variance is `70 V` for column +/// means of variance `V`). It replaces [`SIDE_TOL`] where the intake's noise makes it the +/// larger, so a noisy intake does not have every smooth vertex declined as a corner; the +/// evidence threshold moves, the certificate does not. +/// +/// Only on an intake the front end found soft or lossy (`RefineCtx::soft`). On a clean render +/// a low-contrast edge (shading) makes `σ/|d|` large too, and there `SIDE_TOL` stays: it is +/// what the clean tiers were tuned on, and they keep their bytes. +const SIDE_Z: f64 = 3.0; + +/// Largest difference, in px, between adjacent column means: the boundary may be at most +/// this steep across the scan, about 56 degrees. +const MAX_STEP: f64 = 1.5; + +/// The projection of pixel `(x, y)` onto the vertex's unmixing axis, *unclamped*, and the +/// squared distance of its colour from the line through the two faces' colours (how far the +/// pixel is from being a mixture of the two). Unclamped because the column sums must stay +/// unbiased under noise. Read straight from the pixel: the strip reading only ever asks at +/// pixel centres, where the bilinear sampler the probes use returns the pixel itself. The +/// caller keeps `(x, y)` inside the image. +fn unmix(axis: &UnmixAxis, src: &Source, x: usize, y: usize) -> (f64, f64) { + let (cb, d) = (axis.cb, axis.d); + let p = src.rgb[y * src.w + x]; + let q = [p[0] - cb[0], p[1] - cb[1], p[2] - cb[2]]; + let a = (q[0] * d[0] + q[1] * d[1] + q[2] * d[2]) as f64 / axis.dd; + let r2: f64 = (0..3) + .map(|c| { + let e = q[c] as f64 - a * d[c] as f64; + e * e + }) + .sum(); + (a, r2) +} + +/// The column mean of the boundary's height across one column (or row, `transpose`), whether +/// the vertex's left face (coverage 1) lies on the low-index side, and how many pixels the +/// window summed. +/// +/// `line` is the column's pixel index, `v0` the vertex's height. Pixels within [`REACH`] +/// of `v0` are read through the unmixing axis; the window is the run from a saturated +/// pixel of one face to the nearest saturated pixel of the other with only partial pixels +/// between, and its sum is the boundary's column mean measured from the window's top edge +/// (`column_sum_eq_average`). Of several such windows the one whose mean lies nearest `v0` +/// is taken. `None` when no window exists within reach, when a pixel of it is not a +/// mixture of the two faces (a third colour, a junction), or when the column is outside +/// the image. +fn line_mean( + ctx: &RefineCtx, + axis: &UnmixAxis, + line: isize, + v0: f64, + transpose: bool, +) -> Option<(f64, bool, usize)> { + let (w, h) = (ctx.src.w as isize, ctx.src.h as isize); + let (n_line, n_along) = if transpose { (h, w) } else { (w, h) }; + if line < 0 || line >= n_line { + return None; + } + let r0 = (v0.floor() as isize - REACH).max(0); + let r1 = (v0.ceil() as isize + REACH).min(n_along - 1); + if r1 - r0 < 2 { + return None; + } + // Coverage and kind of every pixel in reach (at most 2·REACH + 2 of them): 1 or 0 for a + // flank, -1 partial, -2 a pixel that is not a mixture of the two faces. + let len = (r1 - r0 + 1) as usize; + let mut a = [0.0f64; 2 * REACH as usize + 2]; + let mut kind = [0i8; 2 * REACH as usize + 2]; + let tol = (4.0 * ctx.sigma_noise) + .max(0.06 * axis.contrast) + .max(2.0 / 255.0); + let tol2 = tol * tol; + for (k, r) in (r0..=r1).enumerate() { + let (x, y) = if transpose { (r, line) } else { (line, r) }; + let (cov, resid2) = unmix(axis, &ctx.src, x as usize, y as usize); + a[k] = cov; + kind[k] = if resid2 > tol2 { + -2 + } else if cov >= 1.0 - SATURATED { + 1 + } else if cov <= SATURATED { + 0 + } else { + -1 + }; + } + let mut best: Option<(f64, bool, usize)> = None; + let mut j = 0usize; + while j < len { + if kind[j] < 0 { + j += 1; + continue; + } + let mut k = j + 1; + while k < len && kind[k] == -1 { + k += 1; + } + if k >= len { + break; + } + if kind[k] >= 0 && kind[k] != kind[j] { + let top_is_left = kind[j] == 1; + let sum: f64 = a[j..=k] + .iter() + .map(|&c| if top_is_left { c } else { 1.0 - c }) + .sum(); + let mean = (r0 + j as isize) as f64 - 0.5 + sum; + if best.is_none_or(|(b, _, _)| (mean - v0).abs() < (b - v0).abs()) { + best = Some((mean, top_is_left, k - j + 1)); + } + } + j = k; + } + best.filter(|(m, _, _)| (m - v0).abs() <= MAX_STEP) +} + +/// The cubic `c₀ + c₁s + c₂s² + c₃s³` whose means over the cells `[-2,-1]`, `[-1,0]`, +/// `[0,1]`, `[1,2]` are `m`: the inverse of the histopolation matrix, exact rationals. +/// Its constant term is the classical fourth-order face value +/// `(7(m₁ + m₂) - (m₀ + m₃))/12`. +/// +/// Generated from the Lean definition its exactness theorem is about (`histopolateK`, with +/// `histopolate_cubic` and `strip_reading_exact`), in the operation order it was written in +/// here, so the reading is unchanged bit for bit. +fn histopolate(m: &[f64; 4]) -> [f64; 4] { + generated::histopolate_f64(m) +} + +/// Largest residual, px, the shift's certificate may leave: `q(s₀ + t·n_u) − t·n_v` for the +/// cubic `q` the column sums determine ([`certified`]). Newton stops at steps of 1e-12, so a +/// converged shift is ten thousand times inside it. +const CERT_TOL: f64 = 1e-9; + +/// Whether the shift `t` along `(nu, nv)` from `s0` provably puts the vertex on the cubic +/// histopolated from the four central means `m[1..5]`, to [`CERT_TOL`]: the generated +/// interval checker (`stripResidualK`; `stripResidual_on_cubic` says the residual is zero +/// exactly on that cubic), evaluated in outward-rounded intervals, so a `true` holds for the +/// exact real numbers and not only for their floating-point rounding. A refusal sends the +/// vertex to the probes. +fn certified(m: &[f64; 6], s0: f64, nu: f64, nv: f64, t: f64) -> bool { + let x = [m[1], m[2], m[3], m[4], s0, nu, nv, t]; + let mut ivs = [Iv { lo: 0.0, hi: 0.0 }; 8]; + for (slot, v) in ivs.iter_mut().zip(x) { + match Iv::point(v) { + Some(p) => *slot = p, + None => return false, + } + } + generated::strip_residual_iv(&ivs).is_some_and(|r| r[0].within(CERT_TOL)) +} + +/// Mean of the cubic `c` over the cell `[k, k+1]`. +#[cfg(test)] +fn cell_mean(c: &[f64; 4], k: f64) -> f64 { + let p = + |s: f64| c[0] * s + c[1] * s * s / 2.0 + c[2] * s.powi(3) / 3.0 + c[3] * s.powi(4) / 4.0; + p(k + 1.0) - p(k) +} + +fn eval(c: &[f64; 4], s: f64) -> f64 { + c[0] + s * (c[1] + s * (c[2] + s * c[3])) +} + +fn slope(c: &[f64; 4], s: f64) -> f64 { + c[1] + s * (2.0 * c[2] + s * 3.0 * c[3]) +} + +/// The shift along the unit normal `(nx, ny)` that puts vertex `p` on the boundary the +/// column sums around it describe, or `None` where the strip reading does not apply (see +/// the module doc); the caller then falls back to the probe inversion. +/// +/// It applies only between two flat fills (`fa`, `fb`): against a gradient the unmixing +/// colours are the model's local prediction, which the probes' root-find tolerates and a +/// sum of coverages does not. Not at a `corner`, not on an alpha axis, and only where the +/// contrast is at least twice the unmixing threshold, as for the probes' step inversion. +/// Measured on the 246-icon gate against the probes alone: dE00 -10.9 % Fast and -4.3 % +/// Quality at 128 px, -8.7 % and -2.3 % at 512 px (`docs/theory/README.md`). +/// +/// Columns are scanned first when the normal is nearer vertical than horizontal (the +/// boundary is then a graph over x with slope at most 1 at the vertex), rows first +/// otherwise; when the first reading declines, the other is tried. A lattice normal is +/// quantised to multiples of 45 degrees, so near the diagonal either axis may be the one +/// over which the boundary is a graph across all six lines. +pub(super) fn strip_offset( + ctx: &RefineCtx, + axis: &UnmixAxis, + fa: &FillModel, + fb: &FillModel, + corner: bool, + p: Point, + (nx, ny): (f64, f64), +) -> Option { + if axis.with_alpha + || corner + || fa.is_gradient() + || fb.is_gradient() + || axis.contrast < 2.0 * ctx.min_contrast + { + return None; + } + let first = nx.abs() > ny.abs(); + strip_along(ctx, axis, p, nx, ny, first).or_else(|| strip_along(ctx, axis, p, nx, ny, !first)) +} + +/// [`strip_offset`] reading columns (`transpose` false) or rows. +fn strip_along( + ctx: &RefineCtx, + axis: &UnmixAxis, + p: Point, + nx: f64, + ny: f64, + transpose: bool, +) -> Option { + let (pu, pv, nu, nv) = if transpose { + (p.y, p.x, ny, nx) + } else { + (p.x, p.y, nx, ny) + }; + // The pixel border nearest the vertex: cells k = -3..=2 of the local coordinate + // s = u - border are the columns whose centres are at border + k + 1/2. + let border = (pu - 0.5).round() + 0.5; + let mut means = [0.0f64; 6]; + let mut widest = 0usize; + let mut orient: Option = None; + let why = |r: std::fmt::Arguments| { + if ctx.debug { + eprintln!( + " [strip] p=({:.2},{:.2}) n=({:.2},{:.2}) declined: {r}", + p.x, p.y, nx, ny + ); + } + }; + // Columns are read from the vertex outwards, each searched around its inner + // neighbour's mean: at 45 degrees the outer columns' crossings are two to three pixels + // above or below the vertex. + for k in [-1isize, 0, -2, 1, -3, 2] { + let slot = (k + 3) as usize; + let near = match k { + -1 | 0 => pv, + k if k < 0 => pv + means[slot + 1], + _ => pv + means[slot - 1], + }; + let line = (border + k as f64 + 0.5).round() as isize; + let Some((m, o, n)) = line_mean(ctx, axis, line, near, transpose) else { + why(format_args!("no window in line {k}")); + return None; + }; + widest = widest.max(n); + if *orient.get_or_insert(o) != o { + why(format_args!("orientation")); + return None; + } + means[slot] = m - pv; + } + if means.windows(2).any(|w| (w[1] - w[0]).abs() > MAX_STEP) { + why(format_args!("step")); + return None; + } + let c = histopolate(&[means[1], means[2], means[3], means[4]]); + // The one-sided cubics, read at the border s = 0 only (their constant terms are taken + // in their own coordinates, shifted by one cell). + let left = eval(&histopolate(&[means[0], means[1], means[2], means[3]]), 1.0); + let right = eval( + &histopolate(&[means[2], means[3], means[4], means[5]]), + -1.0, + ); + let side_tol = side_tol(ctx.soft, widest, ctx.sigma_noise, axis.dd); + if (left - c[0]).abs() > side_tol || (right - c[0]).abs() > side_tol { + why(format_args!("sides {:.3} {:.3}", left - c[0], right - c[0])); + return None; + } + // Newton on q(s0 + t·nu) - t·nv = 0: where the normal line meets the cubic. + let s0 = pu - border; + let mut t = 0.0f64; + for _ in 0..8 { + let s = s0 + t * nu; + let f = eval(&c, s) - t * nv; + let df = slope(&c, s) * nu - nv; + if df.abs() < 0.3 { + why(format_args!("newton slope")); + return None; + } + let step = f / df; + t -= step; + if step.abs() < 1e-12 { + break; + } + } + if !(t.is_finite() && t.abs() <= 1.0) { + why(format_args!("shift {t:.3}")); + return None; + } + if !certified(&means, s0, nu, nv, t) { + why(format_args!("certificate {t:.4}")); + return None; + } + if ctx.debug { + eprintln!( + " [strip] p=({:.2},{:.2}) n=({:.2},{:.2}) t={t:.4}", + p.x, p.y, nx, ny + ); + } + Some(t) +} + +/// The side test's threshold, px: [`SIDE_TOL`] on a clean intake; on a soft one the larger of +/// it and [`SIDE_Z`] standard deviations of the one-sided difference, `√(70 V)/12`. `V` is a +/// column mean's variance: `widest` pixels, each with its weight's variance `σ²/|d|²` +/// (`sigma` the per-channel noise, `dd` the squared colour separation of the two faces). +fn side_tol(soft: bool, widest: usize, sigma: f64, dd: f64) -> f64 { + if !soft { + return SIDE_TOL; + } + let col_var = widest as f64 * sigma * sigma / dd.max(1e-300); + SIDE_TOL.max(SIDE_Z * (70.0 * col_var).sqrt() / 12.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A clean intake keeps `SIDE_TOL` whatever its noise and contrast; a soft one moves to + /// three standard deviations of the one-sided difference once that is the larger, and + /// not before. + #[test] + fn the_side_test_scales_with_noise_on_a_soft_intake_only() { + let (sigma, faint, strong) = (2.0 / 255.0, 0.03f64.powi(2) * 3.0, 3.0); + assert_eq!(side_tol(false, 4, sigma, faint), SIDE_TOL); + assert_eq!(side_tol(false, 4, 0.1, 1e-6), SIDE_TOL); + // Black on white at two levels of noise: the statistical term is far below. + assert_eq!(side_tol(true, 4, sigma, strong), SIDE_TOL); + // A faint edge (3 % per channel): sqrt(70 · 4 σ²/dd)/12 · 3. + let want = 3.0 * (70.0 * 4.0 * sigma * sigma / faint).sqrt() / 12.0; + assert!(want > SIDE_TOL); + assert!((side_tol(true, 4, sigma, faint) - want).abs() < 1e-12); + } + + /// The histopolated cubic reproduces any cubic from its four cell means, and its + /// constant term is the value at the border (`cubic_point_from_means` and + /// `poly_eq_of_averages` in the Lean development, checked here on numbers). + #[test] + fn histopolation_is_exact_on_cubics() { + let q = [0.3, -0.7, 0.25, 0.04]; + let m = [ + cell_mean(&q, -2.0), + cell_mean(&q, -1.0), + cell_mean(&q, 0.0), + cell_mean(&q, 1.0), + ]; + let c = histopolate(&m); + for (a, b) in c.iter().zip(q.iter()) { + assert!((a - b).abs() < 1e-12, "{c:?} vs {q:?}"); + } + assert!((cell_mean(&c, -3.0) - cell_mean(&q, -3.0)).abs() < 1e-12); + // Shifted one cell, the same means describe the same cubic one unit along. + let m2 = [ + cell_mean(&q, -3.0), + cell_mean(&q, -2.0), + cell_mean(&q, -1.0), + cell_mean(&q, 0.0), + ]; + assert!((eval(&histopolate(&m2), 1.0) - eval(&q, 0.0)).abs() < 1e-12); + } +} diff --git a/crates/inkvec-trace/src/regularize.rs b/crates/inkvec-trace/src/regularize.rs index f26701d7..df593448 100644 --- a/crates/inkvec-trace/src/regularize.rs +++ b/crates/inkvec-trace/src/regularize.rs @@ -125,10 +125,27 @@ pub fn residual_incoherence( /// Returns the larger of the two, in sRGB units, clamped to `[NOISE_FLOOR, 8/255]`. /// Images under 3x3 return the floor. pub fn residual_sigma(rgb: &[[f32; 3]], labels: &[u16], w: usize, h: usize, pal: &Palette) -> f64 { + let (interior, edge) = residual_sigmas(rgb, labels, w, h, pal); + interior.max(edge) +} + +/// [`residual_sigma`]'s two populations apart: `(interior, edge)`, each clamped to +/// `[NOISE_FLOOR, 8/255]`. Compression noise is not stationary: on the gate's `web` tier +/// (`bench/theory/noise_profile.py`) the JPEG's error is 4.5 levels within a pixel of an +/// edge and 0.2 eight pixels from one, so a decision about interiors and a decision about +/// edges each want their own. +pub fn residual_sigmas( + rgb: &[[f32; 3]], + labels: &[u16], + w: usize, + h: usize, + pal: &Palette, +) -> (f64, f64) { let mut errors = Vec::new(); let mut edge_errors = Vec::new(); + let clamp = |v: f64| v.clamp(crate::coverage::NOISE_FLOOR, 8.0 / 255.0); if w < 3 || h < 3 { - return crate::coverage::NOISE_FLOOR; + return (crate::coverage::NOISE_FLOOR, crate::coverage::NOISE_FLOOR); } for y in 1..h - 1 { for x in 1..w - 1 { @@ -189,9 +206,7 @@ pub fn residual_sigma(rgb: &[[f32; 3]], labels: &[u16], w: usize, h: usize, pal: } else { crate::coverage::NOISE_FLOOR }; - interior - .max(edge) - .clamp(crate::coverage::NOISE_FLOOR, 8.0 / 255.0) + (clamp(interior), clamp(edge)) } /// Deterministic four-neighbour Potts descent. Every change strictly lowers energy. @@ -474,6 +489,42 @@ mod tests { ); } #[test] + fn interior_and_edge_noise_are_read_apart() { + // Two inks split down the middle of a 16 x 24 image (44 edge pixels off the frame, + // over the 32 a median needs); the edge columns carry a colour off the line between + // the inks (compression damage), the interiors a small wobble. + let p = palette(vec![[0.2; 3], [0.8; 3]]); + let (w, h) = (16usize, 24usize); + let mut rgb = vec![[0.0f32; 3]; w * h]; + let mut labels = vec![0u16; w * h]; + for y in 0..h { + for x in 0..w { + let i = y * w + x; + labels[i] = u16::from(x >= w / 2); + let ink = p.rgb[labels[i] as usize]; + let wobble = if (x + y) % 2 == 0 { 2.0 } else { -2.0 } / 255.0; + let damage = if x == w / 2 - 1 || x == w / 2 { + 10.0 / 255.0 + } else { + 0.0 + }; + rgb[i] = [ + ink[0] + wobble + damage, + ink[1] + wobble - damage, + ink[2] + wobble, + ]; + } + } + let (interior, edge) = residual_sigmas(&rgb, &labels, w, h, &p); + assert!(edge > 3.0 * interior, "edge {edge} interior {interior}"); + assert!( + (interior * 255.0 - 2.0).abs() < 0.01, + "interior {}", + interior * 255.0 + ); + assert_eq!(residual_sigma(&rgb, &labels, w, h, &p), interior.max(edge)); + } + #[test] fn label_changes_reduce_the_stated_global_energy() { let p = palette(vec![[0.2; 3], [0.3; 3]]); let rgb = vec![[0.24; 3]; 64]; diff --git a/crates/inkvec-trace/src/ribbon.rs b/crates/inkvec-trace/src/ribbon.rs index a2a00f0b..a0831aa4 100644 --- a/crates/inkvec-trace/src/ribbon.rs +++ b/crates/inkvec-trace/src/ribbon.rs @@ -1,4 +1,4 @@ -//! Stroke-drawn faces as centrelines plus one width (`--detect-strokes`, off by default). +//! Stroke-drawn faces as centrelines plus one width (`Options::detect_strokes`, on by default in Quality mode). //! //! **The problem.** Line art (lucide entirely, openmoji's black outlines, much of every //! icon set) is drawn as centrelines `C` with one stroke width `w` and round caps and @@ -62,8 +62,8 @@ //! empty margin, row-major. //! //! **Where it sits.** Quality mode only, after the boundary fits, the crossing repair and -//! the mirrors, before the emitter; off unless `--detect-strokes` -//! (`Options::detect_strokes`) asks for it. +//! the mirrors, before the emitter; on by default (`Options::detect_strokes`, +//! `--no-detect-strokes` to switch it off). //! //! The literature each pass stands on is cited in that pass's module. @@ -319,13 +319,17 @@ pub enum Decline { /// sigma, px. `budget` is the parameter count the strokes must stay under to be worth /// anything (the caller's: what the outline costs); a hypothesis whose fitted /// centrelines already reach it before the solve is abandoned, since the solve never -/// removes parameters and its splits only add them. Returns the stroke description with -/// its score; whether it is *better* than the outline is the caller's decision. +/// removes parameters and its splits only add them. `chi2_cap` gives, for the face's +/// number of boundary points, the chi-squared the strokes may reach and still be worth +/// anything (the caller's fidelity bound): the solve's merges stay under it. Returns the +/// stroke description with its score; whether it is *better* than the outline is the +/// caller's decision. pub fn fit_face( rings: &[Polyline], mask: &FaceMask, cfg: &FitConfig, budget: f64, + chi2_cap: &dyn Fn(usize) -> f64, ) -> Result { let mut b = boundary::Boundary::new(rings, &|p| mask.contains(p), 2.0).ok_or(Decline::NoBoundary)?; @@ -345,6 +349,7 @@ pub fn fit_face( mask, w0, share, + chi2_cap: chi2_cap(b.len()), }; let round = hypothesis(&face, cfg, budget, Join::Round.into()); // A round fit that leaves a boundary point more than a quarter pixel out is also tried @@ -466,6 +471,8 @@ struct Face<'a> { w0: f64, /// The share of the boundary that paired at it. share: f64, + /// The chi-squared the strokes may reach ([`fit_face`]). + chi2_cap: f64, } /// One hypothesis of a face's strokes: topology read with `join`'s rules @@ -567,7 +574,15 @@ fn reading( return Err(Decline::Misfit { rms: pre.rms }); } let (lines, half) = { - let (l, h) = refine::solve_adaptive(&lines, 0.5 * w0, b, cfg.lambda, style, budget); + let (l, h) = refine::solve_adaptive( + &lines, + 0.5 * w0, + b, + cfg.lambda, + style, + budget, + face.chi2_cap, + ); (l, Some(h)) }; if !refine::drawable(&lines, style) { @@ -693,7 +708,7 @@ pub fn path_chi2(points: &[Point], sigma: &[f64], path: &FittedPath) -> f64 { /// caps with a notch between them. The last segment's end is moved onto the start; the /// stroke solve then refits the geometry round it. fn fit_chain(poly: &Polyline, cfg: &FitConfig) -> Centreline { - let mut curve = multimodel::optimal_multimodel(poly, cfg); + let mut curve = inkvec_fit::extrema::without(|| multimodel::optimal_multimodel(poly, cfg)); if poly.closed { curve.closed = true; let start = curve.start; @@ -791,7 +806,7 @@ mod tests { let bb = FaceMask::bounding_boxes(&labels, 64, 64, 2); let mask = FaceMask::from_labels(&labels, 64, 1, bb[1].expect("ink")); let cfg = FitConfig::from_precision(64.0, 0.1, 2.0); - let r = fit_face(&rings, &mask, &cfg, f64::INFINITY).expect("a stroke"); + let r = fit_face(&rings, &mask, &cfg, f64::INFINITY, &|_| f64::INFINITY).expect("a stroke"); assert!((r.width - 8.0).abs() < 0.05, "width {}", r.width); assert_eq!(r.lines.len(), 1); let p = &r.lines[0].path; @@ -832,7 +847,8 @@ mod tests { let bb = FaceMask::bounding_boxes(&labels, n, n, 2); let mask = FaceMask::from_labels(&labels, n, 1, bb[1].expect("ink")); let cfg = FitConfig::from_precision(64.0, 0.1, 2.0); - let r = fit_face(&[ring], &mask, &cfg, f64::INFINITY).expect("a stroke"); + let r = + fit_face(&[ring], &mask, &cfg, f64::INFINITY, &|_| f64::INFINITY).expect("a stroke"); assert_eq!(r.cap, Cap::Butt, "{r:?}"); assert!((r.width - 9.0).abs() < 0.1, "width {}", r.width); let p = &r.lines[0].path; @@ -868,7 +884,7 @@ mod tests { let bb = FaceMask::bounding_boxes(&labels, n, n, 2); let mask = FaceMask::from_labels(&labels, n, 1, bb[1].expect("ink")); let cfg = FitConfig::from_precision(40.0, 0.1, 2.0); - assert!(fit_face(&[ring], &mask, &cfg, f64::INFINITY).is_err()); + assert!(fit_face(&[ring], &mask, &cfg, f64::INFINITY, &|_| f64::INFINITY).is_err()); } #[test] diff --git a/crates/inkvec-trace/src/ribbon/refine.rs b/crates/inkvec-trace/src/ribbon/refine.rs index c6169fe7..fdca3af0 100644 --- a/crates/inkvec-trace/src/ribbon/refine.rs +++ b/crates/inkvec-trace/src/ribbon/refine.rs @@ -66,6 +66,7 @@ use super::join::{butt_gauge, miter_gauge, tangents, Cap, Join, Style}; use super::score::flatten; use super::Centreline; +mod merge; mod normal; use normal::{normal_equations, profile}; @@ -898,6 +899,7 @@ pub(crate) fn solve_adaptive( lambda: f64, style: Style, budget: f64, + chi2_cap: f64, ) -> (Vec, f64) { let (mut cur, mut h) = solve(lines, h, b, style, MAX_ITERS); let max_splits = MAX_SPLITS; @@ -952,7 +954,10 @@ pub(crate) fn solve_adaptive( refused.push((shape, seg)); } } - if accepted_any { + // Then the joints the description length would rather not pay for. + let merged; + (cur, h, best, _, merged) = merge::merges(cur, h, cur_rows, best, b, lambda, style, chi2_cap); + if accepted_any || merged { let (polished, ph) = solve(&cur, h, b, style, MAX_ITERS); if drawable(&polished, style) && cost(&polished, ph).0 <= best { return (polished, ph); @@ -1081,6 +1086,11 @@ const MITER_MAX_TURN_COS: f64 = -0.866; /// every segment's chord must be at least [`MITER_MIN_SEG`] px and no vertex may turn /// by more than 150° ([`MITER_MAX_TURN_COS`]). Round joins draw a disc at every vertex /// whatever the tangents, and need neither. +/// * **No circular arc within [`merge::HALF_TURN_BAND_DEGREES`] of a half turn** unless it +/// is the half circle on its chord (radius at most the half-chord): there SVG's +/// rebuilt centre moves by `R/k` times any rounding of the radius (see the constant), +/// so the arc written is not the arc solved. The fitter's arcs stop at 120° and a +/// split halves them; only a merge makes one this wide. /// /// Not from the literature: a sampled hodograph test and two drawing rules, because the /// solve needs a cheap yes/no on every candidate step rather than an exact cusp locus. @@ -1099,6 +1109,9 @@ fn regular(model: &Model) -> bool { } for k in 0..segs.len() { let (a, seg) = model.segment(*start, segs, k); + if !conditioned(a, &seg) { + return false; + } let Segment::Cubic(c1, c2, b) = seg else { continue; }; @@ -1123,6 +1136,24 @@ fn regular(model: &Model) -> bool { true } +/// The arc rule of [`regular`]: false for a circular arc from `a` whose radius exceeds its +/// half-chord `L` and whose centre sits closer to the chord than `R·sin(band/2)`, i.e. +/// within [`merge::HALF_TURN_BAND_DEGREES`] of a half turn; true for anything else. +fn conditioned(a: Point, seg: &Segment) -> bool { + let Segment::Arc { rx, end, .. } = *seg else { + return true; + }; + if !seg.is_circular() { + return true; + } + let l = 0.5 * a.dist(end); + if rx <= l * (1.0 + 1e-9) { + return true; + } + let k = (rx * rx - l * l).sqrt(); + k >= rx * (0.5 * merge::HALF_TURN_BAND_DEGREES.to_radians()).sin() +} + /// The miter rules of [`regular`] for one path: every chord at least [`MITER_MIN_SEG`] /// px, and every vertex (including a closed path's start) turning by at most 150°. fn miter_drawable(model: &Model, start: usize, segs: &[SegVar], closed: bool) -> bool { diff --git a/crates/inkvec-trace/src/ribbon/refine/merge.rs b/crates/inkvec-trace/src/ribbon/refine/merge.rs new file mode 100644 index 00000000..9e860589 --- /dev/null +++ b/crates/inkvec-trace/src/ribbon/refine/merge.rs @@ -0,0 +1,871 @@ +//! Merges: the stroke solve's splits run backwards ([`merges`]). +//! +//! The curve fitter segments each centreline from its centre samples, and its arcs stop at +//! [`inkvec_fit::primitives::MAX_ARC_DEGREES`]; the solve then moves the segments but +//! never removes one. So a stroke the artist drew as one arc of 270° comes back as three +//! arcs on one circle, a cap as an arc and a short line that continues it, a straight run +//! as two lines meeting at 1°, a straight stroke as a cubic with its handles on the chord: +//! the right curve, in more numbers than it takes. Each of those is a joint the +//! description length would rather not pay for, and the solve can show which. + +use std::f64::consts::{PI, TAU}; + +use inkvec_core::{Point, Vec2}; +use inkvec_fit::curves::{arc_center, Segment}; +use inkvec_fit::primitives::{PrimitiveFit, PrimitiveKind, PARAMS_CIRCLE}; +use inkvec_fit::{FittedPath, PARAMS_LINE}; + +use super::super::boundary::Boundary; +use super::super::join::{tangents, Style}; +use super::super::Centreline; +use super::{circle_path, drawable, local_eval, rows, solve, Model, Row, Shape, TRIAL_ITERS}; + +/// Most merges [`merges`] solves per face. A merge whose unsolved description length +/// already falls is kept without a solve and is not counted. +const MAX_MERGE_TRIALS: usize = 12; + +/// How far the local estimate of a merge's description length may sit above the price it +/// saves for the merge to be tried at all, as a multiple of that price: a merge is tried +/// when `½·Δχ²_local < (1 + MERGE_SLACK)·λ·Δk`. +/// +/// The local estimate measures the merged segment where the two it replaces stood, before +/// any solve; the solve then moves every variable, and buys back part of the damage. +const MERGE_SLACK: f64 = 1.0; + +/// Half-width of the band round a half turn, degrees, in which a merged arc is not +/// written with its own radius ([`arc_about`], [`super::regular`]). +/// +/// SVG rebuilds an arc's centre from its end points and radius, at a distance +/// `k = sqrt(R² - L²)` from the chord's midpoint (`L` the half-chord). Near a half turn +/// `k` is small and `∂k/∂R = R/k` large: at 165° a radius rounded by 0.005 px (two +/// decimals) moves the drawn arc by 0.04 px, at 175° by 0.11 px. Inside the band a merged +/// arc is the exact half circle on its chord instead (a radius under the half-chord, +/// which SVG scales up to it: F.6.6), which rounding cannot move. +pub(super) const HALF_TURN_BAND_DEGREES: f64 = 15.0; + +/// A merged arc may sweep at most this much, degrees; a centreline closer to a full turn +/// is a circle (the closed-path candidate of [`candidates`]). +const MAX_SWEEP_DEGREES: f64 = 350.0; + +/// One proposed merge. +#[derive(Clone, Debug)] +struct Merge { + /// The centreline. + shape: usize, + /// What replaces it. + with: Centreline, + /// Parameters saved. + saved: f64, + /// Which joint (or segment) of the centreline as it stands, to refuse it by. + key: (usize, usize), + /// Local estimate of the merge's change in `Σ r²` before any solve. + dchi2: f64, +} + +/// The joints of the strokes `cur` (half-width `h`, rows `rws` measured on them, total +/// cost `best`) that the description length would rather not pay for, merged. +/// +/// Every interior joint of a path (and a closed path's closing one) is offered the +/// segments that could replace the two it joins ([`joint`]): a line through their outer +/// ends; an arc on the circle of either one that is an arc, or of both when they share a +/// sense of turn, or through the three points; a cubic with the outer tangents +/// ([`cubic_through`]). Every cubic and arc is offered the line on its chord, and a +/// closed path of arcs the circle they lie on. Each is measured, unsolved, against the +/// boundary points the replaced segments explained (`Δχ²_local`), and tried, best first, +/// when `½·Δχ²_local - λ·Δk` is under [`MERGE_SLACK`] times the price it saves: kept +/// outright when the unsolved strokes' description length `χ²/2 + λ·k` already falls, +/// else solved for [`TRIAL_ITERS`] iterations and kept when it falls then. A kept merge +/// must also be drawable ([`drawable`]) and leave the strokes' `χ²` at most `chi2_cap` +/// (the caller's: what the face may cost and still be written as strokes). At most +/// [`MAX_MERGE_TRIALS`] are solved. Returns the strokes, half-width, cost and rows, and +/// whether anything was merged. +/// +/// Inspired by: Pavlidis, Horowitz (1974), Segmentation of plane curves, IEEE Transactions +/// on Computers C-23(8), 860-870, doi:10.1109/T-C.1974.224041 -- split-and-merge, where +/// adjacent pieces are merged while the merged piece still fits. Ours prices the merge by +/// description length after a solve against the stroke's painted outline, and offers the +/// kinds of curve a designer draws with: Schneider (1990), An algorithm for automatically +/// fitting digitized curves, Graphics Gems, pp. 612-626, for the cubic with fixed end +/// tangents. +#[allow(clippy::too_many_arguments)] +pub(super) fn merges( + mut cur: Vec, + mut h: f64, + mut rws: Vec>, + mut best: f64, + b: &Boundary, + lambda: f64, + style: Style, + chi2_cap: f64, +) -> (Vec, f64, f64, Vec>, bool) { + let reach = 8.0 * h + 4.0; + let cost = |ls: &[Centreline], h: f64| -> (f64, f64, Vec>) { + let (e, r) = rows(&Model::new(ls, h, style), b, reach); + ( + 0.5 * e + lambda * ls.iter().map(Centreline::params).sum::(), + e, + r, + ) + }; + let fits = |ls: &[Centreline], c: f64, e: f64, best: f64| { + c < best && e <= chi2_cap && drawable(ls, style) + }; + let mut refused: Vec<(usize, usize)> = Vec::new(); + let (mut trials, mut merged) = (0usize, false); + while trials < MAX_MERGE_TRIALS { + let model = Model::new(&cur, h, style); + let mut cands: Vec = candidates(&cur, &model, &rws, b) + .into_iter() + .filter(|m| { + !refused.contains(&m.key) && 0.5 * m.dchi2 < (1.0 + MERGE_SLACK) * lambda * m.saved + }) + .collect(); + let gain = |m: &Merge| 0.5 * m.dchi2 - lambda * m.saved; + cands.sort_by(|x, y| gain(x).total_cmp(&gain(y))); + let Some(m) = cands.into_iter().next() else { + break; + }; + let mut trial = cur.clone(); + trial[m.shape] = m.with.clone(); + let (c0, e0, r0) = cost(&trial, h); + if fits(&trial, c0, e0, best) { + (cur, best, rws, merged) = (trial, c0, r0, true); + refused.clear(); + continue; + } + trials += 1; + let (tl, th) = solve(&trial, h, b, style, TRIAL_ITERS); + let (c1, e1, r1) = cost(&tl, th); + if fits(&tl, c1, e1, best) { + (cur, h, best, rws, merged) = (tl, th, c1, r1, true); + refused.clear(); + } else { + refused.push(m.key); + } + } + (cur, h, best, rws, merged) +} + +/// Every merge of [`merges`] on the strokes `cur` (as `model`, rows `rws`), with its +/// local estimate. +fn candidates(cur: &[Centreline], model: &Model, rws: &[Option], b: &Boundary) -> Vec { + // The boundary points each path segment explains: (point, foot parameter). + let mut owned: Vec>> = model + .shapes + .iter() + .map(|s| match s { + Shape::Path { segs, .. } => vec![Vec::new(); segs.len()], + _ => Vec::new(), + }) + .collect(); + for (i, r) in rws.iter().enumerate() { + if let Some(r) = r { + if let Some(v) = owned.get_mut(r.shape).and_then(|s| s.get_mut(r.seg)) { + v.push((i, r.t)); + } + } + } + let ctx = Ctx { + cur, + style: model.style, + h: model.h(), + rws, + b, + owned, + }; + let mut out = Vec::new(); + for (s, line) in cur.iter().enumerate() { + if line.prim.is_none() { + ctx.singles(s, &mut out); + ctx.joints(s, &mut out); + ctx.circle(s, &mut out); + } + } + out +} + +/// What [`candidates`] measures merges against. +struct Ctx<'a> { + /// The strokes as they stand. + cur: &'a [Centreline], + /// Their joins and caps. + style: Style, + /// Their half-width. + h: f64, + /// Each boundary point's row on them. + rws: &'a [Option], + /// The boundary. + b: &'a Boundary, + /// Per shape and segment, the boundary points it explains and their foot parameters. + owned: Vec>>, +} + +impl Ctx<'_> { + /// `Σ r²` of the points `pts` as they stand. + fn old(&self, pts: &[(usize, f64)]) -> f64 { + pts.iter() + .map(|&(i, _)| { + let d = self.rws[i].as_ref().map_or(0.0, |r| r.d); + self.b.residual(i, d, self.h).0.powi(2) + }) + .sum() + } + + /// The merge that gives centreline `s` the centreline `with`, saving `saved` + /// parameters, with its local estimate: the points `pts` (index, foot hint, segment of + /// `with`) measured against it alone, less their `before`. + fn local( + &self, + (s, key): (usize, (usize, usize)), + with: Centreline, + saved: f64, + before: f64, + pts: &[(usize, f64, usize)], + ) -> Merge { + let mut trial = self.cur.to_vec(); + trial[s] = with.clone(); + let tm = Model::new(&trial, self.h, self.style); + let after: f64 = pts + .iter() + .map(|&(i, t, k)| { + let d = local_eval(&tm, s, k, self.b.pts[i], t).d; + self.b.residual(i, d, self.h).0.powi(2) + }) + .sum(); + Merge { + shape: s, + with, + saved, + key, + dchi2: after - before, + } + } + + /// Each segment of centreline `s` alone: a cubic or an arc as the line on its chord. + fn singles(&self, s: usize, out: &mut Vec) { + let path = &self.cur[s].path; + for (k, seg) in path.segments.iter().enumerate() { + let a = if k == 0 { + path.start + } else { + path.segments[k - 1].end() + }; + if matches!(seg, Segment::Line(_)) || a.dist(seg.end()) < 0.5 { + continue; + } + let mut p = path.clone(); + p.segments[k] = Segment::Line(seg.end()); + let pts = &self.owned[s][k]; + let mine: Vec<(usize, f64, usize)> = pts.iter().map(|&(i, t)| (i, t, k)).collect(); + let with = Centreline { + path: p, + prim: None, + }; + let saved = seg.params() - PARAMS_LINE; + out.push(self.local((s, (k, usize::MAX)), with, saved, self.old(pts), &mine)); + } + } + + /// Each joint of centreline `s`, the closing one of a closed path of three or more + /// included (the path is turned to start at the end of its first segment, so that + /// joint is interior): every segment of [`joint`] cheaper than the pair. + fn joints(&self, s: usize, out: &mut Vec) { + let path = &self.cur[s].path; + let n = path.segments.len(); + let joints = if path.closed && n >= 3 { + n + } else { + n.saturating_sub(1) + }; + for j in 0..joints { + let (p, at, ka, kb) = if j + 1 < n { + (path.clone(), j, j, j + 1) + } else { + (rotated(path), n - 2, n - 1, 0) + }; + let p0 = if at == 0 { + p.start + } else { + p.segments[at - 1].end() + }; + let (sa, sb) = (&p.segments[at], &p.segments[at + 1]); + let k_pair = sa.params() + sb.params(); + let la = p0.dist(sa.end()); + let frac = la / (la + sa.end().dist(sb.end())).max(1e-12); + // Each point's foot on the merged segment, from where it stood on its own. + let (own_a, own_b) = (&self.owned[s][ka], &self.owned[s][kb]); + let pts: Vec<(usize, f64, usize)> = own_a + .iter() + .map(|&(i, t)| (i, frac * t, at)) + .chain(own_b.iter().map(|&(i, t)| (i, frac + (1.0 - frac) * t, at))) + .collect(); + let before = self.old(own_a) + self.old(own_b); + for seg in joint(p0, sa, sb) { + if seg.params() >= k_pair { + continue; + } + let mut q = p.clone(); + let saved = k_pair - seg.params(); + q.segments.splice(at..=at + 1, [seg]); + let with = Centreline { + path: q, + prim: None, + }; + out.push(self.local((s, (j, n)), with, saved, before, &pts)); + } + } + } + + /// A closed centreline `s` of arcs on one circle: that circle. + fn circle(&self, s: usize, out: &mut Vec) { + let line = &self.cur[s]; + if !line.path.closed { + return; + } + let Some((c, r)) = common_circle(&line.path) else { + return; + }; + let with = Centreline { + path: circle_path(c, r), + prim: Some(PrimitiveFit { + kind: PrimitiveKind::Circle { c, r }, + chi2: 0.0, + params: PARAMS_CIRCLE, + }), + }; + let before: f64 = self.owned[s].iter().map(|v| self.old(v)).sum(); + let pts: Vec<(usize, f64, usize)> = self.owned[s] + .iter() + .flatten() + .map(|&(i, t)| (i, t, 0)) + .collect(); + let saved = line.params() - PARAMS_CIRCLE; + out.push(self.local((s, (usize::MAX, s)), with, saved, before, &pts)); + } +} + +/// A closed path turned to start at the end of its first segment, which becomes its last. +fn rotated(path: &FittedPath) -> FittedPath { + let mut segments = path.segments[1..].to_vec(); + segments.push(path.segments[0].clone()); + FittedPath { + start: path.segments[0].end(), + segments, + closed: true, + } +} + +/// The segments, from `p0` to `b`'s end, that could replace segment `a` (from `p0`) and +/// segment `b` (from `a`'s end): the line; arcs on `a`'s circle, `b`'s, both's (when they +/// turn the same way) and the circle through the three points; the cubic with the outer +/// tangents. The caller keeps those cheaper than the pair. +fn joint(p0: Point, a: &Segment, b: &Segment) -> Vec { + let (p1, p2) = (a.end(), b.end()); + let mut out = Vec::new(); + if p0.dist(p2) < 0.5 { + return out; + } + out.push(Segment::Line(p2)); + let ca = circle_of(p0, a); + let cb = circle_of(p1, b); + match (ca, cb) { + (Some((c1, w1, s1)), Some((c2, w2, s2))) if s1 == s2 => { + let w = w1 + w2; + let c = Point::new((w1 * c1.x + w2 * c2.x) / w, (w1 * c1.y + w2 * c2.y) / w); + out.extend(arc_about(p0, p2, c, s1)); + } + _ => { + for (c, _, s) in [ca, cb].into_iter().flatten() { + out.extend(arc_about(p0, p2, c, s)); + } + } + } + let turn = (p1 - p0).cross(p2 - p1); + if let Some(c) = circumcentre(p0, p1, p2) { + out.extend(arc_about(p0, p2, c, turn > 0.0)); + } + out.extend(cubic_through(p0, a, b)); + out +} + +/// A circular arc's centre, sweep (radians, unsigned) and SVG sweep flag; `None` for +/// anything else. +fn circle_of(a: Point, s: &Segment) -> Option<(Point, f64, bool)> { + let Segment::Arc { + rx, + large_arc, + sweep, + end, + .. + } = *s + else { + return None; + }; + if !s.is_circular() { + return None; + } + let (c, _, _, delta) = arc_center(a, rx, large_arc, sweep, end); + (delta != 0.0).then_some((c, delta.abs(), sweep)) +} + +/// The circle through three points, `None` when they are (nearly) collinear. +fn circumcentre(a: Point, b: Point, c: Point) -> Option { + let (u, v) = (b - a, c - a); + let d = 2.0 * u.cross(v); + let scale = u.norm() * v.norm(); + if d.abs() <= 1e-9 * scale { + return None; + } + let (uu, vv) = (u.dot(u), v.dot(v)); + let x = (v.y * uu - u.y * vv) / d; + let y = (u.x * vv - v.x * uu) / d; + let o = Point::new(a.x + x, a.y + y); + // A circle much larger than the points' spread is a straight run in disguise. + (o.dist(a) <= 1e3 * a.dist(c).max(1.0)).then_some(o) +} + +/// The arc from `p0` to `p2` round centre `c` the way SVG's `sweep` flag says, with the +/// mean of the two end points' distances as its radius; within +/// [`HALF_TURN_BAND_DEGREES`] of a half turn the exact half circle on the chord. `None` +/// for a sweep under 1e-3 rad or over [`MAX_SWEEP_DEGREES`]. +fn arc_about(p0: Point, p2: Point, c: Point, sweep: bool) -> Option { + let (u, v) = (p0 - c, p2 - c); + let mut d = v.y.atan2(v.x) - u.y.atan2(u.x); + if sweep { + while d <= 0.0 { + d += TAU; + } + } else { + while d >= 0.0 { + d -= TAU; + } + } + let s = d.abs(); + if !(1e-3..=MAX_SWEEP_DEGREES.to_radians()).contains(&s) { + return None; + } + if (s - PI).abs() < HALF_TURN_BAND_DEGREES.to_radians() { + let l = 0.5 * p0.dist(p2); + return Some(Segment::circular_arc( + half_circle_radius(l), + false, + sweep, + p2, + )); + } + let r = 0.5 * (u.norm() + v.norm()); + Some(Segment::circular_arc(r, s > PI, sweep, p2)) +} + +/// The radius written for a half circle on a chord of half-length `l`: enough under `l` +/// that two-decimal rounding of it and of the end points cannot lift it over the chord +/// (SVG then draws the half circle whatever the radius, F.6.6). +pub(super) fn half_circle_radius(l: f64) -> f64 { + (l - 0.02).max(0.5 * l) +} + +/// The cubic from `p0` to `b`'s end leaving along `a`'s first tangent and arriving along +/// `b`'s last, its two arm lengths fitted by least squares to 16 samples of each segment, +/// from chord-length parameters reparametrised [`REPARAM_ROUNDS`] times (Schneider's), or a third of the +/// chord each when that fit is degenerate or turns an arm backwards. +fn cubic_through(p0: Point, a: &Segment, b: &Segment) -> Option { + const PER: usize = 16; + const REPARAM_ROUNDS: usize = 8; + let p1 = a.end(); + let p2 = b.end(); + let (t0, _) = tangents(p0, a)?; + let (_, t1) = tangents(p1, b)?; + let mut pts = vec![p0]; + sample(p0, a, PER, &mut pts); + sample(p1, b, PER, &mut pts); + let mut u = vec![0.0]; + for w in pts.windows(2) { + u.push(u[u.len() - 1] + w[0].dist(w[1])); + } + let len = u[u.len() - 1]; + if len < 1e-9 { + return None; + } + for t in &mut u { + *t /= len; + } + let chord = p0.dist(p2); + let third = chord / 3.0; + let mut arms = arms_for(p0, p2, t0, t1, &pts, &u).unwrap_or((third, third)); + // Rounds of Schneider's reparametrisation: each sample's parameter moved to its + // foot on the cubic by one Newton step, and the arms fitted again. + for _ in 0..REPARAM_ROUNDS { + let q = cubic_of(p0, p2, t0, t1, arms); + for (p, t) in pts.iter().zip(u.iter_mut()) { + // Derivatives come back as points: (x, y) of the vectors. + let (c, d1, d2) = super::cubic_eval(&q, *t); + let (rx, ry) = (c.x - p.x, c.y - p.y); + let den = d1.x * d1.x + d1.y * d1.y + rx * d2.x + ry * d2.y; + if den.abs() > 1e-12 { + *t = (*t - (rx * d1.x + ry * d1.y) / den).clamp(0.0, 1.0); + } + } + arms = arms_for(p0, p2, t0, t1, &pts, &u).unwrap_or(arms); + } + if arms.0 <= 1e-6 * chord || arms.1 <= 1e-6 * chord { + arms = (third, third); + } + let q = cubic_of(p0, p2, t0, t1, arms); + Some(Segment::Cubic(q[1], q[2], p2)) +} + +/// The cubic from `p0` along `t0` to `p2` along `t1` with arm lengths `arms`. +fn cubic_of(p0: Point, p2: Point, t0: Vec2, t1: Vec2, arms: (f64, f64)) -> [Point; 4] { + [ + p0, + Point::new(p0.x + arms.0 * t0.x, p0.y + arms.0 * t0.y), + Point::new(p2.x - arms.1 * t1.x, p2.y - arms.1 * t1.y), + p2, + ] +} + +/// The least-squares arm lengths of the cubic from `p0` along `t0` to `p2` along `t1` +/// through `pts` at parameters `u`; `None` when the system is singular. +fn arms_for( + p0: Point, + p2: Point, + t0: Vec2, + t1: Vec2, + pts: &[Point], + u: &[f64], +) -> Option<(f64, f64)> { + let (mut c00, mut c01, mut c11, mut x0, mut x1) = (0.0, 0.0, 0.0, 0.0, 0.0); + for (p, &t) in pts.iter().zip(u) { + let s = 1.0 - t; + let (b0, b1, b2, b3) = (s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t); + let a1 = Vec2 { + x: b1 * t0.x, + y: b1 * t0.y, + }; + let a2 = Vec2 { + x: -b2 * t1.x, + y: -b2 * t1.y, + }; + let rest = Vec2 { + x: p.x - (b0 + b1) * p0.x - (b2 + b3) * p2.x, + y: p.y - (b0 + b1) * p0.y - (b2 + b3) * p2.y, + }; + c00 += a1.dot(a1); + c01 += a1.dot(a2); + c11 += a2.dot(a2); + x0 += a1.dot(rest); + x1 += a2.dot(rest); + } + let det = c00 * c11 - c01 * c01; + (det.abs() > 1e-12 * (c00 * c11).max(1e-300)) + .then(|| ((x0 * c11 - x1 * c01) / det, (c00 * x1 - c01 * x0) / det)) +} + +/// `n` points along segment `s` from `a`, at equal steps of its own parameter, its start +/// excluded and its end included. +fn sample(a: Point, s: &Segment, n: usize, out: &mut Vec) { + for k in 1..=n { + let t = k as f64 / n as f64; + out.push(match *s { + Segment::Line(e) => Point::new(a.x + t * (e.x - a.x), a.y + t * (e.y - a.y)), + Segment::Cubic(c1, c2, e) => super::cubic_eval(&[a, c1, c2, e], t).0, + Segment::Arc { + rx, + ry, + phi, + large_arc, + sweep, + end, + } => { + let f = + inkvec_fit::curves::arc_ellipse_center(a, rx, ry, phi, large_arc, sweep, end); + if k == n { + end + } else { + f.at(f.theta1 + f.delta * t) + } + } + }); + } +} + +/// The circle a closed path of circular arcs lies on: the sweep-weighted mean of their +/// centres and the mean distance of their end points from it, when every centre is +/// within 2% of the radius of it and every end point within 2% of the radius from the +/// circle. `None` otherwise. +fn common_circle(path: &FittedPath) -> Option<(Point, f64)> { + let mut a = path.start; + let mut acc = (0.0, 0.0, 0.0); + let mut cs = Vec::new(); + for s in &path.segments { + let (c, w, _) = circle_of(a, s)?; + acc = (acc.0 + w * c.x, acc.1 + w * c.y, acc.2 + w); + cs.push(c); + a = s.end(); + } + if acc.2 <= 0.0 { + return None; + } + let c = Point::new(acc.0 / acc.2, acc.1 / acc.2); + let ends: Vec = path.segments.iter().map(Segment::end).collect(); + let r = ends.iter().map(|e| e.dist(c)).sum::() / ends.len() as f64; + let tol = 0.02 * r; + (cs.iter().all(|q| q.dist(c) <= tol) && ends.iter().all(|e| (e.dist(c) - r).abs() <= tol)) + .then_some((c, r)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ribbon::join::Join; + use inkvec_core::Polyline; + + /// The outline of a round-capped stroke of half-width `h` along the arc of centre `c`, + /// radius `r`, from angle 0 to `sweep` (radians, increasing), as one dense ring, and + /// the stroke's inside test. + fn arc_stroke(c: Point, r: f64, sweep: f64, h: f64) -> Boundary { + let at = |rad: f64, th: f64| Point::new(c.x + rad * th.cos(), c.y + rad * th.sin()); + let mut pts = Vec::new(); + let n_arc = (sweep * (r + h) / 0.25) as usize; + for i in 0..n_arc { + pts.push(at(r + h, sweep * i as f64 / n_arc as f64)); + } + let cap = |e: Point, t0: f64, pts: &mut Vec| { + for j in 0..60 { + let t = t0 + PI * j as f64 / 60.0; + pts.push(Point::new(e.x + h * t.cos(), e.y + h * t.sin())); + } + }; + cap(at(r, sweep), sweep, &mut pts); + for i in 0..n_arc { + pts.push(at(r - h, sweep * (1.0 - i as f64 / n_arc as f64))); + } + cap(at(r, 0.0), PI, &mut pts); + let ring = Polyline::with_uniform_sigma(pts, 0.05, true); + let inside = move |p: Point| { + let v = p - c; + let th = v.y.atan2(v.x).rem_euclid(TAU); + let d = if th <= sweep { + (v.norm() - r).abs() + } else { + p.dist(at(r, 0.0)).min(p.dist(at(r, sweep))) + }; + d < h + }; + Boundary::new(&[ring], &inside, 2.0).expect("a ring") + } + + fn run(lines: Vec, h: f64, b: &Boundary) -> (Vec, bool) { + let style: Style = Join::Round.into(); + let lambda = 10.0; + let (e, rws) = rows(&Model::new(&lines, h, style), b, 8.0 * h + 4.0); + let best = 0.5 * e + lambda * lines.iter().map(Centreline::params).sum::(); + let (out, _, _, _, merged) = merges(lines, h, rws, best, b, lambda, style, f64::INFINITY); + (out, merged) + } + + #[test] + fn three_arcs_on_one_circle_become_one_large_arc() { + let (c, r) = (Point::new(50.0, 50.0), 30.0); + let b = arc_stroke(c, r, 1.5 * PI, 4.0); + let at = |th: f64| Point::new(c.x + r * th.cos(), c.y + r * th.sin()); + let line = Centreline { + path: FittedPath { + start: at(0.0), + segments: (1..=3) + .map(|k| Segment::circular_arc(r, false, true, at(0.5 * PI * k as f64))) + .collect(), + closed: false, + }, + prim: None, + }; + let (out, merged) = run(vec![line], 4.0, &b); + assert!(merged); + let segs = &out[0].path.segments; + assert_eq!(segs.len(), 1, "{segs:?}"); + let Segment::Arc { + rx, + large_arc, + sweep, + .. + } = segs[0] + else { + panic!("{segs:?}") + }; + assert!(large_arc && sweep && (rx - r).abs() < 0.05, "{segs:?}"); + } + + #[test] + fn two_lines_in_line_become_one() { + let b = arc_stroke(Point::new(0.0, -1e4), 1e4, 30.0 / 1e4, 3.0); + let p0 = Point::new(1e4 * 0.0f64.cos(), -1e4 + 1e4 * 0.0f64.sin()); + let p2 = Point::new( + 1e4 * (30.0f64 / 1e4).cos(), + -1e4 + 1e4 * (30.0f64 / 1e4).sin(), + ); + let mid = Point::new(0.5 * (p0.x + p2.x), 0.5 * (p0.y + p2.y)); + let line = Centreline { + path: FittedPath { + start: p0, + segments: vec![Segment::Line(mid), Segment::Line(p2)], + closed: false, + }, + prim: None, + }; + let (out, merged) = run(vec![line], 3.0, &b); + assert!(merged); + assert_eq!(out[0].path.segments.len(), 1, "{:?}", out[0].path); + } + + #[test] + fn a_bent_pair_is_kept() { + // Two lines meeting at a right angle: no merge fits the boundary of that corner. + let c = Point::new(50.0, 50.0); + let b = arc_stroke(c, 30.0, 1.5 * PI, 4.0); + let line = Centreline { + path: FittedPath { + start: Point::new(80.0, 50.0), + segments: vec![ + Segment::circular_arc(30.0, false, true, Point::new(50.0, 80.0)), + Segment::circular_arc(30.0, false, true, Point::new(20.0, 50.0)), + Segment::Line(Point::new(50.0, 20.0)), + ], + closed: false, + }, + prim: None, + }; + let (out, _) = run(vec![line], 4.0, &b); + // The line cuts the last quarter's corner by 8.8 px: it is never merged into a + // line with its neighbour, whatever else is. + assert!(!out[0].path.segments.iter().any( + |s| matches!(s, Segment::Line(e) if e.dist(Point::new(50.0, 20.0)) < 1.0) + && out[0].path.segments.len() == 1 + )); + } + + #[test] + fn a_closed_ring_of_arcs_becomes_a_circle() { + let (c, r) = (Point::new(40.0, 40.0), 20.0); + let at = |th: f64| Point::new(c.x + r * th.cos(), c.y + r * th.sin()); + let mut pts = Vec::new(); + for i in 0..800 { + let th = TAU * i as f64 / 800.0; + pts.push(Point::new(c.x + 23.0 * th.cos(), c.y + 23.0 * th.sin())); + } + let outer = Polyline::with_uniform_sigma(pts.clone(), 0.05, true); + let inner = Polyline::with_uniform_sigma( + pts.iter() + .rev() + .map(|p| { + Point::new( + c.x + (p.x - c.x) * 17.0 / 23.0, + c.y + (p.y - c.y) * 17.0 / 23.0, + ) + }) + .collect(), + 0.05, + true, + ); + let inside = move |p: Point| (p.dist(c) - r).abs() < 3.0; + let b = Boundary::new(&[outer, inner], &inside, 2.0).expect("rings"); + let third = TAU / 3.0; + let line = Centreline { + path: FittedPath { + start: at(0.0), + segments: (1..=3) + .map(|k| Segment::circular_arc(r, false, true, at(third * k as f64))) + .collect(), + closed: true, + }, + prim: None, + }; + let line = Centreline { + path: FittedPath { + segments: { + let mut s = line.path.segments.clone(); + if let Some(Segment::Arc { end, .. }) = s.last_mut() { + *end = at(0.0); + } + s + }, + ..line.path.clone() + }, + prim: None, + }; + let (out, merged) = run(vec![line], 3.0, &b); + assert!(merged); + assert!( + matches!( + out[0].prim, + Some(PrimitiveFit { + kind: PrimitiveKind::Circle { .. }, + .. + }) + ), + "{:?}", + out[0] + ); + } + + #[test] + fn the_cubic_through_two_halves_is_the_whole() { + let q = [ + Point::new(0.0, 0.0), + Point::new(10.0, 20.0), + Point::new(30.0, 25.0), + Point::new(40.0, 0.0), + ]; + let lerp = |p: Point, r: Point| Point::new(0.5 * (p.x + r.x), 0.5 * (p.y + r.y)); + let (p01, p12, p23) = (lerp(q[0], q[1]), lerp(q[1], q[2]), lerp(q[2], q[3])); + let (p012, p123) = (lerp(p01, p12), lerp(p12, p23)); + let m = lerp(p012, p123); + let a = Segment::Cubic(p01, p012, m); + let b = Segment::Cubic(p123, p23, q[3]); + let Some(Segment::Cubic(c1, c2, e)) = cubic_through(q[0], &a, &b) else { + panic!("a cubic"); + }; + assert_eq!(e, q[3]); + // The arms are a start for the solve, not the cubic's own: the curve they draw + // stays within a few hundredths of a pixel of it. + let fitted = [q[0], c1, c2, e]; + let worst = (0..=64) + .map(|k| { + let p = super::super::cubic_eval(&q, k as f64 / 64.0).0; + crate::ribbon::dist::cubic_dist(p, fitted, k as f64 / 64.0).0 + }) + .fold(0.0, f64::max); + assert!(worst < 0.1, "{worst} px: {c1:?} {c2:?}"); + } + + #[test] + fn arcs_near_a_half_turn_are_written_as_the_half_circle() { + let (p0, p2) = (Point::new(0.0, 0.0), Point::new(20.0, 0.0)); + // Centre 0.5 px off the chord: a sweep of 177°. + let s = arc_about(p0, p2, Point::new(10.0, 0.5), true).expect("an arc"); + let Segment::Arc { rx, .. } = s else { + panic!("{s:?}") + }; + assert!(rx < 10.0 && super::super::conditioned(p0, &s)); + // Centre 3 px off: 147°, its own radius. + let s = arc_about(p0, p2, Point::new(10.0, 3.0), true).expect("an arc"); + let Segment::Arc { rx, .. } = s else { + panic!("{s:?}") + }; + assert!((rx - 109f64.sqrt()).abs() < 1e-9 && super::super::conditioned(p0, &s)); + // The same chord with a radius 0.05 px over the half-chord (168.6°) is refused by + // the solve. + let near = Segment::circular_arc(10.05, false, true, p2); + assert!(!super::super::conditioned(p0, &near)); + // Nearly a full turn is not an arc. + assert!(arc_about(p0, Point::new(0.5, -0.1), Point::new(0.0, 10.0), false).is_none()); + } + + #[test] + fn the_half_circle_radius_survives_rounding() { + for l in [0.3, 1.0, 10.0, 213.33] { + let r = half_circle_radius(l); + let rounded = (r * 100.0).round() / 100.0; + assert!(rounded < l - 0.0071, "{l} -> {r}"); + } + } +} diff --git a/crates/inkvec-verified/Cargo.toml b/crates/inkvec-verified/Cargo.toml new file mode 100644 index 00000000..12cef95b --- /dev/null +++ b/crates/inkvec-verified/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "inkvec-verified" +description = "Checkers generated from the Lean definitions Inkvec's theorems are about" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +authors.workspace = true +repository.workspace = true +readme.workspace = true +keywords.workspace = true +categories.workspace = true + +# No dependencies: the trusted base is this crate's two runtime files and rustc. +[dependencies] + +[lints] +workspace = true diff --git a/crates/inkvec-verified/src/generated/design.rs b/crates/inkvec-verified/src/generated/design.rs new file mode 100644 index 00000000..f5250368 --- /dev/null +++ b/crates/inkvec-verified/src/generated/design.rs @@ -0,0 +1,53 @@ +// @generated by `lake env lean InkvecTheory/Gen/Emit.lean` (formal/InkvecTheory) from +// `InkvecTheory.Gen.Design (designKernels)`. Do not edit: CI regenerates this file and fails on any difference. +#![allow(clippy::all, unused_parens, unused_variables, missing_docs)] + +use crate::iv::{self, Iv}; +use crate::q::{self, Q}; + +/// For `x = [a₀, a₁, b₀, b₁, s]`: `[a₀ − b₀ + s, b₁ − a₁ + s]`, both non-negative exactly when the span `[a₀, a₁]` lies in `[b₀ − s, b₁ + s]` (`spanWithin_meaning`); the per-span check of the painter's interval (`painter_interval_iff`). +#[inline] +pub fn span_within_f64(x: &[f64; 5]) -> [f64; 2] { + [ + ((x[0] - x[2]) + x[4]), + ((x[3] - x[1]) + x[4]), + ] +} + +/// [`span_within_f64`] as an enclosure: contains the exact value, or `None` (a refusal). +pub fn span_within_iv(x: &[Iv; 5]) -> Option<[Iv; 2]> { + Some([ + iv::add(iv::sub(x[0], x[2])?, x[4])?, + iv::add(iv::sub(x[3], x[1])?, x[4])?, + ]) +} + +/// [`span_within_f64`] exactly, or `None` (an overflow, a division by zero, a square root). +pub fn span_within_q(x: &[Q; 5]) -> Option<[Q; 2]> { + Some([ + q::add(q::sub(x[0], x[2])?, x[4])?, + q::add(q::sub(x[3], x[1])?, x[4])?, + ]) +} + +/// For `x = [p₁, q₀, s]`: `p₁ − q₀ + 2s`, non-negative exactly when a span ending at `p₁` and the next one starting at `q₀`, each widened by `s`, touch (`chain_cover`). +#[inline] +pub fn span_link_f64(x: &[f64; 3]) -> [f64; 1] { + [ + ((x[0] - x[1]) + (x[2] + x[2])), + ] +} + +/// [`span_link_f64`] as an enclosure: contains the exact value, or `None` (a refusal). +pub fn span_link_iv(x: &[Iv; 3]) -> Option<[Iv; 1]> { + Some([ + iv::add(iv::sub(x[0], x[1])?, iv::add(x[2], x[2])?)?, + ]) +} + +/// [`span_link_f64`] exactly, or `None` (an overflow, a division by zero, a square root). +pub fn span_link_q(x: &[Q; 3]) -> Option<[Q; 1]> { + Some([ + q::add(q::sub(x[0], x[1])?, q::add(x[2], x[2])?)?, + ]) +} diff --git a/crates/inkvec-verified/src/generated/evidence.rs b/crates/inkvec-verified/src/generated/evidence.rs new file mode 100644 index 00000000..49fda4f4 --- /dev/null +++ b/crates/inkvec-verified/src/generated/evidence.rs @@ -0,0 +1,97 @@ +// @generated by `lake env lean InkvecTheory/Gen/Emit.lean` (formal/InkvecTheory) from +// `InkvecTheory.Gen.Evidence (evidenceKernels)`. Do not edit: CI regenerates this file and fails on any difference. +#![allow(clippy::all, unused_parens, unused_variables, missing_docs)] + +use crate::iv::{self, Iv}; +use crate::q::{self, Q}; + +/// The area `(ub − ua)((va − vlo) + (vb − vlo))/2` a straight piece from `(ua, va)` to `(ub, vb)` inside a window adds above its end `vlo`, `x = [ua, va, ub, vb, vlo]` (`trapezoidK_integral`). +#[inline] +pub fn trapezoid_f64(x: &[f64; 5]) -> [f64; 1] { + [ + (((x[2] - x[0]) * ((x[1] - x[4]) + (x[3] - x[4]))) / 2.0), + ] +} + +/// [`trapezoid_f64`] as an enclosure: contains the exact value, or `None` (a refusal). +pub fn trapezoid_iv(x: &[Iv; 5]) -> Option<[Iv; 1]> { + Some([ + iv::div(iv::mul(iv::sub(x[2], x[0])?, iv::add(iv::sub(x[1], x[4])?, iv::sub(x[3], x[4])?)?)?, iv::lit(2, 1)?)?, + ]) +} + +/// [`trapezoid_f64`] exactly, or `None` (an overflow, a division by zero, a square root). +pub fn trapezoid_q(x: &[Q; 5]) -> Option<[Q; 1]> { + Some([ + q::div(q::mul(q::sub(x[2], x[0])?, q::add(q::sub(x[1], x[4])?, q::sub(x[3], x[4])?)?)?, q::lit(2, 1)?)?, + ]) +} + +/// One window's `χ²` term `(S − A)²/V` and its residual `S − A`, `x = [S, A, V]`. +#[inline] +pub fn window_term_f64(x: &[f64; 3]) -> [f64; 2] { + [ + (((x[0] - x[1]) * (x[0] - x[1])) / x[2]), + (x[0] - x[1]), + ] +} + +/// [`window_term_f64`] as an enclosure: contains the exact value, or `None` (a refusal). +pub fn window_term_iv(x: &[Iv; 3]) -> Option<[Iv; 2]> { + Some([ + iv::div(iv::mul(iv::sub(x[0], x[1])?, iv::sub(x[0], x[1])?)?, x[2])?, + iv::sub(x[0], x[1])?, + ]) +} + +/// [`window_term_f64`] exactly, or `None` (an overflow, a division by zero, a square root). +pub fn window_term_q(x: &[Q; 3]) -> Option<[Q; 2]> { + Some([ + q::div(q::mul(q::sub(x[0], x[1])?, q::sub(x[0], x[1])?)?, x[2])?, + q::sub(x[0], x[1])?, + ]) +} + +/// The fourth difference `h₀ − 4h₁ + 6h₂ − 4h₃ + h₄` of five consecutive window means (`fourthDiff_cubic`: zero on every cubic; `fourthDiff_side`: twelve times `strip.rs`'s one-sided disagreement). +#[inline] +pub fn fourth_difference_f64(x: &[f64; 5]) -> [f64; 1] { + [ + ((((x[0] - (4.0 * x[1])) + (6.0 * x[2])) - (4.0 * x[3])) + x[4]), + ] +} + +/// [`fourth_difference_f64`] as an enclosure: contains the exact value, or `None` (a refusal). +pub fn fourth_difference_iv(x: &[Iv; 5]) -> Option<[Iv; 1]> { + Some([ + iv::add(iv::sub(iv::add(iv::sub(x[0], iv::mul(iv::lit(4, 1)?, x[1])?)?, iv::mul(iv::lit(6, 1)?, x[2])?)?, iv::mul(iv::lit(4, 1)?, x[3])?)?, x[4])?, + ]) +} + +/// [`fourth_difference_f64`] exactly, or `None` (an overflow, a division by zero, a square root). +pub fn fourth_difference_q(x: &[Q; 5]) -> Option<[Q; 1]> { + Some([ + q::add(q::sub(q::add(q::sub(x[0], q::mul(q::lit(4, 1)?, x[1])?)?, q::mul(q::lit(6, 1)?, x[2])?)?, q::mul(q::lit(4, 1)?, x[3])?)?, x[4])?, + ]) +} + +/// `D² − z²·Var D` for the fourth difference `D` of five window means with variances `V₀..V₄`, `x = [h₀..h₄, V₀..V₄, z²]`: non-negative exactly when `|D|` is at least `z` of its standard deviations (a corner proposal). +#[inline] +pub fn corner_excess_f64(x: &[f64; 11]) -> [f64; 1] { + [ + ((((((x[0] - (4.0 * x[1])) + (6.0 * x[2])) - (4.0 * x[3])) + x[4]) * ((((x[0] - (4.0 * x[1])) + (6.0 * x[2])) - (4.0 * x[3])) + x[4])) - (x[10] * ((((x[5] + (16.0 * x[6])) + (36.0 * x[7])) + (16.0 * x[8])) + x[9]))), + ] +} + +/// [`corner_excess_f64`] as an enclosure: contains the exact value, or `None` (a refusal). +pub fn corner_excess_iv(x: &[Iv; 11]) -> Option<[Iv; 1]> { + Some([ + iv::sub(iv::mul(iv::add(iv::sub(iv::add(iv::sub(x[0], iv::mul(iv::lit(4, 1)?, x[1])?)?, iv::mul(iv::lit(6, 1)?, x[2])?)?, iv::mul(iv::lit(4, 1)?, x[3])?)?, x[4])?, iv::add(iv::sub(iv::add(iv::sub(x[0], iv::mul(iv::lit(4, 1)?, x[1])?)?, iv::mul(iv::lit(6, 1)?, x[2])?)?, iv::mul(iv::lit(4, 1)?, x[3])?)?, x[4])?)?, iv::mul(x[10], iv::add(iv::add(iv::add(iv::add(x[5], iv::mul(iv::lit(16, 1)?, x[6])?)?, iv::mul(iv::lit(36, 1)?, x[7])?)?, iv::mul(iv::lit(16, 1)?, x[8])?)?, x[9])?)?)?, + ]) +} + +/// [`corner_excess_f64`] exactly, or `None` (an overflow, a division by zero, a square root). +pub fn corner_excess_q(x: &[Q; 11]) -> Option<[Q; 1]> { + Some([ + q::sub(q::mul(q::add(q::sub(q::add(q::sub(x[0], q::mul(q::lit(4, 1)?, x[1])?)?, q::mul(q::lit(6, 1)?, x[2])?)?, q::mul(q::lit(4, 1)?, x[3])?)?, x[4])?, q::add(q::sub(q::add(q::sub(x[0], q::mul(q::lit(4, 1)?, x[1])?)?, q::mul(q::lit(6, 1)?, x[2])?)?, q::mul(q::lit(4, 1)?, x[3])?)?, x[4])?)?, q::mul(x[10], q::add(q::add(q::add(q::add(x[5], q::mul(q::lit(16, 1)?, x[6])?)?, q::mul(q::lit(36, 1)?, x[7])?)?, q::mul(q::lit(16, 1)?, x[8])?)?, x[9])?)?)?, + ]) +} diff --git a/crates/inkvec-verified/src/generated/mod.rs b/crates/inkvec-verified/src/generated/mod.rs new file mode 100644 index 00000000..defa439b --- /dev/null +++ b/crates/inkvec-verified/src/generated/mod.rs @@ -0,0 +1,9 @@ +// @generated by `lake env lean InkvecTheory/Gen/Emit.lean` (formal/InkvecTheory). Do not edit. +//! Kernels generated from the Lean definitions their theorems are about. + +#[rustfmt::skip] +pub mod strip; +#[rustfmt::skip] +pub mod design; +#[rustfmt::skip] +pub mod evidence; diff --git a/crates/inkvec-verified/src/generated/strip.rs b/crates/inkvec-verified/src/generated/strip.rs new file mode 100644 index 00000000..a3e2b777 --- /dev/null +++ b/crates/inkvec-verified/src/generated/strip.rs @@ -0,0 +1,59 @@ +// @generated by `lake env lean InkvecTheory/Gen/Emit.lean` (formal/InkvecTheory) from +// `InkvecTheory.Gen.Strip (stripKernels)`. Do not edit: CI regenerates this file and fails on any difference. +#![allow(clippy::all, unused_parens, unused_variables, missing_docs)] + +use crate::iv::{self, Iv}; +use crate::q::{self, Q}; + +/// The cubic `c₀ + c₁s + c₂s² + c₃s³` whose means over the cells `[-2,-1] … [1,2]` are `x[0..4]` (`Inkvec.histopolate`; exact on every cubic: `histopolate_cubic`). +#[inline] +pub fn histopolate_f64(x: &[f64; 4]) -> [f64; 4] { + [ + (((((-x[0]) + (7.0 * x[1])) + (7.0 * x[2])) - x[3]) / 12.0), + ((((x[0] - (15.0 * x[1])) + (15.0 * x[2])) - x[3]) / 12.0), + ((((x[0] - x[1]) - x[2]) + x[3]) / 4.0), + (((((-x[0]) + (3.0 * x[1])) - (3.0 * x[2])) + x[3]) / 6.0), + ] +} + +/// [`histopolate_f64`] as an enclosure: contains the exact value, or `None` (a refusal). +pub fn histopolate_iv(x: &[Iv; 4]) -> Option<[Iv; 4]> { + Some([ + iv::div(iv::sub(iv::add(iv::add(iv::neg(x[0])?, iv::mul(iv::lit(7, 1)?, x[1])?)?, iv::mul(iv::lit(7, 1)?, x[2])?)?, x[3])?, iv::lit(12, 1)?)?, + iv::div(iv::sub(iv::add(iv::sub(x[0], iv::mul(iv::lit(15, 1)?, x[1])?)?, iv::mul(iv::lit(15, 1)?, x[2])?)?, x[3])?, iv::lit(12, 1)?)?, + iv::div(iv::add(iv::sub(iv::sub(x[0], x[1])?, x[2])?, x[3])?, iv::lit(4, 1)?)?, + iv::div(iv::add(iv::sub(iv::add(iv::neg(x[0])?, iv::mul(iv::lit(3, 1)?, x[1])?)?, iv::mul(iv::lit(3, 1)?, x[2])?)?, x[3])?, iv::lit(6, 1)?)?, + ]) +} + +/// [`histopolate_f64`] exactly, or `None` (an overflow, a division by zero, a square root). +pub fn histopolate_q(x: &[Q; 4]) -> Option<[Q; 4]> { + Some([ + q::div(q::sub(q::add(q::add(q::neg(x[0])?, q::mul(q::lit(7, 1)?, x[1])?)?, q::mul(q::lit(7, 1)?, x[2])?)?, x[3])?, q::lit(12, 1)?)?, + q::div(q::sub(q::add(q::sub(x[0], q::mul(q::lit(15, 1)?, x[1])?)?, q::mul(q::lit(15, 1)?, x[2])?)?, x[3])?, q::lit(12, 1)?)?, + q::div(q::add(q::sub(q::sub(x[0], x[1])?, x[2])?, x[3])?, q::lit(4, 1)?)?, + q::div(q::add(q::sub(q::add(q::neg(x[0])?, q::mul(q::lit(3, 1)?, x[1])?)?, q::mul(q::lit(3, 1)?, x[2])?)?, x[3])?, q::lit(6, 1)?)?, + ]) +} + +/// `q(s₀ + t·n_u) − t·n_v` for the cubic `q` of [`histopolate_f64`] and `x = [m₀, m₁, m₂, m₃, s₀, n_u, n_v, t]`: zero where the normal line meets the cubic (`stripResidualK_eq`). +#[inline] +pub fn strip_residual_f64(x: &[f64; 8]) -> [f64; 1] { + [ + (((((((-x[0]) + (7.0 * x[1])) + (7.0 * x[2])) - x[3]) / 12.0) + ((x[4] + (x[7] * x[5])) * (((((x[0] - (15.0 * x[1])) + (15.0 * x[2])) - x[3]) / 12.0) + ((x[4] + (x[7] * x[5])) * (((((x[0] - x[1]) - x[2]) + x[3]) / 4.0) + ((x[4] + (x[7] * x[5])) * (((((-x[0]) + (3.0 * x[1])) - (3.0 * x[2])) + x[3]) / 6.0))))))) - (x[7] * x[6])), + ] +} + +/// [`strip_residual_f64`] as an enclosure: contains the exact value, or `None` (a refusal). +pub fn strip_residual_iv(x: &[Iv; 8]) -> Option<[Iv; 1]> { + Some([ + iv::sub(iv::add(iv::div(iv::sub(iv::add(iv::add(iv::neg(x[0])?, iv::mul(iv::lit(7, 1)?, x[1])?)?, iv::mul(iv::lit(7, 1)?, x[2])?)?, x[3])?, iv::lit(12, 1)?)?, iv::mul(iv::add(x[4], iv::mul(x[7], x[5])?)?, iv::add(iv::div(iv::sub(iv::add(iv::sub(x[0], iv::mul(iv::lit(15, 1)?, x[1])?)?, iv::mul(iv::lit(15, 1)?, x[2])?)?, x[3])?, iv::lit(12, 1)?)?, iv::mul(iv::add(x[4], iv::mul(x[7], x[5])?)?, iv::add(iv::div(iv::add(iv::sub(iv::sub(x[0], x[1])?, x[2])?, x[3])?, iv::lit(4, 1)?)?, iv::mul(iv::add(x[4], iv::mul(x[7], x[5])?)?, iv::div(iv::add(iv::sub(iv::add(iv::neg(x[0])?, iv::mul(iv::lit(3, 1)?, x[1])?)?, iv::mul(iv::lit(3, 1)?, x[2])?)?, x[3])?, iv::lit(6, 1)?)?)?)?)?)?)?)?, iv::mul(x[7], x[6])?)?, + ]) +} + +/// [`strip_residual_f64`] exactly, or `None` (an overflow, a division by zero, a square root). +pub fn strip_residual_q(x: &[Q; 8]) -> Option<[Q; 1]> { + Some([ + q::sub(q::add(q::div(q::sub(q::add(q::add(q::neg(x[0])?, q::mul(q::lit(7, 1)?, x[1])?)?, q::mul(q::lit(7, 1)?, x[2])?)?, x[3])?, q::lit(12, 1)?)?, q::mul(q::add(x[4], q::mul(x[7], x[5])?)?, q::add(q::div(q::sub(q::add(q::sub(x[0], q::mul(q::lit(15, 1)?, x[1])?)?, q::mul(q::lit(15, 1)?, x[2])?)?, x[3])?, q::lit(12, 1)?)?, q::mul(q::add(x[4], q::mul(x[7], x[5])?)?, q::add(q::div(q::add(q::sub(q::sub(x[0], x[1])?, x[2])?, x[3])?, q::lit(4, 1)?)?, q::mul(q::add(x[4], q::mul(x[7], x[5])?)?, q::div(q::add(q::sub(q::add(q::neg(x[0])?, q::mul(q::lit(3, 1)?, x[1])?)?, q::mul(q::lit(3, 1)?, x[2])?)?, x[3])?, q::lit(6, 1)?)?)?)?)?)?)?)?, q::mul(x[7], x[6])?)?, + ]) +} diff --git a/crates/inkvec-verified/src/iv.rs b/crates/inkvec-verified/src/iv.rs new file mode 100644 index 00000000..ab3b2273 --- /dev/null +++ b/crates/inkvec-verified/src/iv.rs @@ -0,0 +1,183 @@ +//! Outward-rounded interval arithmetic in `f64`: the runtime of the generated `_iv` kernels. +//! +//! Each operation computes its endpoints in `f64` and moves each one float outward +//! (`next_down`, `next_up`). IEEE 754 rounds `+ − × ÷ √` to the nearest float, within half +//! the gap to the next one, so the widened interval contains the exact result of the +//! operation on the endpoints: the hypothesis `Inkvec.Gen.Enclosing` of the soundness theorem +//! `Inkvec.Gen.Expr.evalI_sound`. Products take the least and greatest of the four endpoint +//! products (rounding is monotone, so the least rounded product moved down is below the least +//! exact one); division multiplies by the reciprocal of a divisor interval that excludes +//! zero; a square root needs an interval of non-negative numbers. Anything else, and any +//! non-finite endpoint, is a refusal (`None`). + +/// A closed interval `[lo, hi]` of reals with `f64` endpoints, `lo <= hi`, both finite. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Iv { + /// Lower endpoint. + pub lo: f64, + /// Upper endpoint. + pub hi: f64, +} + +impl Iv { + /// The point interval of a finite `x`: an `f64` is an exact real. + pub fn point(x: f64) -> Option { + ok(x, x) + } + + /// `[lo, hi]`, when finite and ordered. + pub fn new(lo: f64, hi: f64) -> Option { + ok(lo, hi) + } + + /// Whether `x` lies in the interval. + pub fn contains(&self, x: f64) -> bool { + self.lo <= x && x <= self.hi + } + + /// Whether every number in the interval is at least zero: the verdict of a checked + /// condition `e >= 0` (`Inkvec.Gen.Expr.nonneg_of_evalI`). + pub fn is_nonneg(&self) -> bool { + self.lo >= 0.0 + } + + /// Whether every number in the interval lies within `tol` of zero. + pub fn within(&self, tol: f64) -> bool { + -tol <= self.lo && self.hi <= tol + } +} + +fn ok(lo: f64, hi: f64) -> Option { + (lo.is_finite() && hi.is_finite() && lo <= hi).then_some(Iv { lo, hi }) +} + +/// An enclosure of the rational `num / den` (`den > 0`); `None` when either is not an +/// exactly representable `f64` integer. +pub fn lit(num: i128, den: i128) -> Option { + const EXACT: i128 = 1 << 53; + if den <= 0 || num.abs() > EXACT || den > EXACT { + return None; + } + let (n, d) = (num as f64, den as f64); + if den == 1 { + return ok(n, n); + } + let q = n / d; + ok(q.next_down(), q.next_up()) +} + +/// `-a`, exactly. +pub fn neg(a: Iv) -> Option { + ok(-a.hi, -a.lo) +} + +/// `a + b`. +pub fn add(a: Iv, b: Iv) -> Option { + ok((a.lo + b.lo).next_down(), (a.hi + b.hi).next_up()) +} + +/// `a − b`. +pub fn sub(a: Iv, b: Iv) -> Option { + ok((a.lo - b.hi).next_down(), (a.hi - b.lo).next_up()) +} + +/// `a · b`. +pub fn mul(a: Iv, b: Iv) -> Option { + let p = [a.lo * b.lo, a.lo * b.hi, a.hi * b.lo, a.hi * b.hi]; + if p.iter().any(|v| !v.is_finite()) { + return None; + } + let lo = p.iter().copied().fold(f64::INFINITY, f64::min); + let hi = p.iter().copied().fold(f64::NEG_INFINITY, f64::max); + ok(lo.next_down(), hi.next_up()) +} + +/// `a / b`, for a divisor interval that excludes zero. +pub fn div(a: Iv, b: Iv) -> Option { + if !(b.lo > 0.0 || b.hi < 0.0) { + return None; + } + let r = ok((1.0 / b.hi).next_down(), (1.0 / b.lo).next_up())?; + mul(a, r) +} + +/// `√a`, for an interval of non-negative numbers. +pub fn sqrt(a: Iv) -> Option { + if a.lo < 0.0 { + return None; + } + ok(a.lo.sqrt().next_down(), a.hi.sqrt().next_up()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::q::{self, Q}; + + /// A small deterministic generator of awkward doubles. + fn values() -> Vec { + let mut s: u64 = 0x9e37_79b9_7f4a_7c15; + let mut out = vec![0.0, 1.0, -1.0, 0.1, -0.3, 1e-9, 7.0 / 3.0, 12.0, -1e6]; + for _ in 0..200 { + s = s + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + let m = (s >> 11) as f64 / (1u64 << 53) as f64; + let e = ((s >> 3) % 20) as i32 - 10; + out.push((m - 0.5) * 2f64.powi(e)); + } + out + } + + #[test] + fn every_operation_encloses_the_exact_rational_result() { + let vs = values(); + for (i, &a) in vs.iter().enumerate() { + let b = vs[(i * 7 + 3) % vs.len()]; + let (ia, ib) = (Iv::point(a).unwrap(), Iv::point(b).unwrap()); + let (qa, qb) = (Q::from_f64(a).unwrap(), Q::from_f64(b).unwrap()); + let cases = [ + (add(ia, ib), q::add(qa, qb)), + (sub(ia, ib), q::sub(qa, qb)), + (mul(ia, ib), q::mul(qa, qb)), + (div(ia, ib), q::div(qa, qb)), + ]; + for (k, (iv, exact)) in cases.into_iter().enumerate() { + // An endpoint too small for an i128 rational (a subnormal) cannot be + // compared exactly; those cases are skipped. + let comparable = + |iv: &Iv| Q::from_f64(iv.lo).is_some() && Q::from_f64(iv.hi).is_some(); + if let (Some(iv), Some(exact)) = (iv, exact) { + if !comparable(&iv) { + continue; + } + assert!( + exact.ge_f64(iv.lo) && exact.le_f64(iv.hi), + "op {k}: {a} {b} -> {iv:?}" + ); + } + } + } + } + + #[test] + fn refusals() { + let z = Iv::new(-1.0, 1.0).unwrap(); + assert!(div(Iv::point(1.0).unwrap(), z).is_none()); + assert!(sqrt(z).is_none()); + assert!(Iv::new(1.0, 0.0).is_none()); + assert!(Iv::point(f64::NAN).is_none()); + assert!(mul(Iv::point(1e300).unwrap(), Iv::point(1e300).unwrap()).is_none()); + assert!(lit(1, 1 << 60).is_none()); + } + + #[test] + fn literals_and_roots_enclose() { + let third = lit(1, 3).unwrap(); + assert!(third.lo < third.hi && third.contains(1.0 / 3.0)); + assert_eq!(lit(7, 1), Iv::point(7.0)); + let r = sqrt(Iv::point(2.0).unwrap()).unwrap(); + assert!(r.lo * r.lo <= 2.0 && r.hi * r.hi >= 2.0); + assert!(r.within(2.0) && !r.within(1.0) && r.is_nonneg()); + } +} diff --git a/crates/inkvec-verified/src/lib.rs b/crates/inkvec-verified/src/lib.rs new file mode 100644 index 00000000..c1d1d048 --- /dev/null +++ b/crates/inkvec-verified/src/lib.rs @@ -0,0 +1,29 @@ +//! Checkers generated from the Lean definitions Inkvec's theorems are about. +//! +//! The engine's solvers are free: floating point, heuristics, any algorithm. A result a +//! theorem speaks about is used only if a checker in this crate accepts it, on a certificate +//! the solver emits (`docs/theory/verification.md`). The checkers are not written here: they +//! are generated (`src/generated/`) from expressions in `formal/InkvecTheory/InkvecTheory/Gen/`, +//! the same expressions the theorems are stated about, and CI regenerates them and fails on +//! any difference, so they cannot drift from the proofs. +//! +//! Every kernel comes in three forms: +//! +//! * `_f64`: the formula in `f64`, in the expression's own order of operations, for the +//! solvers; +//! * `_iv`: an enclosure through [`iv`]'s outward-rounded intervals, which contains the +//! exact real value whenever it returns one (`Inkvec.Gen.Expr.evalI_sound`); +//! * `_q`: the exact rational value through [`q`]'s checked `i128` arithmetic +//! (`Inkvec.Gen.Expr.evalQ_sound`). +//! +//! The trusted base is small and stated: [`iv`] and [`q`] implement the operations the Lean +//! development models (`Inkvec.Gen.Enclosing`, the field operations on ℚ); IEEE 754 makes +//! `+ − × ÷ √` correctly rounded, so a result widened by one unit in the last place on each +//! side contains the exact one; and the printer in `Gen/Rust.lean` maps each constructor to +//! one runtime call. A refusal (`None`) is always safe: the caller keeps its fallback. + +#![forbid(unsafe_code)] + +pub mod generated; +pub mod iv; +pub mod q; diff --git a/crates/inkvec-verified/src/q.rs b/crates/inkvec-verified/src/q.rs new file mode 100644 index 00000000..14916db6 --- /dev/null +++ b/crates/inkvec-verified/src/q.rs @@ -0,0 +1,214 @@ +//! Exact rationals on checked `i128`: the runtime of the generated `_q` kernels. +//! +//! A [`Q`] is `num / den` in lowest terms with `den > 0`. Every operation is the field +//! operation on ℚ (`Inkvec.Gen.Expr.evalQ`) or a refusal (`None`) when a numerator or +//! denominator would leave `i128`, or on a division by zero. Every finite `f64` is a +//! rational (`Q::from_f64`, exact when it fits). + +/// An exact rational `num / den`, in lowest terms, `den > 0`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Q { + /// Numerator. + pub num: i128, + /// Denominator, positive. + pub den: i128, +} + +fn gcd(mut a: i128, mut b: i128) -> i128 { + a = a.abs(); + b = b.abs(); + while b != 0 { + (a, b) = (b, a % b); + } + a +} + +impl Q { + /// The integer `n`. + pub fn int(n: i64) -> Q { + Q { + num: n as i128, + den: 1, + } + } + + /// `num / den` in lowest terms; `None` for `den == 0`. + pub fn new(num: i128, den: i128) -> Option { + if den == 0 { + return None; + } + let g = gcd(num, den).max(1); + let (mut n, mut d) = (num / g, den / g); + if d < 0 { + n = n.checked_neg()?; + d = d.checked_neg()?; + } + Some(Q { num: n, den: d }) + } + + /// The exact value of a finite `f64`, when its numerator and denominator fit `i128`. + pub fn from_f64(x: f64) -> Option { + if !x.is_finite() { + return None; + } + if x == 0.0 { + return Some(Q::int(0)); + } + let bits = x.to_bits(); + let sign = if bits >> 63 == 1 { -1i128 } else { 1 }; + let exp = ((bits >> 52) & 0x7ff) as i32; + let frac = (bits & ((1u64 << 52) - 1)) as i128; + let (mant, e) = if exp == 0 { + (frac, -1074) + } else { + (frac | (1i128 << 52), exp - 1075) + }; + if e >= 0 { + if e > 70 { + return None; + } + Q::new(sign * (mant << e), 1) + } else { + let k = (-e) as u32; + if k > 126 { + return None; + } + Q::new(sign * mant, 1i128 << k) + } + } + + /// Whether `self >= x` for a finite `f64` `x`, exactly; `false` when `x` has no `i128` + /// rational form (a subnormal, or beyond 2^70). + pub fn ge_f64(&self, x: f64) -> bool { + Q::from_f64(x).is_some_and(|q| cmp(*self, q).is_ge()) + } + + /// Whether `self <= x` for a finite `f64` `x`, exactly; `false` when `x` has no `i128` + /// rational form. + pub fn le_f64(&self, x: f64) -> bool { + Q::from_f64(x).is_some_and(|q| cmp(*self, q).is_le()) + } + + /// Whether the value is at least zero. + pub fn is_nonneg(&self) -> bool { + self.num >= 0 + } +} + +/// `a` against `b`, exactly and without overflow: integer parts first, then the +/// reciprocals of the fractional parts in reverse order (Euclid's algorithm, as continued +/// fractions compare). +pub fn cmp(a: Q, b: Q) -> std::cmp::Ordering { + use std::cmp::Ordering::{Equal, Greater, Less}; + let (mut an, mut ad, mut bn, mut bd) = (a.num, a.den, b.num, b.den); + let mut flip = false; + loop { + let (qa, ra) = (an.div_euclid(ad), an.rem_euclid(ad)); + let (qb, rb) = (bn.div_euclid(bd), bn.rem_euclid(bd)); + let o = if qa != qb { + qa.cmp(&qb) + } else if ra == 0 || rb == 0 { + match (ra == 0, rb == 0) { + (true, true) => Equal, + (true, false) => Less, + _ => Greater, + } + } else { + // ra/ad against rb/bd is ad/ra against bd/rb, the other way round. + (an, ad, bn, bd) = (ad, ra, bd, rb); + flip = !flip; + continue; + }; + return if flip { o.reverse() } else { o }; + } +} + +/// The literal `num / den`. +pub fn lit(num: i128, den: i128) -> Option { + Q::new(num, den) +} + +/// `-a`. +pub fn neg(a: Q) -> Option { + Some(Q { + num: a.num.checked_neg()?, + den: a.den, + }) +} + +/// `a + b`. +pub fn add(a: Q, b: Q) -> Option { + let n = a + .num + .checked_mul(b.den)? + .checked_add(b.num.checked_mul(a.den)?)?; + Q::new(n, a.den.checked_mul(b.den)?) +} + +/// `a − b`. +pub fn sub(a: Q, b: Q) -> Option { + add(a, neg(b)?) +} + +/// `a · b`. +pub fn mul(a: Q, b: Q) -> Option { + // Cross-reduce first so products stay small. + let g1 = gcd(a.num, b.den).max(1); + let g2 = gcd(b.num, a.den).max(1); + let n = (a.num / g1).checked_mul(b.num / g2)?; + let d = (a.den / g2).checked_mul(b.den / g1)?; + Q::new(n, d) +} + +/// `a / b`; `None` for `b == 0`. +pub fn div(a: Q, b: Q) -> Option { + if b.num == 0 { + return None; + } + mul(a, Q::new(b.den, b.num)?) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn field_operations() { + let a = Q::new(1, 3).unwrap(); + let b = Q::new(-1, 6).unwrap(); + assert_eq!(add(a, b), Q::new(1, 6)); + assert_eq!(sub(a, b), Q::new(1, 2)); + assert_eq!(mul(a, b), Q::new(-1, 18)); + assert_eq!(div(a, b), Q::new(-2, 1)); + assert_eq!(div(a, Q::int(0)), None); + assert_eq!(Q::new(4, -8), Q::new(-1, 2)); + assert!(Q::new(1, 0).is_none()); + assert!(add(Q::new(i128::MAX, 1).unwrap(), Q::int(1)).is_none()); + assert_eq!(cmp(a, b), std::cmp::Ordering::Greater); + assert_eq!(cmp(b, a), std::cmp::Ordering::Less); + assert_eq!(cmp(a, Q::new(2, 6).unwrap()), std::cmp::Ordering::Equal); + // Cross products far beyond i128: compared exactly all the same. + let big = Q::new(i128::MAX - 1, i128::MAX).unwrap(); + let bigger = Q::new(i128::MAX - 2, i128::MAX - 1).unwrap(); + assert_eq!(cmp(big, bigger), std::cmp::Ordering::Greater); + assert_eq!( + cmp(Q::int(-3), Q::new(-5, 2).unwrap()), + std::cmp::Ordering::Less + ); + assert!(a.is_nonneg() && !b.is_nonneg()); + } + + #[test] + fn doubles_are_exact_rationals() { + assert_eq!(Q::from_f64(0.5), Q::new(1, 2)); + assert_eq!(Q::from_f64(-3.0), Some(Q::int(-3))); + assert_eq!( + Q::from_f64(0.1), + Q::new(3602879701896397, 36028797018963968) + ); + assert!(Q::from_f64(f64::NAN).is_none()); + assert!(Q::from_f64(1e300).is_none()); + let q = Q::from_f64(0.1).unwrap(); + assert!(q.ge_f64(0.1) && q.le_f64(0.1) && !q.le_f64(0.0999)); + } +} diff --git a/crates/inkvec-verified/tests/evidence.rs b/crates/inkvec-verified/tests/evidence.rs new file mode 100644 index 00000000..e41ed8a7 --- /dev/null +++ b/crates/inkvec-verified/tests/evidence.rs @@ -0,0 +1,130 @@ +//! The generated evidence kernels (`Gen/Evidence.lean`): each form against the others, and +//! the exact facts their theorems state. + +use inkvec_verified::generated::evidence::{ + corner_excess_f64, corner_excess_iv, corner_excess_q, fourth_difference_f64, + fourth_difference_iv, fourth_difference_q, trapezoid_f64, trapezoid_iv, trapezoid_q, + window_term_f64, window_term_iv, window_term_q, +}; +use inkvec_verified::iv::Iv; +use inkvec_verified::q::{self, Q}; + +/// Deterministic values in `[lo, hi)`. +fn values(n: usize, lo: f64, hi: f64) -> Vec { + let mut s: u64 = 987654321; + (0..n) + .map(|_| { + s = s + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + lo + (hi - lo) * ((s >> 11) as f64 / (1u64 << 53) as f64) + }) + .collect() +} + +/// Every form agrees: the exact value and the float one lie in the enclosure. +fn agree( + x: [f64; N], + f: fn(&[f64; N]) -> [f64; M], + i: fn(&[Iv; N]) -> Option<[Iv; M]>, + e: fn(&[Q; N]) -> Option<[Q; M]>, +) { + let fx = f(&x); + let ix = i(&x.map(|v| Iv::point(v).unwrap())).unwrap(); + let qx = e(&x.map(|v| Q::from_f64(v).unwrap())); + for k in 0..M { + assert!(ix[k].contains(fx[k]), "{x:?} {k}"); + if let Some(qx) = qx { + assert!( + qx[k].ge_f64(ix[k].lo) && qx[k].le_f64(ix[k].hi), + "{x:?} {k}" + ); + } + } +} + +#[test] +fn the_forms_agree() { + let v = values(4 * 11 * 50, -3.0, 3.0); + for c in v.as_chunks::<11>().0 { + let x5 = [c[0], c[1], c[2], c[3], c[4]]; + agree(x5, trapezoid_f64, trapezoid_iv, trapezoid_q); + agree( + x5, + fourth_difference_f64, + fourth_difference_iv, + fourth_difference_q, + ); + // A variance is positive. + agree( + [c[0], c[1], c[2].abs() + 0.01], + window_term_f64, + window_term_iv, + window_term_q, + ); + let mut x11 = *c; + for v in &mut x11[5..] { + *v = v.abs(); + } + agree(x11, corner_excess_f64, corner_excess_iv, corner_excess_q); + } +} + +#[test] +fn a_straight_piece_is_a_trapezoid() { + // From (0, 1/2) to (1, 3/4) above 0: area 5/8, exactly. + let r = |n: i128, d: i128| Q::new(n, d).unwrap(); + let [a] = trapezoid_q(&[r(0, 1), r(1, 2), r(1, 1), r(3, 4), r(0, 1)]).unwrap(); + assert_eq!(a, r(5, 8)); + // Walking the other way the area changes sign (`trapezoidK_integral`'s orientation). + let [b] = trapezoid_q(&[r(1, 1), r(3, 4), r(0, 1), r(1, 2), r(0, 1)]).unwrap(); + assert_eq!(b, r(-5, 8)); +} + +#[test] +fn the_fourth_difference_annihilates_cubics_and_reads_a_kink() { + // `fourthDiff_cubic`: zero on every cubic, exactly. + let r = |n: i128, d: i128| Q::new(n, d).unwrap(); + let cubic = |s: i128| r(3 + 2 * s - 5 * s * s + 7 * s * s * s, 4); + let x = [-2i128, -1, 0, 1, 2].map(cubic); + let [d] = fourth_difference_q(&x).unwrap(); + assert_eq!(d, Q::int(0)); + // A slope change of 1 at the centre, read as window means (the cell averages of + // max(0, s): 0, 0, 1/8, 1, 2), gives |D| = 5/4: the kink response. + let x = [r(0, 1), r(0, 1), r(1, 8), r(1, 1), r(2, 1)]; + let [d] = fourth_difference_q(&x).unwrap(); + assert_eq!(d, r(-5, 4)); +} + +#[test] +fn the_corner_excess_decides_the_threshold() { + // h = (0, 0, 0, 1, 2) gives D = −2; with unit variances Σ wᵢ² = 70, so + // D² − z²·70 ≥ 0 iff z² ≤ 4/70. + let h = [0.0, 0.0, 0.0, 1.0, 2.0]; + let at = |z2: f64| { + let mut x = [Iv::point(1.0).unwrap(); 11]; + for k in 0..5 { + x[k] = Iv::point(h[k]).unwrap(); + } + x[10] = Iv::point(z2).unwrap(); + corner_excess_iv(&x).unwrap()[0] + }; + assert!(at(4.0 / 71.0).is_nonneg()); + assert!(!at(4.0 / 69.0).is_nonneg()); + // Exactly on the threshold the excess is zero. + let mut x = [Q::int(1); 11]; + for (k, v) in [0, 0, 0, 1, 2].into_iter().enumerate() { + x[k] = Q::int(v); + } + x[10] = Q::new(4, 70).unwrap(); + let [e] = corner_excess_q(&x).unwrap(); + assert_eq!(q::cmp(e, Q::int(0)), std::cmp::Ordering::Equal); +} + +#[test] +fn a_window_term_is_the_squared_standardised_residual() { + let r = |n: i128, d: i128| Q::new(n, d).unwrap(); + let [t, res] = window_term_q(&[r(7, 4), r(5, 4), r(1, 16)]).unwrap(); + assert_eq!(res, r(1, 2)); + assert_eq!(t, Q::int(4)); +} diff --git a/crates/inkvec-verified/tests/strip.rs b/crates/inkvec-verified/tests/strip.rs new file mode 100644 index 00000000..2a498531 --- /dev/null +++ b/crates/inkvec-verified/tests/strip.rs @@ -0,0 +1,89 @@ +//! The generated strip kernels against the formula they replaced and against each other. + +use inkvec_verified::generated::strip::{ + histopolate_f64, histopolate_iv, histopolate_q, strip_residual_f64, strip_residual_iv, +}; +use inkvec_verified::iv::Iv; +use inkvec_verified::q::{self, Q}; + +/// `strip.rs`'s formula before it was generated. +fn by_hand(m: &[f64; 4]) -> [f64; 4] { + [ + (-m[0] + 7.0 * m[1] + 7.0 * m[2] - m[3]) / 12.0, + (m[0] - 15.0 * m[1] + 15.0 * m[2] - m[3]) / 12.0, + (m[0] - m[1] - m[2] + m[3]) / 4.0, + (-m[0] + 3.0 * m[1] - 3.0 * m[2] + m[3]) / 6.0, + ] +} + +fn means() -> Vec<[f64; 4]> { + let mut s: u64 = 12345; + let mut next = || { + s = s + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + ((s >> 11) as f64 / (1u64 << 53) as f64 - 0.5) * 6.0 + }; + (0..500).map(|_| [next(), next(), next(), next()]).collect() +} + +#[test] +fn the_generated_formula_is_bit_for_bit_the_one_it_replaced() { + for m in means() { + let (a, b) = (histopolate_f64(&m), by_hand(&m)); + for k in 0..4 { + assert_eq!(a[k].to_bits(), b[k].to_bits(), "{m:?}"); + } + } +} + +#[test] +fn the_enclosure_holds_the_exact_value_and_the_float_one() { + for m in means() { + let iv = histopolate_iv(&m.map(|v| Iv::point(v).unwrap())).unwrap(); + let q = histopolate_q(&m.map(|v| Q::from_f64(v).unwrap())).unwrap(); + let f = histopolate_f64(&m); + for k in 0..4 { + assert!(q[k].ge_f64(iv[k].lo) && q[k].le_f64(iv[k].hi), "{m:?} {k}"); + assert!(iv[k].contains(f[k]), "{m:?} {k}"); + } + } +} + +#[test] +fn a_cubic_is_rebuilt_exactly_and_its_crossing_certified() { + // The cell means of q(s) = 1/4 + s/2 − s²/8 + s³/16 over [-2,-1] … [1,2], computed + // exactly; histopolate returns q exactly (`histopolate_cubic`). + let r = |n: i128, d: i128| Q::new(n, d).unwrap(); + let c = [r(1, 4), r(1, 2), r(-1, 8), r(1, 16)]; + // The antiderivative c₀s + c₁s²/2 + c₂s³/3 + c₃s⁴/4 at an integer s. + let prim = |s: i128| { + let terms = [ + q::mul(c[0], r(s, 1)).unwrap(), + q::mul(c[1], r(s * s, 2)).unwrap(), + q::mul(c[2], r(s * s * s, 3)).unwrap(), + q::mul(c[3], r(s * s * s * s, 4)).unwrap(), + ]; + terms + .into_iter() + .fold(Q::int(0), |a, t| q::add(a, t).unwrap()) + }; + let m: [Q; 4] = [-2i128, -1, 0, 1].map(|k| q::sub(prim(k + 1), prim(k)).unwrap()); + let back = histopolate_q(&m).unwrap(); + assert_eq!(back, c); + // Where the vertical through s₀ = 0.3 meets q: t = q(0.3). The means as doubles + // (exact here: dyadic denominators) feed the float and interval kernels. + let mf = m.map(|v| v.num as f64 / v.den as f64); + let cf = [0.25, 0.5, -0.125, 0.0625]; + let s0 = 0.3; + let t = cf[0] + s0 * (cf[1] + s0 * (cf[2] + s0 * cf[3])); + let x = [mf[0], mf[1], mf[2], mf[3], s0, 0.0, 1.0, t]; + assert!(strip_residual_f64(&x)[0].abs() < 1e-12); + let res = strip_residual_iv(&x.map(|v| Iv::point(v).unwrap())).unwrap(); + assert!(res[0].within(1e-12)); + // A shift 0.01 off is refused. + let mut off = x; + off[7] += 0.01; + let res = strip_residual_iv(&off.map(|v| Iv::point(v).unwrap())).unwrap(); + assert!(!res[0].within(1e-9)); +} diff --git a/crates/inkvec/README.md b/crates/inkvec/README.md index b1bdda08..12880405 100644 --- a/crates/inkvec/README.md +++ b/crates/inkvec/README.md @@ -57,7 +57,7 @@ panicked; panics never escape). | `harmonize_threshold` | number | `0.92` | >= 0 and <= 1 | Shape-equivalence threshold for harmonization: the outline similarity (IoU after affine normalisation) above which two marks count as the same shape. | | `mode` | string | `"quality"` | - | Which engine traces the image. "quality" (the default) is the full engine: the best fidelity and the fewest parameters, at about half a second for a 512 px logo. "fast" is a Potrace-class fit on the same palette, planar map and emitter, with a one-pass gradient check in place of gradient recovery: several times faster (tens of milliseconds at 512 px), a little less faithful, with somewhat more parameters. Options that only steer quality stages (precision, content_units, harmonize, harmonize_threshold, time_budget) are ignored in fast mode. "balanced" (opt-in) is fast plus eight iterations of quality's boundary solve and a fit with tolerances a quarter finer: in between the two in fidelity and time, on rasters up to 1024 px on the longer side; a larger raster is traced exactly as in fast mode. It ignores the same options as fast. | | `hypotheses` | bool | `false` | - | Also trace three structural alternatives -- blend absorption off, a matte instead of native alpha, and a merge distance of 0.020 -- and keep the trace whose render explains the input in the fewest nats (its squared error at the input's resolution against the best one's, plus a price per parameter). Quality colour mode only; up to four traces, about 3.6 times the trace time at 512 px. Measured on the 246-icon screen set: 6 % closer to the artist's file at 128 px, 1 % at 512 px (9 % on the hardest tenth). Off by default. | -| `detect_strokes` | bool | `false` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count. Quality mode only; off by default. | +| `detect_strokes` | bool | `true` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count, and a ring on a plain page as one stroke over the page rather than two discs. Quality mode only; on by default. | | `merge_colors` | string | `""` | - | Colour groups: fills to draw as one, so the shapes between them join rather than being recoloured. Empty (the default) changes nothing. Groups are separated by ';' and members by ','; a member is a colour '#rrggbb' as it appears in a trace of the same image, or a gradient written as its stop colours joined by '>'. An optional '=' says what the group becomes: '=#rrggbb' a flat colour, '=@n' its n-th member (1-based; a gradient there is refitted over the whole group); without it, the member covering the most of the image. Example: '#c0392b,#e74c3c;#f00>#00f,#0a0=@1'. A group costs one extra trace. | diff --git a/crates/inkvec/src/options.rs b/crates/inkvec/src/options.rs index 57043cd5..37b287f5 100644 --- a/crates/inkvec/src/options.rs +++ b/crates/inkvec/src/options.rs @@ -108,7 +108,7 @@ pub struct Options { /// Also trace three structural alternatives -- blend absorption off, a matte instead of native alpha, and a merge distance of 0.020 -- and keep the trace whose render explains the input in the fewest nats (its squared error at the input's resolution against the best one's, plus a price per parameter). Quality colour mode only; up to four traces, about 3.6 times the trace time at 512 px. Measured on the 246-icon screen set: 6 % closer to the artist's file at 128 px, 1 % at 512 px (9 % on the hardest tenth). Off by default. pub hypotheses: bool, - /// Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count. Quality mode only; off by default. + /// Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count, and a ring on a plain page as one stroke over the page rather than two discs. Quality mode only; on by default. pub detect_strokes: bool, /// Colour groups: fills to draw as one, so the shapes between them join rather than being recoloured. Empty (the default) changes nothing. Groups are separated by ';' and members by ','; a member is a colour '#rrggbb' as it appears in a trace of the same image, or a gradient written as its stop colours joined by '>'. An optional '=' says what the group becomes: '=#rrggbb' a flat colour, '=@n' its n-th member (1-based; a gradient there is refitted over the whole group); without it, the member covering the most of the image. Example: '#c0392b,#e74c3c;#f00>#00f,#0a0=@1'. A group costs one extra trace. diff --git a/crates/inkvec/tests/api.rs b/crates/inkvec/tests/api.rs index 1ad5c5a2..4a22e42b 100644 --- a/crates/inkvec/tests/api.rs +++ b/crates/inkvec/tests/api.rs @@ -133,6 +133,12 @@ fn concurrent_calls_are_independent() { /// configuration from the one raw pixels get -- and on an input with the kind of ringing a /// restorer leaves behind, a visibly different trace. If this ever stops differing, the /// forcing has stopped reaching the pipeline. +/// +/// The ripple is strong enough for the palette to see it: unforced, its crests are traced as +/// specks; forced, the soft intake's noise guard absorbs them. At 9 levels both configurations +/// trace a clean disc, and the two SVGs used to differ only because the sub-pixel reading +/// put the centre 0.01 px off on one of them; reading boundaries from exact column sums +/// (`planar/strip.rs`) puts both on the true centre. #[test] fn restored_pixels_are_traced_with_soft_intake() { let size = 96; @@ -141,7 +147,7 @@ fn restored_pixels_are_traced_with_soft_intake() { for y in 0..size { for x in 0..size { let i = ((y * size + x) * 4) as usize; - let ripple = ((x as f64 * 0.7).sin() * (y as f64 * 0.7).cos() * 9.0) as i16; + let ripple = ((x as f64 * 0.7).sin() * (y as f64 * 0.7).cos() * 12.0) as i16; for c in 0..3 { px[i + c] = (px[i + c] as i16 + ripple).clamp(0, 255) as u8; } diff --git a/docs/BINDINGS.md b/docs/BINDINGS.md index 5a79cd70..e694855b 100644 --- a/docs/BINDINGS.md +++ b/docs/BINDINGS.md @@ -121,7 +121,7 @@ error naming the option. | `harmonize_threshold` | number | `0.92` | >= 0 and <= 1 | Shape-equivalence threshold for harmonization: the outline similarity (IoU after affine normalisation) above which two marks count as the same shape. | | `mode` | string | `"quality"` | - | Which engine traces the image. "quality" (the default) is the full engine: the best fidelity and the fewest parameters, at about half a second for a 512 px logo. "fast" is a Potrace-class fit on the same palette, planar map and emitter, with a one-pass gradient check in place of gradient recovery: several times faster (tens of milliseconds at 512 px), a little less faithful, with somewhat more parameters. Options that only steer quality stages (precision, content_units, harmonize, harmonize_threshold, time_budget) are ignored in fast mode. "balanced" (opt-in) is fast plus eight iterations of quality's boundary solve and a fit with tolerances a quarter finer: in between the two in fidelity and time, on rasters up to 1024 px on the longer side; a larger raster is traced exactly as in fast mode. It ignores the same options as fast. | | `hypotheses` | bool | `false` | - | Also trace three structural alternatives -- blend absorption off, a matte instead of native alpha, and a merge distance of 0.020 -- and keep the trace whose render explains the input in the fewest nats (its squared error at the input's resolution against the best one's, plus a price per parameter). Quality colour mode only; up to four traces, about 3.6 times the trace time at 512 px. Measured on the 246-icon screen set: 6 % closer to the artist's file at 128 px, 1 % at 512 px (9 % on the hardest tenth). Off by default. | -| `detect_strokes` | bool | `false` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count. Quality mode only; off by default. | +| `detect_strokes` | bool | `true` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count, and a ring on a plain page as one stroke over the page rather than two discs. Quality mode only; on by default. | | `merge_colors` | string | `""` | - | Colour groups: fills to draw as one, so the shapes between them join rather than being recoloured. Empty (the default) changes nothing. Groups are separated by ';' and members by ','; a member is a colour '#rrggbb' as it appears in a trace of the same image, or a gradient written as its stop colours joined by '>'. An optional '=' says what the group becomes: '=#rrggbb' a flat colour, '=@n' its n-th member (1-based; a gradient there is refitted over the whole group); without it, the member covering the most of the image. Example: '#c0392b,#e74c3c;#f00>#00f,#0a0=@1'. A group costs one extra trace. | diff --git a/docs/LIMITATIONS.md b/docs/LIMITATIONS.md index b57809bd..ab9e81dd 100644 --- a/docs/LIMITATIONS.md +++ b/docs/LIMITATIONS.md @@ -80,7 +80,7 @@ This document outlines Inkvec's known limitations, failure modes, performance tr ### 5.1 Restorer Deblocking (`restorer.onnx`) - **Inductive Bias:** The denoiser was trained on synthetic degradation kernels representing discrete cosine transform (DCT) artifacts, WebP compression, and VAE decode haze. - **Limitation:** It is an image-to-image convolutional regression model. When presented with intentional high-frequency patterns—such as fine halftone dots, comic-book stippling, dithering, or paper textures—it may misclassify them as compression noise and smooth them out. -- **Mitigation:** The restorer is disabled by default (`--restore off`) and must be explicitly enabled when processing damaged assets. +- **Mitigation:** The restorer runs only where it can help: by default only in Quality mode and only in a build that carries it (`--restore auto`), and then only on input that shows compression and that its own trace disagrees with; Fast and balanced keep it off unless asked, and `--restore off` always turns it off. ### 5.2 Geometric Graph Neural Network (`TraceRefineGNN20M` — Research Stage) - **Inductive Bias:** The experimental GNN post-processor predicts continuous coordinate offsets ($\Delta \mathbf{x}$) and CAD regularity constraints (parallelism, perpendicularity, tangency) based on learned geometric priors. diff --git a/docs/TODO.md b/docs/TODO.md index 607a1774..e68902d4 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -24,7 +24,7 @@ We have trained a 20M vision-conditioned Graph Neural Network (`TraceRefineGNN20 ## 2. High-Volume Benchmarking & Extended Corpus Evaluation -The continuous integration gate tests the 246-icon screen set in six conditions (Quality and Fast, 128 and 512 px) against per-platform baselines in `bench/gate/baselines/`. To further harden quality across diverse visual styles, higher-volume, large-scale benchmarks are required. +The continuous integration gate tests the 246-icon screen set in eight conditions (Quality and Fast; 128 px, 512 px, 512 px opaque, and a resized JPEG) against per-platform baselines in `bench/gate/baselines/`. To further harden quality across diverse visual styles, higher-volume, large-scale benchmarks are required. ### Implementation Tasks: - [ ] **Large-Scale Multi-Thousand Icon Benchmark Suite:** diff --git a/docs/algorithm/00-overview.md b/docs/algorithm/00-overview.md index 35bfa309..aa9217bd 100644 --- a/docs/algorithm/00-overview.md +++ b/docs/algorithm/00-overview.md @@ -5,7 +5,7 @@ **Source:** the whole tree; this page indexes it. **Entry points:** `inkvec_trace::trace_color_full_with_alpha` (`crates/inkvec-trace/src/lib.rs:299`, -called via `trace_color_full` at `lib.rs:263`) for the raster-to-planar-map half; +called via `trace_color_full` at `lib.rs:265`) for the raster-to-planar-map half; `inkvec_cli::trace_image` (`crates/inkvec-cli/src/lib.rs:198`) for the whole command, intake through SVG text. **Pipeline position:** none — this is the front door. Every numbered stage document assumes @@ -103,22 +103,22 @@ each timed by the `Stopwatch` (`crates/inkvec-trace/src/lib.rs:1228`, `mark` at | `saddles` | `crates/inkvec-trace/src/lib.rs:1102` (`merge_saddle_faces` :1091) | saddle join | resolve the one ambiguity labels cannot: four pixels meeting diagonally at one corner | | `build_map` | `crates/inkvec-trace/src/lib.rs:1106` (`planar::build` :1105) | planar map | shared edges between exactly two faces, from the exact integer label grid, read off its row runs (`planar/cracks.rs`, `planar/runs.rs`) | | `symmetry_detect` | `crates/inkvec-trace/src/lib.rs:1121` | refinement setup | since 2026-09-30 this mark times only the setup of the refinement's inputs (each face's fill model and opacity); `symmetry::detect` itself runs inside the next mark | -| `refine_subpix` | `crates/inkvec-trace/src/lib.rs:1156` (`symmetry::detect` beside `planar::measure_subpixel`, `lib.rs:1150-1154`; `Refined::apply`, `:1155`) | symmetry detect + sub-pixel | find mirror pairs on the label lattice, where the comparison is exact, and, at the same time, measure where each boundary point sits along its local normal (the 0.5-coverage level); both only read the lattice map, so they run side by side under `rayon::join`, and the measured points are written back afterwards | +| `refine_subpix` | `crates/inkvec-trace/src/lib.rs:1156` (`symmetry::detect` beside `planar::measure_subpixel`, `lib.rs:1125-1129`; `Refined::apply`, `:1155`) | symmetry detect + sub-pixel | find mirror pairs on the label lattice, where the comparison is exact, and, at the same time, measure where each boundary point sits along its local normal (the 0.5-coverage level); both only read the lattice map, so they run side by side under `rayon::join`, and the measured points are written back afterwards | | `refine_junc` | `crates/inkvec-trace/src/lib.rs:1159` (`planar::refine_junctions` :1158) | junctions | settle shared endpoints | | `boundary_opt` | `crates/inkvec-trace/src/lib.rs:1167` (`boundary_opt::optimise_for` :1166) | boundary solve | move every boundary point at once so the *rendered* partition matches the image; not run when its band tables would pass a memory budget (`boundary_opt/band.rs`) | | `decode` | `crates/inkvec-trace/src/lib.rs:1189` (`decode::decode_faces` :1178) | decode | order-first colour/geometry fix for faces too thin to own a fully-covered pixel; off unless `INKVEC_DECODE` (*research build*) is set | | `symmetry` | `crates/inkvec-trace/src/lib.rs:1199` (`symmetry::enforce` :1197) | symmetry enforce | put back the exactness every upstream tie-break quietly broke | | — | `crates/inkvec-cli/src/pipeline.rs:255` (`trace_total`) | — | end of the `inkvec_trace` half | -| — | `crates/inkvec-cli/src/pipeline.rs:495` (`fit_dp`) | curve fit | one global DP per boundary over lines, cubics and arcs, MDL cost; a whole-boundary primitive is offered beside it and taken when it costs less (`inkvec_fit::choice`) | -| — | `crates/inkvec-cli/src/pipeline.rs:504` (`repair`) | repair | close self-crossing rings the independent per-edge fits can produce | +| — | `crates/inkvec-cli/src/pipeline.rs:494` (`fit_dp`) | curve fit | one global DP per boundary over lines, cubics and arcs, MDL cost; a whole-boundary primitive is offered beside it and taken when it costs less (`inkvec_fit::choice`) | +| — | `crates/inkvec-cli/src/pipeline.rs:503` (`repair`) | repair | close self-crossing rings the independent per-edge fits can produce | | — | `crates/inkvec-cli/src/pipeline.rs:396` (`fills`) | fills | per-face fill model already chosen upstream; a gradient whose every stop lies within a just-noticeable difference of every other is painted flat (`pipeline/demote.rs`) | -| — | `crates/inkvec-cli/src/pipeline.rs:446` (`emit`) | emit | fitted geometry to SVG text, each ring wound by nesting depth so no `fill-rule` is needed; layers vs. flat form costed against each other | +| — | `crates/inkvec-cli/src/pipeline.rs:445` (`emit`) | emit | fitted geometry to SVG text, each ring wound by nesting depth so no `fill-rule` is needed; layers vs. flat form costed against each other | | — | `crates/inkvec-cli/src/post.rs` | post | viewBox retarget, background knock-out, margin, minify | Fast mode (`--mode fast`) takes another route through the same table. Its front end (`crates/inkvec-trace/src/fast/front.rs`) replaces the marks from `palette` to `split` with its own `palette`, `slivers`, `despeckle`, `split` and `ramps`; it shares `build_map`, -`refine_subpix`, `refine_junc` and `symmetry`, and skips `decode` (`lib.rs:1177`) and +`refine_subpix`, `refine_junc` and `symmetry`, and skips `decode` (`lib.rs:1152`) and `boundary_opt`, which runs in Fast only when `--mode balanced` caps it by iterations (`boundary_opt.rs:605`). Under `fit_dp` it runs a Potrace-class fitter instead of the DP, and it skips `repair` and shape harmonization (`repair_fits` and `emit_options` in @@ -164,7 +164,7 @@ edge to move. `Edge.sigma` is the per-point positional uncertainty from the coverage inversion, carried all the way to the curve fitter; `Edge.left` / `Edge.right` are face ids, `u16::MAX` when an edge has been merged into the interior of a layer and no longer belongs to any ring -(`merge_map`, `crates/inkvec-cli/src/pipeline.rs:1111-1126`). +(`merge_map`, `crates/inkvec-cli/src/pipeline.rs:1110-1125`). ## Reading order @@ -173,7 +173,8 @@ the SR pre-pass, resolution-invariant tolerances, alpha matting. Stages 02 onwar per the pipeline table above) go module by module through `inkvec-trace` and `inkvec-fit`. `14-fast-mode.md` then covers Fast mode: which of those stages it replaces, which it shares, and how each of its own stages works. `15-strokes.md` covers the optional stroke stage -(`--detect-strokes`, off by default), which writes faces drawn as strokes as stroked paths. +(on by default in Quality mode, `--no-detect-strokes` to switch it off), which writes faces +drawn as strokes as stroked paths. `constants.md` collects every named constant across the tree in one table. ## `docs/DESIGN.md` against the code as it stands @@ -217,7 +218,7 @@ disagreements are where the real design lives: descriptions costs less under the shared MDL cost (`choice::choose`, `crates/inkvec-fit/src/choice.rs:211-226`). That is model *selection between* two fits, not primitives as states inside one DP. `choice::describe` (called per boundary from - `fit_boundaries`, `crates/inkvec-cli/src/pipeline.rs:720`) also orders the work: for + `fit_boundaries`, `crates/inkvec-cli/src/pipeline.rs:719`) also orders the work: for the image frame it tries the rectangle first and skips the dynamic program when the rectangle is below a lower bound on any fitted path (`choice::cost_floor`); for every other boundary it runs the program and the primitive search side by side under @@ -230,7 +231,7 @@ disagreements are where the real design lives: * **S5, structured refinement with topology not frozen.** DESIGN.md §S5 explicitly reverses an earlier decision to freeze topology during polish, arguing for a structured move set searched to convergence. The code has gone the other way again: `repair_fits` - (`crates/inkvec-cli/src/pipeline.rs:852-920`) records that both `polish` (per-cubic control-point refinement against the coverage + (`crates/inkvec-cli/src/pipeline.rs:851-919`) records that both `polish` (per-cubic control-point refinement against the coverage field) and the "adjudication" re-scoring stage were *removed*, with a measured result — "removing them takes the objective from 0.5477 to 0.4960 and dE00 from 0.2503 to 0.2146... Polish alone made 197 of 246 better by not running." The stated reason is that @@ -244,7 +245,7 @@ disagreements are where the real design lives: geometry moves: it runs beside the sub-pixel refinement's measuring phase, which writes nothing to the map until detection has returned), and enforces it twice more downstream — once on the map (`symmetry::enforce`, `trace/lib.rs:1197`) and once on the fitted curves, by reflecting one boundary's fit onto - its mirror rather than re-solving both (`apply_mirrors`, `crates/inkvec-cli/src/pipeline.rs:947`). That is "detect once, + its mirror rather than re-solving both (`apply_mirrors`, `crates/inkvec-cli/src/pipeline.rs:946`). That is "detect once, then copy," which is cheaper and exact by construction, but it is a different design from "enforced as a constraint during re-optimisation." * **§0 governing directive ("best algorithm at every stage, even substantially slower").** @@ -272,6 +273,6 @@ disagreements are where the real design lives: `crates/inkvec-fit/examples/primitives_demo.rs`, `crates/inkvec-fit/tests/multimodel.rs`, `crates/inkvec-fit/tests/primitives.rs` — that exercise the line-then-cubic fit directly. The CLI pipeline instead calls `multimodel::optimal_multimodel` - (`crates/inkvec-cli/src/pipeline.rs:729`, and `optimal_multimodel_without_structural` at + (`crates/inkvec-cli/src/pipeline.rs:728`, and `optimal_multimodel_without_structural` at `:766` for the research baseline) directly. `fit_path` exists for examples and tests, not as part of the shipped trace. diff --git a/docs/algorithm/01-intake.md b/docs/algorithm/01-intake.md index be83d06d..8853c2f5 100644 --- a/docs/algorithm/01-intake.md +++ b/docs/algorithm/01-intake.md @@ -78,7 +78,7 @@ slice (`decode_image` / `decode_image_capped`, `load.rs:104-108`, `:475-488`), o pixels (`rgba8_capped`, `load.rs:490-519`, which has no format, profile or orientation to read and only applies the cap). The decoders compiled in are PNG, JPEG, WebP, GIF, BMP and TIFF (`crates/inkvec-trace/Cargo.toml:18`); the command line's usage line names the same six -(`crates/inkvec-cli/src/args.rs:333`). Every decoded image funnels through `from_dynamic` (`load.rs:298-342`), which produces straight +(`crates/inkvec-cli/src/args.rs:334`). Every decoded image funnels through `from_dynamic` (`load.rs:298-342`), which produces straight (unpremultiplied) floats in `[0, 1]`, alpha 1 where the image has none — the same `Rgba` type stage 02 consumes. How it gets there depends on the layout the decoder handed over: @@ -315,7 +315,7 @@ file. An unreadable or unrecognised container resolves to `Off` — "not known t because, as the doc comment states, the guard this feeds costs **10.9%** on the 246-icon screen set when it runs on a clean intake (0.4005 → 0.4442, measured 2026-09-08) and must not fire on a guess (`lib.rs:871-876`). `--lossy` defaults to `Auto` -(`crates/inkvec-cli/src/args.rs:274`), so container-format detection runs on every trace +(`crates/inkvec-cli/src/args.rs:275`), so container-format detection runs on every trace unless a user overrides it; `On` is there for a file that no longer admits what was done to it — "a PNG that was once a JPEG -- a re-saved screenshot, an export from a chat app" (`args.rs:150-155`). @@ -436,7 +436,7 @@ the output was rounded on its own, the two pitches can differ slightly (448 × 1 whenever the viewBox and the presented size differ in aspect, where the default `xMidYMid meet` would letterbox the drawing by up to half a source pixel (SVG 1.1 section 7.8: `none`, "Do not force uniform scaling"). `--max-dim` is not stretched; its box filter is free -to choose its size. `--no-unblock` disables the pass (`crates/inkvec-cli/src/args.rs:397-404`). +to choose its size. `--no-unblock` disables the pass (`crates/inkvec-cli/src/args.rs:398-405`). Detection is exact-match only: an upscale that was anti-aliased, resampled or JPEG-compressed has no constant cells and fails by design; a resampled or blurred one is the soft intake's (next), damage is the restorer's and `--sr`'s. @@ -444,7 +444,7 @@ has no constant cells and fails by design; a resampled or blurred one is the sof ### Soft intake — reducing a resampled or blurred raster to its detail `soft_intake::reduce` (`crates/inkvec-cli/src/soft_intake.rs:217-271`) runs next, in Quality -mode, unless `--no-soft-intake` (`args.rs:405-412`) or `--intake-scale` is given, the +mode, unless `--no-soft-intake` (`args.rs:406-413`) or `--intake-scale` is given, the raster was unblocked, or `--sr` is on, which wants the soft raster to put detail back into (`reduce_intake`, `crates/inkvec-cli/src/lib.rs:254-282`). A raster upscaled from a smaller one, or blurred, spreads every edge over several pixels, and the tracer meets the wide ramp three @@ -556,7 +556,7 @@ upscaler wants the soft raster to put detail back into. ### The SR pre-pass itself: `Mode::Auto | On | Off` -`--sr` (default `Off`, `crates/inkvec-cli/src/args.rs:275`) controls a network-based +`--sr` (default `Off`, `crates/inkvec-cli/src/args.rs:276`) controls a network-based upscale-then-halve cleanup, implemented in the `inkvec-sr` crate. `inkvec_sr::Mode` (`crates/inkvec-sr/src/lib.rs:35-45`): @@ -576,7 +576,7 @@ pub enum Mode { zeroes the colour channels of every fully transparent pixel (alpha `<= 1e-4`, so they cannot drag their upscaled neighbours toward an arbitrary stored colour), upscales by the upscaler's factor, box-averages back down (`clean::box_downsample`) to the requested -`--sr-scale` (default 2, `args.rs:277`), and — unless `--sr-no-recolour` — refits each colour +`--sr-scale` (default 2, `args.rs:278`), and — unless `--sr-no-recolour` — refits each colour channel of the result onto a bicubic upsample of the zeroed source over its flat pixels (`clean::match_flats`) rather than trusting the network's colour reconstruction. The upscaler always runs out of process: the network is not compiled in @@ -589,7 +589,14 @@ above it, then the source checkout the binary was built from. The pass prints on (`lib.rs:667`). **The restorer comes first.** `trace_prepared_priced` runs the restorer pre-pass -(`--restore`, off by default, `args.rs:280`; `restore_prepass`, `lib.rs:984-1069`) before SR. +(`--restore`; `restore_prepass`, `lib.rs:984-1069`) before SR. Its default is the mode's +(`Args::restore_mode`, 2026-10-11): `auto` in Quality mode when the build can restore (the +network compiled in, or `--restore-command`), `off` in Fast and balanced, where a restore's +seconds would undo the point of the mode, and `off` in a build with nothing to restore with, +which then traces exactly as `--restore off` does, stats included. A given `--restore` value +always wins. On a clean input `auto` asks for a sign of compression first and makes no probe +without one (below), so the default costs a clean PNG the ringing score alone, about 2.7 ms +at 512 px. Its `auto` mode works exactly like SR's — one probe trace, kept when the input measures clean, and "handed on so the two pre-passes never trace the same image twice" (`lib.rs:984-985`); with SR off, a kept probe is returned as the trace (`lib.rs:556-572`), and @@ -599,7 +606,7 @@ itself is outside this page. `Mode::Auto` (`crates/inkvec-cli/src/lib.rs:588-653`) is the more interesting path: it takes the restorer's probe when there is one, and otherwise traces the image once as it arrived (`trace_once`, `lib.rs:1107-1136`), a stripped version of the ordinary pipeline — the same -`fit_config`, bilevel or colour, matte included (through the copying `alpha_source`), and +`fit_config`, bilevel or colour, matte and border pad included (through `trace_bordered`, the plain path's own, since 2026-10-10, so a kept probe is byte for byte the plain trace), and always in colour, because "a monochrome drawing disagrees with a colour input everywhere it is not black or white, which would read as damage on every image"; under `--monochrome` the probe decides and the trace is then made again as asked (`lib.rs:551-555`). It renders that @@ -637,6 +644,33 @@ trace, in colour and in monochrome, and that `on` still errors. The fallback cov upscaler that cannot be built; a packaged tool that is found but fails while running still fails the trace, under `auto` as under `on` (`prepass(...)?`, `crates/inkvec-cli/src/lib.rs:665`). +**`auto` also needs a sign of damage of the input's own** (`crates/inkvec-cli/src/damage.rs`, +2026-10-10). The residual reads smooth shading in clean, gradient-heavy art as damage: with +`--restore auto` on the gate's opaque 512 px tier (PNG renders), the restorer ran on 7 of 246 +clean icons, all Noto emoji with shading, and the condition read dE00 +4.49 % and geom +13.9 % +(`emoji_u1f5a8` geom 0.19 → 3.05). So a `Restore` decision stands only when the file or the +pixels say the input was compressed (`damage::compressed`): a lossy container (`--lossy`, +resolved from the file's first bytes), or JPEG ringing around the edges +(`coverage::ringing_score` above the gate the palette's noise guard uses, `SOFT_RINGING_LARGE` +from 256 px on, `SOFT_RINGING` below), which is how a JPEG re-saved as PNG is told. SR's `Clean` +also accepts edges wider than a native render's (`damage::soft`: `intake_scale` above +`SOFT_INTAKE_EDGE`), since the upscaler undoes resampling too. These are the three signals that +open the palette's soft intake, and the corpus's clean renders pass none of them. Without one, +`auto` keeps its probe and says so ("restore no sign of compression; traced directly"; SR: "no +sign of resampling or compression"). The evidence is asked first and the residual only after +it: the residual renders the probe at full size, the costly half. Asked the other way round, +`auto` cost a clean Fast trace at 512 px 16.5 ms of CPU on 31 (the render and the residual) +and the ringing 5.5 ms more where the residual fired; both are needed, so the order changes no +decision. Without evidence `--restore auto` makes no probe at all, and the input takes the +plain path, so its trace is the plain one by construction and a clean input pays the evidence +alone. In Fast mode the evidence is the container only: its trace of a 512 px icon costs about +31 ms of CPU and the ringing score 2.5 ms of it, which every clean PNG would pay; what Fast +gives up is a JPEG re-saved as PNG (on the `web` tier's own pixels the score passes the gate on +186 of 246 icons, on the clean tiers on none). On the `web` tier (JPEG files) every input has a +lossy container and `auto` decides exactly as before. Tests: +`restore_auto_needs_a_sign_of_compression`, `sr_auto_needs_a_sign_of_resampling_or_compression` +(`crates/inkvec-cli/tests/pipeline.rs`). + `interior_residual` (`inkvec-sr/src/detect.rs:97-155`) is the signal: both images are composited onto white, a mask marks pixels where the *traced model* is flat (using the composited colour, not the straight-alpha one, because straight-alpha channels are constant @@ -660,7 +694,7 @@ mistake — three times worse than doing nothing, dE00 0.605 against 0.195, per doc (`detect.rs:3-7`). `DEGRADED_RESIDUAL = 0.5` (`detect.rs:35-36`, also the default for `--sr-threshold`, -`crates/inkvec-cli/src/args.rs:276`) is calibrated over 30 icons in five conditions +`crates/inkvec-cli/src/args.rs:277`) is calibrated over 30 icons in five conditions (`detect.rs:13-25`): | condition | min | median | p95 | max | @@ -709,15 +743,15 @@ on both sides is returned untouched (`lib.rs:148-152`). `INTAKE_SCALE_FLOOR = 1. (`lib.rs:121-123`) — below this the intake is left alone; "Every image in the corpus reads exactly 1.00" per the constant's own comment. `INTAKE_SCALE_CAP = 8.0` (`lib.rs:124-126`) bounds how much a single, possibly wrong, estimate is allowed to throw away at once. -`--intake-scale` defaults off (`args.rs:286`); the usage text states the trade explicitly -(`args.rs:553-566`): on 8×-upsampled input at 1024 px it is 24× faster with a twelfth of the +`--intake-scale` defaults off (`args.rs:287`); the usage text states the trade explicitly +(`args.rs:556-569`): on 8×-upsampled input at 1024 px it is 24× faster with a twelfth of the parameters and half the colour error, but **DINO** — the corpus's structural-similarity measure — falls from 0.954 to 0.916, so it is offered for input too slow to trace at all, not to make an already-tractable trace faster. ### `--max-dim` and `--time-budget` -`--max-dim` (default `2048`, `args.rs:358`) is a hard ceiling on the size that is traced, +`--max-dim` (default `2048`, `args.rs:359`) is a hard ceiling on the size that is traced, applied in two places. The command line hands it to the decoder (`run`, `crates/inkvec-cli/src/lib.rs:856`), which box-averages the 8-bit buffer down before the floats exist (pass 5 above, with the larger allocation allowance of pass 3); and `intake` @@ -727,9 +761,9 @@ bindings): each side divided and rounded, at least 8 px, by "the same exact area intake normaliser uses, so edges stay edges". Either way the SVG is written at the original size (`trace_image_sized`'s `display_size`, `lib.rs:205-211`). The stated reason is trace time, which grows with pixel count; 2048 is chosen because it "keeps a typical logo under a -few seconds" (`args.rs:358-362`), a qualitative target rather than a swept figure. +few seconds" (`args.rs:359-363`), a qualitative target rather than a swept figure. -`--time-budget` (default `0.0`, meaning no budget, `args.rs:254`) is advisory rather than a +`--time-budget` (default `0.0`, meaning no budget, `args.rs:255`) is advisory rather than a hard deadline. It is spent in `color_options` (`crates/inkvec-cli/src/pipeline.rs:145-153`), which the colour pipeline calls as it starts (`pipeline.rs:229`), so the clock runs from there and each probe trace gets a clock of its own: 60% of the budget becomes @@ -737,7 +771,7 @@ there and each probe trace gets a clock of its own: 60% of the budget becomes grows with the square of the region count — "an unmerged band is a correct fill, just a separate one", `crates/inkvec-trace/src/lib.rs:166-169`); 25%, and at least 50 ms, becomes `boundary_ms`, the boundary solve's wall-clock budget (`crates/inkvec-trace/src/lib.rs:178-181`). -The help text states the contract (`crates/inkvec-cli/src/args.rs:363-370`): "Gradient-band +The help text states the contract (`crates/inkvec-cli/src/args.rs:364-371`): "Gradient-band merging stops at 60% of it, checked between fits, and the boundary solve gets 25%; the output is still a correct trace, with more fills or a less polished outline. The palette and the writer do not read it. A nonzero budget makes the output depend on the machine; 0 means @@ -880,9 +914,9 @@ hands to `run_strokes`, `run_bilevel` and `run_color` through `fit_config` No test checks that identity, or that the flag now scales lambda; see Open questions. -`content_units` defaults to `false` (`crates/inkvec-cli/src/args.rs:252`); the +`content_units` defaults to `false` (`crates/inkvec-cli/src/args.rs:253`); the `INKVEC_CONTENT_SCALE` environment equivalent was removed in 0.1.7 (CHANGELOG, *Removed*). -The help text keeps it off as a trade, "it trades fidelity for parsimony" (`args.rs:437-440`). +The help text keeps it off as a trade, "it trades fidelity for parsimony" (`args.rs:438-441`). It used to name two failures as the price (5-px squares fitted as circles, thin rings broken); `content_scale`'s own doc comment traces those to the old `extent / REF_EXTENT` scale — "that over-correction, described but never traced to its cause" (`units.rs:41-50`) — so the help no @@ -925,7 +959,7 @@ let up = if edge > inkvec_trace::color::SOFT_INTAKE_EDGE { * min-area `× r²` when the longest side exceeds `R`, else unchanged; * lambda `× r` when the longest side exceeds `R` and `r > 1`, else unchanged — through `args.lambda_scale`, which `fit_boundaries` multiplies into every boundary's lambda - (`crates/inkvec-cli/src/pipeline.rs:685-689`) and the ring repair prices with + (`crates/inkvec-cli/src/pipeline.rs:684-688`) and the ring repair prices with (`pipeline.rs:895`). The round trip is not 1 on every native render: it reads 1 for 212 of the 246 screen icons @@ -1153,8 +1187,9 @@ on a transparent ground read 1.00 and no icon of the screen set reads above 0.32 removed in 0.1.7 (CHANGELOG, *Removed*). **Applying the matte: once, in place, in parallel.** The intake calls `alpha_source_owned` -(`alpha.rs:599-625`) rather than the copying `alpha_source` (`alpha.rs:561-597`), which only -the probe trace of `--sr auto` / `--restore auto` still uses (`crates/inkvec-cli/src/lib.rs:1128`). +(`alpha.rs:599-625`) rather than the copying `alpha_source` (`alpha.rs:561-597`), which is +now compiled for the tests only, as the oracle of the in-place version; the probe trace of +`--sr auto` / `--restore auto` goes through the plain path since 2026-10-10. The steps: 1. **Any transparency at all?** `has_transparency` (`crates/inkvec-cli/src/alpha.rs:832-853`) @@ -1214,7 +1249,7 @@ because a false layer is a visible error: it unions faces that are not one shape them a colour that appears nowhere in the source. This is exposed as `--layers` (default off; `INKVEC_LAYERS` is *removed*), and the CLI's help records it firing on "about one real icon in twenty" of the census used to tune it — two of forty -(`crates/inkvec-cli/src/args.rs:383-391`, `crates/inkvec-cli/src/alpha/layers.rs:49-54`). The CLI +(`crates/inkvec-cli/src/args.rs:384-392`, `crates/inkvec-cli/src/alpha/layers.rs:49-54`). The CLI side, `recover_layers` (`layers.rs:100`, split out of the CLI's `alpha.rs` on 2026-10-02), holds the decomposition to three rules, each closing a way the layered document used to draw something other than the image (`layers.rs:62-99`): @@ -1233,7 +1268,7 @@ something other than the image (`layers.rs:62-99`): The emitter then paints the recovered layers back to front: the decomposition peels the frontmost layer first, and painting in peel order put the front layer underneath (`synthetic/stack_overlap`, dE00 0.019 -> 2.90 with `--layers`; `write_layers`, -`crates/inkvec-cli/src/emit.rs:1307-1324`; see `13-emit.md`). Citations, as the code gives +`crates/inkvec-cli/src/emit.rs:1318-1335`; see `13-emit.md`). Citations, as the code gives them: "Method from" Porter & Duff 1984 (doi:10.1145/800031.808606) and SVG 1.1 §11.7.1; the three rules "Not from the literature"; "See also" Richardt et al., EGSR 2014 (doi:10.1111/cgf.12408). @@ -1245,8 +1280,8 @@ three rules "Not from the literature"; "See also" Richardt et al., EGSR 2014 | `REF_EXTENT` | `128.0` px | the intake size every pixel-denominated tracer constant was tuned at; above it `price_in_raster_units` scales `--min-area` and lambda | measured: 3.54×/6.02×/11.62× the artist's parameter count at 128/256/512 px for unchanged content (`crates/inkvec-cli/src/units.rs:17-31`); the guard measured: without it 128ss objective 0.4005 → 0.4112 (`crates/inkvec-cli/src/lib.rs:470-477`) | | `INTAKE_SCALE_FLOOR` | `1.5` | below this, `--intake-scale` leaves the input alone | "Every image in the corpus reads exactly 1.00" (`lib.rs:121-123`) | | `INTAKE_SCALE_CAP` | `8.0` | ceiling on how much `--intake-scale` will discard from one estimate | "A wrong estimate should cost detail slowly, not all at once" (`lib.rs:124-126`) | -| `--max-dim` default | `2048` px | ceiling on traced (not emitted) size | qualitative: "keeps a typical logo under a few seconds" (`crates/inkvec-cli/src/args.rs:253, 358-362`); no sweep cited | -| `--time-budget` split | `0.6` merge / `0.25` boundary-solve | how an advisory wall-clock budget is allotted between the two stages that read a clock | stated as a fixed split, no numeric derivation given (`args.rs:363-370`, `crates/inkvec-cli/src/pipeline.rs:145-153`) | +| `--max-dim` default | `2048` px | ceiling on traced (not emitted) size | qualitative: "keeps a typical logo under a few seconds" (`crates/inkvec-cli/src/args.rs:254, 358-362`); no sweep cited | +| `--time-budget` split | `0.6` merge / `0.25` boundary-solve | how an advisory wall-clock budget is allotted between the two stages that read a clock | stated as a fixed split, no numeric derivation given (`args.rs:364-371`, `crates/inkvec-cli/src/pipeline.rs:145-153`) | | boundary-solve budget floor | `50` ms | least wall-clock budget the boundary solve gets under any `--time-budget` | none (`pipeline.rs:152`) | | `MIN_SOURCE` (`pixel_grid`) | `16` px | least source size the unblock keeps on the short axis | measured motive: the old 64 px floor on both sides undid five 4× wordmarks only 2× (dE00 1.971 against 1.400, params 928 against 327) (`crates/inkvec-cli/src/alpha/unblock.rs:102-110`); the value itself not swept | | `MIN_SOURCE_LONG` (`pixel_grid`) | `64` px | least source size on the long axis; a smaller source comes back as the coarsest finer lattice that keeps it | the old floor, for the old reason: "a 2x undo of a small icon leaves too few pixels for the boundary solve to work with" (`unblock.rs:112-118`); not swept | @@ -1279,7 +1314,7 @@ three rules "Not from the literature"; "See also" Richardt et al., EGSR 2014 | `SOFT_SHARE` | `0.05` | share of drawn+soft pixels that must be "glow" before white is kept outright without running the candidate ladder | no stated numeric derivation (`alpha.rs:439`) | | `FLAT_ALPHA` | `0.02` | spread in a pixel's neighbour alphas below which its translucency counts as "flat" rather than a glow | no stated numeric derivation (`alpha.rs:440`) | | `DEGRADED_RESIDUAL` / `--sr-threshold` default | `0.5` | interior-residual threshold above which `--sr auto` cleans | measured over 30 icons, five conditions: sits above the worst clean reading (`0.376`) and below the weakest damaged one (`0.454`, jpeg-q80); "4.2% of damaged ones are missed" at this value (`crates/inkvec-sr/src/detect.rs:13-36`) | -| `--sr-scale` default | `2` | output scale of the pre-pass relative to the input | not derived in what was read; stated as the default only (`crates/inkvec-cli/src/args.rs:277`) | +| `--sr-scale` default | `2` | output scale of the pre-pass relative to the input | not derived in what was read; stated as the default only (`crates/inkvec-cli/src/args.rs:278`) | | interior-residual normalisation | `sum / 9n`, not `sum / 3n` | scales every residual reading (and therefore `DEGRADED_RESIDUAL`) to `1/sqrt(3)` of a true RMS | deliberate, matched to the reference Python implementation; explicitly "not a bug to fix" (`inkvec-sr/src/detect.rs:103-110`) | | `SOFT_INTAKE_EDGE` | `1.75` px | gates whether the round trip scales `--precision` | fully documented in `03-palette.md`; reused here unmodified (`crates/inkvec-trace/src/color.rs:479-488`) | | `OVERSAMPLE_TOL` | `3.0` | absolute round-trip error tolerance inside `oversample_factor` | fully documented in `02-coverage.md`; reused here unmodified (`crates/inkvec-trace/src/coverage/oversample.rs:10-24`) | @@ -1345,13 +1380,13 @@ three rules "Not from the literature"; "See also" Richardt et al., EGSR 2014 box-averaged by the cap's factor; its cells are then no longer constant and the upscale is not undone. Read from the code; no case was measured. - **`--content-units` is offered as a trade, not a free fix**: its help text says "it trades - fidelity for parsimony" (`crates/inkvec-cli/src/args.rs:437-440`). The two failures it used + fidelity for parsimony" (`crates/inkvec-cli/src/args.rs:438-441`). The two failures it used to name (5-px squares fitted as circles, thin rings broken) are ones `content_scale`'s doc comment attributes to the scale it replaced (`crates/inkvec-cli/src/units.rs:41-50`). - **`--intake-scale` costs structural accuracy for speed**, and says so in its own help text: 24× faster with a twelfth of the parameters and half the colour error on 8×-upsampled input at 1024 px, but DINO — the corpus's structural measure — falls from 0.954 to 0.916 - (`crates/inkvec-cli/src/args.rs:560-564`). + (`crates/inkvec-cli/src/args.rs:563-567`). - **The SR pre-pass is three times worse than doing nothing on clean input** (dE00 0.605 against 0.195, `crates/inkvec-sr/src/detect.rs:3-7`), which is why `Mode::Auto` pays for a full probe trace before deciding, rather than guessing from pixel statistics. @@ -1360,7 +1395,7 @@ three rules "Not from the literature"; "See also" Richardt et al., EGSR 2014 (`crates/inkvec-cli/src/lib.rs:617-626`). A packaged tool that is found but fails while running still fails the trace in either mode (`lib.rs:665`). - **With a `--time-budget`, the output depends on the machine**, and the palette and the - writer read no budget at all (`crates/inkvec-cli/src/args.rs:363-370`); without one, the + writer read no budget at all (`crates/inkvec-cli/src/args.rs:364-371`); without one, the merge and the boundary solve are bounded only by their work and memory caps, which apply either way, and the output is reproducible. - **A soft glow is deliberately excluded from voting on the matte**, and the cost of getting @@ -1387,11 +1422,11 @@ Since the settings cleanup (CHANGELOG, 0.2.0, *Changed*) the engine reads its en | `INKVEC_MATTE` (*removed*) | forced `choose_matte`'s answer, bypassing the swallowed-mass search | unset (`choose_matte` decides) | removed in 0.1.7 (CHANGELOG, *Removed*) | | `INKVEC_LAYERS` (*removed*) | forced `--layers` on | unset (off, same as `--layers` unset) | removed; `--layers` only | | `INKVEC_LAYER_SIGMA` (*removed*) | overrode the sRGB noise sigma used when fitting a translucent layer | `LAYER_SIGMA_SRGB` (`crates/inkvec-cli/src/alpha/layers.rs:14-22`) | removed | -| `INKVEC_NATIVE_ALPHA=0` | turns native alpha off, as `--no-native-alpha` does: the image is matted first | unset (native alpha on) | `crates/inkvec-cli/src/args.rs:263` | +| `INKVEC_NATIVE_ALPHA=0` | turns native alpha off, as `--no-native-alpha` does: the image is matted first | unset (native alpha on) | `crates/inkvec-cli/src/args.rs:264` | | `INKVEC_TOOLS_DIR=` | the folder holding the packaged SR pre-pass (`inkvec_sr`); when set, the only folder looked in | unset (`tools/` beside the binary or up to three folders above it, then the source checkout) | `crates/inkvec-cli/src/lib.rs:912-922` | | `INKVEC_PYTHON=` | the interpreter the packaged SR pre-pass runs with | unset (`python` on Windows, `python3` elsewhere) | `crates/inkvec-sr/src/external.rs:59-68` | | `INKVEC_DIAG=1\|json` | structured diagnostic lines on stderr; the intake's are the ICC outcome (`load/icc.rs`) and the soft-intake gate (edge width, ringing, lossy flag) | unset (silent) | `crates/inkvec-trace/src/diag.rs:47-60`; intake lines at `crates/inkvec-trace/src/load/icc.rs:79-147`, `crates/inkvec-trace/src/lib.rs:383-389` | -| `INKVEC_ALPHADBG` | prints per-face alpha diagnostics and the emitter's face dump to stderr | unset (silent) | `crates/inkvec-cli/src/alpha.rs:1030`, `crates/inkvec-cli/src/emit.rs:625-628` | +| `INKVEC_ALPHADBG` | prints per-face alpha diagnostics and the emitter's face dump to stderr | unset (silent) | `crates/inkvec-cli/src/alpha.rs:1030`, `crates/inkvec-cli/src/emit.rs:636-639` | No `INKVEC_*` variable is read in `inkvec-trace/src/load.rs` or `inkvec-trace/src/load/icc.rs`: sniffing, the zero-side check, the decode limits, the ICC conversion, the orientation, @@ -1413,7 +1448,7 @@ those reads happen in the loader. `--content-units` now scales lambda in the emitted trace or that the default path is unchanged by building through `fit_config`. - **`--content-units`' trade is unmeasured since the scale changed.** The help text used to - warn of "5-px squares fitted as circles, thin rings broken" (`args.rs:437-440`), while + warn of "5-px squares fitted as circles, thin rings broken" (`args.rs:438-441`), while `content_scale`'s doc comment says those failures were the over-correction of the old `extent / REF_EXTENT` scale (`units.rs:41-50`); the help now says only that the flag "trades fidelity for parsimony". No measurement of the measured scale against those cases, diff --git a/docs/algorithm/02-coverage.md b/docs/algorithm/02-coverage.md index 4b535321..0e8f1f74 100644 --- a/docs/algorithm/02-coverage.md +++ b/docs/algorithm/02-coverage.md @@ -16,8 +16,8 @@ takes the noise estimate (`estimate_noise`, `inkvec-trace/src/lib.rs:325`), the (`intake_scale`, `inkvec-trace/src/lib.rs:358`) and the ringing score (`ringing_score`, `inkvec-trace/src/lib.rs:363`) and feeds them into palette extraction (stage 03); the native-alpha path makes the same three measurements (`native.rs:828-833`). Later, `planar::refine_subpixel` -(`planar.rs:445`) computes each boundary point's uncertainty in `vertex_sigma` -(`planar.rs:1198-1256`), which re-derives the coverage-gradient formula this module documents +(`planar.rs:438`) computes each boundary point's uncertainty in `vertex_sigma` +(`planar.rs:1159-1217`), which re-derives the coverage-gradient formula this module documents rather than sharing a `CoverageField` object. Fast mode measures none of the three: its front end hands the shared stages `NOISE_FLOOR` as the noise (`fast/front.rs:152-163`). `inkvec-cli`'s intake reads `intake_scale` and `oversample_factor` to price its options in the raster's own units @@ -577,7 +577,7 @@ opened (`inkvec-trace/src/lib.rs:396-401`), and `INKVEC_NOISE_SIGMAS` (*removed* than swept constants. - **The colour path never constructs a `CoverageField`, and its sigma is a separate copy.** It calls `estimate_noise` (`inkvec-trace/src/lib.rs:325`) and `intake_scale` - (`inkvec-trace/src/lib.rs:358`) itself, and `vertex_sigma` (`planar.rs:1198-1256`) re-derives the + (`inkvec-trace/src/lib.rs:358`) itself, and `vertex_sigma` (`planar.rs:1159-1217`) re-derives the `sigma_noise / contrast / |grad a|` formula and adds `DEFAULT_SIGMA_MODEL` in quadrature by hand rather than calling `CoverageField::position_sigma`. The two already differ in detail: `vertex_sigma` reads the coverage change across one pixel along the boundary normal on the diff --git a/docs/algorithm/03-palette.md b/docs/algorithm/03-palette.md index d0658d12..65dee56c 100644 --- a/docs/algorithm/03-palette.md +++ b/docs/algorithm/03-palette.md @@ -689,3 +689,44 @@ Since the settings cleanup (CHANGELOG, 0.2.0, *Changed*) the engine reads its en and on two of the 12 dots the gradient stage explains them with a radial gradient ending in the rim colour (`#bc934e`). The input really is brighter there; whether a flat dot would be the better description is a question for the fill fit, not the palette. +- **Real inks inside the soft floor (measured, not shipped).** On a soft intake + `SOFT_SAME_INK_DE00` folds every candidate within 5 dE00 of an accepted ink, and so folds real + neighbouring inks too: on `synthetic/mosaic_grid6` (`web` tier) eleven of 37 fills lie 3.2-4.9 + dE00 from a neighbour. A rule that held such a candidate to the clean floor (`SAME_INK_DE00`) + when its claim has an interior (>= 64 pixels whose 5x5 window is all claimed), it is >= 12 + levels from the ink it would join (beyond the codec's p99 error two pixels from an edge), and + its claim's border steps by >= half that distance (edge-bounded, not a gradient band) was + measured on `quality-web` (246 icons, against the recorded baseline, 2026-10-10): + + | version | dE00 | geom | ratio | turning | + |---|---|---|---|---| + | interior only | −6.01 % | −15.42 % | +17.63 % | +6.43 % | + | interior and step | −6.16 % | −16.66 % | +15.18 % | +1.44 % | + | interior, step and border (42 changed icons rescored) | −6.93 % | −16.82 % | +0.21 % | +1.18 % | + + The mosaic gets its fills back (dE00 0.787 → 0.524, geom 2.47 → 1.04, ratio 2.05 → 2.35), but + noto-emoji's shading inks come back as faces too (27 icons: family dE00 −0.045, geom −0.12, + ratio +0.07), and parameters and turning may not rise at all, so it is not shipped. The rule, + its tests and its constants are kept on the branch `quality-soft-support-measured`. + + Judged by the gate's distances from the artist's file (`turning_gap`, `ratio_gap`) the last + version reads dE00 −6.93 %, geom −16.82 %, `ratio_gap` +0.02 % and `turning_gap` +2.53 %, a + failure (upper bound 6.53 % against the 5.71 % the set can resolve). Of the 152 fills it adds, + the mosaic's 9 are the artist's (each within 2 dE00 of an artist fill, region IoU 0.92-0.99); + of noto-emoji's 100, 24 are within 2 dE00 of an artist fill and those overlap its region at a + mean IoU of 0.31 (`bench/theory/human_gap.py --faces`): codec variants that split one artist + fill into several (`#44322b`, `#45342c`, `#48362d` around `#49362e`). Two narrowings separate + nothing. The share of a candidate's border on the JPEG's 8 px block lines is 0.14 (median) + for noto-emoji's candidates, 0.11-0.21 for the mosaic's, against 0.125 by chance: the + variants' claims are scattered pixel sets, not unions of blocks. And requiring the 12-level + step from every accepted ink, not only the nearest, rejects no candidate the nearest-ink step + admits. + + The turning failure is partly the boundary fit's, not the palette's. The mosaic's recovered + quads come back as polylines of 11-14 commands where the artist drew four sides, and the + faces already there read 8-12. The fit prices every boundary point with one image-wide noise, + 4.88 levels on this icon, while the codec's error at the edge pixel is 4.5 levels of luma and + 6.5 of chroma (`docs/theory/noise.md`), about 9-12 levels in RGB across a hue edge of about 23: + the fitter is chasing the chroma's bleed. **Retry this rule unchanged** once the boundary + chain's per-edge noise and its noise fold (which wait on the representation chain's robust + fitter) are in: the measurement above is the one to repeat. diff --git a/docs/algorithm/04-regions.md b/docs/algorithm/04-regions.md index 50ec62b6..ff7fb803 100644 --- a/docs/algorithm/04-regions.md +++ b/docs/algorithm/04-regions.md @@ -3,35 +3,35 @@ > Turns a per-pixel palette label into a set of connected, single-ink faces: speckle gone, anti-aliasing folded into its neighbours, disconnected same-colour shapes told apart, and pixel-corner ambiguities resolved by the image. **Source:** `crates/inkvec-trace/src/regions.rs` (connected components in `crates/inkvec-trace/src/regions/components.rs`), called from `crates/inkvec-trace/src/lib.rs` -**Entry point:** `trace_color_full_with_alpha()` (`lib.rs:299`), stages within it; the saddle pass runs at the head of `finish_color_trace_alpha()` (`lib.rs:1073`) -**Pipeline position:** after `color::label_image` (mark `"labels"`, `lib.rs:542`), before `gradient::merge_gradient_bands_with_ink` (mark `"merge_bands"`, `lib.rs:613`). The `split` sub-stage runs later, after stage 05's `carve` (`lib.rs:683`), and the saddle pass after it, just before `planar::build` (mark `"build_map"`, `lib.rs:1106`) +**Entry point:** `trace_color_full_with_alpha()` (`lib.rs:301`), stages within it; the saddle pass runs at the head of `finish_color_trace_alpha()` (`lib.rs:1048`) +**Pipeline position:** after `color::label_image` (mark `"labels"`, `lib.rs:544`), before `gradient::merge_gradient_bands_with_ink` (mark `"merge_bands"`, `lib.rs:615`). The `split` sub-stage runs later, after stage 05's `carve` (`lib.rs:685`), and the saddle pass after it, just before `planar::build` (mark `"build_map"`, `lib.rs:1106`) This stage is four sub-stages, with stopwatch marks; the first two run before stage 05 and the last two after it: | mark | line | function(s) | |---|---|---| -| `despeckle` | `lib.rs:546` | `despeckle` (`regions.rs:1027-1053`) | -| `blend_absorb` | `lib.rs:584` | `absorb_blend_slivers` (`regions.rs:754-820`), `reassign_blend_pixels` (`regions.rs:929-1025`) | -| `split` | `lib.rs:697` | `split_components` (`regions.rs:210-242`) | -| `saddles` | `lib.rs:1102` | `merge_saddle_faces` (`regions.rs:46-203`), compiled only in a `research` build; `planar::build`'s own corner logic acts on its result downstream | +| `despeckle` | `lib.rs:548` | `despeckle` (`regions.rs:1027-1053`) | +| `blend_absorb` | `lib.rs:586` | `absorb_blend_slivers` (`regions.rs:754-820`), `reassign_blend_pixels` (`regions.rs:929-1025`) | +| `split` | `lib.rs:699` | `split_components` (`regions.rs:210-242`) | +| `saddles` | `lib.rs:1077` | `merge_saddle_faces` (`regions.rs:46-203`), compiled only in a `research` build; `planar::build`'s own corner logic acts on its result downstream | -The module overview (`regions.rs:1-31`) lists the same order. The native-alpha path (`native.rs:885-896`, `native.rs:953`) runs `despeckle` and `split_components` unchanged and four-channel counterparts of the two blend passes; `trace_color_from_labels` runs `despeckle` (`lib.rs:869`) and `split_components` (`lib.rs:966`). Fast mode has its own face writer (see [14-fast-mode.md](14-fast-mode.md)). +The module overview (`regions.rs:1-31`) lists the same order. The native-alpha path (`native.rs:885-896`, `native.rs:953`) runs `despeckle` and `split_components` unchanged and four-channel counterparts of the two blend passes; `trace_color_from_labels` runs `despeckle` (`lib.rs:874`) and `split_components` (`lib.rs:971`). Fast mode has its own face writer (see [14-fast-mode.md](14-fast-mode.md)). ## What problem this solves `color::label_image` assigns every pixel the palette entry nearest its measured colour. That is a per-pixel decision with no notion of shape: it does not know that a pixel is noise, that a run of pixels is only anti-aliasing between two real inks, that two blobs of the same colour on opposite sides of the canvas are different objects, or that four pixels meeting at one corner might belong to a single connected mark. Each of those is a distinct failure mode, and each gets its own pass: - **Speckle** — an isolated pixel or tiny cluster that landed on the wrong palette entry (JPEG ringing, a stray anti-aliased pixel) becomes its own face with its own boundary unless removed first. -- **Blend slivers** — anti-aliased pixels between two real inks are frequently nearest a *third* palette entry, not either of the two they are blending. Left alone they form thin sliver faces along every boundary in the image, each minting junctions the boundary fitter has to honour (`regions.rs:756-760`). Measured on `mosaic_grid6` (36 flat cells): 128 faces and 368 edges, where the truth has 37 regions (`lib.rs:549-554`). +- **Blend slivers** — anti-aliased pixels between two real inks are frequently nearest a *third* palette entry, not either of the two they are blending. Left alone they form thin sliver faces along every boundary in the image, each minting junctions the boundary fitter has to honour (`regions.rs:756-760`). Measured on `mosaic_grid6` (36 flat cells): 128 faces and 368 edges, where the truth has 37 regions (`lib.rs:551-556`). - **Disconnected same colour** — palette labelling only records colour, not connectivity. Two separate shapes of one ink must become two faces, not one, or every per-face measurement downstream (including gradient fitting) is corrupted. - **Bowtie corners** — where two arms of one shape (or two separate shapes) meet at exactly one pixel corner, the labels alone cannot say whether that corner is one connected mark or two shapes touching at a point. ## Inputs and outputs -Working state through this stage is `labels: Vec`, one palette index per pixel (`w * h` long), plus the palette `pal: color::Palette`, the composited sRGB image `rgb: &[[f32; 3]]` (composited onto white), the true alpha channel (`source_alpha` when its length matches, else `img.data[..][3]`, `lib.rs:556-561`), and `sigma_noise: f64` (from `coverage::estimate_noise`). All colour distances in this stage are plain Euclidean distances in sRGB `[0, 1]`, on purpose: anti-aliasing mixes encoded values linearly, so a blend pixel lies on the straight sRGB segment between its two inks (`regions.rs:23-28`). +Working state through this stage is `labels: Vec`, one palette index per pixel (`w * h` long), plus the palette `pal: color::Palette`, the composited sRGB image `rgb: &[[f32; 3]]` (composited onto white), the true alpha channel (`source_alpha` when its length matches, else `img.data[..][3]`, `lib.rs:558-563`), and `sigma_noise: f64` (from `coverage::estimate_noise`). All colour distances in this stage are plain Euclidean distances in sRGB `[0, 1]`, on purpose: anti-aliasing mixes encoded values linearly, so a blend pixel lies on the straight sRGB segment between its two inks (`regions.rs:23-28`). - `despeckle` and `absorb_blend_slivers`/`reassign_blend_pixels` **relabel pixels in place** — the array stays `w * h` long, only the label at each pixel changes. -- `split_components` **changes the indexing scheme**: it turns the label map (one id per ink, or per label stage 05 minted) into a face map (a `u16` per pixel that is now a connected-component id), plus `face_color: Vec` mapping each face id back to the label it came from (`regions.rs:210-214`). `lib.rs:700-724` then gives each face its label's fill and maps a minted label back to its palette entry. +- `split_components` **changes the indexing scheme**: it turns the label map (one id per ink, or per label stage 05 minted) into a face map (a `u16` per pixel that is now a connected-component id), plus `face_color: Vec` mapping each face id back to the label it came from (`regions.rs:210-214`). `lib.rs:702-726` then gives each face its label's fill and maps a minted label back to its palette entry. - `merge_saddle_faces` **may reduce the number of faces in use** by unioning face ids at resolved corners. Only `labels` is rewritten; `face_fill`, `face_color` and `n_faces` are returned unchanged, so absorbed faces keep their (now unused) entries (`regions.rs:75-77`). ## How it works @@ -42,9 +42,19 @@ Working state through this stage is `labels: Vec`, one palette index per pi `min_size` is `opts.min_region`, described below. -### Blend absorption (`blend_absorb`, `lib.rs:547-584`) +### Codec clean-up on a lossy intake (`fast/codec.rs`, 2026-10-11) -Two passes, both skipped when `INKVEC_NO_ABSORB` is set (`lib.rs:555`): +On an opaque lossy intake (`ColorOptions::lossy_intake`) that did not come out of the restorer (`ColorOptions::restored`), the despeckled labels go through three passes before blend absorption, the first Quality's own and the other two Fast's halo pass ([`14-fast-mode.md`](14-fast-mode.md), "Noisy input"): + +1. **Codec variants** (`codec::variant_map`). A JPEG stores chroma at half resolution, so a stroke beside a coloured fill takes the fill's tint over its whole width without moving its luma, and the MDL palette founds the tint as an ink of its own: on `openmoji/E056` (`web`) it kept `#000109`, `#080100` and `#030801` beside `#000000`, and the trace came back with 674 faces, 41 colours and 250 subpaths where the artist drew four colours. An ink within `CODEC_VARIANT_LEVELS` (8 levels) of a heavier ink in luma-weighted YCbCr (each chroma channel at a quarter of luma's weight on squares, the halo pass's metric) and within the soft floor (`SOFT_SAME_INK_DE00`) is relabelled to it everywhere; inks are taken in descending weight, and a variant is never a target. The three tints lie 2.7-5.9 levels from black; the mosaic's neighbouring fills differ in luma and lie farther. +2. **Halos**, `RunLabels::absorb_halos_held` in its strict form: every thin component is held to the strip rule and the segment test, not only one of an ink that owns an area elsewhere as in Fast, because Quality's palette admits a thin ink on evidence and a real strip can lie on the segment between its neighbours (`noto-emoji/emoji_u1f9ed`'s needle shadow, three to four pixels wide between the teal needle and the white dial, went with the hull test alone). +3. **Thin variants**: `RunLabels::merge_same_inks` at the soft floor for thin components, as in Fast. + +The labels come back as palette indices; the palette is not changed, and an ink nothing is labelled with draws no face. Measured on `quality-web` against the build before it (246 icons, 2026-10-11, the gate's distance axes): dE00 −6.83 %, `turning_gap` −36.57 %, `ratio_gap` −11.89 %, geom −3.73 %, all four better, 87 icons changed (69 better and 18 worse in dE00); per icon, openmoji's colours and subpaths went 10.6 and 38.0 to 5.7 and 12.8 (the artists': 3.9 and 11.7), noto-emoji's 15.6 and 32.3 to 14.8 and 29.2 (9.0 and 25.0). The halo passes alone (without the variant merge) read dE00 −4.69 % and `turning_gap` −25.8 %; the halo test in Fast's form instead of the strict one, dE00 −7.09 % and `turning_gap` −43.2 %, but it erased real strips like the needle shadow. A restored image takes none of it either: the restorer took the codec's damage out, and on the restored path (`quality-web`, `--restore on`, the gate's 0.3 sample) the clean-up read dE00 +0.24 % (the brown border strip of `openmoji/E30B`, a real ink between the black outline and the white sheet, went to the outline), so it is off there; the intake stays lossy for the palette. A clean intake takes none of this and is byte-identical. Tests: `fast/codec/tests.rs`. + +### Blend absorption (`blend_absorb`, `lib.rs:549-586`) + +Two passes, both skipped when `INKVEC_NO_ABSORB` is set (`lib.rs:557`): **`absorb_blend_slivers` (`regions.rs:754-820`).** Runs at most two rounds, because dissolving one sliver can leave a neighbouring one thinner or bounded by fewer inks (`regions.rs:768-771`). Each round finds the components once (`SliverRound`, `regions.rs:822-859`), visits them in raster order, and lets each edit be seen by later components in the same round. The three tests, each on counts rather than colours so that one noisy pixel cannot swing them, are listed on `absorb_sliver` (`regions.rs:673-752`): 1. **Thin**: fewer than 20 % of its pixels are interior (`5 · interior < area`; a pixel is interior when all its in-image 4-neighbours are in the component), and it has at least one neighbour. "A blob with a real interior is a shape, not a seam." @@ -60,7 +70,7 @@ On success each pixel moves to its own dominant ink (`sliver_destinations`, `reg - The pixel moves to the dominant ink of its nearest convex `mixture()` of those inks (pairs and triples) only when all three hold: that ink differs from its current one; the residual `r <= tol` with the same `tol`; and `r < 0.5 · |c − own|`, "the blend explains the pixel at least twice as well as the ink it has, so a pixel that is a plausible match for its own ink is left alone" (`regions.rs:938-941`, test at `regions.rs:1018`). - Each round decides pixels from the labels as the round found them, in parallel with `rayon`, and then applies the moves, so the result does not depend on scan order. A decision reads only the pixel's 3x3 neighbourhood, so after the first round only the neighbourhoods of the pixels that just moved are decided again (`relabel_rounds`, `regions.rs:861-927`); every other pixel would decide "stay" as it did before. "Not from the literature: a plain worklist, because the moves after the first round are few (on the screen set 94 % of them happen in round one)". -If either pass changed anything, `despeckle` is run again (`lib.rs:580-582`) to clean up whatever the reassignment left behind. +If either pass changed anything, `despeckle` is run again (`lib.rs:582-584`) to clean up whatever the reassignment left behind. ### Split into connected faces (`split`, `split_components`, `regions.rs:210-242`) @@ -79,7 +89,7 @@ Measured (w2-robust report, section 4, 2026-10-03): on the r2-product `noise_102 ### Saddle resolution (`saddles`, `merge_saddle_faces`, `regions.rs:46-203`) -**An experiment**: compiled only with the `research` feature (`regions.rs:78`, call site `lib.rs:1087-1101`), and even then a no-op unless `INKVEC_SADDLE` is set, or when the image is narrower or shorter than 2 px (`regions.rs:91-93`). See Environment overrides. +**An experiment**: compiled only with the `research` feature (`regions.rs:78`, call site `lib.rs:1062-1076`), and even then a no-op unless `INKVEC_SADDLE` is set, or when the image is narrower or shorter than 2 px (`regions.rs:91-93`). See Environment overrides. For every interior pixel corner `(i, j)` where `1 <= i < w`, `1 <= j < h`, look at the four pixels meeting there: `nw = (i-1,j-1)`, `ne = (i,j-1)`, `sw = (i-1,j)`, `se = (i,j)`. @@ -99,13 +109,13 @@ For every interior pixel corner `(i, j)` where `1 <= i < w`, `1 <= j < h`, look After the scan, every pixel's label is rewritten to its union-find root (`regions.rs:193-195`). Absorbed face ids are left in `face_fill`, `face_color` and `n_faces`, unused, rather than renumbered (`regions.rs:75-77`). -`planar::build`, called immediately afterward (`lib.rs:1105`), is what turns a merged corner into two boundary points instead of one junction: `split_saddle_corners` (`planar.rs:182-267`) gives the two faces on the cut diagonal their own copy of a degree-4 corner when exactly one diagonal is a single face, and leaves a corner whose diagonals are both one face, or neither, as a junction (`planar.rs:232-234`). "Which diagonal is one face is settled upstream, in `merge_saddle_faces`, where the image can be consulted" (`planar.rs:204-207`). The rule is covered by `planar.rs`'s `saddle_tests` module (`planar.rs:1351-1430`): `four_inks_meeting_at_a_corner_stay_a_junction` confirms an unreadable four-way corner keeps its junction, and `a_corner_two_shapes_share_becomes_two_points` / `splitting_gives_each_shape_its_own_copy_of_the_corner` confirm that once one diagonal is a single face, the corner becomes two independent points, one per touching shape, and every edge still separates exactly the two faces it did before. +`planar::build`, called immediately afterward (`lib.rs:1080`), is what turns a merged corner into two boundary points instead of one junction: `split_saddle_corners` (`planar.rs:185-270`) gives the two faces on the cut diagonal their own copy of a degree-4 corner when exactly one diagonal is a single face, and leaves a corner whose diagonals are both one face, or neither, as a junction (`planar.rs:235-237`). "Which diagonal is one face is settled upstream, in `merge_saddle_faces`, where the image can be consulted" (`planar.rs:207-210`). The rule is covered by `planar.rs`'s `saddle_tests` module (`planar.rs:1312-1391`): `four_inks_meeting_at_a_corner_stay_a_junction` confirms an unreadable four-way corner keeps its junction, and `a_corner_two_shapes_share_becomes_two_points` / `splitting_gives_each_shape_its_own_copy_of_the_corner` confirm that once one diagonal is a single face, the corner becomes two independent points, one per touching shape, and every edge still separates exactly the two faces it did before. ## Constants and thresholds | name | value | controls | stated derivation | |---|---|---|---| -| `ColorOptions::min_region` (default) | `4` (library default, `lib.rs:217`), but the CLI always overrides it with `args.min_area.max(1.0) as usize` (`crates/inkvec-cli/src/pipeline.rs:180`), and `args.min_area` defaults to `2.0` (`crates/inkvec-cli/src/args.rs:250`) — so the shipped default is **2 pixels**. Above the reference extent the CLI scales `--min-area` by the square of the measured oversampling factor (`price_in_raster_units`, `crates/inkvec-cli/src/lib.rs:382-396`, reasons at `lib.rs:442-473`) | `despeckle`'s `min_size`, and (via `min_region.max(2)`) the carve pass's minimum feature size (`crates/inkvec-trace/src/lib.rs:676`) | See the comment at `crates/inkvec-cli/src/pipeline.rs:168-179`, quoted below | +| `ColorOptions::min_region` (default) | `4` (library default, `lib.rs:217`), but the CLI always overrides it with `args.min_area.max(1.0) as usize` (`crates/inkvec-cli/src/pipeline.rs:180`), and `args.min_area` defaults to `2.0` (`crates/inkvec-cli/src/args.rs:251`) — so the shipped default is **2 pixels**. Above the reference extent the CLI scales `--min-area` by the square of the measured oversampling factor (`price_in_raster_units`, `crates/inkvec-cli/src/lib.rs:382-396`, reasons at `lib.rs:442-473`) | `despeckle`'s `min_size`, and (via `min_region.max(2)`) the carve pass's minimum feature size (`crates/inkvec-trace/src/lib.rs:676`) | See the comment at `crates/inkvec-cli/src/pipeline.rs:168-179`, quoted below | | `SADDLE_SIGMAS` | `3.0` | how many propagated-noise sigma a corner's coverage value must clear the 0.5 mark by before a saddle is resolved | `regions.rs:43-45`: "three sigma of the propagated coverage noise. Below that the two readings are indistinguishable, and the corner keeps the junction it has always had." No further derivation than "three sigma" as a standard significance bar; not tuned against a benchmark in the comment. | | `MAX_FACES` | `65,535` (`u16::MAX`) | most faces a face map can number; past it `cap_components` merges the smallest components | derived: ids are `u16` and `u16::MAX` is reserved for the outside of the image (`regions.rs:205-208`) | | absorption rounds | `2` | how many rounds `absorb_blend_slivers` runs | `regions.rs:768-769`: "dissolving one sliver can leave a neighbouring one thinner or bounded by fewer inks"; no numeric derivation for two | @@ -114,6 +124,7 @@ After the scan, every pixel's label is rewritten to its union-find root (`region | absorption pass threshold | `>= 4/5` of pixels within tolerance | whether a qualifying component is actually absorbed | `regions.rs:684-685`; no numeric derivation for 80 % | | translucency gate | `alpha < 0.99` | when the white backdrop joins the candidate inks | `regions.rs:685-687`, `regions.rs:934-935`: a translucent edge composited onto white is a blend with white; no derivation for 0.99 | | `tol` (both blend passes) | `max(3 * sigma_noise, 0.025)` sRGB | how close a pixel's colour must be to a mixture hypothesis to count as a match | three sigma of the measured noise; the floor keeps clean synthetic input from rejecting blends over float rounding (`regions.rs:764-766`); no derivation for 0.025 (about 6.4/255) itself | +| `CODEC_VARIANT_LEVELS` | 8 levels (luma-weighted YCbCr) | on a lossy intake, how close an ink may lie to a heavier one and be the codec's variant of it (`fast/codec.rs`) | the codec's tinted blacks on `openmoji/E056` lie 2.7-5.9 levels from black; measured with the clean-up on `quality-web` (above). No sweep of the value | | `reassign_blend_pixels::ROUNDS` | `4` | how many rounds the per-pixel reassignment runs | no stated derivation (`regions.rs:958`) | | reassign "beats own label" margin | residual `< 0.5 * |c − own|` | how much better a blend hypothesis must be than the pixel's own ink before it moves | `regions.rs:940-941`: "the blend explains the pixel at least twice as well as the ink it has, so a pixel that is a plausible match for its own ink is left alone"; no derivation for the half | | **9-pixel colour-mode floor (rejected)** | tried, not shipped | would have been `min_region` in colour mode | `crates/inkvec-cli/src/pipeline.rs:176-181` (quoted below): tried 2026-09-03, measured *worse* on the 980-icon set — objective `0.7885` vs `0.7673` with the 2 px floor, 508 icons worse / 171 better in dE00. It erased real dots and thin details more often than it removed confetti; the shipped default stays at `--min-area` (2 px). | diff --git a/docs/algorithm/05-gradients.md b/docs/algorithm/05-gradients.md index dff27b17..56fda0df 100644 --- a/docs/algorithm/05-gradients.md +++ b/docs/algorithm/05-gradients.md @@ -4,7 +4,7 @@ **Source:** `crates/inkvec-trace/src/gradient.rs` (1,163 lines: the model types, colour helpers, sample gathering, scoring, the ramp-or-step test and model selection) and its modules in `crates/inkvec-trace/src/gradient/`: `bands.rs` (band merging), `carve.rs` (residual features), `fit.rs` (the flat, linear and radial fitters) and `fit/profile.rs` (the profile-aware radial search), `stops.rs` and `stops/knots.rs` (interior stops), `evidence.rs` (which pixels testify about a fill), `regions.rs` (region recovery switches), `score.rs`, `eval.rs`, `budget.rs` (sampling caps and timing counters), `debug.rs` and `svg.rs` (the file list is `gradient.rs:56-67`) **Entry points:** `merge_gradient_bands_with_ink()` (`gradient/bands.rs:287-305`), `carve_residual_features_with_detail_noise()` (`gradient/carve.rs:72-119`), `fit_fill()` (`gradient.rs:1110-1138`) -**Pipeline position:** `merge_bands` (`lib.rs:599-613`) runs after blend absorption (stage 04) and before `carve` (`lib.rs:661-683`); `carve` runs before `split` (`lib.rs:686-697`, stage 04's face-splitting). The native-alpha path runs the same two passes (`native.rs:898-933`), the merge through `merge_gradient_bands_guarded` with an opacity veto. Each face then inherits the fill of the label it came from (`lib.rs:700-718`); the pipeline does not refit fills per face, because "a per-face fit would re-shatter a gradient the merge stage had just reassembled" (`lib.rs:771-775`). `fit_fill`/`fit_candidates` are the same machinery for one label; `regroup.rs:300` calls `fit_candidates` directly. +**Pipeline position:** `merge_bands` (`lib.rs:601-615`) runs after blend absorption (stage 04) and before `carve` (`lib.rs:663-685`); `carve` runs before `split` (`lib.rs:688-699`, stage 04's face-splitting). The native-alpha path runs the same two passes (`native.rs:898-933`), the merge through `merge_gradient_bands_guarded` with an opacity veto. Each face then inherits the fill of the label it came from (`lib.rs:702-720`); the pipeline does not refit fills per face, because "a per-face fit would re-shatter a gradient the merge stage had just reassembled" (`lib.rs:771-775`). `fit_fill`/`fit_candidates` are the same machinery for one label; `regroup.rs:300` calls `fit_candidates` directly. ## What problem this solves @@ -26,7 +26,7 @@ Two further problems this module solves, beyond band merging and model selection ## Inputs and outputs - `merge_gradient_bands_with_ink(labels: &mut [u16], rgb: &[[f32;3]], w, h, pal: &Palette, sigma_noise: f64, lambda: f64, deadline: Option) -> (Vec, Vec)` — mutates `labels` in place (each gradient region and each flat region with an interior of its own gets a fresh label past the palette's range) and returns one `FillFit` per resulting label id, palette labels first, plus a parallel `Vec` mapping each label back to the palette entry it was cut from (a merged gradient maps to its first band's entry) (`gradient/bands.rs:271-290`). `merge_gradient_bands_guarded` adds `same_class`, a veto on which palette entries may share a fill (`gradient/bands.rs:307-334`). -- `carve_residual_features_with_detail_noise(labels: &mut [u16], rgb, w, h, pal, fills: &mut Vec, ink: &mut Vec, sigma_noise, lambda, min_size, detail_sigma: Option) -> usize` — further mutates `labels`, appends newly minted flat regions to `fills`/`ink` in place, refits the parents, and returns the count minted. `carve_residual_features` is the same with `detail_sigma = None` (`gradient/carve.rs:24-70`). +- `carve_residual_features_with_detail_noise(labels: &mut [u16], rgb, w, h, pal, fills: &mut Vec, ink: &mut Vec, sigma_noise, lambda, min_size, detail_sigma: Option, codec_band: usize) -> usize` — further mutates `labels`, appends newly minted flat regions to `fills`/`ink` in place, refits the parents, and returns the count minted. `carve_residual_features` is the same with `detail_sigma = None` and `codec_band = 0` (`gradient/carve.rs:24-70`). - `fit_fill(rgb, w, h, labels, label, sigma_noise, lambda) -> FillFit` — the single-label entry point, `select(fit_candidates(...))`. - `FillModel` (`gradient.rs:127-178`) — the fitted geometry: `Flat([f32;3])`, `Linear { p0, p1, c0, c1, interp, mids }`, `Radial { c, r, c0, c1, interp, aspect, angle, mids }`. Points are pixel-centre coordinates, matching the tracer's `-0.5 -0.5 w h` viewBox (`gradient.rs:132-134`). - `FillFit` (`gradient.rs:306-318`) — `{ model: FillModel, chi2: f64, params: f64, cost: f64 }`, the fitted model plus the numbers the selection was made on. @@ -85,13 +85,14 @@ Either way the loop just stops: "every merge accepted so far stands and the othe ### `carve_residual_features` (`gradient/carve.rs`) -Runs after band merging, before faces are split into connected components, with `opts.gradients` and unless `INKVEC_NO_CARVE` is set (`lib.rs:665`). The palette sees colours, not features: a two-pixel white seam through a black shape, a pair of dots, the end of a thin stroke all quantise to the ink around them. The fill fitter then sees a solid region with a residual cluster it cannot explain and buys a gradient to cover it — "three radials on solid black (ebox), black lightening to grey at a rim (luanti), a dark core on a flat face (kiss, zebra)" (`gradient/carve.rs:24-36`). The pass runs in three stages (`gradient/carve.rs:80-82`): +Runs after band merging, before faces are split into connected components, with `opts.gradients` and unless `INKVEC_NO_CARVE` is set (`lib.rs:667`). The palette sees colours, not features: a two-pixel white seam through a black shape, a pair of dots, the end of a thin stroke all quantise to the ink around them. The fill fitter then sees a solid region with a residual cluster it cannot explain and buys a gradient to cover it — "three radials on solid black (ebox), black lightening to grey at a rim (luanti), a dark core on a flat face (kiss, zebra)" (`gradient/carve.rs:24-36`). The pass runs in three stages (`gradient/carve.rs:80-82`): -1. **`residual_mask`** (`gradient/carve.rs:170-239`). `fill_evidence` is computed fresh over the current labels, each label's ink being its palette colour, or for a label minted after the palette its fill's representative colour (`CarveImage::inks`, `gradient/carve.rs:139-153`). Each label's **flat colour** — the per-channel median of its pure interior pixels — is computed only where there are at least 8 such pixels (`region_flat_colours`, `gradient/carve.rs:241-285`); this is a gate, not the residual test: "a region with too few pure interior pixels to take a median of has no reliable notion of its own colour, and its pixels are skipped rather than carved". A pixel is a candidate when it is strictly interior to its label, pure (not a blend), its label passes that gate, and its residual against the label's fill, `max_ch |c − fill.color_at(x, y)|`, exceeds `thr = max(8*sigma_noise, CARVE_RESIDUAL)`. Where `detail_sigma` is given and the pixel's 7x7 neighbourhood is all one label, `σ` is `detail_sigma` instead; `lib.rs` passes it only for a lossy intake in a research build with `INKVEC_LOSSY_REGULARIZE` (`lib.rs:1217-1220`, `lib.rs:1217-1221`), otherwise `None`. +1. **`residual_mask`** (`gradient/carve.rs:170-239`). `fill_evidence` is computed fresh over the current labels, each label's ink being its palette colour, or for a label minted after the palette its fill's representative colour (`CarveImage::inks`, `gradient/carve.rs:139-153`). Each label's **flat colour** — the per-channel median of its pure interior pixels — is computed only where there are at least 8 such pixels (`region_flat_colours`, `gradient/carve.rs:241-285`); this is a gate, not the residual test: "a region with too few pure interior pixels to take a median of has no reliable notion of its own colour, and its pixels are skipped rather than carved". A pixel is a candidate when it is strictly interior to its label, on a lossy intake also at least `CODEC_BAND = 2` px from its label's edge (`beyond_band`: its whole 5x5 window carries its label), pure (not a blend), its label passes that gate, and its residual against the label's fill, `max_ch |c − fill.color_at(x, y)|`, exceeds `thr = max(8*sigma_noise, CARVE_RESIDUAL)`. Where `detail_sigma` is given and the pixel's 7x7 neighbourhood is all one label, `σ` is `detail_sigma` instead; `lib.rs` passes it only for a lossy intake in a research build with `INKVEC_LOSSY_REGULARIZE` (`lib.rs:1193-1196`, `lib.rs:1193-1197`), otherwise `None`. 2. **The residual test is against the fill the fitter actually chose, not the region's flat colour** — the reverse of the original design. "Testing the residual against the flat colour instead carved hard-edged shading the fitter had legitimately captured with a gradient (noto 1f9d1_1f3fc_200d_1f37c +0.13, 1F3DD +0.10); requiring both residuals to fail is stricter still. The dev set (51 icons) preferred the flat rule with the size and step-edge guards below (0.7797 against 0.7888), but the full 980-icon set reversed it: against the plain fit rule without guards, flat+guards was 82 better / 193 worse in dE00 (+0.0022) and fit+guards 57 / 191 (+0.0031), both at an unchanged objective. The plain rule ships" (`gradient/carve.rs:195-204`). -3. Blend exclusion matters concretely: "a two-pixel grey fleck where two black strokes almost touch is anti-aliasing of the gap, not a thing to draw, and minted as a region it paints over the gap (send_and_archive: two such flecks cost 0.19 dE00). A seam *inside* a region has no other ink within reach and stays eligible" (`gradient/carve.rs:187-191`). -4. **`mint_features`** (`gradient/carve.rs:340-428`). 4-connected clusters of the mask, within one label, taken in raster order of their first pixel; one of at least `max(min_size, 4)` pixels, while fewer than `CARVE_MAX = 64` have been minted and the `u16` label space has room, gets the next label id, a flat fill of its per-channel median colour, and as its ink the palette entry nearest that colour (squared sRGB distance). The earlier idea of capping a cluster relative to its parent (a fifth of the parent, or 200 px) was rejected: "Measured on the full set that guard, with the step-edge test below, lost more small features than the explosions it prevented. Only `CARVE_MAX` survives, against a textured region shattering" (`gradient/carve.rs:367-372`). -5. **`refit_parents`** (`gradient/carve.rs:430-456`). The evidence mask is recomputed on the new labels (the minted features are inks now, so pixels blending towards them stop counting), and each parent that lost pixels is refitted by full model selection over its remaining pixels. +3. **The codec's band is not carved on a lossy intake** (`CODEC_BAND`, `lib.rs::codec_band`, 2026-10-10). A codec's error sits at the edges (on the `web` tier the RMS is 4.5 levels of luma and 6.5 of chroma on the edge pixel, 0.2 and 0.35 in the interiors, `docs/theory/noise.md`), and its ringing is a pattern just inside every region, brighter or darker by turns. Carved, that rim became extra regions along the edges. With the band the carve keeps what lies two pixels or more inside its region; measured on `quality-web` (246 icons, the gate's distance axes) at 1, 2 and 3 px: dE00 +0.21 / −0.01 / −0.03 %, `turning_gap` −4.89 / −5.38 / −5.47 %, `ratio_gap` −0.58 / −0.80 / −0.82 %, geom −0.01 / −0.10 / +0.08 %, so two pixels, the one reach no axis reads worse at. A clean intake passes 0 and is byte-identical. Test: `the_codec_band_along_an_edge_is_not_carved`. +4. Blend exclusion matters concretely: "a two-pixel grey fleck where two black strokes almost touch is anti-aliasing of the gap, not a thing to draw, and minted as a region it paints over the gap (send_and_archive: two such flecks cost 0.19 dE00). A seam *inside* a region has no other ink within reach and stays eligible" (`gradient/carve.rs:187-191`). +5. **`mint_features`** (`gradient/carve.rs:340-428`). 4-connected clusters of the mask, within one label, taken in raster order of their first pixel; one of at least `max(min_size, 4)` pixels, while fewer than `CARVE_MAX = 64` have been minted and the `u16` label space has room, gets the next label id, a flat fill of its per-channel median colour, and as its ink the palette entry nearest that colour (squared sRGB distance). The earlier idea of capping a cluster relative to its parent (a fifth of the parent, or 200 px) was rejected: "Measured on the full set that guard, with the step-edge test below, lost more small features than the explosions it prevented. Only `CARVE_MAX` survives, against a textured region shattering" (`gradient/carve.rs:367-372`). +6. **`refit_parents`** (`gradient/carve.rs:430-456`). The evidence mask is recomputed on the new labels (the minted features are inks now, so pixels blending towards them stop counting), and each parent that lost pixels is refitted by full model selection over its remaining pixels. A **step-edge test** (requiring the mean contrast across a cluster's boundary with the rest of its parent to reach the residual threshold) was tried alongside the flat-colour rule and rejected along with it: sound against a *flat* residual — "the bright end of a genuine gradient is also a small cluster of large residual, but it is reached by a ramp where a seam is a step (a skin-tone highlight carved this way cost +0.06 on emoji_u1f469_1f3fd_200d_1f4bc; the ebox seam steps by 0.5)" — but it only ever ran alongside the flat rule, which does not ship, and cost a four-neighbour sweep of every candidate cluster on the default path (`gradient/carve.rs:376-383`). @@ -131,7 +132,7 @@ Measured with the edge rule (gate v2 against v0.2.5, 246 icons): quality-128ss d ### `bic_lambda` vs the fitter's `lambda` -`bic_lambda(n) = 0.5 * ln(n)` (`gradient.rs:320-327`) is the value of `lambda` at which the MDL cost equals the Bayesian information criterion for `n` observations: "it grows slowly with region size, so a large region has to earn a gradient with proportionally more evidence than a small one does". The pipeline calls it with the image's **pixel count** wherever a fill decision is made (`gradient::bic_lambda(img.width * img.height)`: the palette's evidence at `lib.rs:418`, the merge at `lib.rs:607`, the carve at `lib.rs:675`; the label-map entry at `lib.rs:819`; the research decode at `lib.rs:1183`). +`bic_lambda(n) = 0.5 * ln(n)` (`gradient.rs:320-327`) is the value of `lambda` at which the MDL cost equals the Bayesian information criterion for `n` observations: "it grows slowly with region size, so a large region has to earn a gradient with proportionally more evidence than a small one does". The pipeline calls it with the image's **pixel count** wherever a fill decision is made (`gradient::bic_lambda(img.width * img.height)`: the palette's evidence at `lib.rs:420`, the merge at `lib.rs:609`, the carve at `lib.rs:677`; the label-map entry at `lib.rs:819`; the research decode at `lib.rs:1158`). This is a **different quantity** from `inkvec-fit::FitConfig::lambda`, which `FitConfig::from_precision` derives (`crates/inkvec-fit/src/lib.rs:147-169`): @@ -154,7 +155,7 @@ Quoted in full, from `ColorOptions::gradients`'s doc comment (`crates/inkvec-tra > Turning this off is a genuine fast path, not a cosmetic one. Gradient fitting is the dominant cost in the tracer: with every optional stage disabled a slow emoji still took 10.9s, and capping the palette — which is what feeds the per-region gradient search — took it to 6.3s. The CLI's `--no-gradients` used to replace the fitted model with a flat one *after* paying for the fit, so it changed the output and saved nothing. -Concretely: when `opts.gradients` is `false`, `merge_gradient_bands_with_ink` is never called at all (`(Vec::new(), Vec::new())` is substituted, `lib.rs:599-612`) and the carve is skipped too (`lib.rs:656`); each face then takes a flat fill of its palette colour (`lib.rs:694-709`). The search itself is what is expensive (the radial centre alone is "six hundred residual evaluations over every sample", `gradient.rs:852-854`), not merely the choice of which model to keep. The CLI help text repeats the same framing: `--no-gradients Skip gradient fitting entirely and fill flat. A genuine fast path: gradient fitting dominates runtime` (`crates/inkvec-cli/src/args.rs:447-448`). +Concretely: when `opts.gradients` is `false`, `merge_gradient_bands_with_ink` is never called at all (`(Vec::new(), Vec::new())` is substituted, `lib.rs:601-614`) and the carve is skipped too (`lib.rs:656`); each face then takes a flat fill of its palette colour (`lib.rs:696-711`). The search itself is what is expensive (the radial centre alone is "six hundred residual evaluations over every sample", `gradient.rs:852-854`), not merely the choice of which model to keep. The CLI help text repeats the same framing: `--no-gradients Skip gradient fitting entirely and fill flat. A genuine fast path: gradient fitting dominates runtime` (`crates/inkvec-cli/src/args.rs:448-449`). ## Constants and thresholds @@ -191,6 +192,7 @@ Concretely: when `opts.gradients` is `false`, `merge_gradient_bands_with_ink` is | `SMOOTH_FRACTION` | 0.5 | fraction of a seam's pixel pairs that must be smooth steps | `gradient/regions.rs:36-38`, no stated derivation | | `CARVE_RESIDUAL` | 0.06 | floor on `thr = max(8*sigma_noise, CARVE_RESIDUAL)`, the carve candidate threshold | "Eight times the noise, and never below 0.06 (about 15 levels): an anti-aliasing fringe the evidence test let through sits below this; a seam, a dot or a stroke that the palette quantised away sits far above it" (`gradient/carve.rs:16-20`) | | `CARVE_MAX` | 64 | most features carved from one image | "a guard against a textured region shattering" (`gradient/carve.rs:21-22`), no numeric derivation for 64 specifically | +| `CODEC_BAND` | 2 px | on a lossy intake, how far inside its region a pixel must lie to be carved | measured 2026-10-10 on `quality-web` at 1, 2 and 3 px: 2 is the one reach no gated axis reads worse at (dE00 −0.01 %, `turning_gap` −5.38 %, `ratio_gap` −0.80 %, geom −0.10 %) | | `CARVED_PAINT_ALPHA` | 0.5 | mean opacity at or above which a carved feature named by the clear ink is renamed to a visible ink (native-alpha path) | measured 2026-10-02: residue reads 0.14-0.36, paint 0.80-1.00 (`native.rs:691-700`) | | `bic_lambda(n)` | `0.5 * ln(n)` | fill-selection lambda | exact: the BIC choice, "the value at which the MDL cost is the Bayesian information criterion" (`gradient.rs:320-327`) | | `IRLS_ROUNDS` | 2 | rounds of Huber reweighting when a stop count's final profile is fitted | `gradient/stops.rs:68-69`, no stated derivation | @@ -216,7 +218,7 @@ Since the settings cleanup (CHANGELOG, 0.2.0, *Changed*) the engine reads its en | variable | effect | |---|---| -| `INKVEC_NO_CARVE` | if set, skips the carve entirely (checked alongside `opts.gradients`: `lib.rs:665`, the label-map entry at `lib.rs:919`, the native-alpha path at `native.rs:912`) | +| `INKVEC_NO_CARVE` | if set, skips the carve entirely (checked alongside `opts.gradients`: `lib.rs:667`, the label-map entry at `lib.rs:924`, the native-alpha path at `native.rs:912`) | | `INKVEC_GRAD_REGIONS` | region recovery, on by default; `0` switches it off (`gradient/regions.rs:17-22`) | | `INKVEC_MERGE_COMMON_PIXELS` (*research build*) | prices every candidate pair on common pixels, not only smooth pairs (`gradient/bands.rs:457-460`) | | `INKVEC_MIN_CONTRAST` (*removed*) | scaled the visible-contrast floor in `fit_samples`; the default (scale 1) never moved (`gradient.rs:863-864`) | @@ -226,10 +228,10 @@ Since the settings cleanup (CHANGELOG, 0.2.0, *Changed*) the engine reads its en | `INKVEC_EVDBG` | verbose per-region fit diagnostics: sample counts, chosen model, contrast/support (`gradient.rs:1024-1069`), refused-candidate reasons (`gradient.rs:892-910`), per-label pixel/blend tallies from `blend_partners` (`gradient/evidence.rs:133-152`) and each carved feature (`gradient/carve.rs:390-408`) | | `INKVEC_MERGEDBG` | verbose band-merge diagnostics: per-pair costs and gains for unions over 200 pixels (`gradient/bands.rs:1174-1184`, `gradient/bands.rs:1219-1226`), legacy and common-pixel gains side by side with `INKVEC_MERGE_COMMON_PIXELS` (`gradient/bands.rs:1216-1218`), and a stop at the time budget (`gradient/bands.rs:978-980`) | | `INKVEC_GRADDBG` | `x0,y0,x1,y1`: after band merging, prints every surviving component in the window and a fresh union fit with each neighbour, flat-flat pairs included (`gradient/debug.rs:1-8`, called at `gradient/bands.rs:465-467`) | -| `INKVEC_TIMING` | prints per-stage timing, the merge's rounds, waves, stale refits and per-model fit time, the profile-aware search included (`profile`; `MergeTiming::report`, `gradient/bands.rs:711-758`; counters in `gradient/budget.rs:12-29`), and the number of carved features (`lib.rs:670-672`) | +| `INKVEC_TIMING` | prints per-stage timing, the merge's rounds, waves, stale refits and per-model fit time, the profile-aware search included (`profile`; `MergeTiming::report`, `gradient/bands.rs:711-758`; counters in `gradient/budget.rs:12-29`), and the number of carved features (`lib.rs:672-674`) | | `INKVEC_DIAG` | reports the merge's work spent, its cap, its rounds and why it stopped, and a stop at the work cap as a saturated budget (`gradient/bands.rs:959-977`) | | `--no-gradients` (CLI) | sets `opts.gradients = false`; see "The `--no-gradients` fast path" above | -| `--time-budget` (CLI) | sets the merge's deadline at 60 % of the budget (`crates/inkvec-cli/src/pipeline.rs:146-149`; help at `crates/inkvec-cli/src/args.rs:363-370`); `0`, the default, means no deadline, and the merge is bounded by the work cap alone | +| `--time-budget` (CLI) | sets the merge's deadline at 60 % of the budget (`crates/inkvec-cli/src/pipeline.rs:146-149`; help at `crates/inkvec-cli/src/args.rs:364-371`); `0`, the default, means no deadline, and the merge is bounded by the work cap alone | ## Open questions diff --git a/docs/algorithm/06-planar-map.md b/docs/algorithm/06-planar-map.md index 35365566..7346f853 100644 --- a/docs/algorithm/06-planar-map.md +++ b/docs/algorithm/06-planar-map.md @@ -5,13 +5,13 @@ **Source:** `crates/inkvec-trace/src/planar.rs`, with the cracks and their incidence in `planar/cracks.rs` and the row-run coding in `planar/runs.rs` -**Entry point:** `fn build()` (`planar.rs:163-180`), which calls `dual_segments` -(`planar/cracks.rs:273`), `split_saddle_corners` (`planar.rs:211`), `Incidence::new` -(`planar/cracks.rs:96`), `walk_open_chains` (`planar.rs:286`) and `walk_closed_loops` -(`planar.rs:360`) +**Entry point:** `fn build()` (`planar.rs:166-183`), which calls `dual_segments` +(`planar/cracks.rs:273`), `split_saddle_corners` (`planar.rs:214`), `Incidence::new` +(`planar/cracks.rs:96`), `walk_open_chains` (`planar.rs:289`) and `walk_closed_loops` +(`planar.rs:363`) **Pipeline position:** after `saddles` (`merge_saddle_faces`, research build only), before symmetry detection and the sub-pixel refinement, which run side by side on the map it -builds (stage mark `"build_map"`, `lib.rs:1106`). Shared by Quality and Fast mode. +builds (stage mark `"build_map"`, `lib.rs:1081`). Shared by Quality and Fast mode. ## What problem this solves @@ -46,8 +46,8 @@ pub fn build(labels: &[u16], w: usize, h: usize, n_labels: usize) -> PlanarMap ``` - `labels`: one face id per pixel, row-major, already split into connected components - upstream (`split_components`, `lib.rs:696`) and, optionally, coalesced across - diagonal-only touches by `merge_saddle_faces` (`lib.rs:1091`, off by default — see + upstream (`split_components`, `lib.rs:698`) and, optionally, coalesced across + diagonal-only touches by `merge_saddle_faces` (`lib.rs:1066`, off by default — see Failure modes). - `n_labels`: number of distinct face ids in `labels`. @@ -71,10 +71,10 @@ pub struct Edge { ``` `left`/`right` are face ids — `u16::MAX` denotes the virtual background outside the image -(`planar.rs:140-149`), so a shape touching the image border still closes. +(`planar.rs:143-152`), so a shape touching the image border still closes. Every `Edge.points` value at the end of `build` sits exactly on a pixel corner (a -half-integer coordinate, `node_point`, `planar.rs:134-138`). `sigma` is a uniform +half-integer coordinate, `node_point`, `planar.rs:137-141`). `sigma` is a uniform placeholder of `0.5`, replaced point-by-point by stage 07 (`refine_subpixel`). ## How it works @@ -94,7 +94,7 @@ on each side (`left`/`right`, oriented so `left` is on the left walking from `a` down), read directly off the two labels straddling it. Because a label difference is required to emit a segment at all, a flat interior produces nothing — the segment set already *is* the full set of pixel-grid boundary cracks, before any topology is built from -it. Node ids are `node_id(i, j, w) = j*(w+1) + i` (`planar.rs:129-131`), so real node ids +it. Node ids are `node_id(i, j, w) = j*(w+1) + i` (`planar.rs:132-134`), so real node ids span `0 .. (w+1)*(h+1)`. This is the bilevel case of marching squares specialised to an arbitrary number of labels: instead of one 0/1 boundary there is one boundary crack per differing label pair. @@ -144,20 +144,20 @@ Four pixels can meet at one grid corner. If the two pixels on one diagonal are t face and the two on the other diagonal are *different* faces, the naive dual-grid segment set gives that face two boundary arms that meet only at a single point — a **bowtie**: the fill pinches to nothing and reopens, and "no later stage can undo it, because one node has -one refined position however many curves end there" (`planar.rs:185-189`). +one refined position however many curves end there" (`planar.rs:188-192`). `build` resolves this before any chain-walking happens, in a dedicated pass over every -degree-4 node (`split_saddle_corners`, `planar.rs:211-267`, which finds each node's +degree-4 node (`split_saddle_corners`, `planar.rs:214-270`, which finds each node's segments through its own `Incidence`, the structure of step 3): 1. For each node with exactly four incident segments, read the four surrounding labels `nw, ne, sw, se`. 2. If both diagonals are a single face, or neither is (`(nw == se) == (ne == sw)`), there is nothing to read off the labels — the node is left as an ordinary junction - (`planar.rs:232-234`). + (`planar.rs:235-237`). 3. Otherwise, exactly one diagonal is a single face. The **other** face's two incident segments (`{right, below}` if `ne == sw`, `{left, below}` if `nw == se`) are given a - second copy of the node id, offset by `plane = (w+1)*(h+1)` (`planar.rs:214-215, + second copy of the node id, offset by `plane = (w+1)*(h+1)` (`planar.rs:217-218, 249-265`). The comment records the invariant this rests on precisely: `NE and SW being *one face* @@ -183,7 +183,7 @@ for the purposes of adjacency — able to move independently once stage 07 and 0 them. Which diagonal is "one face" is decided upstream of `build`, by `merge_saddle_faces` -(`lib.rs:1091`) when it runs, or simply by whatever `split_components`'s 4-connected +(`lib.rs:1066`) when it runs, or simply by whatever `split_components`'s 4-connected flood fill already produced. `build` itself makes no image-based judgement here — it only reads face ids. @@ -222,25 +222,25 @@ fn is_junction(segs_here: Option<&[usize]>) -> bool { } ``` -(`planar.rs:276-278`). Degree 4 is always treated as a junction rather than guessed at — +(`planar.rs:279-281`). Degree 4 is always treated as a junction rather than guessed at — "splitting there is always topologically safe, whereas picking a diagonal pairing can -weld two regions that should be separate" (`planar.rs:271-275`); what the split in step 2 +weld two regions that should be separate" (`planar.rs:274-278`); what the split in step 2 resolved no longer arrives here as degree 4. From every junction node, `build` walks each unused incident segment forward, following the unique unused segment at each intermediate degree-2 node, until it reaches another -junction (or runs out) (`walk_open_chains`, `planar.rs:286-354`). The resulting point +junction (or runs out) (`walk_open_chains`, `planar.rs:289-357`). The resulting point sequence becomes one open `Edge`, with `left`/`right` taken from the first segment's orientation at the starting junction. Any segment left unused after every junction has been walked belongs to a boundary loop with no junction anywhere on it at all — an isolated region such as a disc on a flat background. Those are walked separately and stored with `closed: true` -(`walk_closed_loops`, `planar.rs:360-411`); the walk is dropped if it has fewer than 3 +(`walk_closed_loops`, `planar.rs:363-414`); the walk is dropped if it has fewer than 3 points. Walk order is deterministic: junctions are visited in increasing node id, the order -`Incidence` holds them in (`planar.rs:294-296`), so a given label image always produces the +`Incidence` holds them in (`planar.rs:297-299`), so a given label image always produces the same edge list. ### 4. `face_edge_order` — per-face ring assembly @@ -249,7 +249,7 @@ same edge list. pub fn face_edge_order(map: &PlanarMap) -> Vec>> ``` -(`planar.rs:1272-1349`). For each face id, this returns +(`planar.rs:1233-1310`). For each face id, this returns one or more **rings** — a shape's outer boundary and any holes are separate rings — each a sequence of `(edge index, reversed)` pairs. @@ -258,23 +258,23 @@ It deliberately returns *references into the map*, not copied geometry: > "the same traversal works whatever alphabet the fitter used — polylines, cubics, or > later arcs and primitives — and, more importantly, every face that touches a boundary > names the same edge index. Nothing is copied, so the two sides of a boundary cannot -> drift apart." (`planar.rs:1261-1264`) +> drift apart." (`planar.rs:1222-1225`) Mechanically: every edge is filed under each face it touches, as `(edge index, reversed)` — `reversed = false` when the face is `left`, `true` when it is `right` -(`planar.rs:1273-1280`). Within one face, rings are assembled by chaining edges whose +(`planar.rs:1234-1241`). Within one face, rings are assembled by chaining edges whose start node (in the direction implied by `reversed`) matches the previous edge's end node, -via a `by_start: HashMap>` lookup (`planar.rs:1286-1348`). A ring closes +via a `by_start: HashMap>` lookup (`planar.rs:1247-1309`). A ring closes when the walk returns to its own starting node, at which point that repeated junction node is *not* re-emitted as a separate point — the ring is a cycle of edges, not of points, so the shared junction is implicit at the seam between the last edge and the first rather than appearing twice in the point list. A face id that is `u16::MAX`, or otherwise `>= map.n_labels`, is silently skipped when -edges are filed (`planar.rs:1275, 1278`) — this is how `inkvec-cli`'s layer-merging code +edges are filed (`planar.rs:1236, 1278`) — this is how `inkvec-cli`'s layer-merging code removes an edge from every ring without touching its geometry: setting both `left` and `right` to `u16::MAX` makes the edge "interior" and it drops out of `face_edge_order`'s -output entirely (`inkvec-cli/src/pipeline.rs:1116-1120`). +output entirely (`inkvec-cli/src/pipeline.rs:1115-1119`). ## Constants and thresholds @@ -304,7 +304,7 @@ saddle-merge decision: same face id) at exactly one pixel corner produces a single junction where two unrelated boundary arms are welded — "a fill pinched to nothing and reopened" — and this cannot be repaired downstream, because by the time curve fitting runs the topology is - fixed (`planar.rs:182-199`). The degree-4 split (step 2 above) exists specifically to + fixed (`planar.rs:185-202`). The degree-4 split (step 2 above) exists specifically to prevent it, but only fires when the two faces on one diagonal already share a face id. - **`merge_saddle_faces` is off by default.** The stage that decides, from the *image*, whether two diagonally-touching-but-currently-separate faces should be read as one @@ -315,18 +315,18 @@ saddle-merge decision: containment tree rewritten by a merge into the background rather than a wrong reading; the current source no longer carries that measurement. Practically, this means `build`'s degree-4 split logic mostly protects *self-touching* shapes that are already one face by ordinary 4-connectivity (the - `touching_corner` test case, `planar.rs:1365`) rather than two visually-touching shapes + `touching_corner` test case, `planar.rs:1326`) rather than two visually-touching shapes of matching colour that never got unioned upstream. A four-way corner where no diagonal shares a face id is left as an ordinary junction (`four_inks_meeting_at_a_corner_stay_a_junction`, - `planar.rs:1389`) — correct when the four regions really are four regions, and a + `planar.rs:1350`) — correct when the four regions really are four regions, and a missed merge when `INKVEC_SADDLE` (*research build*) would have said otherwise. - **Chain walking can stall.** If the list at the next node (`inc.end`) holds no unused candidate segment before a junction is reached, the walk simply stops there - (`planar.rs:324-331, 386-388`) rather than panicking; this silently produces a shorter + (`planar.rs:327-334, 386-388`) rather than panicking; this silently produces a shorter edge than the true boundary would warrant. No test in this module exercises that path directly. - **Loops under 3 points are dropped.** A junction-less closed walk with fewer than three - points is discarded (`planar.rs:393`) — degenerate single- or two-pixel islands that + points is discarded (`planar.rs:396`) — degenerate single- or two-pixel islands that cannot bound any area. ## Environment overrides @@ -348,7 +348,7 @@ None inside `planar::build` itself. The upstream decision that feeds it — corner-splitting logic fire on genuinely separate, same-coloured touching shapes rather than only self-touching ones. - `face_edge_order`'s ring assembly is exercised by the saddle-split test - (`splitting_gives_each_shape_its_own_copy_of_the_corner`, `planar.rs:1411`), which + (`splitting_gives_each_shape_its_own_copy_of_the_corner`, `planar.rs:1372`), which checks that both affected faces keep a non-empty ring, but there is no test in this file specifically constructing a face with a hole (an outer ring plus an inner ring) to check that the two rings are correctly separated rather than merged or lost. @@ -357,4 +357,4 @@ None inside `planar::build` itself. The upstream decision that feeds it — from both ends of every segment before either walk begins and `next_node` is always an end of an existing segment. The walks now read that node's list through `Incidence::end`, which returns it directly, so the dead branch is gone; the comment at the call site - records that `get` found every such node (`planar.rs:321-324`). + records that `get` found every such node (`planar.rs:324-327`). diff --git a/docs/algorithm/07-subpixel.md b/docs/algorithm/07-subpixel.md index 5a2483fa..04e2de07 100644 --- a/docs/algorithm/07-subpixel.md +++ b/docs/algorithm/07-subpixel.md @@ -4,12 +4,12 @@ > the image actually supports, and attaches an honest uncertainty to each one. **Source:** `crates/inkvec-trace/src/planar.rs`, `crates/inkvec-trace/src/planar/junctions.rs` -**Entry points:** `fn refine_subpixel_alpha()` (`planar.rs:468-477`; `refine_subpixel`, -`planar.rs:445`, is its opaque form), which is `measure_subpixel` (`planar.rs:528-603`) -followed by `Refined::apply` (`planar.rs:487-500`), stage mark `"refine_subpix"`; and +**Entry points:** `fn refine_subpixel_alpha()` (`planar.rs:461-470`; `refine_subpixel`, +`planar.rs:438`, is its opaque form), which is `measure_subpixel` (`planar.rs:521-596`) +followed by `Refined::apply` (`planar.rs:480-493`), stage mark `"refine_subpix"`; and `fn refine_junctions()` (`planar/junctions.rs:340`, stage mark `"refine_junc"`) **Pipeline position:** after `build_map`, before `boundary_opt`. The measuring phase runs -side by side with symmetry detection under `rayon::join` (`lib.rs:1122-1156`); both read the +side by side with symmetry detection under `rayon::join` (`lib.rs:1097-1131`); both read the lattice map and neither writes it, and the measured points are written back afterwards. Shared by Quality and Fast mode. @@ -44,7 +44,7 @@ pub fn refine_subpixel( Replaces every open and closed edge's `points` and `sigma`. `face_fill[f]` is the fill model for face `f` (`Flat` or a gradient) — not the palette entry, because several faces can share one ink and a gradient face has no single palette colour at all -(`planar.rs:718-720`). `refine_subpixel_alpha` takes the same arguments plus the source +(`planar.rs:711-713`). `refine_subpixel_alpha` takes the same arguments plus the source alpha and each face's opacity, for unmixing in four channels on a transparent image. Since 2026-09-30 the work is split in two phases: @@ -69,28 +69,28 @@ edge sharing a node keeps bit-identical coordinates afterwards (`planar/junction ### `refine_subpixel`: per-point normal search -For each edge point `p` (`planar.rs:793-839`): +For each edge point `p` (`planar.rs:788-839`): 1. **Local tangent.** Estimated from neighbours `window` points to either side (`INKVEC_SUBPX_WIN` (*removed*), default 1 — see Environment overrides), unless the turning angle - between the two chords exceeds `CORNER_COS` (60°, `planar.rs:424`), in which case the + between the two chords exceeds `CORNER_COS` (60°, `planar/chord.rs:15`), in which case the narrow one-point window is used instead so a wide window does not smear a real corner. The normal is perpendicular to the tangent. 2. **Unmix colours.** `gradient::unmix_pair(fa, fb, p.x, p.y)` (`gradient.rs:574`) returns the two colours to project against and their separation `contrast`. If `contrast` is below `min_contrast = max(3*sigma_noise, MIN_UNMIX_CONTRAST)` - (`planar.rs:414, 586`), the point is left on the grid at placeholder sigma `0.5` — there + (`planar.rs:417, 586`), the point is left on the grid at placeholder sigma `0.5` — there is nothing to unmix across. 3. **Sample coverage along the normal.** `UnmixAxis::coverage(x, y)` bilinearly samples the - source image and projects onto the unmixed colour axis (`planar.rs:620-647, 961-969`), + source image and projects onto the unmixed colour axis (`planar.rs:613-640, 961-969`), giving a 1-D coverage profile along the normal. 4. **Classify the profile and invert it.** Two inversion strategies: - - **Step inversion** (`edge_offset`, `planar.rs:1021-1031`): closed-form inversion of the + - **Step inversion** (`edge_offset`, `planar.rs:982-992`): closed-form inversion of the *exact* half-plane coverage of a unit square, used when the profile is `step_like` — both flat fills, monotone (not a one-pixel-wide ridge), saturating on both sides within the probe span, and contrast at least `2 * min_contrast` - (`planar.rs:1138-1175`). - - **Root-find** (`planar.rs:1180-1196`): a 9-step scan for the `0.5` crossing along the + (`planar.rs:1099-1136`). + - **Root-find** (`planar.rs:1141-1157`): a 9-step scan for the `0.5` crossing along the normal, `[-1, 1]` pixels either side of `p`, used otherwise — including at any corner, at any gradient boundary, or wherever the profile is not step-like. 5. **Positional uncertainty.** Combines statistical uncertainty @@ -99,7 +99,7 @@ For each edge point `p` (`planar.rs:793-839`): in quadrature, floors it at `crate::contour::SIGMA_FLOOR` (zero, so no floor), applies curvature inflation (`crate::contour::inflate_for_curvature`, shared with the bilevel front end — see stage 08/09 docs for that mechanism), and clamps to `[0.02, 2.0]` - (`planar.rs:1213-1256`). + (`planar.rs:1174-1217`). ### Measure, then apply: the parallel schedule @@ -107,11 +107,11 @@ The per-point search above reads only the image, the two faces' fills and its ow *original* points (its lattice neighbours, for the normal), and writes only its own result: it is a pure map over vertices. The curvature correction of a vertex's sigma then reads the edge's *moved* points, all of which are known by then: a pure map again. So since -2026-09-30 both run as parallel maps (`measure_subpixel`, `planar.rs:528-603`; -`refine_edge`, `planar.rs:697-759`): +2026-09-30 both run as parallel maps (`measure_subpixel`, `planar.rs:521-596`; +`refine_edge`, `planar.rs:690-752`): - **edges in parallel**, and, inside an edge of at least `PAR_VERTICES = 64` points - (`planar.rs:502-506`), **vertices in parallel too**, in chunks of at least 64, so a task + (`planar.rs:495-499`), **vertices in parallel too**, in chunks of at least 64, so a task is at least about 30 µs of work (0.44 µs per vertex measured at 2048 px) against rayon's few-µs cost per split. The second level matters because one edge can hold most of an image's vertices: longest edge 8,192 points, median edge 450, on the opaque `big` set; @@ -131,7 +131,7 @@ indexed outputs computes the serial result on every schedule; adapted to two nes with a minimum task size. The doc comment names Demmel & Nguyen, "Fast Reproducible Floating-Point Summation", ARITH 2013, as the related work behind the no-reductions rule; nothing here sums across vertices, so no reproducible summation is needed -(`planar.rs:537-567`). The serial loop is kept as `refine_serial` in +(`planar.rs:530-560`). The serial loop is kept as `refine_serial` in `planar/refine_tests.rs`, and `parallel_refinement_equals_the_serial_loop` compares points and sigmas bit for bit on anti-aliased scenes with flat and gradient fills, with and without the alpha channel, down to one pixel and one row. @@ -140,7 +140,7 @@ the alpha channel, down to one pixel and one row. vertex order, as before: - a small map: fewer than `PAR_MAP_VERTICES = 512` boundary vertices in all - (`refine_in_parallel`, `planar.rs:508-526`). Waking rayon's sleeping workers only pays + (`refine_in_parallel`, `planar.rs:501-519`). Waking rayon's sleeping workers only pays when there is enough to share; measured per icon (refinement and symmetry detection, the minimum of 3 interleaved runs, serial / parallel, ms): 512–1,024 vertices 0.263 / 0.206 (16 screen icons), 1,024–2,048 0.506 / 0.253 (187), 2,048–4,096 0.998 / 0.351 (43), @@ -152,7 +152,7 @@ vertex order, as before: order. The path is now read once per map (it was read per edge). The same `refine_in_parallel` test decides whether symmetry detection runs beside the -measuring phase under `rayon::join` or before it (`lib.rs:1148-1154`); on a single-thread +measuring phase under `rayon::join` or before it (`lib.rs:1123-1129`); on a single-thread build (WebAssembly) `join` runs the two in turn with no work added. Measured at 2048 px before the change, the refinement took 10.6 ms, serial, at 0.44 µs per vertex (shared-stage research, 2026-09-30). The shared stages that round rewrote (the ramp pass, the planar map @@ -160,6 +160,68 @@ and this refinement, plus the face-alpha pass on transparent images) went from 4 per 2048 px opaque image and from 130 to 21 ms per transparent one, output byte-identical in Fast and Quality; Quality gains the planar-map and refinement part too. +### The strip reading: exact column sums, before the probes + +Since 2026-10-10, a vertex between two flat fills with contrast of at least +`2 * min_contrast` (and not on an alpha axis) is first read by `planar/strip.rs` +(`strip_offset`, tried in `refine_vertex` before `probe_pixel_centres`). The per-point probes +below decide only where it declines. + +It rests on three theorems proved in Lean in `formal/InkvecTheory` (see +[`docs/theory`](../theory/README.md)): + +* **A column's coverages sum to the boundary's mean height over the column** + (`column_sum_eq_average`), for any boundary that is a graph over the column, whatever its + slope or curvature. No normal, threshold or interpolation enters. This is the identity of + volume-of-fluid reconstruction (Puckett 2010) and of the partial-area edge detector + (Trujillo-Pino et al. 2013). +* **Four adjacent column means determine a unique cubic** (`poly_eq_of_averages`), and + `histopolate`'s rational constants return it exactly (`histopolate_cubic`). +* **The ½-crossing of interpolated coverage is biased by up to `3/2 − √2 ≈ 0.086 px`** on a + straight edge (`levelSetBias_max`), the reading the root-find and the two-probe bracket use. + +The procedure (`strip_along`): + +1. Columns are read when the lattice normal is nearer vertical (the boundary is then a graph + over x), rows otherwise; when one axis declines the other is tried. +2. In each of the six columns whose centres lie within 2.5 px of the vertex's pixel border, + `line_mean` finds the window from a pixel saturated in one face (unmixed coverage within + `SATURATED` = 0.06 of 0 or 1) to the nearest pixel saturated in the other, with only + partial pixels between, and sums the window's coverages *unclamped*, flanks included + (`UnmixAxis::coverage_unclamped`). Summing the flanks' own values keeps the sum unbiased + under noise (`strip_unbiased`). A pixel whose colour lies more than + `max(4σ, 0.06·contrast, 2/255)` off the line between the two faces' colours (a third + colour, a junction) voids its window. Columns are read from the vertex outwards, each + searched within `REACH` = 3 px of its inner neighbour's mean, so a 45° boundary is followed. +3. The orientation (which face is on the low side) must agree across the six, and adjacent + means may differ by at most `MAX_STEP` = 1.5 px. +4. The cubic through the four central means is histopolated. The cubics through the left + four and the right four must agree with it at the vertex's border to within + `SIDE_TOL` = 0.05 px: every cubic passes (`side_stencil_cubic`), a corner within reach + does not. +5. The vertex slides along its lattice normal onto the cubic (Newton, at most 8 steps, + declining if the normal runs within about 17° of the cubic's tangent or the shift exceeds + 1 px). The edge keeps one point per vertex; the vertex's sigma is computed as before. +6. The shift is certified: a checker generated from the Lean definition its theorem is + about (`stripResidual_on_cubic`; `crates/inkvec-verified`) evaluates the residual + `q(s₀ + t·n_u) − t·n_v` in outward-rounded intervals and accepts the shift only if it is + provably within `CERT_TOL` = 1e-9 px of zero for the exact real numbers. The cubic + stencil `histopolate` is the generated one too, bit for bit the formula it replaced + (`docs/theory/verification.md`). + +Measured, stage-07 points against exactly known geometry (`bench/theory/inkvec_compare.py`: +circles, ellipses, straight edges at random angles, rotated squares and regular polygons, +64 px, 8-bit), distance to the true boundary in px: + +| renderer | before: mean / p99 / max | after: mean / p99 / max | +|---|---|---| +| exact area coverage | 0.0734 / 0.319 / 0.516 | 0.0106 / 0.180 / 0.368 | +| 8x8 point supersampling | 0.0732 / 0.318 / 0.443 | 0.0159 / 0.194 / 0.351 | + +The tail that remains is vertices the strip reading declines (corners, junctions, windows a +third colour enters). The regression gate's verdict is under *Measurements* in +[`docs/theory`](../theory/README.md#5-what-changed). + ### The exact inversion, and why it replaced a biased root-find The step-inversion path (`edge_offset`) is the more heavily documented piece of this @@ -170,29 +232,29 @@ measurements that justified each change: systematically pulled every edge towards the `.0`/`.5` grid: "interpolating from a pure neighbour (alpha 0) to the partial pixel (alpha 0.67) puts the 0.5 crossing at 0.25 of the way, not 0.33" — measured 0.19px off on straight runs, 2.5% of ink missing on a - Material icon whose edges fall at multiples of 5.33px (`planar.rs:1047-1053`). + Material icon whose edges fall at multiples of 5.33px (`planar.rs:1008-1014`). - **The chord-length fix.** Coverage changes with the chord length the normal cuts through a pixel per unit of edge movement (`1` on an axis, `sqrt(2)` on a diagonal), so the edge sits at `(alpha - 0.5) / chord` from the centre, with `chord = 1 / max(|nx|, |ny|)` - (`planar.rs:1054-1056`). Dividing by `max` rather than the alternative was itself measured: + (`planar.rs:1015-1017`). Dividing by `max` rather than the alternative was itself measured: the wrong denominator "pushed every diagonal and curved edge out by up to 2x: rounded - outlines came back uniformly fat" (`planar.rs:1057-1058`). + outlines came back uniformly fat" (`planar.rs:1018-1019`). - **The quadratic correction.** That linear rule is exact only for an axis-aligned edge. At 45°, a pixel's coverage curve is quadratic throughout, and the linear rule put a 90%-covered pixel's edge at 0.57px from centre where the truth is 0.39 — "slanted - strokes came out fat by 0.1-0.2px" (`planar.rs:1062-1063`). `edge_offset` therefore + strokes came out fat by 0.1-0.2px" (`planar.rs:1023-1024`). `edge_offset` therefore inverts the *exact* half-plane coverage of a unit square rather than a linear - approximation (`planar.rs:1021-1031`). + approximation (`planar.rs:982-992`). - **Bracketing, not averaging.** Only the two probes that straddle the `0.5` crossing are used; averaging in a third, already-saturated probe was measured to pull a point half a pixel into a stroke under two pixels wide, because the far probe's partial coverage came - from the stroke's *other* edge (`planar.rs:1088-1092`). + from the stroke's *other* edge (`planar.rs:1049-1053`). - **Why the root-find survives at all.** A soft boundary (two gradient bands, a shadow edge) is a ramp, not a step, and reading it as a step "throws the point up to a pixel off" (synthetic gradients 0.15 → 0.35 dE00 when the step inversion was applied there, - `planar.rs:1145-1151`). A one-pixel stroke is a ridge with background on both sides, and + `planar.rs:1106-1112`). A one-pixel stroke is a ridge with background on both sides, and reading a ridge as a step likewise throws the point out (synthetic `thin_features` 0.91 - → 3.00 dE00, `planar.rs:1152-1155`). The `monotone` test excludes both (`planar.rs: + → 3.00 dE00, `planar.rs:1113-1116`). The `monotone` test excludes both (`planar.rs: 1156-1161`), and `both_flat` additionally excludes gradient boundaries, where the unmixing colours are only the model's local *prediction* and a small model error misplaces an inverted edge (colour families +0.015 dE00 when the inversion was applied @@ -201,7 +263,7 @@ measurements that justified each change: Two switches this history left behind are recorded as no longer switchable: `INKVEC_SUBPX_MODE=inv` (*removed*) (force step-inversion everywhere) and `=root` (force root-find everywhere) were both measured worse than the classifier and are dead code paths in -intent even though the comments describing them remain (`planar.rs:1084-1086, 1166-1167`). +intent even though the comments describing them remain (`planar.rs:1045-1047, 1166-1167`). ### Corpus intake and 8x supersampling @@ -218,14 +280,14 @@ grid was produced. The one *runtime* mechanism that reasons about raster resolution is `coverage::intake_scale` (`coverage.rs:832-882`), which measures how many raster pixels one unit of genuine edge detail occupies and is used upstream (in -`trace_color_full_with_alpha`, `lib.rs:358`) to decide whether the *palette's* noise +`trace_color_full_with_alpha`, `lib.rs:360`) to decide whether the *palette's* noise guard should widen its same-ink tolerance — not to change anything in `refine_subpixel` itself. `refine_subpixel` runs identically regardless of `intake_scale`. ### `simplify_faint`: spending coordinates where they can be seen Positional uncertainty at each point is inflated below a reference contrast when -`--simplify-faint` is set (`planar.rs:1225-1252`): +`--simplify-faint` is set (`planar.rs:1186-1213`): ```rust const CONTRAST_REF: f64 = 0.25; @@ -240,7 +302,7 @@ let visibility = if simplify_faint { This follows directly from the `sigma = sigma_pixel / (|F-B| * |grad a|)` relation in `coverage.rs:30` — contrast (`|F-B|`) already appears in the denominator of the *statistical* uncertainty term computed a few lines above (`s = (sigma_noise / contrast) / -g`, `planar.rs:1224`), so a faint boundary is already measured with wider uncertainty than +g`, `planar.rs:1185`), so a faint boundary is already measured with wider uncertainty than a crisp one. `simplify_faint`'s inflation is a second, independent adjustment layered on top, and the doc comment is explicit about why it is a separate knob rather than folded into the physical sigma: @@ -250,7 +312,7 @@ into the physical sigma: > 7%, the tracer spent 100 and 103 segments. That is the right answer to 'where is the > boundary' and the wrong answer to 'how much description is this boundary worth': the > error a viewer sees is the position error times the contrast across it, so at a tenth of -> the contrast a coordinate buys a tenth of the visible accuracy." (`planar.rs:1228-1234`) +> the contrast a coordinate buys a tenth of the visible accuracy." (`planar.rs:1189-1195`) In other words: the physical sigma answers *how precisely is this point located*; `simplify_faint`'s visibility multiplier answers *how much does mislocating it matter*, @@ -266,7 +328,7 @@ It ships **off by default**, and the doc comment is candid about why: > "the corpus disagrees with the argument: on the 246-icon screen set it saves 0.3% of the > parameters and costs 0.2% of the colour error, objective 0.3992 -> 0.4023. Those icons > are high-contrast art where the faint case barely arises, and the metric sees the loss -> and not the gain — the same blindness that keeps `--cutout` off." (`planar.rs:1240-1244`) +> and not the gain — the same blindness that keeps `--cutout` off." (`planar.rs:1201-1205`) ### `refine_junctions`: why a junction cannot be refined like an edge point @@ -321,14 +383,18 @@ them, so the edge does not double back through itself (`planar/junctions.rs:407- | name | value | controls | derivation | |---|---|---|---| -| `MIN_UNMIX_CONTRAST` (`planar.rs:414`) | `0.02` | floor on unmixing contrast below which a point is not moved at all | no stated derivation | -| `CORNER_COS` (`planar.rs:424`) | `0.5` (60°) | turning angle above which the tangent window narrows to 1 point | stated: "A staircase at any slope turns by at most 45 degrees between chords two points long, so slanted edges stay smooth" (`planar.rs:421-423`) — a geometric bound, not a sweep | -| `PAR_VERTICES` (`planar.rs:506`) | `64` | fewest points an edge needs before its vertices are refined in parallel, and the smallest chunk of a long edge one thread takes | motivated by a measured cost: a task of at least ~30 µs (0.44 µs per vertex at 2048 px) against rayon's few-µs cost per split (`planar.rs:502-505`); chooses only the schedule, never the result | -| `PAR_MAP_VERTICES` (`planar.rs:520`) | `512` | fewest boundary vertices in the whole map for the refinement (and symmetry detection beside it) to use threads at all | measured: per-icon serial / parallel timings by vertex count, parallel already ahead in the smallest bucket (512–1,024: 0.263 / 0.206 ms), so the cutoff sits at its lower end (`planar.rs:508-519`); chooses only the schedule, never the result | -| `INKVEC_SUBPX_WIN` (*removed*) (`planar.rs:416-419`) | default `1`, range `1..=8` | width of the tangent-estimation window | measured trade-off: widening to 2 improved dE00 0.2663→0.2534 on a 620-icon subset but cost DISTS 0.0418→0.0435 and caused a face-order regression on one icon (0.23→3.20 dE00); default left at 1 "until that is understood (LOG-43)" (`planar.rs:854-864`) | +| `MIN_UNMIX_CONTRAST` (`planar.rs:417`) | `0.02` | floor on unmixing contrast below which a point is not moved at all | no stated derivation | +| `CORNER_COS` (`planar/chord.rs:15`) | `0.5` (60°) | turning angle above which the tangent window narrows to 1 point | stated: "A staircase at any slope turns by at most 45 degrees between chords two points long, so slanted edges stay smooth" (`planar/chord.rs:12-14`) — a geometric bound, not a sweep | +| `PAR_VERTICES` (`planar.rs:499`) | `64` | fewest points an edge needs before its vertices are refined in parallel, and the smallest chunk of a long edge one thread takes | motivated by a measured cost: a task of at least ~30 µs (0.44 µs per vertex at 2048 px) against rayon's few-µs cost per split (`planar.rs:495-498`); chooses only the schedule, never the result | +| `PAR_MAP_VERTICES` (`planar.rs:513`) | `512` | fewest boundary vertices in the whole map for the refinement (and symmetry detection beside it) to use threads at all | measured: per-icon serial / parallel timings by vertex count, parallel already ahead in the smallest bucket (512–1,024: 0.263 / 0.206 ms), so the cutoff sits at its lower end (`planar.rs:501-512`); chooses only the schedule, never the result | +| `INKVEC_SUBPX_WIN` (*removed*) (`planar/chord.rs:7-10`) | default `1`, range `1..=8` | width of the tangent-estimation window | measured trade-off: widening to 2 improved dE00 0.2663→0.2534 on a 620-icon subset but cost DISTS 0.0418→0.0435 and caused a face-order regression on one icon (0.23→3.20 dE00); default left at 1 "until that is understood (LOG-43)" (`planar/chord.rs:47-58`) | +| `REACH` (`planar/strip.rs`) | `3` px | how far along a column the strip reading searches for a window's flanks, from the inner neighbour's mean | geometric: a boundary within 45° of the column's normal crosses at most two pixels of it | +| `SATURATED` (`planar/strip.rs`) | `0.06` | unmixed coverage within this of 0 or 1 makes a pixel a window flank | not swept; the flanks' own values are summed, so a near-saturated pixel classed as a flank costs nothing in bias (`strip_unbiased`) | +| `SIDE_TOL` (`planar/strip.rs`) | `0.05` px | largest disagreement at the vertex's border between the central and the one-sided cubics before the strip reading declines (the corner test) | each one-sided difference carries 0.7× the noise of one column mean; every cubic passes exactly (`side_stencil_cubic`); a 45° turn at the border moves it by 0.04 px, so gentler corners are rounded, by up to about 0.1 px | +| `MAX_STEP` (`planar/strip.rs`) | `1.5` px | largest difference between adjacent column means: the steepest boundary the strip reading follows, about 56° | not swept | | `DEFAULT_SIGMA_MODEL` (`coverage.rs:81`) | `0.05` px | irreducible resolution limit of level-set extraction, added in quadrature to statistical noise | stated: "Measured on analytic circles..., level-set extraction lands within roughly 0.05px" (`coverage.rs:104-105`) | -| `CONTRAST_REF` (`planar.rs:1246`) | `0.25` | reference contrast for `simplify_faint`'s inflation | no stated derivation | -| `MAX_INFLATION` (`planar.rs:1247`) | `4.0` | cap on `simplify_faint`'s sigma multiplier | no stated derivation | +| `CONTRAST_REF` (`planar.rs:1207`) | `0.25` | reference contrast for `simplify_faint`'s inflation | no stated derivation | +| `MAX_INFLATION` (`planar.rs:1208`) | `4.0` | cap on `simplify_faint`'s sigma multiplier | no stated derivation | | `JUNCTION_MAX_MOVE` (`planar/junctions.rs:73`) | `1.5` px | reject an intersection solution beyond this move | no stated derivation: the doc comment says only "Farthest a junction may move from its grid node before the solution is distrusted" (`planar/junctions.rs:72`). Earlier revisions recorded a rejected 0.5 px limit (one test phase 0.178px → 1.006px residual); the current source no longer does | | `JUNCTION_MIN_CONDITION` (`planar/junctions.rs:78`) | `0.02` | minimum eigenvalue ratio admitted for a junction intersection | stated as equivalent to rejecting crossings below about 16°, from `tan^2(theta/2)` (`planar/junctions.rs:75-77`) | | `junction_fit_points()` (`planar/junctions.rs:36`) | `6` | interior points used for the near-junction extrapolation | no stated derivation | @@ -348,8 +414,17 @@ them, so the edge does not double back through itself (`planar/junctions.rs:407- ## Failure modes and edge cases +- **The seam of a closed ring was never refined** (fixed 2026-10-10). `probe_chord` clamped + its neighbour indices at the ends of an edge, and a closed edge stores its first point + once, so the first and last vertices of every closed ring took their chord from one + neighbour. On a ring whose seam lies on a horizontal run that is a horizontal normal on a + horizontal boundary: the probe ran along the boundary and the vertex stayed on the + lattice, 0.30 px off on an exactly rendered disc. Quality's boundary solve repaired it; + Fast mode kept it. The chord now wraps round the seam of a closed edge. On the gate the + fix alone is within noise everywhere (the corpus's closed rings mostly start at a + junction or a corner); on exact discs it removes the worst stage-07 point. - **`refine_subpixel`'s misclassification cost is asymmetric and recorded exactly once - each way.** Every branch of the `step_like` classifier (`planar.rs:1168-1174`) exists + each way.** Every branch of the `step_like` classifier (`planar.rs:1129-1135`) exists because the *other* choice was tried and measured worse on a named case (gradients, thin features, script wordmarks — see How it works above). There is no held-out ablation covering all combinations at once. @@ -372,11 +447,11 @@ Since the settings cleanup (CHANGELOG, 0.2.0, *Changed*) the engine reads its en | variable | effect | |---|---| -| `INKVEC_SUBPX_WIN` (*removed*) | tangent-window width for `refine_subpixel`, `1..=8`, default `1` (`planar.rs:416-418`) | -| `INKVEC_SUBPXDBG` | per-point debug trace of the subpixel search; read once per map into the refinement context (`planar.rs:588`), and while set the whole refinement runs serially, in edge and vertex order, so the lines come out as before (`planar.rs:591`) | +| `INKVEC_SUBPX_WIN` (*removed*) | tangent-window width for `refine_subpixel`, `1..=8`, default `1` (`planar/chord.rs:7-10`) | +| `INKVEC_SUBPXDBG` | per-point debug trace of the subpixel search; read once per map into the refinement context (`planar.rs:581`), and while set the whole refinement runs serially, in edge and vertex order, so the lines come out as before (`planar.rs:584`) | | `INKVEC_SIGMA_FLOOR` (*removed*) | overrode the sigma floor shared with the bilevel front end; now the constant `contour::SIGMA_FLOOR`, zero (`contour.rs:325-327`) | | `INKVEC_CURV_GAIN` (*removed*) | overrode the curvature gain `inflate_for_curvature` uses; now the constant `NONLINEARITY_GAIN = 0.35`, chosen by sweep (`contour.rs:248-261`) | -| `INKVEC_DUMP_CONTOUR` | appends every refined edge's points and sigmas to a file, for offline study of extraction error structure (`dump_contour`, `planar.rs:769-781`); the path is read once per map (`planar.rs:589`; it used to be read per edge), and while it is set the refinement runs serially so the file keeps edge order | +| `INKVEC_DUMP_CONTOUR` | appends every refined edge's points and sigmas to a file, for offline study of extraction error structure (`dump_contour`, `planar.rs:762-774`); the path is read once per map (`planar.rs:582`; it used to be read per edge), and while it is set the refinement runs serially so the file keeps edge order | | `INKVEC_NO_TAPER` | disables `taper_junction` (`planar/junctions.rs:490-491`); read once per process into a `OnceLock` through `inkvec_core::env::flag`, so an empty value counts as unset | | `INKVEC_TAPERDBG` | per-node taper fit debug trace; read once per process into a `OnceLock` (`taperdbg`, `planar/junctions.rs:66-70`) | | `INKVEC_TAPER_SKIP=` (*removed*) | skipped the n-th accepted taper relocation, to attribute a corpus-level change to one junction; nothing reads it now | diff --git a/docs/algorithm/08-boundary-solve.md b/docs/algorithm/08-boundary-solve.md index 1e2edc29..e231f880 100644 --- a/docs/algorithm/08-boundary-solve.md +++ b/docs/algorithm/08-boundary-solve.md @@ -12,12 +12,12 @@ guard), `boundary_opt/band.rs` (the data term, and the memory budget of its tabl pipeline through `optimise_for()` (`boundary_opt.rs:598-611`); `optimise_alpha()` (`boundary_opt.rs:583-591`) is it without an iteration cap and `optimise()` (`boundary_opt.rs:565-572`) the same without alpha -**Pipeline position:** after `refine_junc` (`planar::refine_junctions`, `lib.rs:1158`), -before `decode` (stage mark `"boundary_opt"`, `lib.rs:1167`). Called once, in -`finish_color_trace_alpha` (`optimise_for`, `lib.rs:1166`), the geometry tail every colour entry point -shares: the opaque Quality path (`trace_color_full_with_alpha` through `finish_color_trace`, -`lib.rs:740`), the native-alpha path (`native::trace_color`, `native.rs:1001`, the only -caller that passes the source alpha) and `trace_color_from_labels` (`lib.rs:994`). Skipped +**Pipeline position:** after `refine_junc` (`planar::refine_junctions`, `lib.rs:1133`), +before `decode` (stage mark `"boundary_opt"`, `lib.rs:1142`). Called once, in +`finish_color_trace_alpha` (`optimise_for`, `lib.rs:1141`), the geometry tail every colour entry point +shares: the opaque Quality path (`trace_color_full_with_alpha`, +`lib.rs:742`), the native-alpha path (`native::trace_color`, `native.rs:1001`, the only +caller that passes the source alpha) and `trace_color_from_labels` (`lib.rs:999`). Skipped when `opts.fast` is set without an iteration cap (Fast mode reaches the same function from `fast/front.rs:154`) or when `INKVEC_BOPT=0` (`boundary_opt.rs:605-608`); `--mode balanced` sets `ColorOptions::boundary_iters` to 8 and runs it capped at 8 iterations per part diff --git a/docs/algorithm/09-decode.md b/docs/algorithm/09-decode.md index 6c180f71..5482c7e0 100644 --- a/docs/algorithm/09-decode.md +++ b/docs/algorithm/09-decode.md @@ -6,11 +6,11 @@ **Source:** `crates/inkvec-trace/src/decode.rs` **Entry point:** `decode_faces()` (`decode.rs:559`) -**Pipeline position:** after `boundary_opt` (stage mark `"boundary_opt"`, `lib.rs:1167`), -before `symmetry` enforcement (stage mark `"decode"`, `lib.rs:1189`). Called only from +**Pipeline position:** after `boundary_opt` (stage mark `"boundary_opt"`, `lib.rs:1142`), +before `symmetry` enforcement (stage mark `"decode"`, `lib.rs:1164`). Called only from `finish_color_trace_alpha`, the geometry tail every colour entry point shares, outside Fast mode, and only when `INKVEC_DECODE` (*research build*) is set to something other than -`"0"` (`lib.rs:1177`) — **off by default**. +`"0"` (`lib.rs:1152`) — **off by default**. ## What problem this solves @@ -53,7 +53,7 @@ second, and decides arc count last, by dynamic programming, in `inkvec-fit`. **Input:** the `PlanarMap` (mutated in place), the rendered image `rgb: &[[f32; 3]]`, the integer `labels: &[u16]` map, `face_fill: &mut [FillFit]` (`gradient.rs:308-318`), and `lambda: f64` — supplied by the caller as `gradient::bic_lambda(width * height)` -(`lib.rs:1183`), the Bayesian-information-criterion choice `0.5 * ln(n)` +(`lib.rs:1158`), the Bayesian-information-criterion choice `0.5 * ln(n)` (`gradient.rs:325-327`). This is a *different* lambda from the one `candidate_orders` and `fitted_params` use internally (`FitConfig::from_precision`, described below) — the two serve different comparisons and are not interchangeable. @@ -452,7 +452,7 @@ Since the settings cleanup (CHANGELOG, 0.2.0, *Changed*) the engine reads its en | variable | default | effect | |---|---|---| -| `INKVEC_DECODE` (*research build*) | off (`"0"` or unset) | master switch — the whole stage is skipped unless set to something other than `"0"` (read in `lib.rs:1177`, not in this file) | +| `INKVEC_DECODE` (*research build*) | off (`"0"` or unset) | master switch — the whole stage is skipped unless set to something other than `"0"` (read in `lib.rs:1152`, not in this file) | | `INKVEC_DECODE_MS` (*research build*) | `600.0` ms | time budget for the per-face loop | | `INKVEC_DECODE_LEAK` (*research build*) | `LEAK_GATE = 0.05` | overrides the (diagnostic-only) leak threshold | | `INKVEC_DECODE_THIN` (*research build*) | `THIN_PX = 2.5` | overrides the width threshold that gates whether a face is attempted | diff --git a/docs/algorithm/10-symmetry.md b/docs/algorithm/10-symmetry.md index 2690a83b..37fdd23d 100644 --- a/docs/algorithm/10-symmetry.md +++ b/docs/algorithm/10-symmetry.md @@ -5,15 +5,15 @@ > boundary point back into exact agreement. **Source:** `crates/inkvec-trace/src/symmetry.rs` (565 lines) -**Entry points:** `fn detect()` (`symmetry.rs:293`, called at `lib.rs:1150-1154` and timed -under the stage mark `"refine_subpix"`, `lib.rs:1156`) and `fn enforce()` (`symmetry.rs:342`, -stage mark `"symmetry"`, `lib.rs:1194-1199`) +**Entry points:** `fn detect()` (`symmetry.rs:293`, called at `lib.rs:1125-1129` and timed +under the stage mark `"refine_subpix"`, `lib.rs:1131`) and `fn enforce()` (`symmetry.rs:342`, +stage mark `"symmetry"`, `lib.rs:1169-1174`) **Pipeline position:** `detect` runs right after `build_map`, *beside* the measuring phase of the sub-pixel refinement: on a map of at least 512 boundary vertices the two run side by side under `rayon::join`, on a smaller one `detect` runs first and the refinement after it, on -the same thread (`lib.rs:1122-1154`). The measured points are written back only once both -have returned (`lib.rs:1155`). `enforce` runs last of all, after `decode` -(`lib.rs:1189-1199`). Since 2026-09-30 the `"symmetry_detect"` mark (`lib.rs:1121`) times +the same thread (`lib.rs:1097-1129`). The measured points are written back only once both +have returned (`lib.rs:1130`). `enforce` runs last of all, after `decode` +(`lib.rs:1164-1174`). Since 2026-09-30 the `"symmetry_detect"` mark (`lib.rs:1096`) times only the setup of the refinement's inputs; detection's time is reported with the refinement's. Shared by Quality and Fast mode. @@ -50,7 +50,7 @@ pub fn detect(map: &PlanarMap, labels: &[u16], ink: &[usize]) -> Symmetry per-connected-component, and a symmetric shape's two mirrored halves are never the same component; comparing face ids directly would reject every real symmetry there is (`symmetry.rs:160-162`). In the pipeline this is `face_color` — the palette entry each -face was cut from (`lib.rs:1151`, `:1153`). +face was cut from (`lib.rs:1126`, `:1153`). ```rust pub struct Symmetry { @@ -144,7 +144,7 @@ support." (`symmetry.rs:333-335`) ### Why detection happens early and enforcement happens last `detect` is run once, immediately after `build_map`, "on the lattice the extractor -produced, where the comparison is exact" (`lib.rs:1123-1124`) — it has to see the map +produced, where the comparison is exact" (`lib.rs:1098-1099`) — it has to see the map before any sub-pixel refinement moves points off that exact lattice, or the point-identity matching in `pair_edges` would need a tolerance instead of exact equality. @@ -153,7 +153,7 @@ starts. The refinement was split into a measuring phase, which reads the lattice writes nothing (`planar::measure_subpixel`), and a write-back (`Refined::apply`). Detection and the measuring phase both only read the map, so they run side by side under `rayon::join`, and the moved points are applied after both have returned -(`lib.rs:1122-1155`): +(`lib.rs:1097-1130`): ```rust let (sym, refined) = if planar::refine_in_parallel(&map) { @@ -240,7 +240,7 @@ differently. `crates/inkvec-cli/src/mirror_fit.rs` fits such a boundary on one side of the axis and reflects the result. `pipeline::fit_boundaries` calls `mirror_fit::choose` -(`crates/inkvec-cli/src/pipeline.rs:726-735`) for every edge `self_mirrors` names: +(`crates/inkvec-cli/src/pipeline.rs:725-734`) for every edge `self_mirrors` names: 1. **The ordinary fit, when it is already symmetric** (every anchor's reflection is an anchor, to 1e-6 px; `choose`, `mirror_fit.rs:217-236`). The program finds the @@ -315,7 +315,7 @@ this solves" above. wordmark rather than across the whole canvas) is out of scope for this stage entirely. - **The ordering hazard** described above (a stage between `detect` and `enforce` overwritten by `enforce`) is a live property of the current pipeline (`boundary_opt`, - `decode` both run in that window, `lib.rs:1158-1189`) and is not defended against by any + `decode` both run in that window, `lib.rs:1133-1164`) and is not defended against by any assertion; it is simply accepted as the intended behaviour, per the "Put it back" comment at the `enforce` call site. diff --git a/docs/algorithm/11-fitting.html b/docs/algorithm/11-fitting.html index 88cef8b7..ba38f14d 100644 --- a/docs/algorithm/11-fitting.html +++ b/docs/algorithm/11-fitting.html @@ -211,6 +211,18 @@

Passes that clean up afterwards, on by default and off by default

The rough candidates also share most of their arithmetic, which is now done once and reused. Neither change alters a single number in the output; the drawing is the same to the last bit, it just arrives sooner.

+

A third pass moves the joins between curves to where a designer would put them. Type + designers and icon artists place a curve's points at its top, bottom, left and right, + where the curve runs exactly horizontal or vertical, so that every handle an editor + shows there points straight along an axis; Adobe's specification for its fonts has + asked for this since 1990. The fitter had no reason to: it puts a join wherever a + measured point happens to lie, and moving a join along a smooth curve hardly changes + the drawing. The pass offers, for every smooth stretch, the same stretch with its joins + at those extreme points and every join smooth, and keeps it only where the fitter's + own measure of fit and economy prefers it. A join at an extreme point is credited for + the one number it no longer has to write: its direction. On the 246 test icons this + moved the trace closer to the artists' files on the gate's own measures (see the + reference document), without writing a single number more or fewer.

Two more exist in the code but are built only into research versions of the program, never into a release. One would snap a line to be perfectly horizontal or vertical when the measurement genuinely cannot tell it apart from one — real drawings do this diff --git a/docs/algorithm/11-fitting.md b/docs/algorithm/11-fitting.md index 83be90d0..539ce9fb 100644 --- a/docs/algorithm/11-fitting.md +++ b/docs/algorithm/11-fitting.md @@ -11,13 +11,13 @@ program), `multimodel.rs` and `multimodel/scan.rs` (the dynamic program), `candi post-fit passes), `choice.rs` (curve or primitive), `simple.rs` (self-crossing test). **Entry point:** `optimal_multimodel()` (`crates/inkvec-fit/src/multimodel.rs:205`), called for every boundary of the colour path from `fit_boundaries` -(`crates/inkvec-cli/src/pipeline.rs:659`) through `inkvec_fit::choice::describe` +(`crates/inkvec-cli/src/pipeline.rs:658`) through `inkvec_fit::choice::describe` (`pipeline.rs:720-744`), and for strokes from `crates/inkvec-cli/src/strokes.rs:263`. **Pipeline position:** after decode and symmetry enforcement (stages 9–10), before repair -(stage 12). Stage mark `"fit_dp"` (`crates/inkvec-cli/src/pipeline.rs:495`, in +(stage 12). Stage mark `"fit_dp"` (`crates/inkvec-cli/src/pipeline.rs:494`, in `fit_and_repair`). -The crate's own overview (`crates/inkvec-fit/src/lib.rs:1-58`) lists the seven steps of the +The crate's own overview (`crates/inkvec-fit/src/lib.rs:1-58`) lists the eight steps of the shipping fit in order; this page follows them and adds what the code comments measured. ## What problem this solves @@ -118,7 +118,7 @@ precision, `tau = 2.0`. In the shipping CLI, `extent` is the intake raster's `max(width, height)` in pixels, and `precision`/`tau` come from `--precision` (default `0.1`) and `--tau` (default `2.0`) -(`crates/inkvec-cli/src/args.rs:248-249`), combined in `fit_config` +(`crates/inkvec-cli/src/args.rs:249-250`), combined in `fit_config` (`crates/inkvec-cli/src/units.rs:92-105`). Under `--content-units`, `fit_config` multiplies `precision` by the content scale `s` before deriving `lambda` and then multiplies `lambda` by `s` again; see `01-intake.md`. @@ -516,6 +516,7 @@ polyline the fit was computed against: if max_span == usize::MAX { crate::merge::merge_free_cubics(&mut fit.path, shifted, &fit.vertices, cfg); crate::merge::sharpen_corners(&mut fit.path); + crate::extrema::anchor_extrema(&mut fit.path, shifted, cfg, crate::extrema::FIT); #[cfg(feature = "research")] { if research::axis() { crate::merge::snap_axis_aligned(/* ... */); } @@ -529,6 +530,7 @@ if max_span == usize::MAX { |---|---|---| | `merge_free_cubics` | **on** | every uncapped fit (`max_span == usize::MAX`) | | `sharpen_corners` | **on** | same | +| `anchor_extrema` (`extrema.rs`) | **on** | same; see *Nodes at extrema* below | | `snap_axis_aligned` | **off** | compiled only with `--features research` (`merge.rs:811-816`), and then only with `INKVEC_AXIS` set | | `snap_smooth_joins` | **off** | research builds only, with `INKVEC_G1` set | | structural simplifier | **off** | research builds only, with `INKVEC_STRUCTURAL` set | @@ -656,6 +658,114 @@ straight edge with a chamfer cubic at each end (chord ≤ `SHARPEN_MAX_EDGE = 8. (`merge.rs:565-574`). `SHARPEN_MIN_TURN` *is* `crate::CORNER_TURN_MIN` (`merge.rs:575-580`): "They were independent copies of `PI / 6.0` until 2026-09-08." +### Nodes at extrema: `extrema.rs` + +`anchor_extrema` (`extrema.rs`) runs after `sharpen_corners` on every uncapped fit, on the +same centred polyline. It re-segments each smooth run of the fitted path so that its nodes sit +where the curve is horizontal or vertical and its joins are smooth, wherever the fit's own +objective prefers that. + +**The convention.** Type designers and icon artists put a curve's on-curve points at its x and +y extrema. Adobe's *Type 1 Font Format* (1990), §4.1 "Points at Extremes": an endpoint "should +be placed at most horizontal or vertical extremes. This implies that most curves should not +include more than 90 degrees of arc"; §4.2 "Tangent Continuity": at a smooth transition the +node and the control points either side "should all be collinear. This is especially important +at horizontal and vertical extremes". Font editors check for it (FontLab's "nodes at extremes", +with a 1° tolerance). At a smooth node the handles lie along the tangent, and the tangent is +horizontal or vertical exactly where the curve has a y or an x extremum, so nodes at extrema and +axis-aligned handles are one convention. Measured with the human battery +(`bench/human_stats.py`, definitions in `bench/inkvec_bench/design.py`) on the 246-icon screen +set at 512 px on white, family-macro means: + +| battery statistic | artists' files | trace before | trace now | `--editability` before | `--editability` now | +|---|---|---|---|---|---| +| `handle_axis`: cubic handles within 0.5° of an axis | 0.380 | 0.061 | 0.075 | 0.104 | 0.329 | +| `extremum`: smooth joins whose tangent is within 1° of an axis | 0.650 | 0.458 | 0.464 | 0.425 | 0.544 | +| `smooth`: joins with a curve on one side turning at most 3° | 0.781 | 0.595 | 0.601 | 0.600 | 0.692 | +| `kinked`: joins between two curves turning 3–30° | 0.035 | 0.142 | 0.135 | 0.144 | 0.072 | + +By family the artists' `extremum` runs from 0.95 in material-icons and 0.74 in lucide to 0.33 +in noto-emoji: a convention of the drawing tools, strong where the art is constructed and weak +in exported emoji. Nothing here forces it; the objective chooses it per run, which is why the +default trace moves only a little (`handle_axis` divergence from the artist −3.3 %, 39 icons +closer and 4 further; `kinked` −6.1 %, 19 closer and 1 further; `smooth` −3.1 %, 51 and 3, all +with 95 % intervals clear of zero) and `--editability`, which prefers it three times as +strongly, a lot (see `13-emit.md`). + +**Why the program never proposed it.** The dynamic program's cubic takes its end directions +from the tangent estimator at measured points, so it can put a node only where a measured +point is, with the estimated direction. A node at an extremum, with an axis direction, is a +different model, and sliding a node along a smooth curve barely changes the drawing: it is in +the likelihood's null space, so nothing pulls the node there. Yet the convention is cheaper. +With both end directions fixed a cubic has four free numbers (its end point and two arm +lengths), against five for a G1 one and six for a free one: at a node where the convention +fixes the direction, the direction is not written (the price of one coordinate, +`docs/theory/chain-representation.md` R0.2). The fit's preference, `extrema::FIT`, credits one +parameter, `λ` nats, per anchored node. + +**How.** + +1. *Runs.* Maximal sequences of cubics and circular arcs whose joins turn by less than + `RUN_BREAK_DEGREES` (30°, the artists' own corner class, R3.1). A line, an elliptical arc, a + corner or an open path's end ends a run; a closed path of curves with no corner is one cyclic + run. +2. *Nodes and measured points.* Each node of the path is mapped to the nearest measured point, + walking forward along the boundary (`node_indices`); a path whose nodes cannot all be mapped + within `FAR_PX` (3 px) is left alone. (The program's own vertex list no longer matches the + path after the merge, which does not report the vertices it absorbs.) +3. *Extrema.* Where a coordinate of the tangent vanishes inside a segment (a quadratic per + coordinate for a cubic; angles that are whole quarter turns on a circle), and at old nodes + where a tangent component changes sign. Two of one axis within `DEDUP_PX` (0.25 px) are one; + a pair of one axis whose extreme values differ by less than `WIGGLE_PX` (0.5 px) is a wiggle + on a flat stretch and both are dropped; none within `END_GAP_PX` (1 px) of an open run's + ends. +4. *Candidates, and the cheapest chain through them.* The run's old interior nodes, each made + G1 on the bisector of its two directions (this is what removes a kink), and the extrema, + each with its axis direction. A shortest path from the run's start to its end over these + candidates chooses the nodes: a span is the cubic with both end directions fixed, its arms + by area and moment (`best_cubic`, Levien's quartic, the program's own fitter, on a + subsample), priced as the program prices a cubic (`½χ² + λ·params_cubic + wobble`), less + `λ·credit` at an anchored node. A span reaches at most `MAX_REACH` (8) candidates + ahead; a cyclic run starts and ends on its first anchored candidate. +5. *Refinement.* Each chosen interior node is moved where its two spans fit best: a compass + search over its position, and over its direction when the convention does not fix it + (`REFINE_STEPS` 0.5 to 0.03 px, `REFINE_ROUNDS` 3). Each span's arms are then polished on + every point (`polish_arms`). +6. *A line at a kink.* Where a run meets a line at a join turning under 30°, the chain is also + proposed leaving (or arriving) along the line, which makes that join smooth; the cheaper of + the two is the proposal. +7. *Acceptance.* The proposal's exact `χ²` (each point's nearest distance to the chain: a + circular arc through its centre, a cubic by kurbo's nearest-point solver) plus its prices, + against the run's own, which also pays the break cost (`tangents::break_cost`) of every + kinked join it has. It replaces the run when it is cheaper, and only when it writes exactly + as many numbers as the run (6 per cubic, 7 per arc, the gate's count): a run with an arc in + it therefore keeps it, and a run of cubics keeps its count. + +**Where it does not run.** A capped or pinned fit (the crossing repair's refits) skips it: +the pinned refit keeps the merge and the sharpening, but its pins are what keep a crossing +closed, and a re-segmentation would move them. So does a stroke's centreline (`inkvec_trace::ribbon::fit_chain` fits it +inside `extrema::without`): the stroke decision weighs the centreline's fit against the +fill's, and re-noding only one side of that comparison flipped the decision on +`openmoji/1F938-1F3FB` (parameter ratio against the artist 1.96 → 2.18; `ratio_gap` +0.10 % +at quality-512ssop). Under `--editability` a centreline's arcs are written as cubics at the +writer instead (`13-emit.md`). + +**What was tried and dropped** (gate samples at 30 % of the screen set unless said): + +- Every extremum a node, no search: dE00 +0.10 % at quality-512ssop, geom +0.03 % at + quality-128ss. +- A `χ²` guard (the proposal may not fit worse): it refuses nearly every anchoring, because + fixing a direction removes a degree of freedom (`simple-icons/elixir`: a run's `χ²` 30.1 + free, 61.9 anchored, 41.1 after the refinement). The credit is the honest price instead. +- Lines inside runs: dE00 +0.30 %, geom +0.14 % and `ratio_gap` +0.48 % at quality-128ss. +- The written count free to fall (credit 1): `ratio_gap` +0.11 % at quality-128ss, 4 icons + closer and 9 further, arcs traded for cubics where the trace already writes fewer numbers + than noto-emoji's and twemoji's artists; credit 2: −0.01 % there but `turning_gap` +0.08 % at + quality-512ssop. Fidelity was better in both (dE00 −0.14 % and geom −0.32 % at + quality-512ssop, dE00 −0.37 % at quality-128ss), so the count guard is the binding one. +- Arcs written as cubics in the default trace: `ratio_gap` +9.76 % at quality-512ssop (0.4375 → + 0.4802), further from the artist in most families. Arcs stay arcs unless `--editability`. + **The research snaps** (`merge/snap.rs`, compiled only with `--features research`): - **`snap_axis_aligned`** (`merge/snap.rs:52`) puts a line the measurement cannot @@ -684,7 +794,7 @@ cheapest whole-ring circle, ellipse or (rounded) rectangle, or a run of arcs (`fit_primitive_or_arcs`, `primitives.rs:720`), which prices itself. The primitive wins when its cost is strictly below the curve's (`choose`, `choice.rs:211-226`); a tie or a NaN keeps the curve. The CLI reaches the choice through `describe` (`choice.rs:243-272`), called from -`fit_boundaries` (`crates/inkvec-cli/src/pipeline.rs:720`), which avoids work the choice +`fit_boundaries` (`crates/inkvec-cli/src/pipeline.rs:719`), which avoids work the choice discards: 1. **The image frame.** When one face touches every border pixel (the background of 166 of @@ -838,6 +948,16 @@ are marked **none**. Paths are under `crates/inkvec-fit/src/`. | `SHARPEN_MAX_CHORD` | `merge.rs:569` | 2.5 | chamfer-cubic chord ceiling | semi-derived (chamfer ~1 px per side) | | `SHARPEN_MAX_EDGE` | `merge.rs:574` | 8.0 | short-edge-with-chamfers ceiling | none | | `SHARPEN_MIN_TURN` | `merge.rs:580` | `CORNER_TURN_MIN` | corner-vs-smooth threshold | shared with `CORNER_TURN_MIN` by design | +| `FIT.credit` | `extrema.rs:76` | 1.0 | parameters credited per node whose direction the extremum convention fixes | derived (the one coordinate it does not write, R0.2); measured: 2.0 also passed the 30 % sample, with the written count free | +| `FIT.same_count` | `extrema.rs:77` | true | a re-segmentation must write as many numbers as the run it replaces | measured (free: ratio_gap +0.11 % at quality-128ss, 4 icons closer and 9 further, where the trace already writes fewer numbers than noto's and twemoji's artists) | +| `RUN_BREAK_DEGREES` | `extrema.rs:82` | 30.0 | a join turning this much ends a smooth run | motivated (the artists' joins between curves are smooth or turn by more, R3.1); not swept | +| `WIGGLE_PX` | `extrema.rs:85` | 0.5 px | two extrema of one axis this close in value are a wiggle and get no node | none | +| `END_GAP_PX` | `extrema.rs:87` | 1.0 px | no node for an extremum this close (arc length) to a run's end | none | +| `DEDUP_PX` | `extrema.rs:90` | 0.25 px | two extrema of one axis this close (arc length) are one | none | +| `MIN_INTERIOR` | `extrema.rs:92` | 2 | fewest measured points inside a span | motivated (the arms need points to fit) | +| `MAX_REACH` | `extrema.rs:94` | 8 | candidates one span may reach in the search | motivated (bounds the search); not swept | +| `FAR_PX` | `extrema.rs:97` | 3.0 px | a path node with no measured point this close leaves the path alone | none | +| `REFINE_ROUNDS`, `REFINE_STEPS` | `extrema.rs:99`, `:101` | 3; 0.5 … 0.03 px | the node refinement's compass search | none | | `PARAMS_AXIS_LINE` (research) | `merge/snap.rs:17` | 1.0 | axis-snapped line cost | derived | | `MAX_AXIS_DEV_SIGMA` (research) | `merge/snap.rs:22` | 3.0 | per-sample axis-snap deviation cap | none | | `PARAMS_SMOOTH_CUBIC` (research) | `merge/snap.rs:204` | 4.0 | `S`-shorthand cost | derived | diff --git a/docs/algorithm/12-repair.md b/docs/algorithm/12-repair.md index b0c22d20..4de6e8a1 100644 --- a/docs/algorithm/12-repair.md +++ b/docs/algorithm/12-repair.md @@ -10,7 +10,7 @@ per-boundary sibling), `crates/inkvec-fit/src/multimodel.rs` (`optimal_multimode and `optimal_multimodel_forced`, the constrained DP) **Entry point:** `repair_ring_crossings()` (`crates/inkvec-cli/src/rings.rs:276`) **Pipeline position:** after curve fitting (stage 11), before fill assignment (stage mark -`"fills"`). Stage mark `"repair"` (`crates/inkvec-cli/src/pipeline.rs:504`). +`"fills"`). Stage mark `"repair"` (`crates/inkvec-cli/src/pipeline.rs:503`). ## What problem this solves @@ -56,7 +56,7 @@ unit the defect can be seen in at all. inverts" — the strongest statement in the source is that a self-crossing ring is "invalid, resolved arbitrarily by whichever fill rule applies, and unpleasant to edit" (`simple.rs:24`, restated in `crates/inkvec-fit/tests/self_intersection.rs:5-7` and in `repair_fits`'s doc, -`crates/inkvec-cli/src/pipeline.rs:837-842`). The mechanism behind that arbitrariness is this +`crates/inkvec-cli/src/pipeline.rs:836-841`). The mechanism behind that arbitrariness is this document's reading of the fill rules (SVG 1.1 §11.3), not a code comment. Since 2026-10 the emitter winds every ring of a compound path by its nesting depth and writes no `fill-rule`, so the default `nonzero` rule paints exactly what `evenodd` would; `fill-rule="evenodd"` remains @@ -335,7 +335,7 @@ changes." ### Where repair sits in the pipeline -`repair_fits` (`crates/inkvec-cli/src/pipeline.rs:834-920`), the call site itself; its doc, +`repair_fits` (`crates/inkvec-cli/src/pipeline.rs:833-919`), the call site itself; its doc, verbatim (`pipeline.rs:837-842`): > "A self-crossing boundary is invisible to the objective — both curves pass through diff --git a/docs/algorithm/13-emit.html b/docs/algorithm/13-emit.html index 91a23d1e..308cfae3 100644 --- a/docs/algorithm/13-emit.html +++ b/docs/algorithm/13-emit.html @@ -129,6 +129,23 @@

Drawing a word as one shape, not one shape per letter

circle or rectangle element, always keeps its own place in the file. +
+

Asking for a file to edit, not just to look at

+

With --editability, a set of passes runs just before the file is written + and spends a few numbers on structure a designer can work with, each change kept only + if the outline stays within a fraction of a pixel of what was measured. Curves that + the tracer wrote as circular arcs are rewritten the way drawing tools write circles: + as curves cut at their top, bottom, left and right, every handle there pointing + straight along an axis, to within three ten-thousandths of the radius. Smooth stretches + get their joins at those same extreme points. A join that bends by less than thirty + degrees is made smooth, since artists draw a join either smooth or as a clear corner + and almost never in between; two straight pieces that meet in a straight line become + one. And where one shape's outline passes + from one boundary piece to the next at a junction with a third colour (what a shape + painted over another leaves behind), the slight kink the separate fits left there is + turned smooth, because the artist's outline ran straight through it.

+
+

The last few knobs: minifying, dropping the background, resizing the canvas

A few finishing options are entirely optional and change only how the file is diff --git a/docs/algorithm/13-emit.md b/docs/algorithm/13-emit.md index ce8f5c2e..bb845e9c 100644 --- a/docs/algorithm/13-emit.md +++ b/docs/algorithm/13-emit.md @@ -7,11 +7,11 @@ `emit/winding.rs` (ring direction), `crates/inkvec-cli/src/pathdata.rs` (path data), `primitive.rs` (circle, ellipse and rectangle elements), `rings.rs` (nesting), `crates/inkvec-cli/src/post.rs` (output options), and `inkvec_svgmin::compact` for `--minify`. -**Entry points:** `emit_color()` (`crates/inkvec-cli/src/emit.rs:163`); post-processing via +**Entry points:** `emit_color()` (`crates/inkvec-cli/src/emit.rs:164`); post-processing via `post_process()` (`crates/inkvec-cli/src/post.rs:451`). **Pipeline position:** after fill assignment (stage mark `"fills"`, `crates/inkvec-cli/src/pipeline.rs:396`), through the stage mark `"emit"` -(`crates/inkvec-cli/src/pipeline.rs:446`); `post_process` then runs separately, outside the +(`crates/inkvec-cli/src/pipeline.rs:445`); `post_process` then runs separately, outside the timed pipeline, just before the file is written. Crate header, `crates/inkvec-cli/src/lib.rs:6-21`, gives the whole pipeline shape: @@ -47,15 +47,15 @@ header (`emit.rs:30-47`) names the two things that make that more than a neutral ## Inputs and outputs -`emit_color` takes a `ColorDoc` (`emit.rs:76-115`): the rings of each face as walks over +`emit_color` takes a `ColorDoc` (`emit.rs:76-116`): the rings of each face as walks over shared edges, every fitted edge and whole-edge primitive, every face's fill model, the palette and per-face colour index, per-face clear/opacity, alpha ramps and native fades, optional recovered layers, the matte, and the raster size; and an `EmitOptions` -(`emit.rs:126-143`): `--cutout`, native transparency, `--no-background`, `--precision`, and +(`emit.rs:127-144`): `--cutout`, native transparency, `--no-background`, `--precision`, and the harmonize settings. Output is a `String` — the complete `...` document, viewBox `-0.5 -0.5 w h`, before `post_process`. The colour pipeline calls it once per candidate document (flat, and with translucent layers when there are any); the bilevel pipeline calls -`emit_bilevel` (`emit.rs:1354`). +`emit_bilevel` (`emit.rs:1365`). ## How it works @@ -65,6 +65,84 @@ order and names (`paint_tree`, `face_ids`), strokes (`annulus_strokes`), writing with same-coloured siblings merged into one compound path), seams (`seam_overrides`), and layers (`write_layers`). +### Before the writer: `--editability` (`crates/inkvec-cli/src/editable.rs`) + +With `--editability`, `finish_color` (`pipeline.rs`) hands every fitted edge to +`editable::edit_all` after repair, mirrors and fills and before `emit_color`, so nothing the +writer does can re-break what it locked. Every pass is held to one test: sample the edited +ring at 8 points per segment and require each sample to lie within `3·σ_j + EDIT_SLACK` +(0.5 px) of some measured point (`MIRROR_SLACK`, 1.5 px, for a mirror lock), one-sided. A +change that fails it is undone, one join, node or ring at a time. The passes, in the order +`edit_all` runs them: + +1. **Arcs as cubics** (`editable/curves.rs`, `pass_arcs`). Every circular arc is written as the + cubics a drawing tool writes: cut at each angle that is a whole quarter turn inside it, so + every cut is an x or y extremum with both handles exactly on an axis, each piece the + standard approximation with handles `4/3·tan(Δ/4)·r` long (0.5523·r for a quarter; Riškus + 2006, *Information Technology and Control* 35(4), whose largest radial error with that + constant is 2.73e-4·r). A cut within `ARC_CUT_GAP_PX` (1 px, along the arc) of the arc's + end is not made: the end is then all but at the extremum, and the sliver the cut would + leave has handles too short for two decimals to point (a 0.4 px piece on + `material-icons/dining`). The piece beside it then turns by up to 112.5° (the gap is + capped at 22.5°), with a radial error under 1.1e-3·r. The fit writes arcs as `A` (19 % of + the trace's segments at 512 px on white, against the artists' 4 %; the artists write 67 % + cubics); an editor shows an `A` as two nodes with no handles, wherever on the circle they + fall. A stroke's centreline gets the same conversion when it is written (`ribbons.rs`, + `arcs_as_cubics`); at 1.1e-3·r it needs no guard. +2. **Runs re-noded at extrema** (`pass_extrema`): `inkvec_fit::extrema::anchor_extrema` + (stage 11, *Nodes at extrema*) with `EDIT_PREFERENCE`: 3 parameters credited per anchored + node instead of the fit's 1, and the written count free to change, so a segment that spans + an extremum gains a node there. Kept only if the ring still guards. These two rewrite + segments, so they run before anything that reads a node or a handle. +3. **Mirror lock, then node alignment** (`pass_mirror`, `pass_nodes`): the passes that move + nodes, before any handle is pointed. A node that alignment moves now carries its handles, + as in an editor; left behind, a handle a pixel long turned by up to 15° for a 0.3 px move + and a smooth node became a kink (`material-icons/dining`: kinked 0 → 0.18 from this pass + alone). +4. **Collinear lines merged** (`pass_collinear`). Node alignment lines nodes up on shared + coordinates and mirror lock splits a line where its axis crosses it; both leave a node in + the middle of a straight run, which artists do not draw (the battery's `collinear` was + 15 % further from the artist's file under `--editability` than without it). Two lines + meeting at a turn of at most `COLLINEAR_DEG` (0.5°, the battery's own threshold) are + written as one, the closing join of a closed ring included. Only the merged line is + judged, against the two it replaces (it may stray no further than they did, or than + `EDIT_SLACK`): judged on the whole ring, a mirror-locked ring, held to the wider + `MIRROR_SLACK`, never lost the node its lock had put on the axis. +5. **G1 within a ring** (`pass_g1`). Every join that turns by at most `KINK_DEG` (30°) is + made smooth: between two cubics both handles turn onto the bisector, and next to a line + the cubic's handle turns onto the line's direction. 30° is where the artists' own joins + between curves separate: smooth (within 3°) or a corner of more than 30°, with only + 8.6 % between (R3.1 of `docs/theory/chain-representation.md`). The pass used to stop at + `G1_SNAP_DEG` (3°), which only made exact what was already smooth to the eye, and never + looked at a join next to a line. It also turned the wrong handle, since it was written: + the incoming cubic's first control point, at its far end, instead of the one at the join, + so a join it "smoothed" kept its kink and the far end gained one (`material-icons/dining`: + kinked 0.18 → 0.45 from this pass, 0 now). +6. **Handle snaps** (`pass_handles`), per node: onto an axis within 2.5°, else onto the 45° + diagonal within 1.5°. A smooth node's two handles snap together or not at all; snapping + them one at a time turned one handle of a pair whose direction sat on either side of the + window's edge and left a kink where there was none (the battery's `kinked` was 3.9 % + further under `--editability`). A handle that leaves a line smoothly is not snapped, since + the line fixes its direction. +7. **Equal handle lengths** (`pass_equalize`), as before. +The per-ring passes (4 to 7) see a boundary with no junction on it as closed. The planar +map hands such a boundary over as one open edge that ends where it starts, at a point of its +own choosing, so its closing join was a join no pass ever looked at: neither these, which +treat an open ring's ends as ends, nor the junction pass, which needs two edges. +`isolated_loops` finds the edges that end where they start at a point no other edge ends at; +they are flagged closed for passes 4 to 7 and the flag is put back after them. + +8. **Joins at junctions** (`editable/junctions.rs`, `pass_junctions`), last. The other passes + see one edge at a time, between two junctions, so they never see the join where a face's + outline passes from one edge to the next. That is where layered art shows: a shape painted + over another leaves the lower one's visible outline with a T-junction on each side, and the + upper one's outline runs smoothly through both, but its two edges were fitted apart and + meet at a kink. The pass walks each face's rings and turns the handles either side of every + join between two edges that turns by at most `JUNCTION_G1_DEG` (30°) onto one direction: + a line's own direction when one side is a line; else the side that the handle pass left + exactly on an axis, when the other is not, so the snap survives; else the bisector. No + node moves, so the junction stays shared and no seam opens; both edges must still guard. + ### The path grammar actually emitted Four serialisers exist: @@ -214,7 +292,7 @@ that happens to come out smooth for any reason gets the short form. ### Compound paths, wound by nesting depth -`Writer::emit_level` (`emit.rs:1076-1087`) writes the faces of one nesting level: +`Writer::emit_level` (`emit.rs:1087-1098`) writes the faces of one nesting level: > "Siblings are disjoint by construction -- every pixel belongs to one face -- so all the > siblings of one flat colour can be one compound path under even-odd, which is how an artist @@ -239,7 +317,7 @@ drawables before API 24 — such a hole fills back in; on the 246-icon screen se (30%) rendered differently under `nonzero` (`emit/winding.rs:6-13`). Now every path is passed through `winding::for_nonzero` (`emit/winding.rs:104-119`) when it is -written (`Writer::path_element`, `emit.rs:1061-1073`). The method (`emit/winding.rs:15-34`): +written (`Writer::path_element`, `emit.rs:1072-1084`). The method (`emit/winding.rs:15-34`): for rings that do not cross each other, a point inside `k` nested rings is crossed once by each, so if the ring at depth `d` runs the way `(−1)^d` says, the winding number is `1 − 1 + 1 − …` over `k` terms — 1 for odd `k`, 0 for even, the even-odd answer at every @@ -265,7 +343,7 @@ where the opposite would reverse 2,152. Per compound path (`emit/winding.rs:36-5 The same pass winds the recovered `--layers` paths (`write_layers`), the harmonized symbols (`harmonize.rs:133`) and the `--monochrome` and bilevel documents (`mono.rs:540`); a `` of a harmonized symbol carries no `fill-rule`, since the symbol itself was wound -(`emit.rs:1019-1020`). +(`emit.rs:1030-1031`). Measured (`emit/winding.rs:66-80`; the 246-icon screen set at 512 px, against v0.2.4 rendered under `evenodd`): with `evenodd` forced back on, the wound files render identically in resvg, @@ -302,18 +380,18 @@ bound of a paired bootstrap, which is a change-detection gate, not an absolute c ### Gradient and fill emission -Each face's fill attribute comes from `face_fill` (`emit.rs:711-775`), in order of precedence: +Each face's fill attribute comes from `face_fill` (`emit.rs:722-786`), in order of precedence: under a recovered layer, the ground colour; a fade traced natively, written by `gradient::fade_to_svg` (id `f{i}`); an alpha ramp, written as the gradient an editor would use — one colour, two `stop-opacity` values, along the axis the fade was measured to run (id -`a{i}`, endpoints at two decimals and opacities at three, `emit.rs:745`); its fill model, +`a{i}`, endpoints at two decimals and opacities at three, `emit.rs:756`); its fill model, delegated to `gradient::fill_to_svg` (`crates/inkvec-trace/src/gradient/svg.rs:74`); and with no fill model, its palette ink, else black. A translucent face's flat colour is "un-matted" before writing, since it was measured over the compositing matte. `fill_to_svg` returns a `(defs fragment, fill attribute)` pair: `FillModel::Flat` needs no defs; `FillModel::Linear`/`Radial` write a ``/`` with `gradientUnits="userSpaceOnUse"`. No empty `` block is written when there is nothing to -put in it (`emit.rs:248-252`). +put in it (`emit.rs:259-263`). Which gradients reach this point is decided in the `fills` mark (below): a gradient whose stops a viewer could not tell apart is painted flat first. @@ -348,12 +426,12 @@ is degenerate", with "See also" He & Chao 2015. ### Stage 9: the recovered layers, back to front -With `--layers`, `write_layers` (`emit.rs:1307-1349`) paints each recovered translucent layer +With `--layers`, `write_layers` (`emit.rs:1318-1360`) paints each recovered translucent layer over everything as one compound path: the union of its faces, from the rings they had before the ground under them was merged, wound by depth so the default rule paints exactly the union, and one path rather than one per face so the translucent paint is composited once and no seam appears where two pieces met. The layers are written **back to front** -(`emit.rs:1316-1323`): the decomposition's list is in peel order, frontmost first, because a +(`emit.rs:1327-1334`): the decomposition's list is in peel order, frontmost first, because a layer can only be taken off once nothing lies over it. Written in that order the frontmost layer went down first and every layer behind it was composited over it: on `synthetic/stack_overlap` the blue disc came out on top of the green one that covers it, dE00 @@ -477,8 +555,8 @@ let pays = pl < pf && bl <= bf; // fewer shapes AND not more bytes | arc rotation precision | `pathdata.rs:114`, `:258`, `:338` | 3 decimals (fixed) | arc `phi` formatting | no stated derivation | | rounded-rect radius floor | `primitive.rs:76`, `:281` | `1e-4` | below this, written as a plain rect | no stated derivation | | ellipse rotation floor | `primitive.rs:258` | `1e-3` | below this, no `transform` written | no stated derivation | -| alpha-ramp endpoint precision | `emit.rs:745` | 2 decimals (fixed) | independent of `EMIT_DECIMALS` | no stated derivation | -| opacity precision | `emit.rs:745`, `:787`, `:793` | 3 decimals | `fill-opacity`/`stop-opacity` | no stated derivation | +| alpha-ramp endpoint precision | `emit.rs:756` | 2 decimals (fixed) | independent of `EMIT_DECIMALS` | no stated derivation | +| opacity precision | `emit.rs:756`, `:787`, `:793` | 3 decimals | `fill-opacity`/`stop-opacity` | no stated derivation | | `INKVEC_EMIT_DECIMALS` | `pathdata.rs:50` | env override | overrides `EMIT_DECIMALS` | the mechanism used to isolate rounding from the segment price in the 7.2% measurement | | `EVENODD` | `emit/winding.rs:102` | ` fill-rule="evenodd"` | written only on a `d` the winding pass cannot read | the old output as a fallback | | `CANVAS_TOL` | `post.rs:186` | 0.25 px | `--no-background` rect match | motivated (a fitted canvas rect lands 0.01-0.02 px off) | @@ -503,20 +581,20 @@ let pays = pl < pf && bl <= bf; // fewer shapes AND not more bytes - **Parity means punching a transparent face out of its painted ancestors only up to the first transparent one.** A second ring inside an already-punched hole flips it back solid — the counter of a heart inside a page inside a book cover came out solid black, dE00 0.19 -> 3.33 - on `lucide/book-heart` (`emit.rs:283-290`). + on `lucide/book-heart` (`emit.rs:294-301`). - **Containment for cutting must be certain, not merely likely.** `ring_inside`'s majority vote is right for paint-order stacking and wrong for deciding what to punch — a black wedge beside - the head on `noto-emoji/emoji_u1f3cb_200d_2642`, dE00 0.58 -> 1.78 (`emit.rs:333-341`). A + the head on `noto-emoji/emoji_u1f3cb_200d_2642`, dE00 0.58 -> 1.78 (`emit.rs:344-352`). A punch needs every probe inside (`strictly_inside`). - **`fill-opacity` in a stacked document blends against whatever painted underneath it, not the page** — the film frames on `noto-emoji/emoji_u1f39e`, dE00 0.46 -> 1.43 - (`emit.rs:503-514`). + (`emit.rs:514-525`). - **A primitive element cannot carry a hole.** A face that must show a hole through it is - written as a path even when its outline would otherwise fit a circle (`emit.rs:1040-1041`). + written as a path even when its outline would otherwise fit a circle (`emit.rs:1051-1052`). - **Drawing every face's own holes (making paths self-contained so any face could drop freely) was tried and reverted** — parameters rose (the arrow 166 to 248) and DISTS regressed on three of six probes, "because a ring contained inside another of the same face is not - reliably a hole, and punching it makes one anyway" (`emit.rs:169-174`). + reliably a hole, and punching it makes one anyway" (`emit.rs:170-175`). - **Two rings of one path that overlap by a sliver** paint the overlap under `nonzero` where `evenodd` cut it out; no ring direction can make the two rules agree there (9 of 246 screen icons at 512 px, 170 px in all; see the winding section). @@ -532,7 +610,7 @@ Since the settings cleanup (CHANGELOG, 0.2.0, *Changed*) the engine reads its en | variable | effect | |---|---| | `INKVEC_EMIT_DECIMALS` | overrides `EMIT_DECIMALS` (coordinate decimal places); `--no-background`'s path match follows it | -| `INKVEC_ALPHADBG` | per-face emit debug dump (rings, areas, outer/clear/parent/drop, holes; `emit.rs:625`) | +| `INKVEC_ALPHADBG` | per-face emit debug dump (rings, areas, outer/clear/parent/drop, holes; `emit.rs:636`) | | `INKVEC_TIMING` | enables the `Stopwatch` printout that surfaces the `fills`/`emit` marks | ## Open questions diff --git a/docs/algorithm/14-fast-mode.md b/docs/algorithm/14-fast-mode.md index c04595d3..5b3d774d 100644 --- a/docs/algorithm/14-fast-mode.md +++ b/docs/algorithm/14-fast-mode.md @@ -25,10 +25,10 @@ fits the result with `fast::fit` (`crates/inkvec-cli/src/fast.rs:115-134`), whic `inkvec_trace::fast::fit_edges` (`fast/mod.rs:380-427`) with the map's width and height. **Pipeline position:** it replaces stages 03–05 (palette, regions, gradients) with its own front end; shares stages 01, 06, 07, 10 and 13; skips 08 (the boundary solve, -`lib.rs:1166`, `boundary_opt::optimise_for` at `boundary_opt.rs:593-611`; balanced runs it, -capped at eight iterations, §8) and 09 (decode, `lib.rs:1177`); and replaces 11 (curve fitting) with its own +`lib.rs:1141`, `boundary_opt::optimise_for` at `boundary_opt.rs:593-611`; balanced runs it, +capped at eight iterations, §8) and 09 (decode, `lib.rs:1152`); and replaces 11 (curve fitting) with its own fitter, without 12 (repair) or shape harmonization (`repair_fits`, -`crates/inkvec-cli/src/pipeline.rs:852`; `emit_options`, `pipeline.rs:526-537`). +`crates/inkvec-cli/src/pipeline.rs:851`; `emit_options`, `pipeline.rs:526-537`). ## What problem this solves @@ -42,7 +42,7 @@ its seam underlap, compound paths and minify" — and replaces the rest with one (the module overview of `fast/mod.rs`). Each stage is linear or near-linear in the number of pixels or boundary points, and nothing reads a clock, so the output is the same on every machine. The command line describes the trade as "several times faster, a little less faithful" -(`args.rs:339-342`). +(`args.rs:340-343`). The round of 2026-09-30 rewrote Fast's own stages and the stages it shares for speed, **with the output held fixed**: every rewrite is exact, keeps the code it replaced as a test @@ -312,7 +312,7 @@ as the test oracle `fast/palette/reference.rs`. **What it computes, in the field's terms** (`fast/faces.rs:1-30`): *connected-component analysis of the flat zones* of the label image (a flat zone is a maximal 4-connected set of pixels of one label), followed by *region merging on the region adjacency graph*. Five -passes, in the order the front end calls them (`fast/front.rs:97-129`): +passes, six on a lossy intake, in the order the front end calls them (`fast/front.rs`): 1. **Slivers** (`absorb_slivers`, `faces.rs:325`, mark `slivers`): pixels of *strips* — components with no interior pixel — that are blends of the inks of the thick components @@ -322,10 +322,14 @@ passes, in the order the front end calls them (`fast/front.rs:97-129`): 2. **Rims** (`absorb_rims`, `faces.rs:431`, mark `slivers`): a strip whose own ink is a blend of two inks it borders is an anti-aliased rim; each of its pixels goes to the side it covers more of. -3. **Same-ink merge** (`merge_same_inks`, `faces.rs:530`, mark `slivers`): a component takes +2b. **Codec halos, lossy intake only** (`absorb_halos`, `faces/halos.rs`, mark `slivers`; + see "Noisy input" below): thin components whose colour lies between two inks around + them in JPEG's colour space go back to those inks, pixel by pixel by luma. +3. **Same-ink merge** (`merge_same_inks`, `faces.rs`, mark `slivers`): a component takes the ink of a larger neighbour the eye cannot tell from its own (CIEDE2000 below `SAME_INK_DE00`, opacities within 0.02), largest components first, longest shared border - winning. + winning. On a lossy intake a component with no interior of radius 2 takes a neighbour's + ink up to `SOFT_SAME_INK_DE00` (5.0) instead (see "Noisy input" below). 4. **Despeckle** (`despeckle`, `faces.rs:614`, mark `despeckle`): components under the speckle floor take the label they share the longest border with — an area filter on flat zones. The floor is `min_region`, or 4 px per 512 × 512 of image up to 16 px, VTracer's default @@ -350,6 +354,68 @@ passes, in the order the front end calls them (`fast/front.rs:97-129`): (impl2/robust) found no real image that reaches the limit in Fast, whose palette and despeckle keep two-ink noise at 18,000 to 35,000 faces. +**Noisy input: codec halos and ink variants** (`fast/faces/halos.rs`, 2026-10-10; Quality runs the same passes on a lossy intake, with the halo test in a stricter form and a variant merge of its own, `fast/codec.rs`, stage 04). Both +passes run only on a lossy intake (`ColorOptions::lossy_intake`, from the container) of an +opaque image; a clean intake takes neither, and the six clean gate conditions are +byte-identical. They read the evidence of the pixels, not the flag alone: a raster with no +halos keeps its components. + +*The problem.* On the `web` tier (512 → 400 px bicubic, JPEG quality 80, 4:2:0) Fast's +palette founds the codec's halos as inks: a band two or three pixels wide on each side of +an edge whose luma overshoots and whose chroma has bled, independently of the luma, so its +colour lies 0.08-0.09 sRGB off the line between the two inks, twice `BLEND_TOL`. Neither +`absorb_slivers` nor `absorb_rims` recognises it: `twemoji/1f1fa`, a blue flag with a +white letter, came back with four inks and 215 faces (the clean raster: two inks, three +paths). And the codec tints an ink with its neighbours' chroma block by block, so one +black outline comes back as #010101, #010009 and #080000 (`openmoji/1F9D1`), which tile it +into fragments with no interior; Fast's parameter ratio on `web` was 7.2 against 3.5 on the +opaque 512 px tier (openmoji 13x, twemoji 8.9x). + +*The halo test* (`RunLabels::absorb_halos`). In BT.601 full-range YCbCr, JPEG's own space, +a component is a halo of inks `a` and `b` when (1) it is thin: no pixel of it has a 5 × 5 +window of its own label (`HALO_REACH` = 2; a JPEG halo reaches about three pixels, which +the radius-one interior rule of the other passes misses; `deep_components`, on runs); +(2) `a` and `b` are inks of thick components bordering it, or bordering a thin component +that borders it (the band between blue and white is a dark halo beside the blue and a +light one beside the white); (3) its mean colour lies channel by channel in +`[min − τ|Δ| − ε, max + τ|Δ| + ε]` of the two inks' values (`HALO_OVERSHOOT` τ = 0.2, +`HALO_SLACK` ε = 0.02), the channels independently. A thin component of an ink that has a +thick component somewhere else is held to more: it must be a strip at radius one +(`STRIP_REACH`) and lie within `HALO_LINE_TOL` = 0.04 of the segment between the inks (a +chroma-weighted YCbCr distance). The box alone takes real ink: `twemoji/1faa3`'s #55ACEE +rim, four pixels wide between a navy and a white, sits in it and 0.054 from the segment, +where the codec's halos sit 0.009-0.035 from theirs. Of the passing pairs the nearest +segment wins; each pixel goes to `b` when its coverage of `b`, read with chroma at a +quarter of luma's weight on squared differences, is at least ½, which keeps each ink's +area. Then an ink some of whose components were halos and that has no thick component left +is a halo ink, and each remaining component of it that borders exactly one other ink takes +that ink (a fleck of halo inside one ink; a ring of it around an eye, which borders two, +stays as it is). + +*The thin-variant merge.* `merge_same_inks` gets a second threshold for components with no +5 × 5 interior: `SOFT_SAME_INK_DE00`, the soft floor Quality's palette applies on the same +intakes. A component with an interior keeps `SAME_INK_DE00`, so two flat inks a few dE00 +apart (the mosaic's neighbours) stay two. + +*Measured* (regression gate, 246 icons, `fast-web` against the recorded baseline): dE00 +−11.83 % (95 % CI −13.90 to −9.64), turning −50.53 %, parameter ratio −42.79 % (7.22 → +4.13), geom −6.84 % (−11.27 to −2.80), all "better"; 113 icons change, 104 better and 9 +worse in dE00. By family (dE00, ratio, geom): openmoji 0.297 → 0.204, 13.19 → 3.88, +0.152 → 0.121; twemoji 0.312 → 0.275, 8.92 → 3.71, 0.232 → 0.164; noto-emoji 0.496 → +0.460, 4.12 → 2.38, 1.493 → 1.514; synthetic 0.148 → 0.138, 11.35 → 5.99, 0.315 → +0.225; lucide, material-icons and simple-icons byte-identical (one ink on white: no chroma +to bleed, and the luma's ringing stays on the grey line the existing passes already take). `twemoji/1f1fa`: 4 inks and 215 faces → +2 inks and 3 paths, dE00 0.242 → 0.144, geom 0.245 → 0.091, ratio 36.5 → 2.7. The +halo pass alone, before the thin-variant merge: dE00 −9.67 %, ratio −39.0 %, geom −6.35 %. +The first version, which held every ink to the box test and let a speck bordering several +inks take the one it shared most border with, read dE00 −11.34 %, ratio −43.5 %, but took +`twemoji/1faa3`'s rim (dE00 0.212 → 0.344) and filled `openmoji/1F9D1`'s eye with yellow +(0.326 → 0.446). + +*Considered and not used.* `coverage::ringing_score` as a second signal, for a JPEG +re-saved as PNG: about 100 ms on a 2048 px image under load, a third of Fast's trace, on +every image clean or not; the container flag costs nothing on a clean intake. + **Method: everything on row runs** (`fast/faces/runs.rs`). The label image is held as its maximal row runs (`RunLabels`); a run is scanned 8 labels at a time while they all equal the run's label, a compare the compiler turns into one vector instruction (`push_row_runs`, @@ -493,9 +559,9 @@ solve and decode. * **Refinement measured in parallel, then applied**: a pure map over edges and, on edges of 64 points or more, over vertices, with no parallel reduction; serial under 512 boundary vertices or while a debug printout or contour dump is on (`measure_subpixel`, - `planar.rs:502-603`). + `planar.rs:495-596`). * **Symmetry detection beside the measuring phase**, under `rayon::join`; both only read the - lattice map (`lib.rs:1122-1155`). + lattice map (`lib.rs:1097-1130`). * **Junction debug flags read once** into a `OnceLock` (`planar/junctions.rs:54-70`). **Citations** (labels as in the doc comments): cracks, "Method from" He, Chao & Suzuki 2008 and @@ -900,7 +966,7 @@ the parallel pass would take it off the critical path, but needs 8 bytes per adm **What it computes.** The SVG document, from the fitted paths, the faces' fills and the palette: shared with Quality and documented in `13-emit.md`. Fast turns shape harmonization -off (`emit_options`, `crates/inkvec-cli/src/pipeline.rs:526-537`). An image traced with its +off (`emit_options`, `crates/inkvec-cli/src/pipeline.rs:525-536`). An image traced with its transparency keeps the native-alpha model: inks carry an opacity and the clear ground is an ink of its own (`fast/front.rs:14-16`). diff --git a/docs/algorithm/15-strokes.html b/docs/algorithm/15-strokes.html index 7a7db4bc..5b7886c1 100644 --- a/docs/algorithm/15-strokes.html +++ b/docs/algorithm/15-strokes.html @@ -9,14 +9,15 @@

-

Stage 15 (optional, off by default)

+

Stage 15 (on by default in Quality mode)

Lines drawn as lines: one centreline and one width

A line icon is drawn with a pen: a path down the middle of each line and one line width for all of them. Traced as filled shapes, every line costs both of its edges and its rounded ends, about four times the numbers the artist wrote. - With --detect-strokes (or detect_strokes in the options), - the tracer looks for shapes that were drawn this way and writes them back as lines — - but only where that is both shorter and as faithful as the filled outline.

+ In Quality mode the tracer looks for shapes that were drawn this way and writes them + back as lines — but only where that is both shorter and as faithful as the filled + outline. Each line is then simplified the way an artist would draw it: two arcs on one + circle become one arc, two lines in line become one.

@@ -109,7 +110,7 @@

The decision

outlined with rounded corners, read as a line with sharp corners, and a puzzle piece whose curved parts are slightly wider than its straight ones. Neither is really drawn with one pen, and both now stay filled shapes.

-

The stage is off by default while it is measured on more drawings.

+

The stage is on by default in Quality mode; --no-detect-strokes turns it off. It adds about a sixth to the trace time at 512 px.

diff --git a/docs/algorithm/15-strokes.md b/docs/algorithm/15-strokes.md index 4bc56bbc..eaa9a347 100644 --- a/docs/algorithm/15-strokes.md +++ b/docs/algorithm/15-strokes.md @@ -1,4 +1,4 @@ -# Stage 15 — Stroke detection (`--detect-strokes`, off by default) +# Stage 15 — Stroke detection (on by default; `--no-detect-strokes` turns it off) > Finds the faces of the colour trace that were drawn as strokes — a centreline and one > width — and writes each as a stroked path where that is the shorter description of its @@ -9,20 +9,21 @@ `graph.rs` (topology), `chordal.rs` (constrained Delaunay chordal axis), `refine.rs` (the stroke solve) and `refine/normal.rs` (its Jacobian rows and normal equations), `dist.rs` (exact distances and their gradients), `skyline.rs` (the envelope Cholesky), `bvh.rs` (nearest-piece search), `grid.rs` (bucket grid and ray walks), -`join.rs` (joins and caps as residual models), `score.rs` (the score). The decision and the -SVG elements: `crates/inkvec-cli/src/ribbons.rs`. -**Entry points:** `ribbon::fit_face()` (`crates/inkvec-trace/src/ribbon.rs:324`), called per -candidate face by `ribbons::choose()` (`crates/inkvec-cli/src/ribbons.rs:168`), which -`ribbons::stage()` (`crates/inkvec-cli/src/ribbons.rs:77`) runs when -`--detect-strokes` / `Options::detect_strokes` is set (`crates/inkvec-cli/src/args.rs:198`, -`crates/inkvec/src/options.rs:112`) or, for the benchmarks, `INKVEC_RIBBONS=1` -(`crates/inkvec-cli/src/ribbons.rs:68`). +`join.rs` (joins and caps as residual models), `score.rs` (the score), `refine/merge.rs` +(merges, the splits run backwards). The decision and the SVG elements: +`crates/inkvec-cli/src/ribbons.rs`. +**Entry points:** `ribbon::fit_face()` (`crates/inkvec-trace/src/ribbon.rs:327`), called per +candidate face by `ribbons::choose()` (`crates/inkvec-cli/src/ribbons.rs:173`), which +`ribbons::stage()` (`crates/inkvec-cli/src/ribbons.rs:79`) runs unless +`--no-detect-strokes` / `Options::detect_strokes = false` (`crates/inkvec-cli/src/args.rs:199`, +`crates/inkvec/src/options.rs:112`) switches it off; for the benchmarks `INKVEC_RIBBONS=0` +switches it off and `INKVEC_RIBBONS=1` on (`crates/inkvec-cli/src/ribbons.rs:70`). **Pipeline position:** Quality mode, colour output only (not `--mode fast`, not `--monochrome`): after every boundary is fitted, repaired and mirrored and every face's fill and transparency are settled, before the document is written -(`crates/inkvec-cli/src/pipeline.rs:439`). The emitter drops the faces written as strokes -from the fill tree and paints the strokes on top (`crates/inkvec-cli/src/emit.rs:180`, -`write_ribbons`, `crates/inkvec-cli/src/emit.rs:1299`). +(`crates/inkvec-cli/src/pipeline.rs:438`). The emitter drops the faces written as strokes +from the fill tree and paints the strokes on top (`crates/inkvec-cli/src/emit.rs:181`, +`write_ribbons`, `crates/inkvec-cli/src/emit.rs:1310`). ## What problem this solves @@ -34,7 +35,7 @@ research, 2026-10-02). No fitting change reaches it; only a change of representa This stage is that change, face by face, and it decides each face by description length — the same currency the fitter uses — with a fidelity bound on top. -## The passes, for one face (`fit_face`, `ribbon.rs:324`) +## The passes, for one face (`fit_face`, `ribbon.rs:327`) 1. **Boundary and width by pairing** (`boundary.rs`). The face's rings after the boundary solve, with inward normals voted against the face mask. Every boundary point walks @@ -49,7 +50,7 @@ the same currency the fitter uses — with a fidelity bound on top. at every node a cross-section from the nearest boundary point across to the other side (`cross_section`, `graph.rs:342`); a sample is reliable when the far side is anti-parallel and the width agrees with `w0`. -3. **Topology readings** (`hypothesis`, `ribbon.rs:474`; `TopoOptions`). Under round joins +3. **Topology readings** (`hypothesis`, `ribbon.rs:481`; `TopoOptions`). Under round joins the readings are tried in turn while the previous one is a misfit: no rebuilt corners; rebuilt corners; and the **chordal axis** with rebuilt corners. Each reading keeps the branches' reliable cores (`cores`, `graph.rs:375`), drops spurs and merges junction @@ -66,29 +67,48 @@ the same currency the fitter uses — with a fidelity bound on top. sleeve triangles link their two chords, junction triangles link their three to the centroid (`axis`, `chordal.rs:458`). Branches with a free end and under half a width of core are dropped there (the axis sends a spur into every ear of the outline). -5. **Centreline fit** (`fit_chain`, `ribbon.rs:695`). Chains are thinned to - `CHAIN_SAMPLES_PER_WIDTH` = 8 samples per stroke width (`ribbon.rs:609`; `decimate`, - `ribbon.rs:650`: runs of measured samples between anchors replaced by their middle +5. **Centreline fit** (`fit_chain`, `ribbon.rs:710`). Chains are thinned to + `CHAIN_SAMPLES_PER_WIDTH` = 8 samples per stroke width (`ribbon.rs:624`; `decimate`, + `ribbon.rs:665`: runs of measured samples between anchors replaced by their middle sample with sigma `sqrt(Σσ²)/m`), then fitted by the outline fitter's MDL dynamic program (`inkvec_fit::multimodel`) or a whole primitive when that is cheaper, in parallel. A coarse fit at an eighth of the samples first declines readings whose - centrelines already cost `COARSE_DECLINE` = 1.25× the budget (`ribbon.rs:632`). -6. **Stroke solve** (`refine::solve_adaptive`, `refine.rs:894`). Levenberg-Marquardt over + centrelines already cost `COARSE_DECLINE` = 1.25× the budget (`ribbon.rs:647`). +6. **Stroke solve** (`refine::solve_adaptive`, `refine.rs:895`). Levenberg-Marquardt over every control point and the half-width against the boundary residual `r_p = (d(p, C) - h)/σ_p` (see the solve below), then up to `MAX_SPLITS` = 12 - (`refine.rs:857`) splits of the segment carrying the most residual, each kept only when + (`refine.rs:858`) splits of the segment carrying the most residual, each kept only when the description length falls. -7. **Score and checks** (`score::score`, `score.rs:154`; `uncovered`, `ribbon.rs:427`; - `refine::drawable`, `refine.rs:1151`): the chi-squared of the strokes' painted outline +7. **Merges** (`merge::merges`, `refine/merge.rs:91`). The splits run backwards: every + joint of a centreline is offered the segments that could replace the two it joins + (`joint`, `refine/merge.rs:362`) -- the line through their outer ends; an arc on + the circle of either one that is an arc, of both when they turn the same way, or through + the three points (`arc_about`, `refine/merge.rs:431`); the cubic with the outer + tangents, its arms fitted by Schneider's least squares (`cubic_through`, + `refine/merge.rs:471`) -- every cubic and arc the line on its chord, and a + closed path of arcs on one circle that circle (`common_circle`, `refine/merge.rs:596`). + Each is measured, unsolved, against the boundary points the replaced segments explained; + the best is kept outright when the strokes' description length already falls, else + solved for `TRIAL_ITERS` iterations and kept when it falls then, drawable and with the + strokes' chi-squared still within the decision's fidelity bound (the caller's + `chi2_cap`). The fitter's arcs stop at 120° (`MAX_ARC_DEGREES`), so a 270° arc drawn + by the artist came back as three; a cap as an arc and a short line continuing it; a + straight run as two lines meeting at 1°. A merged arc within `HALF_TURN_BAND_DEGREES` = + 15° of a half turn is written as the exact half circle on its chord, and the solve + refuses any arc that drifts into that band otherwise (`conditioned`, + `refine.rs:1142`): there SVG's rebuilt centre moves by `R/k` times any rounding + of the radius. +8. **Score and checks** (`score::score`, `score.rs:154`; `uncovered`, `ribbon.rs:432`; + `refine::drawable`, `refine.rs:1182`): the chi-squared of the strokes' painted outline against every boundary point, the face's interior pixels checked as painted - (`MAX_UNCOVERED` = 0.2% of its pixels, `ribbon.rs:420`), and no cusp (no + (`MAX_UNCOVERED` = 0.2% of its pixels, `ribbon.rs:425`), and no cusp (no micro-segment or hairpin under miter joins). -Passes 3-7 run with round joins and round caps first; when the round fit leaves a point -more than `MITER_TRIGGER` = 0.25 px out (`ribbon.rs:410`) the face is also read under miter +Passes 3-8 run with round joins and round caps first; when the round fit leaves a point +more than `MITER_TRIGGER` = 0.25 px out (`ribbon.rs:415`) the face is also read under miter joins, and when the better reading has free ends and leaves a point more than -`BUTT_TRIGGER` = 0.1 of the width out (`ribbon.rs:406`), under butt caps. The cheaper by -`χ²/2 + λ·k` wins (`cheaper`, `ribbon.rs:385`). +`BUTT_TRIGGER` = 0.1 of the width out (`ribbon.rs:411`), under butt caps. The cheaper by +`χ²/2 + λ·k` wins (`cheaper`, `ribbon.rs:390`). ## The stroke model (`join.rs`, `score.rs`) @@ -104,11 +124,11 @@ distance to the end face — independent of `h`, which the Jacobian row records. Unknowns: every centreline control point, circular arcs' radii, circle primitives' centre and radius, and the half-width. Energy `E = Σ_p ((d_p - h)/σ_p)² + Σ_j ((θ_j - θ_j⁰)/σ_a)²` with a weak anchor (`ANCHOR` = 2 px, -`refine.rs:87`; the half-width's `ANCHOR_HALF` = 5% of itself, `refine.rs:95`). +`refine.rs:88`; the half-width's `ANCHOR_HALF` = 5% of itself, `refine.rs:96`). -- **Measurement** (`rows`, `refine.rs:708`). Each boundary point's nearest piece among the - centrelines flattened to chords within `FLAT_TOL` = 0.02 px (`refine.rs:546`; - `flat_pieces`, `refine.rs:570`: de Casteljau halving of cubics, equal-angle arcs), found +- **Measurement** (`rows`, `refine.rs:709`). Each boundary point's nearest piece among the + centrelines flattened to chords within `FLAT_TOL` = 0.02 px (`refine.rs:547`; + `flat_pieces`, `refine.rs:571`: de Casteljau halving of cubics, equal-angle arcs), found by a bounding-box hierarchy built along the pieces' order (`PieceTree`, `bvh.rs:97`), names its segment and a parameter; the exact distance is then polished on that segment (`dist.rs`: closed form for lines and circular arcs, Newton on the foot condition for @@ -127,15 +147,15 @@ and radius, and the half-width. Energy result bit for bit. - **Steps.** A step that lowers `E` and leaves every cubic free of cusps is taken (the cusp test runs before the measurement); `μ` shrinks by 3 after a step and grows by 4 after a - refusal. Stops after `MAX_ITERS` = 30 (`refine.rs:73`), when `E` falls by under 1e-5 - relatively, or after `MAX_RETRIES` = 8 refusals (`refine.rs:82`); more than `MAX_VARS` = - 400 unknowns (`refine.rs:100`) skips the solve. -- **Splits** (`solve_adaptive`, `refine.rs:894`). The segment carrying the most residual + refusal. Stops after `MAX_ITERS` = 30 (`refine.rs:74`), when `E` falls by under 1e-5 + relatively, or after `MAX_RETRIES` = 8 refusals (`refine.rs:83`); more than `MAX_VARS` = + 400 unknowns (`refine.rs:101`) skips the solve. +- **Splits** (`solve_adaptive`, `refine.rs:895`). The segment carrying the most residual is split (a line becomes a cubic on its chord, a cubic is cut by de Casteljau, an arc at its worst point). Before the split is solved, one Gauss-Newton step prices it - (`predicted_gain`, `refine.rs:832`, the score test): a split predicted to gain under - `SCREEN_KAPPA` = 0.25 of its price is refused unsolved (`refine.rs:871`). A solved trial - runs `TRIAL_ITERS` = 8 iterations (`refine.rs:79`) and is kept when the description + (`predicted_gain`, `refine.rs:833`, the score test): a split predicted to gain under + `SCREEN_KAPPA` = 0.25 of its price is refused unsolved (`refine.rs:872`). A solved trial + runs `TRIAL_ITERS` = 8 iterations (`refine.rs:80`) and is kept when the description length falls; the kept strokes are solved once more at the end. ## The decision (`ribbons.rs`) @@ -145,19 +165,30 @@ For each opaque, flat-filled, not transparent face of 16 px² to half the image: `ΔL = (χ²_stroke - χ²_outline)/2 + λ·(k_stroke - k_vanish)`, `χ²_outline` the face's fitted edges against their own measured points (`outline_chi2`, -`ribbons.rs:334`), `k_vanish` the parameters only this face writes in the stacked document -(`vanishing_params`, `ribbons.rs:372`). The face becomes strokes when `ΔL < 0`, +`ribbons.rs:347`), `k_vanish` the parameters only this face writes in the stacked document +(`vanishing_params`, `ribbons.rs:385`). The face becomes strokes when `ΔL < 0`, `k_stroke < k_vanish`, and `χ²_stroke - χ²_outline <= FIT_MARGIN_SD·sqrt(2N)` on its `N` -boundary points, `FIT_MARGIN_SD` = 2 (`ribbons.rs:278`; `decide`, `ribbons.rs:244`): the +boundary points, `FIT_MARGIN_SD` = 2 (`ribbons.rs:291`; `decide`, `ribbons.rs:257`): the strokes must fit as well as the outline within two standard deviations of a chi-squared statistic. Each centreline is its own element, as stroke icon sets draw them: a ``, or a stroked ``/``/`` for a centreline that is a whole primitive. One element carries `fill="none" stroke=… stroke-width=… stroke-linecap=… stroke-linejoin=…` -itself; several go in one `` that carries them (`element`, `ribbons.rs:419`). One path +itself; several go in one `` that carries them (`element`, `ribbons.rs:500`). One path per centreline rather than one compound path costs no numbers (a subpath's move-to is a path's) and keeps a reader that walks a path's points as one line from reading the pen lifts between strokes as turns. +**Faces that leave with it** (`absorbed_by`, `crates/inkvec-cli/src/ribbons.rs:430`). On an +opaque page the inside of a stroked ring is a face of its own, painted the page's colour on +top of the ring's filled disc. Once the ring is a stroke, that face paints what already +shows: the face the ring sits in is painted across all of its area underneath. So a child +the candidate alone encloses, painted exactly the colour of the face the candidate sits in +(flat, opaque, the same `#rrggbb`), leaves with it, and its outline counts in `k_vanish`. +The emitter drops it only where its nearest painted ancestor after the drop still has its +colour and nothing is punched out of it (`crates/inkvec-cli/src/emit.rs:188`). Lucide +`closed-caption` on white: a black rounded rectangle under a white one (12 parameters) +becomes one stroked rectangle (7), as the artist drew it. + ## Constants | Constant | Value | Where | Why | @@ -168,21 +199,25 @@ lifts between strokes as turns. | `SIGMA_FRAME` | 0.05 px | `boundary.rs:74` | the canvas frame is known exactly | | `SIGMA_JUNCTION`, `SIGMA_CAP` | 0.25, 0.15 px | `graph.rs:68`, `graph.rs:72` | rebuilt points, extrapolated | | `COS_CONTINUE` | 0.766 (40°) | `graph.rs:76` | sleeves continue through a junction | -| `MITER_TRIGGER` | 0.25 px | `ribbon.rs:410` | round fits of round art sit at 0.05-0.3 px | -| `BUTT_TRIGGER` | 0.1 w | `ribbon.rs:406` | a butt end fitted round misses by up to 0.2 w | -| `MAX_UNCOVERED` | 0.002 | `ribbon.rs:420` | a blob read as a ring of stroke paints a hole | -| `MAX_PRE_RMS` | 0.15 w | `ribbon.rs:455` | a blob read as a stroke starts a quarter of a width out | -| `CHAIN_SAMPLES_PER_WIDTH` | 8 | `ribbon.rs:609` | 4 cost 5% more parameters at 512 px | -| `COARSE_STRIDE`, `COARSE_DECLINE` | 8, 1.25 | `ribbon.rs:612`, `ribbon.rs:632` | calibrated on every reading (see the code) | -| `MAX_ITERS`, `TRIAL_ITERS`, `MAX_RETRIES` | 30, 8, 8 | `refine.rs:82`, `refine.rs:79`, `refine.rs:82` | | -| `ANCHOR`, `ANCHOR_HALF` | 2 px, 0.05 | `refine.rs:87`, `refine.rs:95` | holds unseen variables; keeps a blob from shrinking to a ring | -| `MAX_VARS` | 400 | `refine.rs:100` | | -| `FLAT_TOL` | 0.02 px | `refine.rs:546` | chords stand in for segments only in the search | -| `MAX_SPLITS`, `SCREEN_KAPPA` | 12, 0.25 | `refine.rs:857`, `refine.rs:871` | see `SCREEN_KAPPA`'s measurement | +| `MITER_TRIGGER` | 0.25 px | `ribbon.rs:415` | round fits of round art sit at 0.05-0.3 px | +| `BUTT_TRIGGER` | 0.1 w | `ribbon.rs:411` | a butt end fitted round misses by up to 0.2 w | +| `MAX_UNCOVERED` | 0.002 | `ribbon.rs:425` | a blob read as a ring of stroke paints a hole | +| `MAX_PRE_RMS` | 0.15 w | `ribbon.rs:460` | a blob read as a stroke starts a quarter of a width out | +| `CHAIN_SAMPLES_PER_WIDTH` | 8 | `ribbon.rs:624` | 4 cost 5% more parameters at 512 px | +| `COARSE_STRIDE`, `COARSE_DECLINE` | 8, 1.25 | `ribbon.rs:627`, `ribbon.rs:647` | calibrated on every reading (see the code) | +| `MAX_ITERS`, `TRIAL_ITERS`, `MAX_RETRIES` | 30, 8, 8 | `refine.rs:83`, `refine.rs:80`, `refine.rs:83` | | +| `ANCHOR`, `ANCHOR_HALF` | 2 px, 0.05 | `refine.rs:88`, `refine.rs:96` | holds unseen variables; keeps a blob from shrinking to a ring | +| `MAX_VARS` | 400 | `refine.rs:101` | | +| `FLAT_TOL` | 0.02 px | `refine.rs:547` | chords stand in for segments only in the search | +| `MAX_SPLITS`, `SCREEN_KAPPA` | 12, 0.25 | `refine.rs:858`, `refine.rs:872` | see `SCREEN_KAPPA`'s measurement | | `ROW_CAP` | 20 | `refine/normal.rs:88` | half-width plus two segments' variables | -| `MITER_MIN_SEG`, `MITER_MAX_TURN_COS` | 0.5 px, -0.866 | `refine.rs:1062`, `refine.rs:1065` | renderers draw short or hairpin miters otherwise | +| `MITER_MIN_SEG`, `MITER_MAX_TURN_COS` | 0.5 px, -0.866 | `refine.rs:1067`, `refine.rs:1070` | renderers draw short or hairpin miters otherwise | | `MITER_LIMIT` | 4 | `join.rs:39` | SVG's default `stroke-miterlimit` | -| `FIT_MARGIN_SD` | 2 | `ribbons.rs:278` | the gear and `wxt` (see the code) | +| `MAX_MERGE_TRIALS` | 12 | `refine/merge.rs:25` | merges solved per face; one kept unsolved is free | +| `MERGE_SLACK` | 1 | `refine/merge.rs:33` | the local estimate may sit at twice the price saved; the solve buys back part | +| `HALF_TURN_BAND_DEGREES` | 15° | `refine/merge.rs:44` | at 165° a radius rounded to 0.005 px moves the arc 0.04 px | +| `MAX_SWEEP_DEGREES` | 350° | `refine/merge.rs:48` | closer to a full turn the centreline is a circle | +| `FIT_MARGIN_SD` | 2 | `ribbons.rs:291` | the gear and `wxt` (see the code) | ## Measured (2026-10-04, switch on, judged as the gate judges) @@ -195,6 +230,33 @@ same quantity falls 4.9% and 3.5%. held_a at 128 px: dE00 0.1310 → 0.1186, par 1.471 → 1.022. Fast mode is unchanged (the stage does not run there). Whole trace at 512 px on lucide and openmoji: 1.5-1.7× v0.2.5's wall time, the stage's worst icon 2.4 s. +## Measured (2026-10-10, on by default, judged as the gate judges) + +Against the committed baseline (the same build with the stage off), Quality, 246 icons, +paired bootstrap: the stage as it was (2026-10-04), then with the merges, then with the +faces that leave with a stroke. + +| condition | axis | stage alone | + merges | + absorbed faces | +|---|---|---|---|---| +| quality-128ss | dE00 | −7.90 % | −8.20 % | −8.18 % | +| | parameter ratio | 1.495 → 0.994 | 0.957 | 0.954 | +| | turning | −5.75 % | −6.09 % | −6.11 % | +| quality-512ss | dE00 | −7.88 % | −8.54 % | −8.57 % | +| | parameter ratio | 1.728 → 1.217 | 1.170 | 1.168 | +| | turning | −5.72 % | −6.00 % | −6.02 % | +| quality-512ssop | dE00 | −6.57 % | −7.03 % | −11.35 % | +| | parameter ratio | 1.967 → 1.566 | 1.531 | 1.414 | +| | turning | −4.82 % | −4.87 % | −5.58 % | + +Every row is a demonstrable gain (the one-sided 95 % bound below zero). Lucide at 512 px +went from 1.46 to 1.16 times the artist's parameters with the merges; `closed-caption` and +`iteration-ccw` now carry exactly the artist's structure (one 219° and one 270° arc where +the trace had three arcs and two short lines each). Fast mode is unchanged (the stage does +not run there). Whole trace at 512 px, minimum of two runs per icon, one process at a +time: 1.16× the time with the stage off over the screen set (lucide 1.29×, material-icons +1.31×, openmoji 1.24×, simple-icons 1.23×, twemoji 1.09×, noto-emoji 1.05×), the worst +icon 0.8 s more. + ## Literature - Pairing: *Inspired by* Hilaire, Tombre (2006), doi:10.1109/TPAMI.2006.127; Tombre et @@ -217,5 +279,9 @@ on lucide and openmoji: 1.5-1.7× v0.2.5's wall time, the stage's worst icon 2.4 doi:10.1109/TPAMI.1980.4766968; split screen by the score test of Rao (1948), doi:10.1017/S0305004100023987, and Moré (1978), doi:10.1007/BFb0067700; splits inspired by Schneider (1990), Graphics Gems. +- Merges: *Inspired by* Pavlidis, Horowitz (1974), Segmentation of plane curves, IEEE + Transactions on Computers C-23(8), doi:10.1109/T-C.1974.224041 (split-and-merge); the + merged cubic's arms by Schneider (1990), above; why a true merge cannot cost fidelity: + `formal/InkvecTheory/InkvecTheory/Naturality.lean` (`natural_model_closer`). - Decision: Rissanen (1978), doi:10.1016/0005-1098(78)90005-5; the fit margin is not from the literature (see also Wilks 1938, doi:10.1214/aoms/1177732360). diff --git a/docs/algorithm/constants.md b/docs/algorithm/constants.md index 984243e7..882522ac 100644 --- a/docs/algorithm/constants.md +++ b/docs/algorithm/constants.md @@ -29,7 +29,7 @@ stage's own reference document — this table only summarizes. Paths are relativ | `REF_EXTENT` | 128.0 px | `inkvec-cli/src/units.rs:17-31` | intake size every pixel-denominated constant was tuned at; above it `price_in_raster_units` scales `--min-area` and lambda | measured (3.54x/6.02x/11.62x the artist's parameters at 128/256/512 px, `units.rs:17-26`; the guard: 128ss objective 0.4005 -> 0.4112 without it, `inkvec-cli/src/lib.rs:470-476`) | | `INTAKE_SCALE_FLOOR` | 1.5 | `inkvec-cli/src/lib.rs:121-123` | below this, `--intake-scale` leaves the input alone | measured (every corpus image reads 1.00) | | `INTAKE_SCALE_CAP` | 8.0 | `inkvec-cli/src/lib.rs:124-126` | ceiling on how much `--intake-scale` discards | motivated | -| `--max-dim` default | 2048 px | `inkvec-cli/src/args.rs:253, 358-362` | ceiling on traced (not emitted) size, applied at decode and again in `intake` | motivated | +| `--max-dim` default | 2048 px | `inkvec-cli/src/args.rs:254, 358-362` | ceiling on traced (not emitted) size, applied at decode and again in `intake` | motivated | | `--time-budget` split | 0.6 merge / 0.25 boundary-solve | `inkvec-cli/src/pipeline.rs:145-153` | advisory wall-clock split between the two stages that read a clock | none | | boundary-solve budget floor | 50 ms | `inkvec-cli/src/pipeline.rs:152` | least wall-clock budget the boundary solve gets under any `--time-budget` | none | | `MIN_SOURCE` (`pixel_grid`) | 16 px | `inkvec-cli/src/alpha/unblock.rs:102-110` | least source size the unblock keeps on the short axis | measured motive (the old 64 px floor on both sides undid 4x wordmarks only 2x) | @@ -60,7 +60,7 @@ stage's own reference document — this table only summarizes. Paths are relativ | `SOFT_SHARE` | 0.05 | `inkvec-cli/src/alpha.rs:439` | glow share that keeps white without the candidate ladder | none | | `FLAT_ALPHA` | 0.02 | `inkvec-cli/src/alpha.rs:440` | neighbour-alpha spread counted as "flat" translucency | none | | `DEGRADED_RESIDUAL` / `--sr-threshold` | 0.5 | `inkvec-sr/src/detect.rs:13-36` | interior-residual threshold above which `--sr auto` cleans | measured (30 icons, 5 conditions) | -| `--sr-scale` default | 2 | `inkvec-cli/src/args.rs:277` | output scale of the SR pre-pass | none | +| `--sr-scale` default | 2 | `inkvec-cli/src/args.rs:278` | output scale of the SR pre-pass | none | | interior-residual normalisation | `sum / 9n` | `inkvec-sr/src/detect.rs:103-110` | matches the reference Python implementation | derived (deliberate match, not a bug) | ## 02 — Coverage ([02-coverage.md](02-coverage.md)) @@ -130,7 +130,7 @@ stage's own reference document — this table only summarizes. Paths are relativ | name | value | file:line | controls | basis | |---|---|---|---|---| -| `min_region` shipped default | 2 px | `inkvec-cli/src/args.rs:250`, `inkvec-cli/src/pipeline.rs:180`, `inkvec-trace/src/lib.rs:214` | smallest component kept by despeckle; `min_region.max(2)` is the carve's minimum feature size (`inkvec-trace/src/lib.rs:676`); scaled by the oversampling factor squared above `REF_EXTENT` (`inkvec-cli/src/lib.rs:381-395`) | measured (a 9 px colour-mode floor was tried and measured worse, `inkvec-cli/src/pipeline.rs:173-178`) | +| `min_region` shipped default | 2 px | `inkvec-cli/src/args.rs:251`, `inkvec-cli/src/pipeline.rs:180`, `inkvec-trace/src/lib.rs:214` | smallest component kept by despeckle; `min_region.max(2)` is the carve's minimum feature size (`inkvec-trace/src/lib.rs:676`); scaled by the oversampling factor squared above `REF_EXTENT` (`inkvec-cli/src/lib.rs:381-395`) | measured (a 9 px colour-mode floor was tried and measured worse, `inkvec-cli/src/pipeline.rs:173-178`) | | `SADDLE_SIGMAS` | 3.0 | `inkvec-trace/src/regions.rs:40-44` | sigma a corner's coverage must clear 0.5 by before a saddle resolves (research build only) | motivated (a standard "three sigma" bar, not swept) | | `MAX_FACES` | 65,535 (`u16::MAX`) | `inkvec-trace/src/regions.rs:205-208` | most faces a face map can number; past it `cap_components` merges the smallest components into their neighbours (`inkvec-trace/src/regions.rs:293-416`) | derived (`u16` face ids, `u16::MAX` reserved for the outside of the image) | | absorption rounds | 2 | `inkvec-trace/src/regions.rs:768-769, 792` | rounds of whole-sliver absorption | motivated (one dissolved sliver can leave a neighbour thinner) | @@ -178,6 +178,8 @@ stage's own reference document — this table only summarizes. Paths are relativ | `SMOOTH_FRACTION` | 0.5 | `inkvec-trace/src/gradient/regions.rs:36-38` | fraction of a seam's pixel pairs that must be smooth steps | none | | `CARVE_RESIDUAL` | 0.06 | `inkvec-trace/src/gradient/carve.rs:16-20` | floor on the carve candidate threshold `max(8*sigma_noise, 0.06)` | motivated | | `CARVE_MAX` | 64 | `inkvec-trace/src/gradient/carve.rs:21-22` | most features carved from one image | motivated | +| `CODEC_VARIANT_LEVELS` | 8 levels | `inkvec-trace/src/fast/codec.rs` | on a lossy intake, how close (luma-weighted YCbCr) an ink may lie to a heavier one and be the codec's variant of it | measured as part of the codec clean-up (`quality-web`); the value itself not swept | +| `CODEC_BAND` | 2 px | `inkvec-trace/src/gradient/carve.rs` | on a lossy intake, how far inside its region a pixel must lie to be carved | measured (`quality-web`, 1/2/3 px: 2 px is the one reach no gated axis reads worse at) | | `CARVED_PAINT_ALPHA` | 0.5 | `inkvec-trace/src/native.rs:691-700` | mean opacity at or above which a carved feature named by the clear ink is renamed to the nearest visible ink (native-alpha path, `name_carved_paint`) | measured (residue 0.14-0.36, painting it cost dE00 on 5 of 8 icons; paint 0.80-1.00) | | `bic_lambda(n)` | 0.5 * ln(n) | `inkvec-trace/src/gradient.rs:320-327` | fill-selection lambda | derived (Bayesian information criterion) | | `IRLS_ROUNDS` | 2 | `inkvec-trace/src/gradient/stops.rs:68-69` | Huber reweighting rounds when a stop profile is fitted | none | @@ -199,14 +201,18 @@ to the upstream saddle merge; the two sizes after it choose only speed, never th | name | value | file:line | controls | basis | |---|---|---|---|---| -| `MIN_UNMIX_CONTRAST` | 0.02 | `inkvec-trace/src/planar.rs:414` | floor on unmixing contrast below which a point does not move | none | -| `CORNER_COS` | 0.5 (60 deg) | `inkvec-trace/src/planar.rs:424` | turning angle above which the tangent window narrows to 1 point | motivated (geometric bound) | -| `PAR_VERTICES` | 64 | `inkvec-trace/src/planar.rs:506` | fewest points before an edge's vertices are refined in parallel; smallest chunk one thread takes | motivated (a task of ~30 µs at 0.44 µs per vertex against rayon's few-µs split cost); schedule only, output identical | -| `PAR_MAP_VERTICES` | 512 | `inkvec-trace/src/planar.rs:520` | fewest boundary vertices in the map for the refinement, and symmetry detection beside it, to use threads | measured (per-icon serial/parallel timings by vertex count, `planar.rs:512-519`); schedule only, output identical | -| `SUBPX_WIN` (was `INKVEC_SUBPX_WIN`, *removed*) | 1 (the variable allowed 1..=8) | `inkvec-trace/src/planar.rs:416-419` (measurement at `:854-864`) | width of the tangent-estimation window | measured (two points each side improved dE00 on a 620-icon subset but cost DISTS and caused a face-order regression on one icon; left at 1, LOG-43) | +| `MIN_UNMIX_CONTRAST` | 0.02 | `inkvec-trace/src/planar.rs:417` | floor on unmixing contrast below which a point does not move | none | +| `CORNER_COS` | 0.5 (60 deg) | `inkvec-trace/src/planar/chord.rs:15` | turning angle above which the tangent window narrows to 1 point | motivated (geometric bound) | +| `PAR_VERTICES` | 64 | `inkvec-trace/src/planar.rs:499` | fewest points before an edge's vertices are refined in parallel; smallest chunk one thread takes | motivated (a task of ~30 µs at 0.44 µs per vertex against rayon's few-µs split cost); schedule only, output identical | +| `PAR_MAP_VERTICES` | 512 | `inkvec-trace/src/planar.rs:513` | fewest boundary vertices in the map for the refinement, and symmetry detection beside it, to use threads | measured (per-icon serial/parallel timings by vertex count, `planar.rs:505-512`); schedule only, output identical | +| `SUBPX_WIN` (was `INKVEC_SUBPX_WIN`, *removed*) | 1 (the variable allowed 1..=8) | `inkvec-trace/src/planar/chord.rs:7-10` (measurement at `:47-58`) | width of the tangent-estimation window | measured (two points each side improved dE00 on a 620-icon subset but cost DISTS and caused a face-order regression on one icon; left at 1, LOG-43) | +| `REACH` (strip reading) | 3 px | `inkvec-trace/src/planar/strip.rs:41` | how far along a column the window's flanks are searched, from the inner neighbour's mean | motivated (geometric: a boundary within 45 deg of the column's normal crosses at most two of its pixels) | +| `SATURATED` (strip reading) | 0.06 | `inkvec-trace/src/planar/strip.rs:44` | unmixed coverage within this of 0 or 1 makes a pixel a window's flank | none (the flanks' own values are summed, so the sum stays unbiased: `strip_unbiased`) | +| `SIDE_TOL` (strip reading) | 0.05 px | `inkvec-trace/src/planar/strip.rs:52` | the corner test: largest disagreement at the vertex's border between the central and the one-sided cubics | derived (every cubic passes exactly, `side_stencil_cubic`; noise gain 0.7 per difference) | +| `MAX_STEP` (strip reading) | 1.5 px | `inkvec-trace/src/planar/strip.rs:56` | largest difference between adjacent column means, about 56 deg | none | | `DEFAULT_SIGMA_MODEL` | 0.05 px | `inkvec-trace/src/coverage.rs:81` | see 02-coverage.md | measured | -| `CONTRAST_REF` | 0.25 | `inkvec-trace/src/planar.rs:1246` | reference contrast for `simplify_faint`'s inflation | none | -| `MAX_INFLATION` | 4.0 | `inkvec-trace/src/planar.rs:1247` | cap on `simplify_faint`'s sigma multiplier | none | +| `CONTRAST_REF` | 0.25 | `inkvec-trace/src/planar.rs:1207` | reference contrast for `simplify_faint`'s inflation | none | +| `MAX_INFLATION` | 4.0 | `inkvec-trace/src/planar.rs:1208` | cap on `simplify_faint`'s sigma multiplier | none | | `JUNCTION_MAX_MOVE` | 1.5 px | `inkvec-trace/src/planar/junctions.rs:73` | rejects an intersection solution beyond this move | none (the doc comment says only what it bounds; the 0.5 px trial 07-subpixel.md cites is not in the code) | | `JUNCTION_MIN_CONDITION` | 0.02 | `inkvec-trace/src/planar/junctions.rs:78` | minimum eigenvalue ratio admitted for a junction intersection | derived (equivalent to rejecting crossings below ~16 degrees) | | `junction_fit_points()` | 6 | `inkvec-trace/src/planar/junctions.rs:36` | interior points for near-junction extrapolation | none | @@ -341,6 +347,16 @@ half-integer lattice points (`inkvec-trace/src/symmetry.rs:19-21,176-186,220,243 | `SHARPEN_MAX_CHORD` | 2.5 | `inkvec-fit/src/merge.rs:569` | chamfer-cubic chord ceiling | motivated (chamfer ~1px/side) | | `SHARPEN_MAX_EDGE` | 8.0 | `inkvec-fit/src/merge.rs:574` | short-edge-with-chamfers ceiling | none | | `SHARPEN_MIN_TURN` | `CORNER_TURN_MIN` | `inkvec-fit/src/merge.rs:580` | corner-vs-smooth threshold | shared with `CORNER_TURN_MIN` by design since 2026-09-08 | +| `FIT.credit` | 1.0 | `inkvec-fit/src/extrema.rs:78` | parameters credited per node whose direction the extremum convention fixes | derived (the one coordinate it does not write, R0.2); measured: 2.0 also passed the 30 % sample, with the written count free | +| `FIT.same_count` | true | `inkvec-fit/src/extrema.rs:79` | a re-segmentation must write as many numbers as the run it replaces | measured (free: ratio_gap +0.11 % at quality-128ss, 4 icons closer and 9 further, where the trace already writes fewer numbers than noto's and twemoji's artists) | +| `RUN_BREAK_DEGREES` | 30.0 | `inkvec-fit/src/extrema.rs:99` | a join turning this much ends a smooth run | motivated (the artists' joins between curves are smooth or turn by more, R3.1); not swept | +| `WIGGLE_PX` | 0.5 px | `inkvec-fit/src/extrema.rs:102` | two extrema of one axis this close in value are a wiggle and get no node | none | +| `END_GAP_PX` | 1.0 px | `inkvec-fit/src/extrema.rs:104` | no node for an extremum this close (arc length) to a run's end | none | +| `DEDUP_PX` | 0.25 px | `inkvec-fit/src/extrema.rs:107` | two extrema of one axis this close (arc length) are one | none | +| `MIN_INTERIOR` | 2 | `inkvec-fit/src/extrema.rs:109` | fewest measured points inside a span | motivated (the arms need points to fit) | +| `MAX_REACH` | 8 | `inkvec-fit/src/extrema.rs:111` | candidates one span may reach in the search | motivated (bounds the search); not swept | +| `FAR_PX` | 3.0 px | `inkvec-fit/src/extrema.rs:114` | a path node with no measured point this close leaves the path alone | none | +| `REFINE_ROUNDS`, `REFINE_STEPS` | 3; 0.5 … 0.03 px | `inkvec-fit/src/extrema.rs:116`, `:118` | the node refinement's compass search | none | | `PARAMS_AXIS_LINE` (research) | 1.0 | `inkvec-fit/src/merge/snap.rs:17` | axis-snapped line cost | derived | | `MAX_AXIS_DEV_SIGMA` (research) | 3.0 | `inkvec-fit/src/merge/snap.rs:22` | per-sample axis-snap deviation cap | none | | `PARAMS_SMOOTH_CUBIC` (research) | 4.0 | `inkvec-fit/src/merge/snap.rs:204` | `S`-shorthand cost | derived | @@ -378,11 +394,11 @@ half-integer lattice points (`inkvec-trace/src/symmetry.rs:19-21,176-186,220,243 | arc rotation precision | 3 decimals | `inkvec-cli/src/pathdata.rs:114,258,338` | arc `phi` formatting | none | | rounded-rect radius floor | 1e-4 | `inkvec-cli/src/primitive.rs:76,281` | below this, written as a plain rect | none | | ellipse rotation floor | 1e-3 | `inkvec-cli/src/primitive.rs:258` | below this, no `transform` written | none | -| alpha-ramp endpoint precision | 2 decimals | `inkvec-cli/src/emit.rs:745` | independent of `EMIT_DECIMALS` | none | +| alpha-ramp endpoint precision | 2 decimals | `inkvec-cli/src/emit.rs:756` | independent of `EMIT_DECIMALS` | none | | `RAMP_MIN_INTERIOR` | 64 px | `inkvec-cli/src/alpha.rs:94` | fewest interior pixels before a plane is fitted to a face's alpha; `face_alpha` skips smaller faces without calling the fit | none (the fit's own first test, now named) | | `RAMP_MIN_FADE` | 0.15 (opacity) | `inkvec-cli/src/alpha.rs:88` | least opacity change across a face for it to count as a fade | none | | `RAMP_MAX_RESIDUAL` | 0.06 (opacity) | `inkvec-cli/src/alpha.rs:91` | largest RMS residual of the alpha plane | none | -| opacity precision | 3 decimals | `inkvec-cli/src/emit.rs:745,787,793` | `fill-opacity`/`stop-opacity` | none | +| opacity precision | 3 decimals | `inkvec-cli/src/emit.rs:756,787,793` | `fill-opacity`/`stop-opacity` | none | | `INKVEC_EMIT_DECIMALS` (env) | overrides `EMIT_DECIMALS` | `inkvec-cli/src/pathdata.rs:50` | the mechanism used to isolate rounding from segment price in the 7.2% measurement | measured | | `EVENODD` | ` fill-rule="evenodd"` | `inkvec-cli/src/emit/winding.rs:102` | written only on a path the winding pass cannot read; every other path is wound by nesting depth and carries no `fill-rule` | derived (the old output as a safe fallback) | | `JND` (gradient demotion) | 0.02 (OKLab) | `inkvec-cli/src/pipeline/demote.rs:41` | a gradient whose every pair of stops is closer than this is painted flat | none ("a conservative multiple of a just-noticeable difference") | @@ -392,6 +408,27 @@ half-integer lattice points (`inkvec-trace/src/symmetry.rs:19-21,176-186,220,243 | margin viewBox precision | 2 decimals | `inkvec-cli/src/post.rs:393` | `--margin` growth | none | | `ci_gate.py` ratio margin | 3% relative at the one-sided 95% upper bound (dE00 1%, turning 2%) | `bench/ci_gate.py:138` `MARGINS` | regression gate on parameter count vs. artist | measured (project's compactness regression budget) | +### Editability mode (`--editability`, `cli/editable.rs`, `cli/editable/`) + +| name | value | file:line | controls | basis | +|---|---|---|---|---| +| `AXIS_SNAP` | 2.5° | `inkvec-cli/src/editable.rs:77` | a handle this close to an axis snaps onto it | motivated (the artists' axis spike: 29 % of 313k handles within 0.05°); the window not swept | +| `DIAG_SNAP` | 1.5° | `inkvec-cli/src/editable.rs:80` | a handle this close to 45° snaps onto it | motivated (a 5× lift at 45° in the artists' handles); the window not swept | +| `G1_SNAP_DEG` | 3° | `inkvec-cli/src/editable.rs:82` | a join within a ring this close to smooth counts as smooth: its handles are snapped together | motivated (the artists' G1 lift); not swept | +| `KINK_DEG` | 30° | `inkvec-cli/src/editable.rs:87` | a join within a ring turning at most this much is made smooth (`pass_g1`), if the ring still guards | motivated (the artists' joins between curves are smooth or turn by more than 30°: 8.6 % of them in 3-30°, against 25.0 % of the trace's; R3.1) | +| `COLLINEAR_DEG` | 0.5° | `inkvec-cli/src/editable.rs:90` | two lines meeting at most this far from straight are written as one (`pass_collinear`) | derived (the battery's `collinear` threshold, `AXIS_DEG` in `bench/inkvec_bench/design.py`) | +| `LEN_MATCH` | 0.10 | `inkvec-cli/src/editable.rs:92` | handle lengths within this ratio are equalised | motivated (the artists' handle-length lift); not swept | +| `NODE_ALIGN` | 0.30 px | `inkvec-cli/src/editable.rs:94` | node coordinates this close share one value | motivated (98 % of the artists' nodes share a coordinate with another); not swept | +| `MIRROR_KEEP` | 0.95 | `inkvec-cli/src/editable.rs:96` | share of points whose reflection must find a partner for a mirror lock | none | +| `EDIT_SLACK` | 0.5 px | `inkvec-cli/src/editable.rs:100` | absolute slack on top of `3σ` in every pass's guard | measured (the deviation the artists' own handles carry from the pixel-optimal fit) | +| `MIRROR_SLACK` | 1.5 px | `inkvec-cli/src/editable.rs:104` | a mirror lock's guard | motivated (traced halves differ by 1-3 px) | +| `EMIT_GRID` | 0.01 px | `inkvec-cli/src/editable.rs:111` | the mirror axis snaps to the emitter's step | derived (`EMIT_DECIMALS`) | +| `AXIS_NODE` | 1.0 px | `inkvec-cli/src/editable.rs:115` | a node this close to the mirror axis is the crossing | none | +| `EDIT_PREFERENCE` | credit 3.0, written count free | `inkvec-cli/src/editable/curves.rs:25` | the extremum re-segmentation's preference in this mode | none (more than the fit's 1.0; held to `EDIT_SLACK`) | +| arc handle length | `4/3·tan(Δ/4)·r` | `inkvec-cli/src/editable/curves.rs` (`arc_as_cubics`) | the cubic standing for a piece of circle of `Δ ≤ 112.5°` | derived (Riškus 2006: 0.5523·r for a quarter, radial error ≤ 2.73e-4·r; 1.04e-3·r at 112.5°, computed) | +| `ARC_CUT_GAP_PX` | 1.0 px (and at most 22.5°) | `inkvec-cli/src/editable/curves.rs:68` | no cut at an extremum this close to an arc's end, along the arc | motivated (a 0.4 px sliver's handles are too short for two decimals to point; the fit's `END_GAP_PX`); not swept | +| `JUNCTION_G1_DEG` | 30° | `inkvec-cli/src/editable/junctions.rs:30` | a join between two edges turning at most this much is made smooth, if both still guard | motivated (the artists' kinked band, 3-30°: 8.6 % of their curve joins, 25.0 % of the trace's) | + ## 14 — Fast mode ([14-fast-mode.md](14-fast-mode.md)) Fast mode's own stages, under `inkvec-trace/src/fast/`. Several rows only choose a @@ -419,6 +456,12 @@ those say so, and none of them can change the output. The fitter round of 2026-0 | `F32_COUNT_LIMIT` | 2^24 | `inkvec-trace/src/fast/palette.rs:1379` | where the old f32 running count of ones stopped growing, reproduced in `ink_shares` | derived | | `BLEND_TOL` | 0.04 (sRGB and opacity) | `inkvec-trace/src/fast/faces.rs:157` | largest distance from a pixel to the line between two inks for it to count as their blend | none | | `SAME_ALPHA` | 0.02 | `inkvec-trace/src/fast/faces.rs:198` | largest opacity difference between two inks that can be one ink | none | +| `HALO_REACH` | 2 px | `inkvec-trace/src/fast/faces/halos.rs` | lossy intake only: a component with no pixel whose 5 x 5 window is all its own label is thin (a codec halo can be one; the thin-variant merge of `merge_same_inks` uses the same radius) | measured (`docs/theory/noise.md`: the codec's luma error 4.5 / 3.1 / 2.3 levels under 1 / 1-2 / 2-3 px from an edge, 0.2 in the interiors) | +| `HALO_OVERSHOOT` | 0.2 | `inkvec-trace/src/fast/faces/halos.rs` | how far beyond either ink, as a share of their difference, a halo's channel may lie | motivated (ringing overshoots its step; the dark halo of `twemoji/1f1fa` sits 5 % beyond the blue in luma) | +| `HALO_SLACK` | 0.02 (YCbCr, about 5 levels) | `inkvec-trace/src/fast/faces/halos.rs` | absolute slack on each channel of the halo hull, for channels in which the two inks barely differ | motivated | +| `STRIP_REACH` | 1 px | `inkvec-trace/src/fast/faces/halos.rs` | a thin component of an ink that has a thick component elsewhere must be a strip at this radius to be a halo | measured (`twemoji/1faa3`: its real 4 px rim taken at radius 2, dE00 0.212 -> 0.344; kept at 1) | +| `HALO_LINE_TOL` | 0.04 (weighted YCbCr) | `inkvec-trace/src/fast/faces/halos.rs` | how far from the segment between its two inks a strip of an ink with an area elsewhere may lie and be their halo | measured (codec halos 0.009-0.035 from theirs on `twemoji/1f1fa` and `openmoji/1F1FF-1F1F2`; `twemoji/1faa3`'s real rim 0.054) | +| `CHROMA_WEIGHT` | 0.25 | `inkvec-trace/src/fast/faces/halos.rs` | weight of each chroma channel against luma's, on squared differences, in a halo pixel's coverage and a halo's distance from its segment | motivated (4:2:0 stores chroma at half resolution, so where luma and chroma disagree on an edge the luma is the better reading of coverage) | | `SCAN_LANES` | 8 labels | `inkvec-trace/src/fast/faces/runs.rs:126` | labels compared per step while a run is scanned (one 128-bit vector of u16) | motivated; speed only | | face-id limit (`write_faces`) | 65,534 faces (`u16::MAX - 1`) | `inkvec-trace/src/fast/faces/runs.rs:513`; the same count as `CAPPED` in `inkvec-trace/src/fast/bands.rs:200` | most faces Fast numbers; past it the smallest components are merged into their neighbours (`regions::cap_components`, as Quality's `split_components` does past `MAX_FACES`) until this many remain, and at this count or more the ramp pass's palette precheck steps aside | motivated (face ids are u16 and `u16::MAX` is the outside of the planar map; the source does not say why Fast stops one below Quality's `MAX_FACES` = 65,535) | | `SPECKLE_PER_512` / `SPECKLE_MAX` | 4.0 px per 512 x 512 / 16.0 px | `inkvec-trace/src/fast/front.rs:32-34` | the speckle floor grows with image area, from `min_region` up to VTracer's 4 x 4 patch | measured (20 brand logos at 2048 px: 14% fewer coordinates, dE00 0.0729 -> 0.0725; masthead 19% at +0.01) | diff --git a/docs/internal/env-vars.md b/docs/internal/env-vars.md index e8527f49..c60e3849 100644 --- a/docs/internal/env-vars.md +++ b/docs/internal/env-vars.md @@ -69,16 +69,19 @@ No name from an unmerged research branch is listed: only what the code in this t | variable | type | default | read at | set by (outside the source) | what / why | |---|---|---|---|---|---| | `INKVEC_ABSDBG` | flag | off | crates/inkvec-trace/src/regions.rs:788 | docs/algorithm/04-regions.md | sliver-absorption rejections. | -| `INKVEC_ALPHADBG` | flag | off | crates/inkvec-cli/src/alpha.rs:1030, crates/inkvec-cli/src/emit.rs:628 | docs/algorithm/01-intake.md, docs/algorithm/13-emit.md | alpha / layer / emit face dump. | +| `INKVEC_ALPHADBG` | flag | off | crates/inkvec-cli/src/alpha.rs:1030, crates/inkvec-cli/src/emit.rs:639 | docs/algorithm/01-intake.md, docs/algorithm/13-emit.md | alpha / layer / emit face dump. | | `INKVEC_BOPT` | switch | on | crates/inkvec-cli/examples/neural_trace.rs:246, crates/inkvec-trace/src/boundary_opt.rs:606 | CHANGELOG.md, bench/ablate.py, bench/spikes.py, docs/BINDINGS.md, docs/algorithm/08-boundary-solve.md, tools/quality_audit/REPORT-2026-09-26.md | `0` skips the global boundary solve. bench/ablate.py and bench/spikes.py price the stage with it. | | `INKVEC_BOPTDBG` | flag | off | crates/inkvec-trace/src/boundary_opt.rs:645 | docs/algorithm/08-boundary-solve.md, tools/quality_audit/REPORT-2026-09-26.md | boundary-solve iteration trace. | +| `INKVEC_COMPLETION` | switch | on | crates/inkvec-cli/src/layers.rs | CHANGELOG.md | `0` skips the completion of faces under what is painted over them (chain R, the painter's interval); the A/B switch the chain's gate runs price the stage with. | +| `INKVEC_COMPLETION_DEBUG` | number | off | crates/inkvec-cli/src/layers.rs, crates/inkvec-cli/src/emit.rs | nothing | `1`: one summary line per trace; `2`: every candidate's measure and certificate. | +| `INKVEC_COMPLETION_DUMP` | count (face) | unset | crates/inkvec-cli/src/layers.rs | nothing | writes `layers-.ppm`: the face's regions and its candidate. | | `INKVEC_DEBUG_FIT` | flag | off | crates/inkvec-fit/src/lib.rs:1109 | nothing | line-vs-cubic run decisions in the fitter. | | `INKVEC_DIAG` | text | off | crates/inkvec-trace/src/diag.rs:55 | bench/degraded_eval.py, docs/TRAZOR_REVIEW.md, docs/algorithm/01-intake.md, docs/algorithm/04-regions.md, docs/algorithm/05-gradients.md, docs/algorithm/08-boundary-solve.md, docs/algorithm/14-fast-mode.md, docs/algorithm/constants.md | `1`/any: diagnostics as text on stderr, `json`: as JSON lines. | | `INKVEC_DPDBG` | flag | off | crates/inkvec-fit/src/multimodel.rs:135 | docs/algorithm/11-fitting.md | multimodel dynamic-program decisions. | -| `INKVEC_DUMP_CONTOUR` | path | unset | crates/inkvec-trace/src/planar.rs:589 | docs/algorithm/07-subpixel.md, docs/algorithm/14-fast-mode.md | appends refined boundary points and sigmas. | +| `INKVEC_DUMP_CONTOUR` | path | unset | crates/inkvec-trace/src/planar.rs:582 | docs/algorithm/07-subpixel.md, docs/algorithm/14-fast-mode.md | appends refined boundary points and sigmas. | | `INKVEC_DUMP_LABELS` | path | unset | crates/inkvec-trace/src/lib.rs:586 | docs/algorithm/04-regions.md | writes the label image as PPM. | -| `INKVEC_DUMP_MAP` | path | unset | crates/inkvec-cli/src/pipeline.rs:581 | nothing | writes the planar map (neural label generation). | -| `INKVEC_EDIT_DEBUG` | flag | off | crates/inkvec-cli/src/editable.rs:677 | nothing | editability mirror pass. | +| `INKVEC_DUMP_MAP` | path | unset | crates/inkvec-cli/src/pipeline.rs:580 | nothing | writes the planar map (neural label generation). | +| `INKVEC_EDIT_DEBUG` | flag | off | crates/inkvec-cli/src/editable.rs:908, crates/inkvec-cli/src/editable/junctions.rs:196 | nothing | editability mirror pass, and the joins at junctions. | | `INKVEC_EMIT_DECIMALS` | count | `EMIT_DECIMALS` (2) | crates/inkvec-cli/src/pathdata.rs:50 | CHANGELOG.md, bench/perceptual_probe.py, docs/algorithm/13-emit.md, docs/algorithm/constants.md | coordinate decimals; bench/perceptual_probe.py isolates rounding with it. | | `INKVEC_EVDBG` | flag | off | crates/inkvec-trace/src/gradient.rs:895, crates/inkvec-trace/src/gradient.rs:1024, crates/inkvec-trace/src/gradient/carve.rs:390 (+1) | docs/algorithm/05-gradients.md | fill-evidence and gradient-refusal trace. | | `INKVEC_FAB_TIMING` | flag | off | crates/inkvec-fab/src/lib.rs:92, crates/inkvec-fab/src/lines.rs:293 | nothing | inkvec-fab timings. | @@ -88,20 +91,20 @@ No name from an unmerged research branch is listed: only what the code in this t | `INKVEC_HARMONIZE_TOL` | number | `HARMONIZE_TOL` | crates/inkvec-cli/src/harmonize.rs:97 | CHANGELOG.md, bench/perceptual_probe.py | shape-harmonize tolerance; bench/perceptual_probe.py sets 1000 to disable it. | | `INKVEC_JDBG` | flag | off | crates/inkvec-trace/src/planar/junctions.rs:63 | CHANGELOG.md, docs/algorithm/07-subpixel.md | junction end-tangent fits (was `JDBG`, renamed to the prefix). | | `INKVEC_MERGEDBG` | flag | off | crates/inkvec-trace/src/gradient/bands.rs:456 | docs/algorithm/05-gradients.md | band-merge trace. | -| `INKVEC_NATIVE_ALPHA` | switch | on | crates/inkvec-cli/src/args.rs:263, crates/inkvec-cli/src/args.rs:834, crates/inkvec/tests/api.rs:211 | CHANGELOG.md, bindings/openapi.json, bindings/options.schema.json, crates/inkvec-py/README.md, crates/inkvec-py/python/inkvec/__init__.pyi, crates/inkvec-py/tests/test_inkvec.py, crates/inkvec-server/README.md, crates/inkvec/README.md, docs/BINDINGS.md, docs/algorithm/01-intake.md, packages/dotnet/README.md, packages/dotnet/src/LogoLabs.Inkvec/InkvecOptions.generated.cs, packages/go/README.md, packages/go/options_generated.go, packages/java/README.md, packages/java/src/main/java/com/logolabs/inkvec/InkvecOptions.java, packages/npm/README.md, packages/npm/src/options.generated.ts, packages/php/README.md, packages/swift/README.md, packages/swift/Sources/Inkvec/InkvecOptions.generated.swift, studio/core/src/options.rs | `0` makes the CLI default `--no-native-alpha` (CHANGELOG 0.1.4; docs/BINDINGS.md). | +| `INKVEC_NATIVE_ALPHA` | switch | on | crates/inkvec-cli/src/args.rs:264, crates/inkvec-cli/src/args.rs:839, crates/inkvec/tests/api.rs:211 | CHANGELOG.md, bindings/openapi.json, bindings/options.schema.json, crates/inkvec-py/README.md, crates/inkvec-py/python/inkvec/__init__.pyi, crates/inkvec-py/tests/test_inkvec.py, crates/inkvec-server/README.md, crates/inkvec/README.md, docs/BINDINGS.md, docs/algorithm/01-intake.md, packages/dotnet/README.md, packages/dotnet/src/LogoLabs.Inkvec/InkvecOptions.generated.cs, packages/go/README.md, packages/go/options_generated.go, packages/java/README.md, packages/java/src/main/java/com/logolabs/inkvec/InkvecOptions.java, packages/npm/README.md, packages/npm/src/options.generated.ts, packages/php/README.md, packages/swift/README.md, packages/swift/Sources/Inkvec/InkvecOptions.generated.swift, studio/core/src/options.rs | `0` makes the CLI default `--no-native-alpha` (CHANGELOG 0.1.4; docs/BINDINGS.md). | | `INKVEC_NO_ABSORB` | flag | off | crates/inkvec-trace/src/lib.rs:555, crates/inkvec-trace/src/native.rs:888 | CHANGELOG.md, bench/ablate.py, docs/algorithm/04-regions.md, tools/quality_audit/REPORT-2026-09-26.md | skips blend-sliver absorption. bench/ablate.py. | | `INKVEC_NO_CARVE` | flag | off | crates/inkvec-trace/src/lib.rs:665, crates/inkvec-trace/src/lib.rs:942, crates/inkvec-trace/src/native.rs:916 | CHANGELOG.md, bench/ablate.py, docs/BINDINGS.md, docs/algorithm/05-gradients.md, tools/quality_audit/REPORT-2026-09-26.md | skips residual carving. bench/ablate.py. | | `INKVEC_NO_TAPER` | flag | off | crates/inkvec-trace/src/planar/junctions.rs:491 | CHANGELOG.md, bench/ablate.py, docs/algorithm/07-subpixel.md, tools/quality_audit/REPORT-2026-09-26.md | skips taper junction placement. bench/ablate.py. | | `INKVEC_PALDBG` | flag | off | crates/inkvec-trace/src/color/mdl.rs:138, crates/inkvec-trace/src/color/reference_tests.rs:442, crates/inkvec-trace/src/lib.rs:401 (+2) | docs/algorithm/02-coverage.md, docs/algorithm/03-palette.md, tools/quality_audit/REPORT-2026-09-26.md | palette accept/reject trace. | -| `INKVEC_RIBBONS` | flag | off | crates/inkvec-cli/src/ribbons.rs:68 | docs/algorithm/15-strokes.md | runs the opt-in stroke stage, as `--detect-strokes` does, for a build the benchmark scripts cannot pass flags to. | +| `INKVEC_RIBBONS` | switch | `detect_strokes` (on) | crates/inkvec-cli/src/ribbons.rs:70 | docs/algorithm/15-strokes.md | `0` switches the stroke stage off and any other value on, overriding `--detect-strokes` / `--no-detect-strokes`, for a build the benchmark scripts cannot pass flags to. | | `INKVEC_RIBBONS_BRANCHES` | flag | off | crates/inkvec-trace/src/ribbon/graph.rs:591 | nothing | stroke stage: one stderr line per centreline branch and whether it is kept. | -| `INKVEC_RIBBONS_CHAINS` | flag | off | crates/inkvec-trace/src/ribbon.rs:515 | nothing | stroke stage: one stderr line per centreline chain of a candidate face. | -| `INKVEC_RIBBONS_DEBUG` | flag | off | crates/inkvec-cli/src/ribbons.rs:114 | nothing | stroke stage: one stderr line per candidate face. | +| `INKVEC_RIBBONS_CHAINS` | flag | off | crates/inkvec-trace/src/ribbon.rs:522 | nothing | stroke stage: one stderr line per centreline chain of a candidate face. | +| `INKVEC_RIBBONS_DEBUG` | flag | off | crates/inkvec-cli/src/ribbons.rs:116 | nothing | stroke stage: one stderr line per candidate face. | | `INKVEC_REFINEDBG` | flag | off | crates/inkvec-trace/src/centerline.rs:959 | nothing | centerline stroke refinement. | -| `INKVEC_SUBPXDBG` | flag | off | crates/inkvec-trace/src/planar.rs:588 | docs/algorithm/07-subpixel.md, docs/algorithm/14-fast-mode.md | sub-pixel search per point. | +| `INKVEC_SUBPXDBG` | flag | off | crates/inkvec-trace/src/planar.rs:581 | docs/algorithm/07-subpixel.md, docs/algorithm/14-fast-mode.md | sub-pixel search per point. | | `INKVEC_SVGMIN_DEBUG` | flag | off | crates/inkvec-svgmin/src/fit.rs:414, crates/inkvec-svgmin/src/fit.rs:592 | nothing | minifier merge decisions. | | `INKVEC_TAPERDBG` | flag | off | crates/inkvec-trace/src/planar/junctions.rs:69 | CHANGELOG.md, docs/algorithm/07-subpixel.md | taper fits (was `TAPERDBG`, renamed to the prefix). | -| `INKVEC_TIMING` | flag | off | crates/inkvec-cli/src/pipeline.rs:697, crates/inkvec-cli/src/ribbons.rs:233, crates/inkvec-cli/src/rings.rs:286 (+6) | docs/algorithm/00-overview.md, docs/algorithm/04-regions.md, docs/algorithm/05-gradients.md, docs/algorithm/10-symmetry.md, docs/algorithm/12-repair.md, docs/algorithm/13-emit.md, docs/algorithm/14-fast-mode.md | stage timings on stderr (Stopwatch and per-stage logs). | +| `INKVEC_TIMING` | flag | off | crates/inkvec-cli/src/pipeline.rs:696, crates/inkvec-cli/src/ribbons.rs:246, crates/inkvec-cli/src/rings.rs:286 (+6) | docs/algorithm/00-overview.md, docs/algorithm/04-regions.md, docs/algorithm/05-gradients.md, docs/algorithm/10-symmetry.md, docs/algorithm/12-repair.md, docs/algorithm/13-emit.md, docs/algorithm/14-fast-mode.md | stage timings on stderr (Stopwatch and per-stage logs). | | `INKVEC_UNDERLAP` | number (px) | `UNDERLAP` | crates/inkvec-cli/src/seams.rs:71 | CHANGELOG.md | seam underlap reach, `0` off (CHANGELOG 0.2.0). | ## (b) RESEARCH: `--features research` only @@ -120,7 +123,7 @@ No name from an unmerged research branch is listed: only what the code in this t | `INKVEC_DECODE_SHARE` | flag | off | crates/inkvec-trace/src/decode.rs:834 | docs/algorithm/09-decode.md | decode ribbon width pooling. | | `INKVEC_DECODE_THIN` | number (px) | `THIN_PX` 2.5 | crates/inkvec-trace/src/decode.rs:680, crates/inkvec-trace/src/decode/ribbon.rs:91 | docs/algorithm/09-decode.md | decode width gate. | | `INKVEC_EDGE_INK_DE00` | number | 4.0 | crates/inkvec-trace/src/ink_ideas.rs:874 | nothing | ink_ideas rule 5. | -| `INKVEC_EDIT_PASSES` | text list | all | crates/inkvec-cli/src/editable.rs:962 | nothing | run only the named editability passes, to price each. | +| `INKVEC_EDIT_PASSES` | text list | all | crates/inkvec-cli/src/editable.rs:1286 | nothing | run only the named editability passes, to price each. | | `INKVEC_FREE_CUBIC` | flag | off | crates/inkvec-fit/src/candidates.rs:85 | crates/inkvec-fit/Cargo.toml, docs/algorithm/11-fitting.md | free-tangent cubic candidate (does not pay; see candidates.rs). | | `INKVEC_G1` | flag | off | crates/inkvec-fit/src/multimodel.rs:259 | crates/inkvec-fit/Cargo.toml, docs/algorithm/11-fitting.md, docs/algorithm/13-emit.md, tools/quality_audit/REPORT-2026-09-26.md | `merge::snap_smooth_joins`. | | `INKVEC_G1DBG` | flag | off | crates/inkvec-fit/src/merge/snap.rs:250 | docs/algorithm/11-fitting.md | snap_smooth_joins trace. | @@ -137,7 +140,7 @@ No name from an unmerged research branch is listed: only what the code in this t | `INKVEC_POTTS_SCALE` | number | 1.0 | crates/inkvec-trace/src/ink_ideas.rs:635 | nothing | ink_ideas rule 3 price. | | `INKVEC_SADDLE` | flag | off | crates/inkvec-trace/src/regions.rs:91 | crates/inkvec-trace/Cargo.toml, docs/algorithm/04-regions.md, docs/algorithm/06-planar-map.md, tools/quality_audit/REPORT-2026-09-26.md | saddle-corner face merging (`merge_saddle_faces`). | | `INKVEC_SADDLEDBG` | flag | off | crates/inkvec-trace/src/regions.rs:94 | docs/algorithm/04-regions.md, docs/algorithm/06-planar-map.md | saddle trace. | -| `INKVEC_STRUCTURAL` | flag | off | crates/inkvec-cli/src/pipeline.rs:668, crates/inkvec-fit/src/multimodel.rs:249 | crates/inkvec-fit/Cargo.toml, docs/algorithm/01-intake.md, docs/algorithm/11-fitting.md, tools/quality_audit/REPORT-2026-09-26.md | structural MDL simplifier (fit) and its transactional baseline (CLI). | +| `INKVEC_STRUCTURAL` | flag | off | crates/inkvec-cli/src/pipeline.rs:667, crates/inkvec-fit/src/multimodel.rs:249 | crates/inkvec-fit/Cargo.toml, docs/algorithm/01-intake.md, docs/algorithm/11-fitting.md, tools/quality_audit/REPORT-2026-09-26.md | structural MDL simplifier (fit) and its transactional baseline (CLI). | | `INKVEC_STRUCTURAL_MAX_DIST` | number (px) | 0.85 | crates/inkvec-fit/src/structural/simplify.rs:92 | nothing | structural simplifier deviation bound. | | `INKVEC_STRUCTURAL_SIGMA_CAP` | number | 2.0 | crates/inkvec-fit/src/structural/simplify.rs:110 | nothing | structural simplifier sigma cap. | | `INKVEC_WITNESS_TAU` | number | 0.2 | crates/inkvec-trace/src/ink_ideas.rs:797 | nothing | ink_ideas rule 4. | @@ -175,7 +178,7 @@ No name from an unmerged research branch is listed: only what the code in this t | `INKVEC_NO_FADES` | flag | off | was crates/inkvec-trace/src/native.rs:1649 | nothing | native fade-merge ablation, undocumented. | | `INKVEC_NO_INK_ESCAPE` | flag | off | was crates/inkvec-trace/src/color.rs:1046 | docs/algorithm/03-palette.md | palette MDL-escape ablation. | | `INKVEC_NO_MEASURED_SIGMA` | flag | off | was crates/inkvec-trace/src/lib.rs:542, crates/inkvec-trace/src/native.rs:1592 | nothing | ablation, undocumented. | -| `INKVEC_NO_PRIMITIVE` | flag | off | was crates/inkvec-cli/src/pipeline.rs:602 | nothing | primitive-path ablation (30.5 % of the ratio; the number is kept in the comment). | +| `INKVEC_NO_PRIMITIVE` | flag | off | was crates/inkvec-cli/src/pipeline.rs:601 | nothing | primitive-path ablation (30.5 % of the ratio; the number is kept in the comment). | | `INKVEC_PARAMS_CUBIC` | number | 6.0 | was crates/inkvec-fit/src/cost.rs:56 | CHANGELOG.md | superseded by `--bezier-cost` (CHANGELOG 0.2.0 said the variable still worked). | | `INKVEC_RAMP_STEP` | number | 15.0 | was crates/inkvec-trace/src/gradient/regions.rs:16 | nothing | now `gradient::regions::RAMP_STEP_DE00`. | | `INKVEC_RINGING` | number | `SOFT_RINGING(_LARGE)` | was crates/inkvec-trace/src/lib.rs:435 | nothing | soft-intake ringing gate; constant. | @@ -187,8 +190,8 @@ No name from an unmerged research branch is listed: only what the code in this t | `INKVEC_SMOOTH` | number | 0.0 | was crates/inkvec-fit/src/merge.rs:82 | nothing | now `merge::SMOOTH_SLACK`. | | `INKVEC_SMOOTH_FRACTION` | number | 0.5 | was crates/inkvec-trace/src/gradient/regions.rs:38 | nothing | now `SMOOTH_FRACTION`. | | `INKVEC_SMOOTH_STEP` | number | 3.0 | was crates/inkvec-trace/src/gradient/regions.rs:29 | nothing | now `SMOOTH_STEP`. | -| `INKVEC_STROKE_TOL` | number | `STROKE_TOL` | was crates/inkvec-cli/src/emit.rs:266 | nothing | annulus-to-stroke tolerance. | -| `INKVEC_SUBPX_WIN` | count | 1 | was crates/inkvec-trace/src/planar.rs:390 | docs/algorithm/07-subpixel.md, docs/algorithm/constants.md | now `planar::SUBPX_WIN`; LOG-43 measurement kept in the comment. | +| `INKVEC_STROKE_TOL` | number | `STROKE_TOL` | was crates/inkvec-cli/src/emit.rs:277 | nothing | annulus-to-stroke tolerance. | +| `INKVEC_SUBPX_WIN` | count | 1 | was crates/inkvec-trace/src/planar.rs:393 | docs/algorithm/07-subpixel.md, docs/algorithm/constants.md | now `planar::chord::SUBPX_WIN`; LOG-43 measurement kept in the comment. | | `INKVEC_SVGMIN_COARSE_CAP` | count | 128 | was crates/inkvec-svgmin/src/fit.rs:461 | nothing | minifier constant. | | `INKVEC_SVGMIN_MERGE` | number | 1 (on) | was crates/inkvec-svgmin/src/fit.rs:474 | nothing | minifier merge pass switch. | | `INKVEC_SVGMIN_PER_SEG` | count | 24 | was crates/inkvec-svgmin/src/path.rs:212 | nothing | minifier constant. | diff --git a/docs/theory/README.md b/docs/theory/README.md new file mode 100644 index 00000000..7dc289b7 --- /dev/null +++ b/docs/theory/README.md @@ -0,0 +1,401 @@ +# Theory: inverting box-filter rasterisation + +> What an anti-aliased raster does and does not determine about the shapes drawn into it, +> proved in Lean, compared against the literature, and turned into a measured improvement of +> inkvec's sub-pixel stage. + +**Formal development:** [`formal/InkvecTheory`](../../formal/InkvecTheory/README.md) +(Lean 4.34.1, Mathlib; no `sorry`, no axiom of its own, 42 headline theorems audited). +**Experiments:** [`bench/theory`](../../bench/theory/README.md). +**Next:** [the optimal vectorizer, informally](optimal.md): what the best possible tracer +computes, how far inkvec is from it, and which approximations to make. +**Noisy inputs:** [what resampling and JPEG do to the evidence](noise.md): where the noise +sits, why area windows stay unbiased under it, and what the engine must change. +**Code it changed:** `crates/inkvec-trace/src/planar/strip.rs` (new) and `probe_chord` +(moved to `crates/inkvec-trace/src/planar/chord.rs`). + +## Summary + +Inkvec's founding claim is that an anti-aliased pixel is a *measurement*, the area of the +shape inside the pixel, not noise to threshold (`coverage.rs`). Reversing rasterisation is +therefore inverting a box filter. This page: + +1. surveys the mathematics behind that inversion and its formalisation status (none existed); +2. states what this repository now proves about it, in Lean, from Lebesgue measure up; +3. uses the theorems to diagnose inkvec's sub-pixel stage (stage 07) and to replace its + per-vertex reading, wherever it applies, by an exact one; +4. reports the measured effect: on the 246-icon regression gate, Fast mode's colour error + falls **8.7–11.0 %** in every condition and Quality's **1.4–4.5 %**, with no axis worse + than its margin. + +The theory is the box-filter model. It does not, and cannot, prove inkvec is "the best +tracer": that is an empirical claim about real inputs and a chosen metric. It proves which +readings of the pixels are exact, which are biased and by exactly how much, what no +estimator can recover, and that the code built on these theorems computes what they say. + +## 1. The problem + +A pixel `(i, j)` covers the unit square `[i, i+1] × [j, j+1]`. An exact-area renderer +(libart, FreeType's smooth rasteriser, font-rs, Skia's analytic AA, and inkvec's own forward +model in `boundary_opt/band.rs`) writes into it + +```text +P = B + a·(F − B), a = area(shape ∩ pixel) +``` + +for a shape of ink `F` on ground `B`. Inkvec unmixes `a` from `P` (`coverage.rs`), so the +question is what the field of `a` values determines about the shape's boundary, and how to +read it. Three classical answers dominate practice: + +* **threshold** `a ≥ ½` and trace the bitmap (Potrace; colour quantisers such as VTracer); +* read the boundary as the **½-level set of the interpolated coverage** (marching squares + on `a`; PolyFit's "isoline at the mean colour"; inkvec's `contour.rs` and its + `root_find_half` fallback); +* **invert the coverage of a straight edge per pixel** along an estimated normal (inkvec's + `planar::edge_offset`, stage 07). + +## 2. The literature + +A survey of the mathematics behind reversing rasterisation, with what each line of work +proves. Citations were checked against the papers or their authors' code; where only +metadata or a secondary source could be reached, that is said. + +**Exact-area (box-filter) rasterisation, the forward model.** Catmull (SIGGRAPH 1978) +computes exact area-weighted pixel colour by per-pixel polygon clipping. Duff (RIDT 1989, +*Polygon scan conversion by exact convolution*) and the signed-area accumulation of libart, +FreeType's `ftgrays.c` and Levien's font-rs make it a scan converter. Manson & Schaefer +(*Wavelet Rasterization*, CGF 30(2), 2011) compute box-filtered coverage of polygons and +quadratic/cubic Béziers exactly through boundary integrals. Auzinger, Guthe & Jeschke +(CGF 31(2), 2012) do the same for radially symmetric polynomial filters. DiffVG (Li et al., +TOG 39(6), 2020) samples a box filter by Monte Carlo and differentiates it with Reynolds +transport. None of these inverts the filter. + +**Volume-of-fluid interface reconstruction: the closest rigorous prior work.** In VOF the +cell volume fractions *are* box-filter coverage. Pilliod & Puckett (*JCP* 199(2), 2004) +build reconstructions (LVIRA, ELVIRA) from 3x3 column sums that reproduce every straight +interface exactly. Puckett (*CAMCoS* 5(1), 2010, eq. 11) states the identity this page calls +the column-sum theorem: when an interface `y = g(x)` enters and leaves a column through its +vertical sides, the column's volume fractions sum to `∫ (g − y₀) dx`. He proves second-order +max-norm convergence of a piecewise-linear reconstruction for `C²` interfaces under a +curvature condition. + +**Sub-pixel edge location by the partial area effect.** Trujillo-Pino, Krissian, +Alemán-Flores & Santana-Cedrés (*Image and Vision Computing* 31(1), 2013) use the same +identity in a 3x5 (up to 3x9) window to recover a quadratic edge `y = a + bx + cx²` from +three column sums: `c = (S_L + S_R − 2S_M)/(2(A−B))`, `b = (S_R − S_L)/(2(A−B))`, and +`a = (2S_M − 5(A+B))/(2(A−B)) − c/12` (confirmed in the authors' slides and MATLAB code; +the paper itself was behind a paywall). The `−c/12` term is the finite-volume cell-average +correction below with `h = 1`. + +**Finite-volume reconstruction.** A polynomial of degree `< n` is determined by its means on +`n` cells (Shu, ICASE 97-65, 1997, eq. 2.9; histopolation goes back to Schoenberg, *Splines +and histograms*, 1973). The point value from cell averages, +`u(xᵢ) = ūᵢ − (ūᵢ₊₁ − 2ūᵢ + ūᵢ₋₁)/24 + O(h⁴)`, is McCorquodale & Colella (*CAMCoS* 6(1), +2011, eqs. 12–13). Harten's subcell resolution (*JCP* 83(1), 1989) and Siddiqi, Kimia & Shu's +GENO (*CVGIP:GMIP* 59(5), 1997) locate a discontinuity inside a cell by preserving its +average: 1-D box-coverage inversion. + +**Finite rate of innovation and shapes from samples.** Dragotti, Vetterli & Blu (*IEEE TSP* +55(5), 2007) recover Diracs and piecewise polynomials from samples taken with kernels that +reproduce polynomials (the box kernel is the degree-0 case). Shukla & Dragotti (*IEEE TSP* +55(7), 2007) recover polygons with rational edge slopes from B-spline (including box) +samples. Pan, Blu & Dragotti (*IEEE TSP* 62(2), 2014) recover curves that are zero sets of +trigonometric polynomials from low-pass samples; a box kernel is not covered by their +exactness theory. Milanfar, Verghese, Karl & Willsky (*IEEE TSP* 43(2), 1995) and Golub, +Milanfar & Varah (*SISC* 21(4), 1999) recover polygon vertices from complex moments. Fatemi, +Amini, Baboulaz & Vetterli (*Shapes from Pixels*, *IEEE TIP* 25(3), 2016) recover the +minimum-perimeter shape consistent with pixel samples via a TV relaxation, exact under a +"reducibility" condition that is combinatorial to check. They show the recovered shape is +the *minimum-perimeter* consistent one, not that it is the true shape. + +**Precision limits.** Kiryati & Bruckstein (*CVGIP:GMIP* 53(1), 1991) prove error-free +reconstruction of straight-edged silhouettes from unquantised grey levels (for a disc-shaped +sensor, not a box) and a lower bound for bilevel sampling. Havelock (*IEEE TPAMI* 11(10), +1989) defines *locales*, the sets of object positions giving the same digital image, and +bounds the best possible position error of any estimator. Dorst & Smeulders (*IEEE TPAMI* +6(4), 1984) characterise the continuous segments consistent with a digital straight line. +Kakarala & Hero (*IEEE TPAMI* 14(7), 1992) give Cramér–Rao bounds for edge localisation in +the continuous domain, before sampling. Classic moment operators (Tabatabai & Mitchell 1984; +Lyvers et al. 1989; Ghosal & Mehrotra 1993) reach about 1/20 px with lookup-table bias +corrections. + +**Vectorisers.** Yang et al. (*TVCG* 22(2), 2016) optimise Bézigons against a box-filtered +(wavelet) rasterisation: analysis by synthesis, as in inkvec's boundary solve, not a +closed-form inverse. Hoshyari et al. (TOG 2018) and Kopf & Lischinski (TOG 2011) do not model +anti-aliasing; PolyFit (Dominici et al., TOG 2020) reads anti-aliased input at the isoline of +the mean colour, the ½-crossing. + +**Formalisation status.** No formalisation of rasterisation coverage, anti-aliasing, +area-sampling inversion or sub-pixel edge recovery was found in Lean, Coq/Rocq, Isabelle or +HOL Light. The nearest formal work is Pick's theorem (HOL Light: Harrison 2011; Isabelle AFP: +Binder & Kosaian 2024), Green's theorem (Isabelle AFP: Abdulaziz & Paulson 2018), a Why3 +proof of Bresenham's line algorithm (Filliâtre), and μSkia (Kulkarni, Whiting & Panchekha, +arXiv 2603.23696, 2026), a Lean semantics of Skia that assumes away anti-aliasing. Mathlib has +a trapezoidal-rule error bound but no midpoint rule, shoelace formula or polygon area. + +## 3. What is proved here + +All of it in [`formal/InkvecTheory`](../../formal/InkvecTheory/README.md), each theorem +named in parentheses. Coverage is *defined* as the Lebesgue area of `Ω ∩ pixel` in `ℝ²`. +Nothing about it is assumed. + +### 3.1 What a column of pixels measures + +**Column sums are boundary means** (`column_sum_eq_average`). If a boundary `y = f(x)`, +`f` continuous, stays within rows `j₀ … j₀+m` over column `i`, then + +```text +Σ_{r 0`. Through *any* `L`-level per-pixel quantiser it is +off by `δ/2` for every `δ < 1/L`. The bound binds every tracer that binarises or +colour-quantises before it finds boundaries, whatever it does afterwards. + +**Sub-pixel strokes** (`hidden_stroke_invisible`, `width_contrast_ambiguity`). A stroke of +width `w < 1` inside one pixel row has every position in a `1 − w` interval give the same +pixels, and its pixels fix only width × contrast (`coverage.rs`: "a 0.3px black stroke and a +1px grey stroke produce the same pixels"). + +### 3.3 What can be recovered, exactly + +**Polynomial boundaries are determined** (`zeros_of_zero_averages`, `poly_eq_of_averages`, +`polynomial_boundary_determined`). A boundary of degree `< n` is fixed by its pixels on `n` +columns. A line needs two (`line_from_two_columns` gives the closed form), a cubic graph four. +This is the other side of §3.2: the null space vanishes once the boundary is drawn from a +model with no more parameters than the columns it covers. That is what a model-selecting +fitter exploits, and what free-point optimisation lacks. + +**Points from pixels, exact for cubics** (`cubic_point_from_means`, `quartic_defect`, +`boundary_point_from_pixels`). From three adjacent column sums `S₋, S, S₊`, the boundary +passes through `(i + ½, j₀ + S − (S₊ − 2S + S₋)/24)` exactly whenever it is a cubic; the +first missed term is `−(3/640)f''''`. This is the finite-volume correction, whose fourth-order +accuracy already implies exactness on cubics, and it is Trujillo-Pino's centre coefficient +(their model is a quadratic; their slope coefficient, unlike the centre, is biased on a +cubic). What is added here is the machine-checked chain from pixel areas to the point. + +**Thin strokes that straddle a border** (`straddle_inversion`). A stroke thinner than a pixel +that crosses a pixel border along a whole column is read exactly from its two pixels: +centre line `j + 1 + (a₊ − a₋)/2`, width `a₋ + a₊`. + +**Under noise** (`strip_unbiased`, `strip_variance`, `face_value_noise`, +`point_from_means_noise`). Zero-mean, pairwise independent pixel noise leaves a column sum +unbiased with variance `k·σ²`. The face value `(7(S₁ + S₂) − (S₀ + S₃))/12` has noise gain +`25/36`; the point correction `113/96`. + +**Under supersampling renderers** (`subCount_close`, `ss_column_sum_close`). With `n × n` +point supersampling instead of exact area, a column sum is the `n`-point midpoint rule of the +boundary height to within `1/(2n)` px, `1/16` px on the 8x8 renders inkvec's regression +corpus uses. That is an upper bound on the column sum's error. Informally it is also a floor +for any reading: a boundary aligned with the sample grid moves no sample until it crosses a +sample row, so its pixels cannot place it more finely. + +### 3.4 How biased the common readings are + +**The ½-crossing** (`levelSet_reading`, `levelSetBias_le`, `levelSetBias_max`). On a +straight, axis-aligned, noiseless step edge (the easiest input there is), reading the edge +where the linear interpolation of pixel-centre coverages crosses ½ puts an edge `δ` above its +pixel's centre at `δ/(½+δ)`. The error is at most `3/2 − √2 ≈ 0.0858` px, and that maximum +is attained. The literature has empirical measurements of this bias (Rockett 1999; Lyvers et +al. 1989) but, as far as the survey found, not the constant. The column sum reads the same +edges with error 0 (`column_sum_reading`). `coverage.rs`'s `DEFAULT_SIGMA_MODEL = 0.05 px`, +"measured on analytic circles" for level-set extraction, is consistent with this bias. + +**The coverage centroid on a thin stroke** (`centroid_bias`, `centroid_bias_worst`). Reading +a straddling sub-pixel stroke's centre as the coverage centroid of its two pixels, as +`planar::ridge_offset` does, is off by `(1 − w)(a₊/w − ½)`, up to `(1 − w)/2`: as large as +the error of not knowing the position at all, in the one case where it is known exactly. + +### 3.5 The code's own constants + +`strip.rs`'s rational constants are proved exact (`histopolate_cubic`, `face_value_cubic`, +`side_stencil_cubic`). Fed the four cell means of any cubic, its `histopolate` returns that +cubic's coefficients, and the one-sided stencils of its corner test agree with the central +one on every cubic. End to end (`strip_reading_exact`): from the raw Lebesgue pixel areas of +the four columns round a pixel border, `histopolate` returns the boundary cubic's own +coefficients, so the vertex `strip.rs` slides onto it lies on the boundary. + +## 4. What the theorems say about inkvec + +Measured on shapes rendered with an exact-area rasteriser (`bench/theory/exact_raster.py`, a +float64 port of font-rs's accumulation, checked against hand computations), 64 px, 8-bit, +by distance from each boundary point to the true boundary (`bench/theory/inkvec_compare.py`): + +| reading | mean px | p99 px | max px | +|---|---|---|---| +| ½-crossing of interpolated coverage | 0.0505 | 0.087 | 0.094 | +| inkvec stage 07 (`refine_subpixel`), before this change | 0.0720 | 0.315 | 0.613 | +| inkvec stage 07, after it (§5) | 0.0034 | 0.073 | 0.349 | +| column sum + cubic correction (Python, `strip_eval.py`) | 0.0011 | 0.003 | 0.004 | + +The per-vertex reading was worse than the plain ½-crossing on average, for three reasons the +theory names: + +1. **It needs a normal and does not have one.** `edge_offset` inverts a straight edge's + coverage exactly *given its normal*. The normal comes from the lattice staircase and is + quantised to multiples of 45°; where two partial pixels bracket ½ the reading falls back to + linear interpolation between them, which is the biased ½-crossing of §3.4. The column sum + needs no normal at all (§3.1). +2. **The seam vertex of every closed ring was never refined.** `probe_chord` clamped + indices at the ends of an edge, so a closed ring's first vertex took its chord from one + neighbour only. On a ring whose seam lies on a horizontal run that is a horizontal normal + on a horizontal boundary: the probe runs along the boundary and the vertex stays on the + lattice, 0.30 px off on an exact disc. Quality's boundary solve repairs it; Fast mode kept + it in every closed ring. +3. **It reads one vertex at a time**, where the evidence about a smooth boundary is spread + over several columns. The cubic through four column means uses all of it. + +The boundary solve (stage 08) recovers most of this in Quality mode: it fits the exact +rendered coverage. On 30 exact circles Quality's emitted `` is within 0.0065 px of +the true radius on average, against 0.027 px for Fast. But §3.2 says the solve's data term +is flat along the zigzag and, with free 2-D points, along at least `2N − M` directions, so it +needs priors (`K_KINK`, `K_ANCHOR`) to choose for it. A start already on the boundary leaves +the priors less to decide. + +## 5. What changed + +**The strip reading** (`crates/inkvec-trace/src/planar/strip.rs`). For a vertex between two +flat fills with enough contrast, before the per-vertex probes: + +1. Read six adjacent pixel columns around the vertex (rows when the boundary is steeper than + 45°, and the other axis when the first declines). In each, find the window from a pixel + saturated in one face to the nearest pixel saturated in the other, and sum its unmixed + coverages, flanks included. By `column_sum_eq_average` that is the boundary's mean height + over the column, and summing the flanks' own values keeps it unbiased under noise + (`strip_unbiased`). Each column's window is searched around its inner neighbour's mean, so + steep boundaries are followed. +2. Histopolate the cubic through the four central means (`histopolate`: exact constants, + `histopolate_cubic`). It *is* the boundary whenever the boundary is a cubic + (`poly_eq_of_averages`). +3. Refuse a corner. The cubics through the left four and the right four columns must agree + with the central one at the vertex's pixel border to within `SIDE_TOL = 0.05` px. Every + cubic passes (`side_stencil_cubic`); a corner within reach, or a third colour in a window, + does not. +4. Slide the vertex along its lattice normal onto the cubic (Newton). The edge keeps one + point per vertex, so nothing downstream sees a different structure. + +A vertex where any step declines takes the per-vertex probes as before. + +**The seam** (`probe_chord`). A closed edge's chord wraps round its seam. + +### Measured + +Stage-07 points, `bench/theory` shapes (circles, ellipses, straight edges at random angles, +rotated squares, regular polygons), distance to the true boundary in px: + +| renderer | before: mean / p99 / max | after: mean / p99 / max | +|---|---|---| +| exact area | 0.0734 / 0.319 / 0.516 | **0.0106 / 0.180 / 0.368** | +| 8x8 supersampled | 0.0732 / 0.318 / 0.443 | **0.0159 / 0.194 / 0.351** | + +The remaining tail is vertices where the strip reading declines (corners, junctions, +windows a third colour enters) and the probes still decide. + +The regression gate (`bench/ci_gate.py`, 246 icons, judged at 1024 px against the artists' +files, paired family-stratified bootstrap) against this branch's `main` with both changes +off: + +| condition | dE00 (95 % CI) | icons better / worse | turning | parameters vs artist | +|---|---|---|---|---| +| fast-128ss | **−10.96 %** [−12.28, −9.71] | 216 / 30 | −0.69 % (better) | −2.72 % (better) | +| fast-512ss | **−8.70 %** [−10.43, −7.18] | 220 / 22 | −1.13 % (better) | −0.02 % | +| fast-512ssop | **−9.83 %** [−11.71, −8.15] | 216 / 21 | −1.22 % (better) | −0.68 % | +| quality-128ss | **−4.51 %** [−6.61, −2.54] | 144 / 79 | +0.01 % | +1.93 % (margin 3 %) | +| quality-512ss | **−1.89 %** [−3.52, −0.26] | 124 / 99 | −0.04 % | +0.72 % | +| quality-512ssop | −1.36 % [−2.87, +0.19] | 131 / 93 | +0.36 % | +0.50 % | + +The gate passed: every dE00 and turning change is a demonstrable gain or non-inferior, and +every parameter-ratio change is inside its 3 % margin. Quality spends slightly more +parameters at 128 px (+1.9 %), because sharper boundary points give the MDL fitter more +evidence for detail, while its colour error falls 4.5 %. Ablated, the strip reading accounts +for the whole gain (fast-128ss −10.92 %, quality-128ss −4.32 % on its own). The seam fix is +within noise on every condition: the corpus's closed rings mostly start at a junction or a +corner. The hard-case ratchet passes 42/42 in Quality and 28/42 in Fast, one more than before +(`edge_axis`). + +Time, whole process, 40 corpus icons at 512 px (minimum of three runs each for Fast): +Fast median 22.3 ms before, 22.7 ms after; Quality median 538 ms before, 529 ms after. The +strip reading reads pixels directly at their centres and compares squared residuals, which +is what keeps it out of Fast's budget; reading them through the probes' bilinear sampler +had cost Fast 14 %. + +## 6. What else the theory suggests, ranked + +1. **Read thin strokes from the straddle formula** (`straddle_inversion`, `centroid_bias`). + `ridge_offset` reads a sub-pixel stroke from its coverage centroid, biased up to + `(1 − w)/2`. Where the stroke straddles a border the exact centre is + `j + 1 + (a₊ − a₋)/2`; where it does not, the pixel centre is the minimax choice. Small, + local, testable on `bench/cases` `ribbon_*`. +2. **Remove the null space from the boundary solve instead of pricing it.** The data term + is flat along exactly the directions `polyline_kernel` and `flat_directions` name. Moving + points only across the boundary removes the tangential half. Parametrising each run by a + curve with no more coefficients than the columns it covers removes the rest + (`polynomial_boundary_determined`). Either leaves the kink prior to express a preference, + not to stand in for missing data, and should cut the iterations a quarter of the parts now + spend at the cap. +3. **Retune `DEFAULT_SIGMA_MODEL`.** It encodes the ½-crossing's resolution limit (0.05 px, + §3.4). Strip-read vertices are an order of magnitude better located. Because sigma scales + with `lambda`, this is a fidelity/compactness move to be swept, not a free gain. +4. **A minimum span for the fitter's segments.** A segment with `p` shape coefficients + needs at least `p` columns of evidence (`polynomial_boundary_determined`); shorter + segments are fitting the null space. +5. **Corners from one-sided stencils.** Where the corner test refuses, the one-sided cubics + (or lines) on either side are each exact on their side; intersecting them would place the + corner, the role `refine_junctions` plays for junctions. +6. **Estimate the compositing curve (DESIGN.md S0).** The column-sum theorem holds in the + space where the renderer blends. A straight edge's column sums are affine in the column + index only under the right transfer curve, which makes the curve measurable from the image. + +## 7. Limits + +* The model is exact area coverage, composited linearly in the encoded values, with two + colours meeting at each boundary. Renderers that point-supersample are covered with the + `1/(2n)` floor of §3.3; linear-light compositing and colour management are not modelled. +* The theorems are about the coverage `a`. Unmixing `a` from colours (`unmix_pair`) is taken + as given; it is exact for two flat fills and approximate at gradients, which is why the + strip reading is used only between flat fills. +* The strip reading is exact on cubic boundaries in the noiseless exact-area model. Elsewhere + its error is bounded by the theorems' error terms (`quartic_defect`, `ss_column_sum_close`) + or it declines. Its corner test cannot tell a gentle corner (under about 30°) from noise and + may round it by up to about 0.1 px. +* The measured gains are on the committed corpus and the synthetic shapes above. Other + inputs (photographs, heavily compressed JPEG, hand-drawn art) are untested here. + +## Reproduce + +```bash +cargo build --release -p inkvec-cli +python3 bench/theory/exact_raster.py # renderer self-check +python3 bench/theory/strip_eval.py # estimators on exact renders +python3 bench/theory/inkvec_compare.py --exe target/release/inkvec +python3 bench/ci_gate.py --exe target/release/inkvec # the regression gate +cd formal/InkvecTheory && lake exe cache get && lake build && lake build InkvecTheory.Audit +``` diff --git a/docs/theory/chain-boundary.md b/docs/theory/chain-boundary.md new file mode 100644 index 00000000..4d6ae250 --- /dev/null +++ b/docs/theory/chain-boundary.md @@ -0,0 +1,1259 @@ +# Chain B: from pixels to a likelihood over descriptions + +> The boundary chain of [`chains.md`](chains.md), stated and argued informally: what the +> pixels measure, the exact likelihood of any candidate description against them, where +> that likelihood is flat, and how precisely it fixes every coordinate the representation +> might write. Each claim says whether it is proved here informally, proved in +> [`formal/InkvecTheory`](../../formal/InkvecTheory/README.md), measured, or open. The +> section [Interface proposal](#interface-proposal) is what this chain hands to the +> representation chain; [Phase 2](#phase-2-formal-then-code) is how it becomes Lean and Rust. + +## Summary + +* **One identity carries the chain.** Summed over any set of whole pixels, a face's unmixed + weights are the area of that face inside those pixels, for any shape whatever (B2.1). So + any candidate description (a curve, a spline, an arc, a primitive, a stroke, the visible + partition of a layered drawing) can be scored exactly against the pixels by computing + areas, with no boundary points extracted first. The column-sum theorem + (`column_sum_eq_average`) is the special case of a graph and one column. +* **The likelihood** is a sum of squared area residuals over a partition of the boundary's + pixels into windows, each with a calibrated variance (B2.2-B2.5). Column windows keep at + least 3/4 of the information that per-pixel terms carry when 8-bit quantisation dominates, + and all of it when supersampling dominates (argued here; measured to three digits). + Evaluating it takes time linear in the windows a candidate touches, and for curves linear + in their parameters it is a quadratic with prefix-sum coefficients. +* **The variances are known.** 8-bit quantisation gives each window `n_partial / (12·255²)` + on a grey axis (measured 0.00114 per partial pixel against 0.00113); `n × n` point + supersampling adds `1/(12n³)` per window at generic slopes (measured 0.0129 against 0.0128 + at `n = 8`) and a bias of up to `1/(2n)` correlated along edges near 0° and 45°. The + corpus's own renderer has to be measured: the fourth difference of consecutive column + means estimates its floor per image, and it is the statistic `strip.rs`'s corner test + already computes. +* **Corners, junctions and thin strokes are not special to the likelihood** (B3): their + pixels are windows like any other, scored per pixel. What is special is identifiability + and precision. A vertex is fixed by its arms to `√(2V(1 + 12 s_m²/L²)/L) / sin α` + (measured within Monte Carlo error at 8-bit, within a factor of 1.4 under 8×8 point + supersampling, whose errors are not independent near 0° and 45°); a fillet can be told + from a sharp corner only above `r ≈ √(3σ / (tan(τ/2) − τ/2))` (0.13-0.42 px for a right + angle, 0.7-2.5 px for a 30° turn); a sub-pixel stroke along a pixel border has a + likelihood that is exactly flat over an interval. So B3 proposes and reports; it does not + decide. +* **Precision belongs to the parametrisation** (B4). The data never decide whether a + likelihood is flat: the parametrisation does (the zigzag of `polyline_kernel` is a + parametrisation's null space). The Fisher information of any parametrisation is + `∫ ρ(s) N(s) N(s)ᵀ ds`, with an information density `ρ` B2 supplies per unit of boundary + length. At the corpus's resolutions every position is known to well under a hundredth of + a design unit, so whether a coordinate lies on the design grid is never in doubt; what the + pixels leave in doubt is structure. +* **Proposed shortening**: corners, junction continuation, stroke-or-fill and + gradient-or-flat become the representation's decisions, tested against this likelihood; + B3 shrinks to proposals and per-pixel terms; stage 08's point solve, its kink and anchor + priors, and `DEFAULT_SIGMA_MODEL` are no longer needed once the fitter scores curves + against calibrated windows. + +| link | claim | status | +|---|---|---| +| B1.1 | a face holding an axis-aligned 2 × 2 square has a pure pixel, which reads a flat ink exactly | informal (elementary) | +| B1.2 | two-ink unmixing is unbiased, variance `dᵀΣd/‖d‖⁴`, at most `(Δ²/12)(‖d‖₁/‖d‖₂²)²` (grey axis) | informal; measured | +| B1.3 | three or more inks: weights need affine independence, geometry needs neighbours; the colour residual needs neither | informal | +| B1.4 | affine inks: exact centre values, first-moment correction, bias at most `|ΔG·ν|/(8‖d‖)` if ignored | informal | +| B1.5 | inks without pure pixels: hidden strokes fix width × contrast; border-straddling strokes fix neither width nor centre without the ink | Lean (first), informal (second) | +| B2.1 | window sum = area of the face in the window, any region (Cavalieri, Green) | Lean for graphs; general form informal | +| B2.2 | window sums lose information iff sensitivities are not proportional to variances; column sums keep `(1 − t/2)/(1 − t/3) ≥ 3/4` (8-bit), all (supersampled) | informal; measured | +| B2.3 | window variances under 8-bit and `n × n` point supersampling; per-image floor estimator | informal (bound in Lean); measured | +| B2.4 | calibration `E χ² = M`; cost linear; prefix sums for linear families | informal; measured | +| B2.5 | first variation `∂A_W = ∫_{γ∩W} δ ds`; information density `ρ = ℓ_W / V_W` | informal (classical) | +| B3.1 | wedge identifiable from about `2 + 3/sin α` px; vertex precision formula | informal; measured | +| B3.2 | junction covariance `(Σ νν/σ²)⁻¹`; conditioning `tan²(α/2)` | informal | +| B3.3 | fillet area `r²(tan(τ/2) − τ/2)`; smallest distinguishable fillet; corner proposals by the fourth difference | informal; measured | +| B3.4 | thin strokes: straddle exact, hidden flat, slanted fraction hidden `max(0, 1 − w/cos θ − |t|)` | Lean (first two); informal | +| B4.1 | the log-likelihood is exactly a sum of edge, vertex and strip terms; couplings are shared windows | informal | +| B4.2 | identifiability ⟺ `rank J` full; null space is the parametrisation's | informal; Lean for the examples | +| B4.3 | covariance `F⁻¹`; closed forms for lines, circles, vertices; the supersampling floor | informal (Gauss-Markov); measured | +| B4.4 | nested and Wald tests, consistency, boundary-of-parameter-space mixture | Lean for nested linear; informal | + +## 0. The model, stated once + +* **Pixels.** Pixel `(i, j)` is the open square `(i, i+1) × (j, j+1)`, as in the Lean + development; inkvec's code puts pixel centres on integers, so its coordinates are these + minus ½. `λ` is area (Lebesgue measure). +* **Descriptions.** A candidate description `𝓓` (what the representation proposes) + determines a partition of the plane into face regions `Ω_f` (for a layered drawing, its + visible partition) and an ink per face: a flat colour `c_f`, an affine colour field + `c_f(x) = c_f(x₀) + G_f (x − x₀)` (a linear gradient between two stops, in the space the + renderer interpolates in), or a radial field. +* **Rendering.** Exact area: `P_p = Σ_f ∫_{Ω_f ∩ p} c_f(x) dx`, composited linearly in the + encoded values (resvg does, and so does the corpus builder's box filter, + `bench/build_corpus_v2.py`); with transparency, in premultiplied channels + `(colour × α, α)`, where mixtures are linear (Porter & Duff 1984, doi:10.1145/800031.808606) + and straight colour is not. +* **Observation.** `O_p = Q(P_p + e_p)`, with `Q` the 8-bit quantiser and `e_p` the + renderer's departure from exact area (point supersampling, curve flattening, per-layer + compositing): the *renderer floor*. +* **The statistical surrogate.** Window errors are independent and zero-mean with known + variances `V_W` (B2.3), Gaussian where a density is needed. Every precision statement + below is also the exact covariance of the weighted least-squares estimate for families + linear in their parameters (the Gauss-Markov theorem needs means and variances only), so + it does not rest on Gaussianity. The surrogate is conservative: under exact uniform + quantisation the consistent set of a boundary shrinks faster than least squares + (Havelock's locales), but the renderer floor violates the hard bounds that would exploit + it, so it is not used. + +Nothing is assumed about the curve. + +## B1. Inks and mixtures + +**In:** the raster. **Out:** per face, candidate ink models (flat, linear, radial) with +their evidence; per pixel, either its unmixed weight against its two inks with its variance +(two flat inks), or its raw colour with its covariance (three or more inks, or a gradient +on either side). + +### B1.1 Pure pixels fix flat inks + +*Claim.* A face that contains an axis-aligned square of side 2 contains a whole pixel. A +pure pixel of a flat ink reads the ink exactly when the ink is on the 8-bit lattice, as an +artist's hex colour is; otherwise every pure pixel reads it to within half a level per +channel, and their mean converges. + +*Proof.* The square `[u, u+2] × [v, v+2]` contains `[⌈u⌉, ⌈u⌉+1] × [⌈v⌉, ⌈v⌉+1]`, +since `⌈u⌉ + 1 ≤ u + 2`. That pixel's coverage by the face is 1, so `P_p = c_f` and +`Q(c_f) = c_f`. ∎ (A disc of radius √2 contains such a square, so faces with that inradius +qualify; a diagonal stroke narrower than √2 px need not.) + +### B1.2 Two-ink unmixing + +*Claim.* For `P = B + a·d + e`, `d = F − B ≠ 0`, the projection +`â = (P − B)·d / ‖d‖²` equals `a + e·d/‖d‖²`. It is unbiased whenever `e` has zero mean, +and must not be clamped to `[0, 1]` (a clamp biases every sum it enters, which is why +`strip.rs` does not). Its variance is `dᵀ Σ_e d / ‖d‖⁴`: `Δ² / (12‖d‖²)` when the three +channels round independently (`Δ = 1/255`), and at most `(Δ²/12)(‖d‖₁/‖d‖₂²)²` whatever +their correlation. The bound is attained on a grey axis, where the three channels hold the +same value and round identically: black on white has variance `Δ²/12`, three times the +independent value. Deterministically, `|â − a| ≤ (Δ/2)·‖d‖₁ / ‖d‖₂²`. The residual +orthogonal to the axis, `P − B − â·d`, is noise for a two-ink pixel; its size against `Σ_e` +(two degrees of freedom) is the test for a third ink. + +*Proof.* Linearity of the projection. With `|Σ_e,cc'| ≤ σ²` for any correlation, +`dᵀΣ_e d ≤ σ² (Σ_c |d_c|)²`, with equality when the channel errors are perfectly +correlated with the signs of `d`'s components, as on a grey axis. ∎ + +*Measured* (`bench/theory/evidence_eval.py calib`, discs, exact area, 8-bit, black on +white): window residuals have rms 0.00114 per √(partial pixel), against `Δ/√12 = 0.00113`, +with no lag-1 correlation along the boundary (−0.003). + +### B1.3 Three or more inks + +*Claim.* (i) A pixel's weights over `k` inks are determined by its colour exactly when the +inks are affinely independent (so `k ≤ 4` in RGB, `k ≤ 5` with alpha). (ii) Whatever the +inks, the pixel's term of the likelihood is its colour residual +`(O_p − μ_p(𝓓))ᵀ Σ_p⁻¹ (O_p − μ_p(𝓓))` with `μ_p(𝓓) = Σ_f a_f(𝓓) c_f`, so scoring a +candidate needs no unmixing at all. (iii) One pixel never fixes a junction: a junction of +`k` straight rays has `k + 2` parameters and its pixel at most `k − 1` independent weights, +so the geometry comes from the neighbours (B3.2). + +*Proof.* (i) `Σ_f a_f = 1` and `Σ_f a_f c_f = P` form a linear system whose matrix +`[c_f; 1]` has full column rank exactly under affine independence. (ii) is the model. +(iii) counts. ∎ So the earlier formulation, "a junction pixel's weights are identifiable +only with geometry from its neighbours", splits in two: the weights need affine +independence, the geometry always needs neighbours, and the likelihood needs neither. + +### B1.4 Affine inks + +*Claim.* For an affine ink `c(x) = c(x_p) + G (x − x_p)`, `x_p` the pixel centre: +(i) a pure pixel reads `c(x_p)` exactly (an affine function's mean over a square is its +value at the centre), so three pure pixels with non-collinear centres fix the field. +(ii) A pixel shared by faces `f` and `g` reads + +```text +P = a·c_f(x_p) + (1 − a)·c_g(x_p) + (G_f − G_g)·m_f, m_f = ∫_{Ω_f ∩ p} (x − x_p) dx, +``` + +the first moment of `f`'s part about the centre, a geometric quantity of the candidate +computable by the same line integrals as its area (B2.1). (iii) Unmixing against the centre +values and ignoring the moment biases the weight by at most `|(G_f − G_g)·ν| / (8‖d‖)` for a +straight edge with normal `ν` (the moment is `a(1 − a)/2` along the normal on an +axis-aligned edge, at most 1/8; √2/12 on a diagonal). (iv) Radial fields and gradients with +interior stops are affine only piecewise: on a pixel the second-order term is `tr(H)/24` +(the midpoint rule's error on a square), negligible unless the field curves within a few +pixels, and a stop inside a pixel is an ink boundary with no geometric edge. + +*Proof.* Linearity of the integral, and `m_f + m_g = 0` because the pixel's own first +moment about its centre vanishes. For (iii), on an axis-aligned edge `f` holds a strip of +height `a` whose centroid sits `(1 − a)/2` from the centre. ∎ + +The term matters: a gradient spanning half the colour range over 50 px (`|G| = 0.01/px`) +next to a flat face at contrast 0.3 biases a weight by up to 0.004, several times the +quantisation noise at that contrast. So windows next to a gradient face are kept per pixel, +with the moment in the model. + +### B1.5 Inks without pure pixels + +*Claim.* (i) A stroke inside one pixel row fixes only width × contrast +(`width_contrast_ambiguity`, proved). (ii) A sub-pixel stroke that straddles one pixel border +along its whole length fixes neither its width nor its centre without its ink: any contrast +`kK` with both edges scaled towards the border by `1/k` gives the same pixels. (iii) A stroke +that straddles different borders along its length (any slanted stroke) fixes its ink, with +information that grows with the number of distinct offsets. + +*Proof.* (ii) From `straddle_inversion`, `a₋ = j+1 − lo`, `a₊ = hi − (j+1)` and +`P± = B + a±(F − B)`; replacing `F − B` by `k(F − B)` and `a±` by `a±/k` leaves both pixels +unchanged and is the stroke `lo' = j+1 − a₋/k`, `hi' = j+1 + a₊/k`. (iii) Two columns that +straddle different borders scale about different points, which agree only for `k = 1`. ∎ + +B1 therefore outputs, per face, the candidate ink models with their parameter counts, +interior `χ²` and covariance, and leaves the choice to the representation (proposal S3). + +## B2. The likelihood of any description + +**In:** the raster, B1's inks, a starting map (topology from the label map, geometry from +stage 07). **Out:** a list of window observations and an evaluator of `χ²(𝓓)` for any +candidate description `𝓓`. + +### B2.1 The window identity + +*Claim.* For every measurable region `Ω` and every finite set `W` of pixels, + +```text +Σ_{p ∈ W} coverage(Ω, p) = λ(Ω ∩ ⋃W). +``` + +For a column window `R = (i, i+1) × (j₀, j₀+m)` this is +`∫_i^{i+1} λ₁{ y ∈ (j₀, j₀+m) : (x, y) ∈ Ω } dx`, the column integral of the length of the +region's vertical cross-section inside the window. If the window's top side lies outside +`Ω` (its top pixel is pure in the other face) and `∂Ω` is piecewise smooth, it is the line +integral `∫_{∂Ω ∩ R} (y − j₀) dx` along the part of the boundary inside the window, oriented +so that a graph contributes positively. For the region below a continuous graph `f` it is +`∫_i^{i+1} f − j₀`: `column_sum_eq_average`. + +*Proof.* Pixels are disjoint, so their areas add; the grid lines between them are null; +Tonelli's theorem slices the window into vertical segments; Green's theorem with the form +`(y − j₀) dx` gets no contribution from the window's vertical sides (`dx = 0`), none from its +bottom (`y = j₀`), and none from its top by hypothesis. ∎ + +*Consequences.* No slope, normal, curvature, graph property or threshold enters. The model +value of any candidate in any window is a sum of line integrals along its boundary inside +the window, in closed form: trapezoids for line segments, polynomials in the parameter for +Bézier segments (after solving `x(t) = i` and `x(t) = i + 1`), sector-and-triangle terms for +circular arcs. A candidate that leaves the window vertically is handled by clamping the +cross-section, which adds its crossings of the window's top and bottom. A layered candidate +is scored through its visible partition (but see B3.2 on per-layer compositing). + +*Status.* Lean for graphs (`column_sum_eq_average`); the general form is phase 2 (finite +additivity and Tonelli). The identity is volume-of-fluid's (Puckett 2010, eq. 11) and the +partial-area effect's (Trujillo-Pino et al. 2013, doi:10.1016/j.imavis.2012.10.005). Not +from the literature: using it as the likelihood interface between boundary recovery and +representation. + +### B2.2 The likelihood, and what windows cost + +*Definition.* Partition the band (the pixels any candidate within reach can touch) into +windows: on runs, column or row windows from a pure pixel of one face to a pure pixel of the +other, crossed by exactly one boundary piece (columns where the boundary is within 45° of +horizontal, rows elsewhere); single pixels where two or more boundary pieces share pixels +(vertex neighbourhoods, thin features) and next to gradient faces. A two-flat-ink window +observes `S_W = Σ_{p ∈ W} â_T(p)`, the weight of its top face `T`, with variance `V_W`; +its model is `A_W(𝓓) = λ(Ω_T(𝓓) ∩ W)`. A single pixel with more inks, or a gradient +neighbour, observes its colour `O_p` with covariance `Σ_p`; its model is the area- and +moment-weighted mixture of B1.3 and B1.4. Then + +```text +χ²(𝓓) = Σ_W (S_W − A_W(𝓓))² / V_W + Σ_p (O_p − μ_p(𝓓))ᵀ Σ_p⁻¹ (O_p − μ_p(𝓓)), +log-likelihood = −χ²/2 + const. +``` + +*Claim (what a window sum keeps).* With independent per-pixel errors of variances `σ_p²` +and sensitivities `g_p = ∂a_p/∂θ`, the window sum carries the information +`F_W = (Σ g_p)(Σ g_p)ᵀ / Σ σ_p²`, never more than the per-pixel +`F_pix = Σ g_p g_pᵀ / σ_p²`, and equal to it exactly when `g_p` is proportional to `σ_p²` +across the window's pixels. + +*Proof.* For any direction `u`, Cauchy-Schwarz gives +`(Σ uᵀg_p)² = (Σ (uᵀg_p/σ_p)·σ_p)² ≤ (Σ (uᵀg_p)²/σ_p²)(Σ σ_p²)`, with equality when +`uᵀg_p/σ_p ∝ σ_p`. ∎ + +*Corollary (8-bit regime).* For the normal offset of a straight edge, with equal noise on +every partial pixel and none on pure ones, column sums keep `(1 − t/2)/(1 − t/3)` of the +per-pixel information, `t = |tan θ| ≤ 1` the slope in the window's frame: never less than +3/4, reached at 45°. + +*Proof.* The sensitivity of a pixel to the normal offset is its chord `ℓ_p`. A column is +crossed with chord `1/cos θ`; with probability `1 − t` (over the edge's position) it has one +partial pixel, with probability `t` two, split `u : 1 − u` with `u` uniform. Per column the +window keeps `(Σℓ)²/n` against `Σℓ²`, in expectation `ℓ²(1 − t + t/2)` against +`ℓ²(1 − t + 2t/3)`. ∎ + +*Corollary (supersampled regime).* Under `n × n` point supersampling a pixel's error is the +sum of the rounding errors of the sample columns whose boundary falls in its row +(`ss_column_sum` writes the column sum that way), so its variance is proportional to its +share of the column's sample columns, that is to its chord: the equality condition holds, +and column sums keep all the information about the offset. + +*Measured* (`evidence_eval.py info`): 1.000, 0.969, 0.932, 0.880, 0.807 at 0°, 10°, 20°, +30°, 40°, against 1.000, 0.969, 0.931, 0.881, 0.805 predicted. For polynomial curves the sums +also lose no identifiability: a polynomial of degree `< n` is fixed by its means on `n` +columns (`poly_eq_of_averages`). + +So: column windows on runs, where they are smooth in the parameters, cheap, and keep at +least 3/4 of the information; per-pixel terms wherever two boundary pieces share a window, +since there a window sum measures only their difference (a thin stroke's width) and loses +both positions. Not from the literature: the information ratio. + +### B2.3 The variances + +*Claim.* (a) **Quantisation.** `V_W = Σ_{p ∈ W partial} var(â_p)` (B1.2): pure pixels +contribute nothing when the inks are on the 8-bit lattice. (b) **Point supersampling.** A +window's error is the mean of `n` per-sample-column rounding errors, each within `±1/(2n)` +(`subCount_close`), so it is within `1/(2n)` (`ss_column_sum_close`). The sub-row phase of +consecutive sample columns differs by the slope `t` (in sub-rows per sample column); away +from `t ≈ 0` and `t ≈ 1` the `n` errors behave as independent uniform variables +(equidistribution) and `V = 1/(12n³)`; near 0° and 45° they coincide and the error is a bias +of up to `1/(2n)` (rms about `1/(n√12)`), constant along an exactly axis-aligned or diagonal +edge and periodic along slopes with small denominators. (c) The two add. (d) **The renderer +floor** of a real renderer must be measured. The corpus is rendered by resvg at 8× and box +filtered, and resvg's own anti-aliasing inside each of the 64 sub-pixels makes its sampling +finer than `8 × 8` points, so (b) at `n = 8` is an upper bound. Estimator: along a run, the +fourth difference `D = h₋₂ − 4h₋₁ + 6h₀ − 4h₁ + h₂` of five consecutive windows' mean +heights annihilates cubics and has variance `70 V` under independent errors, so +`V̂ = (median |D| / 0.6745)² / 70` over an image's runs estimates the floor robustly against +the few corners (the difference-based variance estimators of Rice 1984; Gasser, Sroka & +Jennen-Steinmetz 1986; Hall, Kay & Titterington 1990). Its quartic bias is `f''''` +(`quartic_defect`), negligible unless the curvature radius is a few pixels. + +*Proof.* (a) B1.2 and independence; (b) as stated, the per-sample-column count reads the +boundary height rounded to the sub-row lattice (`subCount_close`) and the column sum is +their mean (`ss_column_sum`); independence away from integer phase steps is a model, checked +below. (d) The weights `1, −4, 6, −4, 1` sum in squares to 70 and annihilate cubics. ∎ + +*Measured* (`evidence_eval.py calib`, discs of radius 6-26 px at 64 px, every window): + +| render | window residual std | predicted | within 0.02 rad of the window's axis | lag-1 correlation | +|---|---|---|---|---| +| exact area, float | 0 | 0 | 0 | — | +| exact area, 8-bit | 0.00135 | 0.00135 | — | −0.003 | +| 8 × 8 points, 8-bit | 0.0129 | 0.0128 | 0.035 (bias, bound 0.0625) | −0.029 | +| 16 × 16 points, 8-bit | 0.0044 | 0.0047 | 0.014 (bound 0.031) | +0.028 | +| 32 × 32 points, 8-bit | 0.0021 | 0.0021 | 0.0065 (bound 0.016) | +0.077 | + +The first row is B2.1 checked on every window: the window sums of an exact render equal the +exact areas, curvature and slope notwithstanding. The 45° regime shows in the spread by +angle: under 8 × 8 points, 0.0123 between 23° and 45° against 0.0073 between 7° and 23°. +Not from the literature: the per-window variance model under point supersampling and its +near-axis bias regime. + +### B2.4 Calibration and cost + +*Claim.* With the variances of B2.3, `E χ²(truth) = M`, the number of windows. For a +candidate family of `p` parameters that contains the truth and is linear in its parameters +on the windows, the minimum of `χ²` has mean `M − p` (`noise_absorbed`: each fitted +dimension absorbs one unit of noise). So "explains the pixels within their noise" is a test +on numbers the evaluator returns: `χ² ≤ M − p + z√(2(M − p))`. + +*Cost.* One pass over the windows a candidate touches, with closed-form integrals; Bézier +segments need the roots of `x(t) = i` per grid line, a bounded computation. For families +linear in their parameters as graphs over the window axis (lines, polynomials), +`S_W − A_W(θ)` is affine in `θ`, so the `χ²` of a fit over any contiguous range of windows +is a quadratic whose coefficients are prefix sums: `O(p²)` per dynamic-programming +candidate after `O(M p²)` preparation per edge. + +*Measured.* At the truth, `χ²/M` is 1.00 for exact area at 8-bit and 1.01 for 8 × 8 points +(the same table). The near-axis windows are the exception (their bias is several times the +generic spread), which is why the floor is reported separately (B4.3). + +### B2.5 First variation and information density + +*Claim.* If a candidate's boundary moves along its normal by `δ(s)`, the window area moves by +`∫_{γ ∩ W} δ ds` to first order. So for parameters `θ` with normal velocity +`N_θ(s) = ∂δ/∂θ`, the Jacobian is `J_W = ∫_{γ∩W} N_θ ds` and the Fisher information + +```text +F = Σ_W J_W J_Wᵀ / V_W ≈ ∫_γ ρ(s) N_θ(s) N_θ(s)ᵀ ds, ρ = ℓ_W / V_W, +``` + +with `ℓ_W` the boundary's length inside the window: the information density per unit of +boundary length. For a column window at angle `θ` to its axis, `ρ = 1/(V_W cos θ)`. + +*Proof.* The first variation of area (moving a boundary by `δν` adds or removes a layer of +thickness `δ`); the continuum form replaces `N_θ` by its value in the window. ∎ + +## B3. Vertices and thin features + +**In:** the places where a single run's window stops being the whole story: a tangent +discontinuity, three or more inks, two edges of a feature under two pixels wide. **Out:** +(1) per-pixel observations there (B2.2), each owned by its vertex or stretch; (2) proposals: +junction nodes from the topology, corner candidates along runs with their test statistic, +thin stretches; (3) for each, the identifiability and precision the likelihood offers, +including its flat directions; (4) starting geometry. **No decision**: whether a candidate +corner is a corner, where a hidden stroke's centre lies, which arms continue through a +junction, are the representation's (proposal S1). + +### B3.1 Corners (wedges) + +*Claim (identifiability).* A corner of apex angle `α` whose arms are straight within +radius `r` of the vertex is fixed by the pixels in that disc when each arm has two windows +of its own (pure flanks, no other boundary). That holds beyond about `3/sin α` px from the +vertex for `α ≤ 90°` (3 px for obtuse corners), so `r ≈ 2 + 3/sin α` suffices. + +*Proof.* The other arm lies `d sin α` from a point at distance `d` along this one (`≥ d` +when `α > 90°`), and a run window reaches at most about 3 px across its crossing. Two +windows of one arm give its line exactly (`line_from_two_columns`); two non-parallel lines +meet once. ∎ (Sufficient, not sharp: a very acute corner is a thin stroke near its apex, +B3.4.) + +*Claim (precision).* An arm fitted over arclength `[d₀, d₀ + L]` from the vertex, with +information density `ρ`, has normal error at the vertex +`σ_n² = (1/(ρL))·(1 + 12 s_m²/L²)`, `s_m = d₀ + L/2`; two arms with independent errors place +the vertex within `E|Δv|² = (σ_n1² + σ_n2²) / sin² α`. + +*Proof.* Least squares on a line: offset variance `1/(ρL)` at the midpoint, slope variance +`12/(ρL³)`, uncorrelated; extrapolate to `s = 0`. The vertex error solves `ν_k·Δv = ε_k`, +whose inverse has `|Δv|² = (ε₁² + ε₂² − 2ε₁ε₂ cos α)/sin² α`. ∎ + +*Measured* (`evidence_eval.py vertex`, 30 random wedges each, arms fitted by column-sum +least squares, `d₀` as above; RMS vertex error against the prediction, px): + +| α | L | exact area, 8-bit | predicted | 8 × 8 points, 8-bit | predicted | +|---|---|---|---|---|---| +| 30° | 6 | 0.0073 | 0.0070 | 0.053 | 0.066 | +| 30° | 12 | 0.0033 | 0.0035 | 0.022 | 0.033 | +| 60° | 12 | 0.0018 | 0.0017 | 0.013 | 0.017 | +| 90° | 6 | 0.0030 | 0.0027 | 0.023 | 0.025 | +| 90° | 12 | 0.0014 | 0.0015 | 0.008 | 0.014 | +| 120° | 12 | 0.0020 | 0.0017 | 0.014 | 0.016 | +| 150° | 6 | 0.0042 | 0.0053 | 0.065 | 0.051 | +| 150° | 12 | 0.0033 | 0.0029 | 0.026 | 0.028 | + +At 8-bit the formula holds within the Monte Carlo error of 30 trials (about 13 % on an rms). +Under 8 × 8 points it holds within a factor of 1.4 either way: arms near 0° or 45° carry the +correlated bias of B2.3, which a line fit partly absorbs and partly does not. + +The vertex's own pixels add the information of a few pixels; the arms dominate as soon as +they are a few pixels long. So the vertex is best fixed by fitting the arms the +representation chooses (lines, arcs, cubics) jointly with the per-pixel terms around it, +not by a local wedge model: straight local arms are biased by about `κd²/(2 sin α)` on a +curved arm, the representation's own arms are not. That is the case for moving corners +across the interface (S1). + +### B3.2 Junctions + +*Claim.* `k` arms whose normal errors at the vertex are `σ_k` give +`Cov(v) = (Σ_k ν_k ν_kᵀ / σ_k²)⁻¹`. The vertex is identified exactly when two arms are not +parallel; for two arms the eigenvalues of `Σ ν_k ν_kᵀ` are `1 ± cos α`, a ratio of +`tan²(α/2)`, which is what `junctions.rs`'s `JUNCTION_MIN_CONDITION = 0.02` thresholds +(about 16°). A tangential junction (a taper) is flat along the common tangent: B3 reports +that direction and its extent, and the representation's prior (a tangency, a taper +constraint) decides. Three-ink pixels enter through their colour residual (B1.3). + +*Proof.* Weighted least squares for the intersection of lines (the normal equations +`junctions.rs`'s `solve_junction` already forms), with the arms' variances from B3.1 instead +of stage 07's per-point sigmas. ∎ + +*Open.* A layered description is rendered by compositing each layer with its own coverage, +which differs from the exact area of the visible partition in pixels that edges of two +layers both cross (the conflation of coverage compositing). Those are junction pixels of +the visible map. At 8× supersampling with a box filter the difference is confined to the +sub-pixels both edges cross; its size on the corpus has not been measured, and the vertex +term should use per-layer compositing when the candidate is layered. + +### B3.3 Corner or rounded corner + +*Claim.* A fillet of radius `r` on a corner of turning angle `τ` removes +`r²(tan(τ/2) − τ/2)` of area. While that lies in one pixel, the sharp corner and the fillet +differ by `Δχ² = (r²(tan(τ/2) − τ/2))² / σ_p²`, so they are distinguishable at +`Δχ² ≥ 9` only for + +```text +r ≥ √(3σ_p / (tan(τ/2) − τ/2)). +``` + +*Proof.* The region between the corner and the arc is the kite of the centre, the two +tangent points and the corner (area `r² tan(τ/2)`) less the sector (`r²τ/2`). ∎ + +*Measured* (`evidence_eval.py fillet`, per-pixel `χ²` with equal noise per pixel, at +`σ_p = 0.00113` for 8-bit and `1/√(12·8³) = 0.0128` for 8 × 8 points): the bound is 0.13 and +0.42 px for a right angle, where `Δχ²` measures 3.4 / 55 at `r` = 0.1 / 0.2 px and 5.8 / 97 +at 0.4 / 0.8 px; 0.25 and 0.84 px for 60°; 0.74 and 2.5 px for 30°. Below those radii the +pixels cannot tell a fillet from a sharp corner and the prior must (icons' corners are sharp +or rounded by at least a design unit, several pixels). + +A fillet against a sharp corner is a test on the boundary of the parameter space +(`r ≥ 0`), whose null distribution is `½χ²₀ + ½χ²₁` (Chernoff 1954; Self & Liang 1987): +`Δχ² > 5.41` gives a 1 % false-alarm rate. Not from the literature: the resolution formula. + +*Corner proposals.* `strip.rs`'s corner test compares the cubic through four column means +with the one-sided cubics at the vertex's pixel border. The one-sided difference is exactly +`D/12` with `D` the fourth difference of B2.3 (weights `(1, −4, 6, −4, 1)/12`, checked in +rationals), which is why every cubic passes (`side_stencil_cubic`) and why `strip.rs` +reports "0.7 times the noise of one column mean" (`√70/12 = 0.70`). A kink with slope +change `Δs` at the stencil's centre gives `|D| = 1.25 Δs` at most (the second difference of +the quadratic B-spline at its centre). So corners should be proposed where +`|D| > z√(70 V̂)`, `z ≈ 3`, which finds kinks down to `Δs = z√(70V)/1.25`: about 1.6° at +8-bit black on white, 14° at 8 × 8 points. The fixed `SIDE_TOL = 0.05` px is `|D| > 0.6`, +`Δs ≈ 0.48`, about 26°: the "gentle corner under about 30°" that `README.md` §7 says the +strip reading cannot tell from noise. Proposals should favour recall: a false proposal +costs the representation one `Δχ²` test, a missed one a corner. + +### B3.4 Thin features + +*Claim.* (i) A stroke straddling a pixel border along a column is read exactly +(`straddle_inversion`): centre `j + 1 + (a₊ − a₋)/2` with variance `(σ₋² + σ₊²)/4`, width +`a₋ + a₊` with variance `σ₋² + σ₊²`. (ii) Inside one pixel row its likelihood is exactly flat +in the centre over an interval of length `1 − w` (`hidden_stroke_invisible`): flat-bottomed, +not Gaussian. (iii) A straight stroke of width `w` at slope `t` is hidden in a column with +probability `max(0, 1 − w/cos θ − |t|)` over its position; when `w/cos θ + |t| ≥ 1` every +column informs the centreline, and otherwise a parametric centreline with at least two +non-hidden columns per segment is still fixed. (iv) The ink: B1.5. + +*Proof.* (i) and (ii) are proved in Lean; the variances are `weighted_variance` with +weights `(−½, ½)` and `(1, 1)`. (iii) The stroke's vertical extent in a column is +`w/cos θ + |t|`, and it is hidden when that extent lies within one row. ∎ + +What B3 reports for a thin stretch: its per-pixel windows, and for every part where the +likelihood is flat, the interval. The representation's prior places the centre (on the +design grid, or at the pixel centre, the minimax choice). + +### B3.5 A refusal is a report + +Where the likelihood is flat or elongated (hidden strokes, tangential junctions, a gentle +corner's position along its line, arms shorter than two windows, parts of a face hidden +behind others, which have no windows at all), B3 reports the flat direction and its extent +instead of a point. Nothing in this chain guesses; the prior decides, in the representation. + +## B4. What the pixels can confirm + +**In:** B2's observations and evaluator; a parametrisation `θ ↦ 𝓓(θ)` from the +representation. **Out:** the decomposition of the log-likelihood into local terms and their +couplings; whether `θ` is identifiable; the precision of every coordinate and constraint; +the test statistics R2 needs. + +### B4.1 The decomposition + +*Claim.* Exactly, with no cross terms, + +```text +χ²(𝓓) = Σ_edges χ²_e(γ_e) + Σ_vertices χ²_v(γ_e : e ∋ v) + Σ_strips χ²_s(γ_e, γ_e'), +``` + +where `χ²_e` sums the windows only edge `e` crosses, `χ²_v` the per-pixel terms around +vertex `v`, and `χ²_s` those of a thin stretch both its sides cross. Two edges interact only +through windows they both cross, so the Fisher matrix is block-sparse along that graph, and +edges can be fitted independently (in parallel, as now) except for the vertex and strip +terms, which a joint polish of the end segments settles. + +*Proof.* Each window is assigned to one term, and `λ(Ω ∩ W)` changes only when the boundary +inside `W` changes (B2.1). ∎ + +*Validity.* The assignment is made on the starting map. It stays exact for every candidate +whose boundaries stay inside the band, that is within about a pixel of where they started +(the representation's trust region). Beyond it the whole-description evaluator is still +exact, but the edges it moves must be scored together. This replaces the earlier +formulation, "exact up to stated cross terms": there are none, only couplings. + +### B4.2 The null space belongs to the parametrisation + +*Claim.* The likelihood depends on a description only through its regions (B2.1), and on +its regions only through the window areas. A parametrisation is locally identifiable exactly +when `J = ∂A/∂θ` has full column rank; its flat directions are `ker J`. + +*Examples.* A polynomial graph of degree `< n` on `n` windows: `J` is the histopolation +matrix, invertible (`poly_eq_of_averages`). A polyline with a vertex on every pixel border: +`ker J` is the zigzag (`polyline_kernel`). Free 2-D points: at least `2N − M` flat directions +(`flat_directions`). A segment with more parameters than the windows it spans. Any change of +description that draws the same regions (a stroke or two fills, one arc or three: the +program ambiguity of `optimal.md` §1) is exactly flat. So the representation checks +`rank J` (cheap, per segment) and never fits a segment over fewer windows than it has +parameters (`README.md` §6.4). + +### B4.3 Precision + +*Claim.* For an identifiable parametrisation, the weighted least-squares estimate has +covariance `F⁻¹ = (Jᵀ V⁻¹ J)⁻¹` to first order, exactly for families linear in their +parameters (Gauss-Markov, whatever the error distribution), and this is the Cramér-Rao bound +under Gaussian errors. Any coordinate or constraint `g(θ)` has `σ_g² = ∇gᵀ F⁻¹ ∇g`. In the +continuum form of B2.5: + +* a line segment of length `L`: offset at its midpoint `1/√(ρL)`, angle `√(12/(ρL³))`; +* a circle of radius `R`: radius `1/√(2πRρ)`, centre `1/√(πRρ)` per axis; +* a vertex: B3.1; a junction: B3.2; +* absolute positions of edges near 0° or 45° under `n × n` point supersampling add the bias + floor of B2.3 (up to `1/(2n)`, rms about `1/(n√12)`), which does not average down with + length; angles are barely affected (the bias is constant along an exactly aligned edge + and varies slowly along a nearly aligned one). + +*Proof.* Gauss-Markov for linear families; linearisation otherwise; the closed forms are +`∫ρ N Nᵀ ds` for `N = (1, s)` on a segment and `N = (1, cos φ, sin φ)` on a circle. ∎ + +Black ink on white, `cos θ ≈ 0.9` on average (other contrasts: `ρ` scales with the squared +contrast where quantisation dominates): + +| regime | `V` per window | `ρ` (px⁻³) | line, 10 px: offset / angle | line, 50 px | circle `R = 10`: radius | vertex, 90°, 12 px arms | +|---|---|---|---|---|---|---| +| exact area, 8-bit | 1.8e-6 | 6.1e5 | 0.0004 px / 0.008° | 0.0002 px / 0.0007° | 0.00016 px | 0.0015 px | +| 8 × 8 points, 8-bit | 1.6e-4 | 6.8e3 | 0.0038 px / 0.076° | 0.0017 px / 0.0068° | 0.0015 px | 0.014 px | +| 32 × 32 points, 8-bit | 4.4e-6 | 2.6e5 | 0.0006 px / 0.012° | 0.0003 px / 0.0011° | 0.00025 px | 0.0023 px | + +What this means for the representation. At 128 px a 24-unit icon has 5.33 px per unit, so +even the worst case here (an axis-aligned edge's absolute position under 8 × 8 points, +about 0.04 px) is under 0.008 units, against a half-unit grid spacing of 2.67 px. Whether a +coordinate is on the design grid, whether a line is horizontal, whether two radii are equal +to a hundredth of a unit: the pixels settle all of these at every tier of the gate. What +they leave open is structure: fillets below the radius of B3.3, gentle corners below the +proposal threshold, hidden strokes, tangential junctions, and occluded parts. The same +sharpness has a cost. The likelihood separates curves that differ by a few hundredths of a +pixel, for instance a true circular arc of radius 200 px from its common four-cubic +approximation (radial error about `2.7·10⁻⁴ R`, 0.05 px, against a radius known to about +0.001 px). So the evaluator must draw a candidate the way the renderer draws it (renderers +approximate arcs by Bézier or conic pieces, each its own way), and the representation must +offer the encodings artists use. + +*Digits.* Writing a coordinate with step `q` adds `q²/12` to its variance; the +representation can choose the coarsest `q` that keeps that small against `σ_g²`, and B +supplies `σ_g`. + +### B4.4 Tests + +*Claim.* (a) A true linear constraint of rank `k` raises the minimum `χ²` by a `χ²_k` +variable (`merge_chi2_increase`: the increase is the noise in the removed directions). +(b) The Wald statistic `W = g(θ̂)ᵀ (G F⁻¹ Gᵀ)⁻¹ g(θ̂)` equals that increase for linear +models and constraints, without refitting. (c) A false constraint whose best constrained fit +leaves a normal deviation `δ(s)` raises `χ²` by about `∫ ρ δ² ds`, which grows linearly +with the boundary length, while a true one does not: the test is consistent. (d) On the +boundary of the parameter space (a fillet radius, a stroke width) the null distribution is +`½χ²₀ + ½χ²₁`. (e) All of this holds only with calibrated variances: the self-calibration of +B2.3 is part of the interface, not an option. + +*Proof.* (a) `Naturality.lean`; (b) the standard equivalence (Wald 1943) for linear +Gaussian models; (c) the expected residual of a misspecified projection; (d) Chernoff +(1954). ∎ + +## Interface proposal + +### What the boundary chain delivers + +One `Evidence` per image, built once (in about stage 07's time: `strip.rs`'s `line_mean` +already computes each window's sum): + +1. **`map`** — the planar map as now: topology exact from the label map, starting geometry + from stage 07 (and stage 08 while it remains). +2. **`inks`** — per face, the candidate ink models (flat, linear, radial), each with its + parameter count, interior `χ²` and covariance, and B1's default. +3. **`runs`** — per edge, the ordered observations along it. A run window is + `{axis: column | row, line, lo, hi, s, top_face, sum, var}`: the window spans pixels + `lo..=hi` of grid line `line`, `s` is its arclength position along the starting edge, and + `h = lo + sum` is the boundary's mean height over the line (Lean convention; minus ½ in + inkvec's), known to `±√var`. Interleaved in order: per-pixel observations at corner + candidates (two flat inks: `{x, y, face, weight, var}`; otherwise `{x, y, colour, cov, + faces}`). +4. **`vertices`** — per junction node (degree ≥ 3, from the topology) and per corner + candidate: incident edge ends, the per-pixel observations within about 2 px, a starting + position with covariance (B3.1, B3.2), the proposal statistic `z = |D| / √(70V̂)` for + corners, and any flat direction with its extent. +5. **`strips`** — thin stretches (edge pairs sharing windows), their per-pixel observations, + and their flat intervals (B3.4). +6. **`noise`** — `σ_q`, the per-image floor `V̂` (B2.3), the bias bound for near-axis + edges, and the calibration check (`χ²/M` of the starting map's smooth runs). + +### The evaluator + +A trait in `inkvec-core`, so that `inkvec-fit` can use it without depending on +`inkvec-trace`, implemented in `inkvec-trace`: + +```rust +pub enum Piece { + Line([Point; 2]), + Quad([Point; 3]), + Cubic([Point; 4]), + Arc { c: Point, r: f64, a0: f64, a1: f64 }, +} + +pub trait BoundaryLikelihood { + /// χ² of edge `e`'s observations `range` (run windows and the per-pixel terms between + /// them) against a candidate curve, given as pieces in order, in px. Returns (χ², M). + fn chi2_run(&self, e: EdgeId, range: Range, curve: &[Piece]) -> (f64, usize); + /// The residuals `(S_W − A_W)/√V_W`, and their Jacobian by the pieces' coordinates. + fn residuals_run(&self, e: EdgeId, range: Range, curve: &[Piece], + jac: Option<&mut Matrix>) -> Vec; + /// Prefix moments for curves linear in their parameters as graphs over the window axis + /// (lines, polynomials): the χ² of a least-squares fit over any range in O(p²). + fn run_moments(&self, e: EdgeId, degree: usize) -> RunMoments; + /// χ² of a vertex neighbourhood or a thin stretch, given every incident edge's candidate + /// near it. + fn chi2_local(&self, owner: Owner, curves: &[(EdgeId, &[Piece])]) -> (f64, usize); + /// The whole description: visible partition and inks. + fn chi2(&self, d: &Description) -> (f64, usize); + /// Information density along an edge, and the floor, for precision without a Jacobian. + fn density(&self, e: EdgeId) -> &[(f64, f64)]; + fn floor(&self) -> Floor; +} +``` + +| call | cost | +|---|---| +| building `Evidence` | one pass over the band, `O(boundary pixels)` | +| `chi2_run`, `residuals_run` | `O(windows in range + pieces)`, closed-form integrals | +| `run_moments` | `O(M p²)` per edge, then `O(p²)` per candidate range | +| `chi2_local` | `O(pixels × pieces near)`, a few dozen pixels | +| `chi2` | `O(all windows + all pieces)` | + +**Semantics.** `χ²` is `−2 log L` up to a constant, calibrated so that the truth has +`E χ² = M`; every call returns `M` so the representation can apply "explains the pixels +within their noise" (B2.4) and the tests of B4.4 directly. Precision for any coordinate or +constraint the representation writes is `∇gᵀ F⁻¹ ∇g` with `F = JᵀV⁻¹J` from +`residuals_run`, or `∫ρ N Nᵀ ds` from `density` (B4.3). + +**Integration, in steps.** (1) The fitter's residual per measured point, a perpendicular +distance over `σ`, becomes a residual per window, the measured mean height minus the +candidate's mean height over the window, over `√V`; its dynamic program indexes windows +instead of points, with breakpoints at window borders (which keeps the cost additive) and a +continuous polish of the breakpoints afterwards. (2) The vertex and strip terms enter a joint +polish of each vertex's incident end segments, where corners, continuation and tangency are +tested (B4.4). (3) Inks become candidates, and strokes a primitive the evaluator renders as a +band. + +### Shortening the chains + +* **S1. Corners and junctions become R2 decisions.** B3 supplies proposals at high recall, + per-pixel terms and precision; the representation's own arms, fitted jointly with the + vertex terms, place the vertex (B3.1 shows that is where the precision is), and a corner, + a fillet or a smooth join is a nested test (B3.3, B4.4). This removes B3's wedge models, + `SIDE_TOL` as a decision, and `refine_junctions`' tangent extrapolation as a final estimate. +* **S2. Continuation through a junction** (the stem of a T, two arms that are one curve) and + tangency at a junction are representation constraints tested against the vertex terms; + `optimal.md` §4 lists continuation as a missing move. +* **S3. Gradient or flat, and which gradient,** is the representation's choice among B1's + candidates, priced by its prior. +* **S4. Stroke or two edges, and the ink of a sub-pixel stroke,** are the representation's, + on B3.4's strip terms and flat intervals. +* **S5. Points stop being the interface.** Stage 08's point solve becomes initialisation at + most: its kink and anchor priors stand in for data the point parametrisation cannot see + (B4.2), and a curve parametrisation does not need them. `DEFAULT_SIGMA_MODEL` and the + curvature inflation of per-point sigmas give way to calibrated window variances, which + means the price of a parameter must be re-derived on the representation's side. +* **S6. The links are re-cut.** `chains.md`'s B2 ("a likelihood for any curve") and B4 ("the + planar map as one likelihood") are one identity (B2.1); here B2 is the likelihood of any + description, decomposition included, and B4 is what the pixels can confirm: precision and + tests, the part of the interface the representation consumes most. + +### Questions for the representation chain + +1. **Residual form.** Can the fitter score a candidate segment by its window residuals + (mean height over a column or row) instead of perpendicular point distances? Which + segment kinds must the evaluator integrate exactly (line, arc, quadratic, cubic, + primitives, stroke bands)? +2. **Additivity.** Is a dynamic program with breakpoints at window borders, followed by a + continuous polish, acceptable, or do you need straddling windows handled inside the + program (a residual that depends on two adjacent segments)? +3. **The price of a parameter.** With calibrated variances, a window's standard deviation + is 0.002-0.013 px where `DEFAULT_SIGMA_MODEL` says 0.05 px, so `χ²` differences grow by a + factor of 15 to 600 and `λ = ln(extent/precision)` no longer balances them. Will R2/R4 use + the fidelity constraint `χ² ≤ M − p + z√(2(M − p))` with a prior over descriptions, or a + refined description length with `½ log det F` per segment (B can return `log det F`)? +4. **Tests.** Wald from `F` (no refit, cheap) or `Δχ²` by refit? Which constraints span + several edges' windows (concurrency, continuation, equal radii, symmetry), so that the + evaluator must score them jointly? +5. **Corners.** Will R own corner, fillet and smooth-join decisions (S1)? What recall and + false-proposal rate should the proposals target, and what starting tangents do you need? +6. **Strokes and hidden geometry.** Should the evaluator accept a stroke (centreline, width, + caps, joins) directly? For a flat interval (a hidden stroke, an occluded part), do you want + it as an interval, or the flat-bottomed likelihood itself? +7. **Inks.** Will R take gradient-or-flat (S3) on B1's candidates? +8. **Layers.** For a layered candidate, will you hand the evaluator its visible partition, + or should it composite per layer as the renderer does (B3.2)? +9. **Units and the floor.** B reports precision in px; is the separate near-axis floor + (B4.3) useful to you as a term in grid-snapping tests, or should it be folded into the + variances? +10. **Primitives the likelihood can separate.** At 512 px a true arc and its four-cubic + approximation differ by about fifty standard deviations (B4.3), and renderers draw arcs + by approximations of their own. Should the evaluator draw each primitive exactly as the + gate's renderer does, and should "circle" be offered in both encodings, or does the + prior decide which the artist meant? + +## Phase 2: formal, then code + +### Lean (`formal/InkvecTheory`) + +| file | lemma | for | difficulty | +|---|---|---|---| +| `Windows.lean` | `window_sum_eq_area` (finite sets of pixels, any measurable region) | B2.1 | easy | +| `Windows.lean` | `column_area_cavalieri` (cross-section form, any measurable region) | B2.1 | medium | +| `Information.lean` | `window_information_le` (Cauchy-Schwarz, equality condition) | B2.2 | easy | +| `Information.lean` | `column_information_ratio`: `(1 − t/2)/(1 − t/3) ≥ 3/4` from the chord split | B2.2 | easy | +| `Information.lean` | `ss_window_variance`: `1/(12n³)` under independent uniform sample-column errors | B2.3 | easy | +| `Unmixing.lean` | `unmix_unbiased`, `unmix_variance_le` (`(Δ²/12)(‖d‖₁/‖d‖₂²)²`) | B1.2 | easy | +| `AffineInk.lean` | centre value of an affine ink; the first-moment correction; `a(1 − a)/2` on an axis edge | B1.4 | easy | +| `ThinStroke.lean` | `straddle_noise`, `straddle_contrast_ambiguity` | B1.5, B3.4 | easy | +| `Vertex.lean` | `line_fit_variance` (offset `1/N`, slope `12/(N(N²−1))` on `N` columns), `intersection_variance`, `wedge_from_four_columns` | B3.1 | medium | +| `Vertex.lean` | `fillet_area_deficit` from Lebesgue measure | B3.3 | medium | +| `Corner.lean` | `one_sided_is_fourth_difference` (the rational identity), `fourth_difference_cubic`, `kink_response` (`5/4`) | B3.3 | easy | +| `Vectors.lean` | rational twins of the constants above, with `#eval` printing the test vectors the Rust tests read | ties | easy | + +The general first variation (B2.5) and the Gauss-Markov theorem are stated and used, not +formalised in this round: Mathlib lacks the latter, and the former needs differentiation +under the integral of a Lipschitz, not smooth, integrand. + +### Rust + +* `crates/inkvec-core/src/likelihood.rs`: the `BoundaryLikelihood` trait, `Piece`, + `Description`, `Floor`. +* `crates/inkvec-trace/src/evidence.rs` with `evidence/windows.rs` (the partition, built from + `strip.rs`'s `line_mean`, which already finds each window), `evidence/area.rs` (exact + window integrals of lines, Béziers and arcs, with clamping), `evidence/noise.rs` (the + variance model and the fourth-difference self-calibration), `evidence/vertex.rs` + (proposals, per-pixel neighbourhoods, flat directions), `evidence/fisher.rs` (Jacobians, + `F`, density). +* `strip.rs`'s `SIDE_TOL` becomes the same test with a calibrated threshold, + `z√(70V̂)/12`, and the vertices it declines become corner proposals. +* The fitter's side (the window residual in `inkvec-fit`'s dynamic program) is the + representation chain's; B provides the evaluator and test fixtures. + +**How Lean constrains Rust.** (1) Every rational constant (histopolation, the fourth +difference, `70`, `12`, `5/4`, `3/4`, the straddle weights) is checked by a `cargo test` +against `Vectors.lean`'s output, committed as a file. (2) Debug assertions of the +inequalities the proofs rely on: for every window and candidate, the faces' areas sum to the +window's size and each lies in `[0, |W|]` (B2.1); a window's information never exceeds its +pixels' (B2.2); the unmixing residual of a two-ink window is within its bound (B1.2); `F` is +positive definite where `rank J` is claimed full (B4.2). (3) Tests on exact renders: window +sums of a known polygon equal its exact areas to `1e-12` (the first row of B2.3's table). + +### Measuring success + +* **Calibration** (`bench/theory`): `χ²/M` at the truth within `1 ± 0.1` on exact, 8 × 8 + and 32 × 32 renders, and on the corpus's own intake (resvg) once its floor is estimated. +* **Efficiency:** the maximum-likelihood estimates of lines, circles, ellipses and polygons + against `F⁻¹`: ratio of predicted to measured variance at least 0.8. +* **Vertices and corners:** vertex error against B3.1; corner precision and recall of the + proposals and of the `Δχ²` decision against turning angle and fillet radius, compared with + `SIDE_TOL`. +* **Thin strokes:** centre and width against B3.4's variances, and flat intervals reported + where the stroke is hidden. +* **Stage 07** (`strip_eval.py`, `inkvec_compare.py`): the starting geometry, which only + changes at gentle corners. +* **The gate:** next to no change in dE00 from the boundary chain alone (the starting map + changes only where the corner test's threshold does); then, with the fitter scoring windows, the geometric match to the artist's file + (edge displacement by symmetric-difference area; corner precision and recall) and the + parameter ratio, against the base. Corners and junctions are where the gain should show: + they hold about 5 % of the colour error (`attribution.py`) but most of the visible + geometric disagreement, and they are where today's point readings decline. + +## Phase 2, milestone 1: the floor measured, the evaluator built + +What landed, against the amendments of `chain-representation.md` (A1–A5) and the +measurements the coordinator asked for. Engine output is unchanged: nothing in the +pipeline calls the evaluator yet. + +### The renderer floor of the corpus intake (measured) + +`bench/theory/renderer_floor.py` scores the intake against the artists' own geometry, +drawn exactly, on six flat-paint icons per family (24 to 30 k windows per tier). The unit is +a window's error in area, which is the error of the boundary's mean position across the +window, px. Every partial pixel lies in exactly one window, including at 45°. + +| tier | family | quantisation | as drawn (`as8`) | per-edge share | straight fills, tiny-skia's lattice | curves, lattice | strokes, lattice | stale levels | +|---|---|---|---|---|---|---|---|---| +| 128 | lucide | 0.0011 | 0.0107 | 0.58 | 0.0017 | – | 0.0106 | 0 | +| 128 | material | 0.0008 | 0.0099 | 0.85 | 0.0016 | 0.0042 | – | 0 | +| 128 | noto | 0.0070 | 0.0083 | 0.23 | 0.0044 | 0.0076 | 0.0073 | 0 | +| 128 | openmoji | 0.0020 | 0.0077 | 0.46 | 0.0025 | 0.0094 | 0.0093 | 0 | +| 128 | simple-icons | 0.0014 | 0.0045 | 0.53 | 0.0015 | 0.0048 | – | 0 | +| 128 | twemoji | 0.0025 | 0.0053 | 0.48 | 0.0026 | 0.0048 | – | 0 | +| 512 | lucide | 0.0011 | 0.0240 (fresh 0.0170) | 0.44 | 0.0019 | – | 0.0207 | 24 | +| 512 | material | 0.0008 | 0.0188 (0.0109) | 0.86 | 0.0018 | 0.0094 | – | 11 | +| 512 | noto | 0.0063 | 0.0140 (0.0081) | 0.53 | 0.0048 | 0.0080 | 0.0076 | 16 | +| 512 | openmoji | 0.0022 | 0.0167 (0.0087) | 0.47 | 0.0050 | 0.0073 | 0.0099 | 22 | +| 512 | simple-icons | 0.0013 | 0.0122 (0.0092) | 0.58 | 0.0017 | 0.0113 | – | 9 | +| 512 | twemoji | 0.0024 | 0.0113 (0.0067) | 0.56 | 0.0024 | 0.0059 | – | 18 | + +The columns: + +* **quantisation:** the 8-bit rounding alone. +* **as drawn:** the intake against usvg's geometry composited per element at 8× with exact + coverage, in brackets against a render made now. +* **per-edge share:** the part of the floor's variance that is a constant per edge. +* **lattice:** a fresh render against the same geometry sampled on tiny-skia's 4 × 4 + lattice. +* **stale levels:** the largest difference between the committed intake and a fresh + resvg 0.48.1 render. + +What this says: + +1. **A1, arcs.** Drawing arcs as usvg does (kurbo cubics at 0.1 user units, ported to + `EllipticalArc::to_cubics`) matters where icons are arcs: on simple-icons the window error + falls from 0.0204 to 0.0122 at 512 (0.0062 to 0.0045 at 128). Elsewhere it is below the + floor. +2. **A1, the lattice.** With tiny-skia's sample lattice replicated, straight fill edges reach + the quantisation level (0.0015 to 0.0026 px at 128, 0.0017 to 0.0050 at 512; material 12mp + per pixel 0.0106 to 0.0014). The rest is tiny-skia's own curve flattening (0.004 to 0.011 + px) and its stroker (0.008 to 0.021 px; round caps up to 0.06 per pixel). These are + deterministic: a forward model that calls tiny-skia removes them, while a floor can only + absorb them. +3. **A3, the correlation.** Most of the floor is a constant per edge (0.44 to 0.86 of its + variance). The fourth-difference self-calibration sees 0 to 22 % of it, as it should, + since a per-edge offset cancels in `D`. On material at 128 the per-edge sd is + 0.009 ≈ 1/(32√12), which is `Floor::lattice(32)`'s `edge_var`. The default floor is + therefore right for straight edges and too small for curves and strokes until (2) is done. +4. **The 512ss tier is stale.** The committed 512ss PNGs differ from a fresh render by up to + 24 levels: an older resvg, or older SVGs. The 128ss tier reproduces byte for byte. + Calibrating at 512 needs that tier re-rendered (the coordinator's call: it moves every + 512 baseline). +5. **A2, conflation.** Compositing each element at 8× and then box-filtering is not the + visible partition. At junction pixels the difference is mean 0.004 to 0.006, p99 0.017 to + 0.040 (colour units), which is many times the quantisation, so junction terms need + per-layer compositing. At two-ink pixels it is negligible, except where shapes abut + (twemoji: 1.3 % of boundary pixels over one level; the synthetic set: 60 %, window error + 0.067 px along such seams). + +### What the evaluator is (`inkvec_core::likelihood`, `inkvec_trace::evidence`) + +* **The trait `BoundaryLikelihood`** (in `inkvec-core`, so `inkvec-fit` needs no + `inkvec-trace`), with these methods: + * `runs(e)` gives the `RunObs {window, s, sum, var, left_low}` of edge `e` in order. + * `chi2_run(e, range, pieces)` gives `Chi2 {chi2, m, chi2_floor}`. Its `chi2_floor` is the + Sherman–Morrison form with the per-edge offset, on edges `edge_on_lattice` says share it. + * `residuals_run`. + * `run_moments(e, degree)` gives prefix sums for least-squares polynomial graphs over any + range in `O(p³)`. + * `chi2_local(Owner::Junction | Owner::Corner, curves)` is the per-pixel term. + * `junctions()` gives arms in angular order with direction sd, and continuations (A4). + * `corners()` and `density(e)`. + + Candidates are `Piece::{Line, Quad, Cubic, Arc}`. The `RenderModel` converts arcs exactly + as usvg does. `left_area` integrates each piece exactly over the strip, clamped, and counts + every pass of the curve through the strip, so a curve that folds or crosses a window twice + is scored correctly (B2.1's identity for any curve, not only graphs). +* **`Evidence::build(map, rgb, faces, σ, opts)`.** For each edge between two flat inks with + enough contrast, it unmixes the pixels onto the two-ink axis. Quantisation variance is + grouped by the channels that round together. Pixels holding a third ink are set aside. + The partial pixels are then grouped into windows. A window the starting geometry does not + cross exactly once becomes a **corner term** (per-pixel areas against the candidate, + closed along a box on its left), with a proposal there. Corners along runs come from the + fourth difference at `z ≥ 3`. Junction neighbourhoods (2.5 px) are kept per pixel, in + colour. Pixels two edges reach away from a junction are listed, not yet scored (B3.4). + +Decisions taken while building it: + +* **No pure flanks.** A pixel that reads as one ink's pure colour can hold up to half a + level of the other's area and reads none of it. That error has one sign, so flanks put + `χ²/M` at 1.85. A window is its partial pixels only; the clamp in `left_area` makes that + exact. +* **Inks on the 8-bit lattice.** The face colours unmixing uses must be the pure pixels' + 8-bit values. Inks a fraction of a level off bias every window by up to 3σ. +* **Calibration.** At the truth, on exact renders rounded to 8 bits, `χ²/M` is 0.97 over 442 + windows (discs and squares at several angles, 45° included). Junction and corner terms + stay below 2. A vertex moved by 1 px, or a 1 px chamfer, costs more than 100. + +### Verified by checkers generated from Lean + +`formal/InkvecTheory/InkvecTheory/Windows.lean` proves the window identity for any finite +set of pixels and any measurable region (`window_sum_eq_area`), and the area of a straight +piece (`trapezoid_integral`). `Gen/Evidence.lean` defines four kernels, each with its +theorem; `#print axioms` gives `propext, Classical.choice, Quot.sound` only: + +* `trapezoidK`: `trapezoidK_eq`, `trapezoidK_integral`. +* `windowTermK`: `(S − A)²/V` and `S − A`. +* `fourthDiffK`: `fourthDiff_cubic` says it vanishes on cubics; `fourthDiff_side` relates + it to `strip.rs`'s one-sided test. +* `cornerExcessK`: `D² − z² Σ wᵢ² Vᵢ`. + +The generated `inkvec_verified::generated::evidence` supplies `_f64`, `_iv` and `_q` forms +of each kernel. Two results are accepted only through them: + +* **Runs.** Every run window must be certified crossed by the starting geometry, with its + area enclosed (`checks::certified_left_area`, outward-rounded intervals). A window the + checker refuses becomes a corner term. +* **Corner proposals.** Each must have `corner_excess_iv ≥ 0`. + +`checks::certify_run_chi2_polyline` certifies a solver's `χ²` of a polyline candidate on any +set of windows. + +### Next (as decided after milestone 1) + +The engine's forward model stays renderer-agnostic: exact geometry and a floor calibrated per +image (`RenderModel::default()` draws arcs exactly; `RenderModel::usvg()` keeps usvg's cubics +for measuring a known renderer). tiny-skia is replicated only in bench tooling. The 512ss +tier stays as committed: its renderer offsets are realistic variation too. + +## Phase 2, milestone 2: noise from the edges + +The engine's intake model was 8-bit rounding and one noise level per image, read from flat +regions. On a resized JPEG (the gate's `web` tier, `docs/theory/noise.md`) the error sits at +the edges, 5 to 9 times the interiors', and has heavy tails. The truth (each icon's exact +geometry at 400 px) scored on the engine's own windows read `χ²/M` = 150 there. This +milestone measures the noise per image from the edges, gives the windows a forward model with +the blur in it, and hands the result to the representation chain as one object +(`inkvec_core::noise::NoiseModel`). + +### What a window's error is made of (measured) + +`bench/theory/floor_selfcal.py` runs the engine on five renders of 21 icons (3 per family) +and on the `web` tier: an exact render, 8 × 8 point samples (`ss8`), tiny-skia's 32-sample +lattice with exact flattening (`lat32`), resvg 0.48.1 now and the committed tier (identical +at 128 px), and `web`. Each run window is scored against the truth's sum on the same pixels +(`crates/inkvec-trace/examples/evidence_calibrate.rs`). A window's error is a function of the +edge's local sub-pixel phase and of what lies near it, and splits three ways: + +* **Replicas.** Neighbouring windows whose mean positions differ by a whole pixel see the + edge at the same phase and repeat one measurement with its error. The correlation between + such neighbours is 0.84 to 0.95 on every input. On an axis-aligned edge every window is a + replica: on `web` 81 % of the fourth differences of one material icon are exactly zero. + Every source is replicated, including the JPEG's: a block holding a horizontal edge has + only vertical frequencies. +* **The rough part.** Errors at different phases are independent on exact, lat32 and ss8 + renders. They anticorrelate at phase steps under 0.05 px (rounding's sawtooth). +* **The smooth part.** On resvg and `web` renders a correlation of about 0.6 remains between + neighbours at every phase step. A smooth error along the run (curve flattening, arc + conversion, a resampler's phase ripple) is indistinguishable from moving the edge. + +### The estimator (`evidence/noise.rs`) + +* **Rounding alone as the base variance.** It is exact for clean renders (`χ²/M` 0.97 at the + truth). It is alpha-aware: where the source drew an ink over the clear ground, the intake + rounds the alpha, and the weight's variance is `Q²/12` whatever the ink's contrast. +* **Replica stretches count once.** A stretch of `k` replicas gets `k` times the variance and + a share `1/k` (`RunObs::share`; `Chi2::dof = Σ share`). +* **The rough part from the windows themselves.** It is solved per class (straight, curved) + from the fourth differences of replica-free stencils. A winsorised second moment + (`E min(z², 6.25)` = 0.9776 for a normal) is exact for normal errors and within 2 % for + rounding's bounded ones. A median is 1.65 times off there: that is what first put exact + renders at 0.55. +* **Geometry kept out of the estimate.** A stencil counts only if its local bend (its largest + second difference of positions) is under the larger of 0.08 px and six noise standard + deviations, iterated from all stencils. Below 0.08 the `D`s of the measured positions and + of the truth's errors agree on every input; above it a tight curve's own fourth + difference leaks in (6 times the noise on "straight" and 60 on curved windows of exact + renders at 128 px). +* **A significance gate.** A class's extra is kept only when it beats a normal's moment by + three standard errors. +* **The smooth part as one offset per edge.** It has the variance of one of the edge's + windows (`edge_offset_var`, read by `chi2_floor`). An axis-aligned edge's constant error + *is* one window's error, replicated. A fitted candidate absorbs it in its own position. +* **The tail.** It is read from the `q90/q50` ratio of the standardised `D`s and matched to + Student-t's. It is then diluted back to one window's: a `D` keeps 0.37 of its windows' + excess kurtosis. +* **The robust cost.** Huber's at `κ(ν) = min(3, √ν)` (agreed with the representation chain: + where Student-t's influence peaks), on the Kalman-standardised innovations (`Chi2::cost`). + It equals `χ²` while every innovation is within `κ`: always on a clean intake's truth. +* **A point-sampling renderer's lattice.** It is read from the image. On an axis-aligned edge + such a renderer's coverage is a multiple of `1/n`, so the smallest `n` that 90 % of the + replica stretches' partial pixels sit on (and a random value would not) is the lattice. + Its sawtooth `1/(12n²)` is added to replica windows. Coverages of one half are left out: + drawings put edges on half pixels by design. + +### Lossy and soft intakes: windows on the observed ramp + +* **Luma unmixing.** With 4:2:0 chroma, weights are read from luma + (`α = (Y − Y_b)/(Y_a − Y_b)`, BT.601), the channel kept at full resolution. This applies + where the inks' lumas differ by at least 0.1 (three times the edge noise); a nearly + isoluminant pair falls back to full colour. The third-ink test allows 26 levels of chroma + bleed. +* **Plateau-median inks.** Each edge's inks are the per-channel medians of the pixels just + beyond its reach on either side, not the palette's means. On a clean render these are the + exact inks. +* **The reach.** It widens to cover the observed ramp: `0.5·w + 1.1` px for the + box-equivalent edge width `w` of `softness::ramp_evidence`. +* **Band windows.** A window takes every pixel of the edge's band on its line, not only + those reading as mixtures: noise splits a blurred ramp's run of partial pixels, and each + fragment would lose mass to the next. +* **Column or row is decided along the edge.** The choice uses the direction smoothed over + ±2 px of arclength with a hysteresis of 0.15 rad about 45°. Decided per pixel from a noisy + polyline's local tangent, diagonals were cut into alternating one- and two-pixel windows + that erred in opposite directions (+0.085 and −0.12 px side by side). + +### Blur: the forward model + +For a blur or resampling `w(y, s)` from input pixels `s` to output pixels `y`, a column +window `W` over the blurred transition sums to + + Σ_{y∈W} (f ∗ k)(x, y) = (A ∗ k_x)(x) + Δ · m_y, + +with three conditions and limits: + +* **Hypothesis: `Σ_{y∈W} w(y, s) = 1` for every input `s` it draws on.** `A` is the column-area + profile, `k_x` the horizontal marginal, `Δ` the plateau step and `m_y` the vertical first + moment (`docs/theory/noise.md`). The mass-preservation step is `window_sum_resampled` + (`Windows.lean`). +* **Box filters and general resamplers.** An integer-ratio box filter satisfies the + hypothesis. A general resampler (Pillow normalises per output pixel) satisfies it only on + average over phase, and its phase ripple, 0.04 px at a factor of 0.78, is the measured + residual. On `web` that ripple is part of the windows' variance. +* **A centred kernel (`m_y = 0`).** It leaves a straight edge's profile alone + (`blur_affine_profile`) and moves a curved one by exactly `½ μ₂ A''` + (`blur_quadratic_profile`). That is the forward model, not noise. +* **The translation.** The first moment, a global sub-pixel translation, cannot be identified + from one image: translating the drawing reproduces it exactly. The coordinator measured it + at 0.004 px, so it is left out. + +`μ₂` comes from `ramp_evidence`'s width: its spread is `(3w² − 1)/12` with a native mean of +1/6, so `μ₂ = (w² − 1)/4`, not `/12`. `RenderModel::window_area` adds `½ μ₂ A''`, with `A''` +the second difference of the window's area profile (the candidate moved a pixel either way +across the strip), only when `μ₂ > 0`. + +On damaged input the target is the artist's clean original: the boundary reported is the +sharp one before the blur, and a corner lost to blur comes back when its arms support it. +This model makes that possible. The per-pixel corner and junction terms still compare +unblurred candidates. Blurring them is the next step, and the soft-intake reduce step could +then be replaced by this forward model (to be gated before acting). + +### In the engine + +The colour path already decides whether an intake is soft: its edges wider than a native +render's, ringing (`coverage::ringing_score`), or a lossy container. That is evidence from +the pixels, not the flag alone. Only then does `evidence::measure_noise` run, which costs 13 +to 49 ms at 400 px, after the crossing test was indexed by arclength. + +Its measurement goes to `ColorTrace::noise` (through `evidence::with_noise`, the colour +path's last step) whenever the edge noise exceeds `FOLD_LEVEL` (3 levels). Clean renders read +at most about 1.3 levels and `web` 4 to 27. Under it, and on every clean intake, the model is +`NoiseModel::clean()`. + +Nothing in the pipeline reads it yet. Against the previous build, every traced file is +byte-identical on all eight gate conditions (246 icons each). + +The two builds were timed interleaved on a shared machine, and their clean run times match: +Quality +0.0 to +1.3 %, Fast −5.6 to +0.4 % (Fast totals are a few seconds). No clean intake +takes the measurement: 0 of 246 at 128 px and 0 of a 62-icon sample at 512 px opaque. Fast +mode never takes it. On a `web` icon in Quality it costs about 60 ms of a 2 s trace. + +`NoiseModel` (agreed with the representation chain) holds: +`{sigma_flat, sigma_edge[4 bands], psf_radius, psf_mu2, nu, lossy, window_scale}`. It also +provides `huber_kappa` and `explained_by_psf` (a band narrower than the blur, coloured on the +line through its two inks or overshooting them). + +Folding the noise into the planar map's per-point `σ` is opt-in (`INKVEC_NOISE_FOLD=1`). Each +point's `σ` then grows by the windows' measured error in quadrature, which is what the fitter +divides by. With today's fitter, honest uncertainties buy simpler fits at a cost in fidelity +(`quality-web`, a 62-icon sample: turning −5.0 %, parameters −1.4 %, dE00 +2.8 %, geom ++1.7 %). So the fold waits for the representation chain's fitter to read it with its robust +loss. + +### `strip.rs`: a statistical side test on soft intakes + +The one-sided corner test is the fourth difference of six column means over 12 +(`fourthDiff_side`), so its noise is `√(70 V)/12` for column means of variance `V`. On a soft +intake a vertex is now declined only beyond `max(SIDE_TOL, 3·√(70 V)/12)`, so the noise, not +the constant, sets the threshold there. `V` is `widest · σ² / |d|²`, from the trace's measured +per-channel `σ` (raised by `regularize::residual_sigma` on a soft intake), the widest column +window and the two faces' colour separation. The certificate (`CERT_TOL`, the shift lands on +the cubic) is unchanged. + +**Why soft intakes only.** On a clean render a low-contrast edge (shading) also makes +`σ/|d|` large, and there the term passed `SIDE_TOL`: ungated, it changed 4 of 246 icons at +`quality-128ss` and 14 at `fast-128ss`. So the front end's own soft-intake decision now +reaches the refinement as `RefineCtx::soft` (`planar::measure_subpixel`'s `soft` argument). +That is the decision that opens the palette guard and the noise measurement: wide edges, +ringing or a lossy container, read from the pixels. On a clean intake the test is `SIDE_TOL` +by construction. + +**Fast is not scaled.** Fast measures no noise and refines against `NOISE_FLOOR`, so a +scaled test there would move the threshold by a constant. On `fast-web` it changed 12 icons, +with dE00 and geom no better, so Fast passes `false`. + +**Measured against the session head (d8a5646), per icon, with the same build otherwise:** + +* All six clean conditions are byte-identical (246 of 246 icons each), as is `fast-web`. + Clean run times match: Quality +0.1 to +1.0 %, Fast −6.2 to −0.0 %, interleaved on a + shared machine. +* `quality-web` changes 111 icons, and every gated axis improves at its point estimate. + The bound is the one-sided 95 % upper bound. + +| `quality-web` axis | base | this change | change | upper bound | verdict | +|---|---|---|---|---|---| +| dE00 | 0.20191 | 0.20163 | −0.14 % | +0.04 % | non-inferior | +| `turning_gap` | 3.67939 | 3.67848 | −0.02 % | +0.77 % | non-inferior | +| `ratio_gap` | 0.61128 | 0.61109 | −0.03 % | +0.35 % | non-inferior | +| geom | 0.34712 | 0.34700 | −0.03 % | +0.15 % | non-inferior | + +### The adapter (`EdgeScorer`, agreed with the representation chain) + +* **The partition.** `windows_between_points(i, j)` gives the run windows whose centres lie + in the span `[i, j)` of the edge's point indices, as two ranges through the seam of a + closed edge. Every window belongs to exactly one span whatever the segmentation, so the + number scored is constant. Corner and junction terms are fixed per edge. +* **Scoring.** `chi2(r, pieces)` scores a span's piece, extended past its ends, on all of its + windows. +* **The O(1) queries.** `best_graph(r, degree)` and `weight_moments(r)` run in `O(1)` from + prefix sums, for the dynamic program's inner loop and the Fisher matrix of a graph of + degree at most 3. +* **Arcs.** `Piece::from_svg_arc` converts the fitter's endpoint arcs to centre form. + +### A2: stroke bands and per-layer compositing + +* **`chi2_band(pair, band, inks)`.** It scores a `StrokeBand`, a centreline and a width, on + the thin-feature pixels its two edges both reach. These pixels were only listed until now. + Each pixel is a mix of the ink left of the band, the band's and the ink right of it, by + their exact areas. On a 1.4 px band at 20° the true band is calibrated, while a 0.3 px + shift or a band 0.3 px too wide costs more than 100. +* **`chi2_local_layers(node, layers, ground)`.** It scores a junction's pixels by compositing + each layer's whole shape over what lies beneath, in paint order, as a renderer does. That + is the term the visible partition misses at junctions (mean 0.004 to 0.006, p99 up to + 0.04, `renderer_floor.py`). On two overlapping squares drawn that way the true shapes are + calibrated, and the top one moved by half a pixel costs more than 100. +* **Arcs in local terms.** The local terms' flattening follows arcs through fine cubics. With + the default render model drawing arcs exactly, it had been dropping them. + +### Validation + +The engine's windows, scored against the truth with the evaluator's own `score` (replicas, +the per-edge offset, Huber at `κ(ν)`): `χ²_floor` per independent measurement (Huber in +brackets). 21 icons, 3 per family. + +| input | rounding alone | per-image noise model | +|---|---|---| +| exact, 128 px | 0.97 | 0.72 (0.72) | +| 8 × 8 point samples, 128 px | 334 | 3.02 (2.07) | +| tiny-skia lattice, 128 px | 14 | 1.79 (1.57) | +| resvg (fresh = committed), 128 px | 32 | 4.33 (3.34) | +| resvg fresh, 512 px | 119 | 13.9 (7.4) | +| committed 512ss | 206 | 9.9 (6.5) | +| `web` (400 px JPEG) | 150 | 3.12 (1.79) | + +On `web` the median standardised residual is 1.02. Against a local cubic fitted over 9 +windows (what a fitter sees) it is 1.37, and 1.05 under Huber. Most families sit at 1.2 to +1.7 under Huber; openmoji is the outlier at 3.4. + +What remains: + +* **resvg's smooth curve error.** Flattening chords and usvg's arc cubics leave about 0.01 px + along curves, smooth enough that no difference sees it (simple-icons, all arcs, is the + worst). It is the price of an exact-geometry model that does not replicate a renderer, and + a fitted candidate absorbs it in its own geometry. +* **A point-sampled render's sawtooth.** On near-axis edges that are not exact replicas it is + only partly modelled. +* **Exact renders are slightly over-calibrated** (0.72): the extra variance is accepted on + significance, and a small geometry leak gets through. + + +```bash +python3 bench/theory/evidence_eval.py all # B1.2, B2.2, B2.3, B3.1, B3.3 (about 10 s) +python3 bench/theory/exact_raster.py # the renderer's self-check +python3 bench/theory/renderer_floor.py --fresh # the intake's floor (about 25 min) +cargo build --release -p inkvec-trace --example evidence_calibrate +python3 bench/theory/floor_selfcal.py --sizes 128 --per-family 3 # five renders +python3 bench/theory/floor_selfcal.py --sizes 400 --conditions web --per-family 3 +cargo test -p inkvec-core likelihood noise +cargo test -p inkvec-trace --lib evidence +``` + +## References + +* Chernoff, H. (1954). On the distribution of the likelihood ratio. *Annals of Mathematical + Statistics* 25(3). +* Gasser, T., Sroka, L., Jennen-Steinmetz, C. (1986). Residual variance and residual pattern + in nonlinear regression. *Biometrika* 73(3). +* Hall, P., Kay, J. W., Titterington, D. M. (1990). Asymptotically optimal difference-based + estimation of variance in nonparametric regression. *Biometrika* 77(3). +* Havelock, D. I. (1989). Geometric precision in noise-free digital images. *IEEE TPAMI* + 11(10). +* Kay, S. M. (1993). *Fundamentals of Statistical Signal Processing: Estimation Theory.* + Prentice Hall. (Cramér-Rao bound, least squares.) +* Porter, T., Duff, T. (1984). Compositing digital images. *SIGGRAPH '84*. + doi:10.1145/800031.808606. +* Puckett, E. G. (2010). A volume-of-fluid interface reconstruction algorithm that is + second-order accurate in the max norm. *CAMCoS* 5(1). +* Rice, J. (1984). Bandwidth choice for nonparametric regression. *Annals of Statistics* + 12(4). +* Self, S. G., Liang, K.-Y. (1987). Asymptotic properties of maximum likelihood estimators + and likelihood ratio tests under nonstandard conditions. *JASA* 82(398). +* Trujillo-Pino, A., Krissian, K., Alemán-Flores, M., Santana-Cedrés, D. (2013). Accurate + subpixel edge location based on partial area effect. *Image and Vision Computing* 31(1). + doi:10.1016/j.imavis.2012.10.005. +* Wald, A. (1943). Tests of statistical hypotheses concerning several parameters when the + number of observations is large. *Transactions of the AMS* 54(3). diff --git a/docs/theory/chain-representation.md b/docs/theory/chain-representation.md new file mode 100644 index 00000000..63a8b28e --- /dev/null +++ b/docs/theory/chain-representation.md @@ -0,0 +1,1812 @@ +# Chain R: representation, informally + +> From the boundary chain's likelihood to the fewest coordinates a person would write. What +> the objective should be and why (R0); constraints and the free coordinates they leave (R1); +> which constraints hold (R2); the human prior, counted from the artists' own files (R3); +> structure and encoding (R4). Each link states its problem, its claims and an informal +> proof of each, or a gap marked as one with what would close it. The numbers the prior needs +> are measured on the corpus (`bench/theory/design_prior.py`). The interface this chain +> needs from the boundary chain is proposed at the end, with the plan for the formal +> development and the code. + +Companion pages: [`chains.md`](chains.md) (the split into two chains), +[`chain-boundary.md`](chain-boundary.md) (the boundary chain, whose likelihood this chain +consumes), [`optimal.md`](optimal.md) (the optimum as the most probable SVG; the +search/model diagnostic), [`README.md`](README.md) (what the pixels determine, proved in +[`formal/InkvecTheory`](../../formal/InkvecTheory/README.md)). + +## Summary + +* **The objective is the posterior probability of the design, with its free coordinates + integrated out.** A design has a discrete part (elements, segment kinds, paint order, + which constraints hold, which numbers are tied or on the design grid) and the continuous + coordinates the constraints leave free. Under a loss that counts structural mistakes + (a missed corner, a wrong segment kind, a broken constraint: what the gate's geometric + match counts) the best decision is the most probable discrete part, and its probability + is the prior times the *evidence*, the likelihood integrated over the free coordinates + (R0.1). The evidence prices each free coordinate at `ln(W/(√(2π)·σ))`, set by how + precisely the pixels fix it, and each constraint at the log prior odds the corpus gives + it (R0.2). Today's `½χ² + λ·P` is the special case with one precision for every + coordinate and a flat prior (R0.3). +* **The lexicographic rule is the high-resolution limit of that objective, proved + informally (R0.5).** As the resolution grows, a design that cannot draw the truth loses + by a misfit that grows at least as the square of the resolution; among designs that draw + it, each extra free coordinate costs a term growing as its logarithm; the prior stays + bounded. So the order "fit within the noise, then fewest free coordinates, then the most + human" of [`chains.md`](chains.md) is what the posterior converges to. It is kept as the + search order and as a check; at finite resolution, and decisively at 128 px where + [`optimal.md`](optimal.md) §6 finds the objective preferring the trace on 117 of 246 + icons, the posterior's own trade decides. +* **Imposing a constraint that is slightly false costs at most what the test let through + (R0.4).** The constrained fit's error is, for every noise, the noise kept in the smaller + model plus the constraint's violation. A constraint lowers the expected error exactly + when its violation is under one standard deviation per removed coordinate. This extends + `natural_model_closer` from true constraints to false ones and bounds the fidelity cost + of every decision of R2 by that decision's own threshold. +* **Free coordinates are counted by rank, and most icon constraints are linear (R1).** + Ties, axis alignment, mirror pairs and translated copies are linear equations with + coefficients 0 and ±1, so their rank is exact (a tie graph with `c` components leaves + `c` values); a finite symmetry group leaves the average of its characters; nonlinear + constraints (tangency, incidence on a curve) are counted at the fitted point with a + rank decision certified by a singular-value gap (Weyl). The gate's count is not the + free-coordinate count (it charges an arc 7 numbers for 3 free ones and a subpath's start + nothing), so the objective uses free coordinates and the encoder minimises the gate's + count separately (R4.6). +* **Which constraints hold is a Bayes-factor test with stated error rates (R2).** Accept + when `½Δχ²` is under the removed coordinates' price plus the log prior odds. A true + constraint is then rejected with probability `P(χ²₁ > 2τ)` (5·10⁻⁴ at a threshold of 6 + nats), a false one accepted only when its violation is within `√(2τ)` standard + deviations (3.5σ at 6 nats), and both rates go to zero as the resolution grows. + Accepted in order of evidence, each tested against the fit under the ones already + accepted, the set is never contradictory. Ties are found exactly by a one-dimensional + dynamic program (equal noise makes the optimal tie classes contiguous), the grid on the + tie classes rather than on the coordinates. +* **The prior is a few hundred numbers counted from 1,408 artist files, and its main + finding is structural (R3).** The design grid governs *construction* points: 95.5 % of + lucide's line–line corners and 100 % of its primitive numbers lie on the half-unit grid, + but only 27 % of the points where its arcs meet, which are intersections the artist + computed and rounded. Artists' constraints are exact or clearly absent: 66.8 % of + lucide's lines and 72.3 % of material's are exactly axis-aligned against 0.0 % and 0.5 % + within half a degree of it; joins between curves are smooth (within 2°) 69 % of the time + and corners (over 30°) 18 %, with 7 % between. Under this prior a coordinate of a grid + family costs 5.3 nats instead of the flat 8.5. In simulation at the boundary chain's + calibrated precision (σ = 0.005 px), the hierarchical prior (ties, then the grid by role) + returns 73–75 % of lucide's and material's numbers *exactly*, which is all of their + on-grid numbers, snaps 0–0.3 % wrong, and cuts the positional error by 77–78 %; ties are + recovered with pairwise precision 0.98–1.00 and recall 1.00. +* **Structure decomposes exactly once the paint order is fixed (R4).** With a back-to-front + order, a set of shapes paints the traced picture if and only if each shape lies between + its visible part and its visible part together with everything painted above it; these + conditions involve no other shape, so each face's shape is chosen alone, and inside that + interval the pixels are indifferent, so the prior alone chooses (amodal completion as + the simplest shape in an interval, invisible by construction). Completion also removes + the compositing seam that `seams.rs`'s underlap works around. In the emoji families + 37–56 % of the elements are partly covered by a differently painted element, and they + hold 44–47 % of the artist's parameters: the largest parameter share the trace cannot + reach today. +* **The interface is a measurement model, not a fitted map, and the two chains agree on + it.** The boundary chain's `Evidence` and `BoundaryLikelihood` + ([`chain-boundary.md`](chain-boundary.md)) score any description exactly by window areas + with calibrated variances; chain R adopts + them, asks that the evaluator draw every candidate exactly as the corpus's renderer + does (the likelihood separates an arc from its four-cubic approximation by about fifty + standard deviations at 512 px), and takes over corners, continuations, gradients and + strokes as its own decisions. R computes the precision of its own parametrisation from + the same terms, so the boundary chain need not. + +## 0. The problem, and notation + +**In.** The boundary chain's output (B4): a planar map (faces, edges between two faces, +vertices) and a likelihood: for any picture `S` drawn by a candidate description, a +negative log-likelihood `ℓ(S) = −ln P(R | S)` of the raster `R`, as a sum of local terms, +one per graph-like run of an edge and one per vertex window (see the interface proposal). +`χ²(S) = 2ℓ(S) + const`. + +**Out.** An SVG document. + +**A design** `D = (T, θ)`: + +* `T`, the **discrete part**: the elements and their kinds (path, circle, rect, stroke or + fill), their paint order, each boundary's segment kinds (line, arc, cubic) and joins, the + set `C` of design constraints that hold (R1's vocabulary), and the discrete labels of + coordinates (which grid point a coordinate sits on, which coordinates are tied to one + value); +* `θ ∈ ℝ^k(T)`, the **free coordinates**: a chart of the set of raw coordinates + satisfying `C`, of dimension `k(T)`, the number of free coordinates. + +It draws a picture `S_T(θ)` and is written as an SVG `enc(T, θ)`. Three counts of one design +differ and must not be confused: the raw coordinates `n(T)` of its segments and primitives; +the free coordinates `k(T) = n(T) − rank J_C` (R1); and the **gate's count** `w(enc)`, the +numbers `bench/inkvec_bench/svgmodel.py` charges: line 2 (also when written `H`/`V`), quadratic +4, cubic 6 (also `S`), arc 7, `` 3, `` 4, `` 6, `` 4, `` 6, +geometry in `` once, and nothing for a subpath's start point, a transform, a stroke +width or a colour. + +**The prior** `P(T)·h_T(θ)`: a probability for each discrete part and a density on its +free coordinates. **The posterior** of the discrete part: + +```text +P(T | R) ∝ P(T) · ∫ exp(−ℓ(S_T(θ))) · h_T(θ) dθ (the evidence of T) +``` + +Coordinates in this page are in design units unless said otherwise; `s` is the resolution +in pixels per design unit (128 px for a 24-unit icon: `s = 5.33`). + +## R0. The objective + +### R0.0 The candidates + +Seven ways to choose among descriptions of the same pixels, and what each gets wrong or +right. + +1. **Flat description length** (inkvec today): `½χ² + λ·P`, `λ = ln(extent/precision)` + (`FitConfig::from_precision`, `cost.rs`), the two-part code of Rissanen (1978). Right in + form. It prices every coordinate the same, however precisely the pixels fix it, and it + has no prior: a horizontal line costs what a skew one costs, a repeated radius what a new + one costs. +2. **Lexicographic**: fit within a `χ²` tolerance, then fewest free coordinates, then the + prior. Potrace orders (segments, penalty) this way. It states the goal directly, but its + tolerance is a hypothesis-test threshold chosen without the prior, it cannot trade a + slightly worse fit for a much more probable structure, and it is discontinuous in the + data. R0.5 shows it is the limit of the posterior at high resolution, which is where its + virtues come from. +3. **Bayesian model selection with learned priors** (Bayes factors, the Laplace + approximation; Kass & Raftery 1995; MacKay 1992), or its coding twin, minimum message + length with the Wallace–Freeman approximation (Wallace & Freeman 1987): the evidence of + each discrete structure, the free numbers integrated out. This is the choice below. +4. **Rate–distortion**: fewest numbers subject to a perceptual error bound. A good loss for + colour error alone, but it recovers the artist's design only by accident: among + descriptions under the bound it has no reason to prefer the one the artist drew. +5. **Constraint inference with fixed tolerances**, as in drawing beautification (Pavlidis & + Van Wyk 1985; Igarashi, Matsuoka, Kawachiya & Tanaka 1997) and relation discovery in + primitive fitting (GlobFit: Li, Wu, Chrysanthou, Sharf, Cohen-Or & Mitra 2011): detect + near-relations, impose them, re-solve. The right moves, with uncalibrated tolerances: the + tolerance should depend on how precisely the pixels fix the quantity and on how often + people use the relation, which is what R2's test gives it. `editable.rs` is a + beautifier of this kind (`3σ` plus a slack). +6. **A learned generative prior** (DeepSVG, Carlier et al. 2020; StarVector): excluded by + the requirement of a small model, and not needed: R3 shows the statistics that decide + are a few hundred counts. +7. **Program synthesis over a grammar** (Ellis, Ritchie, Solar-Lezama & Tenenbaum 2018; + Szalinski, Nandi et al. 2020, which recovers loops and symmetry in CAD by equality + saturation): the right search space for repetition and symmetry (R4.5); its objective is + still a choice among 1–5. + +### R0.1 Claim: the Bayes decision is the most probable discrete part + +**Claim.** Under the loss "1 if the discrete part differs from the artist's, else 0", the +estimate minimising the expected loss is `argmax_T P(T | R)`. Under the Hamming loss that +counts mismatched components of `T` (each corner, each segment kind, each constraint), it is +the component-wise posterior mode, which coincides with the joint mode whenever the joint +mode has posterior probability above ½. + +**Proof.** The expected 0–1 loss of `T̂` is `1 − P(T̂ | R)`. For the Hamming loss the +expected loss is a sum over components of `1 − P(T_i = T̂_i | R)`, minimised component by +component. If `P(T* | R) > ½` then every component has `P(T_i = T*_i | R) ≥ P(T* | R) > ½`, so +`T*_i` is that component's mode. ∎ + +The gate's geometric match (corner precision and recall, segment-type agreement) is a +Hamming-type loss on `T`, so this is the objective the gate's newest axis rewards, and the +condition says when the joint mode, which a search can find, is also the component-wise +optimum. + +### R0.2 Claim: the evidence prices each free coordinate by its precision + +**Claim.** Let the picture be affine in `θ` near the best fit (or linearised there), the +noise Gaussian with covariance `Σ`, so `χ²(θ) = χ²_min + (θ − θ̂)ᵀ F (θ − θ̂)` with Fisher +information `F = AᵀΣ⁻¹A`, and the prior a density `h` that is nearly constant where the +likelihood is not negligible. Then + +```text +−ln P(R | T) = ½ χ²_min(T) + ½ ln det(F_T / 2π) − ln h_T(θ̂) + const(R) +``` + +and in coordinates in which `F_T` is diagonal, `diag(1/σ_i²)`, with `h` uniform of width `W_i` +along each, the cost of the design is + +```text +L(T) = ½ χ²_min(T) + Σ_i ln( W_i / (√(2π)·σ_i) ) − ln P(T). +``` + +The constrained case uses the same formula with `F_T = Nᵀ F_raw N`, `N` an orthonormal basis +of the constraint set's tangent space (the null space of the constraint Jacobian `J_C`): +the information the pixels carry about the directions the constraints leave free. + +**Proof.** `∫ exp(−½(θ − θ̂)ᵀF(θ − θ̂)) dθ = (2π)^{k/2} det(F)^{−1/2}`, and the rest is the +logarithm. On a constraint manifold, a chart `θ ↦ x(θ)` with orthonormal tangent vectors at +`x̂` gives `∂x/∂θ = N` and `F_T = Nᵀ F_raw N`. For a nonlinear model the formula is +Laplace's method, with relative error `O(1/m)` in the number of measurements (Tierney & +Kadane 1986). ∎ + +Two consequences. A coordinate the pixels pin down more precisely costs *more* to state, +because more of its digits are information: from 6.2 nats (σ = 0.1 px) to 8.5 nats (σ = 0.01 +px) at 128 px, 7.6 to 9.9 at 512 px, for `W` the canvas; at the boundary chain's calibrated +precisions (0.0004–0.04 px, `chain-boundary.md` B4.3) about 7–13 nats. And a coordinate +that is not free costs nothing here; what it costs instead is the prior of the constraint +that fixed it, in `−ln P(T)`. + +### R0.3 Claim: inkvec's objective is the special case with one precision and no prior + +**Claim.** `E = ½χ² + λ·P` with `λ = ln(extent/precision)` is R0.2 with every `W_i` the +canvas, every `σ_i = precision/√(2π)`, `P(T)` uniform, and `P` the free-coordinate count. + +**Proof.** Substitute. ∎ + +So the present objective is right in form and wrong in two terms. Its precision is global +(0.1 px), where R0.2 asks for each coordinate's own (B4's), so it over-prices coordinates +the pixels fix loosely and under-prices those they fix tightly by about ±1.5 nats. And its +prior is flat, where the corpus says a coordinate of a grid family is worth about 3 nats +less than a free one (R3, Table R3.3). Both errors move the choice at 128 px, where +[`optimal.md`](optimal.md) §6 measured the objective preferring the trace over the artist's +file on 117 of 246 icons. + +### R0.4 Claim: a slightly false constraint costs at most what the test admitted + +**Setting.** As in `Naturality.lean`: whitened measurements `y = s + ε`, the larger model's +tangent space `L`, the constrained model's `K ≤ L`, fits by orthogonal projection. Unlike +there, the truth `s` is only assumed to lie in `L`, not in `K`. + +**Claim.** For every noise `ε`, + +```text +‖P_K y − s‖² = ‖P_K ε‖² + ‖s − P_K s‖², ‖P_L y − s‖² = ‖P_L ε‖², +``` + +so with isotropic unit noise the expected squared errors are `dim K + b²` and `dim L`, where +`b = ‖s − P_K s‖` is the constraint's violation in standard deviations. Imposing the +constraint lowers the expected error if and only if `b² < dim L − dim K`. + +**Proof.** `P_K y − s = P_K ε − (s − P_K s)`; the first term lies in `K` and the second is +orthogonal to `K`, so their squared norms add. `P_L y − s = P_L ε` because `s ∈ L`. The +expectations follow from `noise_absorbed` (`E‖P_K ε‖² = dim K`). ∎ + +**Consequence for R2.** The constraint test accepts only when `Δχ² < 2τ` (R2.1), and +`E Δχ² = Δk + b²`, so an accepted false constraint has `b²` of the order of `2τ` or less: its +fidelity cost is bounded by the test's own threshold, a few standard deviations of the +removed coordinate. At 512 px that is a few thousandths of a pixel for a line's direction. +With `b = 0` this is `natural_model_closer` and `natural_model_gain`. The statement is the +mean-square criterion for restricted least squares (Toro-Vizcarrondo & Wallace 1968), +here pointwise in the noise. + +### R0.5 Claim: the lexicographic rule is the high-resolution limit + +**Setting.** A fixed artist's design `T_A` drawn at resolution `s`, per-pixel noise fixed, +B4's likelihood calibrated (the truth's `χ²` has its nominal distribution). Candidates are +compared by `L(T)` of R0.2. + +**Claim.** As `s → ∞`, for every candidate `T`: + +1. if `T` cannot draw the artist's picture (its closest picture differs by a positive area + in design units), `L(T) − L(T_A) → +∞` at least as fast as `s²`; +2. if `T` can draw it and has `k(T) > k(T_A)` free coordinates, `L(T) − L(T_A) = + (k(T) − k(T_A))·β·ln s + O_p(1)` with `β > 0`; +3. if `T` can draw it and `k(T) = k(T_A)`, `L(T) − L(T_A) = −ln(P(T)/P(T_A)) + + ½ ln(det F_T / det F_{T_A}) + O_p(1)`, bounded. + +So with probability tending to one, the ranking by `L` is the lexicographic ranking by +(draws the picture, fewest free coordinates, prior and an Occam ratio). + +**Proof.** (1) A boundary displaced by `δ` design units is displaced by `sδ` px, which +changes each crossed column sum by about `sδ` against a column variance that does not grow, +over a number of columns proportional to `s`: `χ²` grows as `s³δ²` for independent column +noise, and at least as `s²δ²` when part of the noise is a floor correlated along the edge +(the supersampling floor of `ss_column_sum_close` is `1/(2n)` px, which shrinks as `1/s` in +design units). Every other term of `L` grows at most logarithmically. (2) Both designs draw +the truth; compare each with a common larger design `T₃` that contains both (for example +the free polyline): by `merge_chi2_increase` the `χ²` excess of each over `T₃` is the noise +in the removed directions, `χ²` with `k(T₃) − k(T)` degrees of freedom, so the difference of +fits is `O_p(1)`. Each free coordinate's Fisher information grows as a power `s^{2β}` (`β = +3/2` for a position read by `∝ s` independent columns), so its term `ln(W/(√(2π)σ))` grows as +`β ln s`. (3) The `det F` of two designs with the same number of coordinates scale by the +same power of `s`, so their ratio is bounded; the rest is (2). ∎ + +This is Schwarz's (1978) consistency of the evidence, read for vector graphics: the order +the chains page asks for ("fidelity is a constraint, not a currency; among those that fit, +the fewest free coordinates; among equals, the most human") is the posterior's own order in +the limit. *Not from the literature* as a statement about vectorisation. What it does not +say: at a finite resolution the terms of (2) and (3) are a few nats each and comparable with +the prior's log odds, and that is exactly where the 128 px model errors of +[`optimal.md`](optimal.md) §6 live. There the posterior decides, not the limit. The +lexicographic order remains useful as the search order (R4.3 prunes by free-coordinate +count) and as an assertion: a decision that raises `k` *and* worsens the fit is a bug. + +If the artist's design is not in the vocabulary at all (a spiral; a hand-drawn wobble), no +candidate draws the truth and (1) applies to all: the limit then picks, at each resolution, +the cheapest description whose misfit is within the noise, and it grows with the resolution, +as today's fits do. + +**The hypothesis that matters in practice is calibration at the truth, and it includes the +renderer.** The picture `S_T(θ)` must be drawn as the renderer that made the input draws it. +If the evaluator draws the artist's own design differently from the renderer by `Δ` px along +a boundary (an arc converted to Béziers another way, a different flattening of curves or +offsets of strokes), (1) applies to the artist's design itself: its misfit grows like +`s·(Δ/σ)²` per unit length, and the limit prefers descriptions that fit the renderer's +approximation with extra segments. The boundary chain measures how sharp this is: a true arc +and its four-cubic approximation differ by about fifty standard deviations at 512 px +(`chain-boundary.md` B4.3). Hence amendment A1 of the interface. + +### R0.6 Claim: the gate ratio is at most one where the design is recovered + +**Claim.** If the posterior mode recovers the artist's discrete part `T_A`, and the encoder +writes every design with the fewest gate-counted numbers among the SVG encodings of that +design (R4.6), the trace's gate count is at most the artist's. + +**Proof.** The artist's file is one encoding of `T_A`; ours is the cheapest. ∎ + +**Gap.** Where `T_A` is not identifiable at the given resolution (a 0.3 px feature at 128 +px), the mode is another design. Its free-coordinate count is no larger than that of any +equally fitting alternative (R0.5 in the large; the evidence at finite resolution), but its +gate count may exceed the artist's because the gate's count is not monotone in free +coordinates (R1.6). Closing this needs the encoder's count inside the search's tie-breaks +(R4.6), and a measurement: the per-icon gap between the posterior mode's gate count and the +artist's on icons where the artist's design is the mode. + +### R0.7 The decision + +**The objective of chain R is `L(T)` of R0.2: the negative log posterior of the discrete +design, its free coordinates integrated out by the Laplace (Wallace–Freeman) approximation, +with B4's likelihood and R3's prior.** Why this and not the alternatives: it is the +optimum for the loss the user's goal describes (R0.1); it contains today's objective as a +special case and corrects its two errors (R0.3); its decisions have computable error rates +and a bounded fidelity cost (R0.4, R2.2); and it reduces to the lexicographic rule exactly +where that rule is right (R0.5). It is still a description length, in nats, so every +existing comparison in the code (`ribbons.rs`'s decision, `mirror_fit.rs`'s choice, the +merges) keeps its form; what changes is the price of each coordinate and the presence of +the prior. + +### R0.8 Claim: within the Laplace regime, more noise never un-accepts a constraint + +Real inputs are resized and compressed ([`noise.md`](noise.md)). On damaged input the target +is still the artist's clean file. Noise should therefore make the description lean more on +the prior, never less. This claim states exactly how far that holds. + +**Setting.** `M₀ ⊂ M₁` are nested descriptions. `M₁` has `k` more free coordinates (one +dropped tie, one unsnapped number: `k = 1`). `Δ ≥ 0` is the drop in the residual sum of +squares that `M₁` buys, in px². It is a property of the geometry and is held fixed while +the noise scale `σ` varies (each window's sd is `σ·g_w`). By R0.2 the log posterior odds of +`M₀` are + +```text +B(σ) = c − Δ/(2σ²) + k·ln(a/σ), a = W/(√(2π)·g), +``` + +where `c` is the log prior odds of the constraint (R3) and `k·ln(a/σ)` is the Occam factor of +the `k` coordinates. + +**Claim.** If `B(σ₁) ≥ 0`, `σ₂ ≥ σ₁`, and at `σ₂` the coordinates still cost at least half a +nat each beyond the prior odds (`k/2 ≤ c + k·ln(a/σ₂)`), then `B(σ₂) ≥ 0`. + +**Proof.** Put `t = σ₂/σ₁ ≥ 1`. + +1. If `Δ ≥ kσ₂²`, the misfit is still significant at `σ₂`. Then + `B(σ₂) − B(σ₁) = Δ(σ₂² − σ₁²)/(2σ₁²σ₂²) − k·ln t ≥ k(t² − 1)/2 − k·ln t ≥ 0`, using + `ln t² ≤ t² − 1`. +2. If `Δ < kσ₂²`, then `B(σ₂) > c − k/2 + k·ln(a/σ₂) ≥ 0` by the regime. + +∎ Lean: `Inkvec.Design.accept_monotone` (`Design/Noise.lean`). + +The claim is about the acceptance set in `σ`, not about `B`'s slope: + +* **`B` is not monotone.** `dB/dσ = (Δ/σ² − k)/σ`, so `B` rises while the misfit is + significant and falls once it is within noise. Where it falls, the Occam factor is + shrinking. Past the regime, the `k` coordinates' posterior is as wide as their prior and + Laplace's approximation fails; the exact evidence ratio there tends to the prior odds `c`, + not to `−∞`. +* **The literal reading is false.** "The Bayes factor for `M₀` rises with `σ` when the extra + fit is within noise" does not hold. What holds is that the constraint, once accepted, stays + accepted. +* **What noise does to a true constraint.** The standardised gain `Δ/σ²` has the `χ²_k` + distribution at every `σ`, and the threshold `2k·ln(a/σ) + 2c` falls only logarithmically. + So a true tie is refused a little more often on noisier input. At `k = 1` and 7 nats, + `P(χ²₁ > 14) ≈ 2·10⁻⁴`. +* **What noise does to a slightly false constraint.** It is accepted while its violation `δ` + stays under `σ_post·√(2k·ln(a/σ) + 2c)`. That acceptance radius grows with `σ`. This is the + sense in which a noisy input snaps more. + +**Heavy tails.** JPEG block steps and ringing lobes are outliers. Under a Gaussian, a +0.05 px wobble at a block edge counts as many-σ evidence against a tie, so the likelihood +needs heavy tails. + +* **Huber with threshold `κ` keeps the claim on inliers, exactly.** On residuals within `κ` + standard units the Huber loss equals the Gaussian `u²/2` (`huber_eq_sq`). An inlier at `σ₁` + is still an inlier at every `σ₂ ≥ σ₁` (`inlier_of_le`). So whenever both fits' residuals are + inliers at `σ₁`, the proof above applies verbatim at every larger `σ`. Outliers always cost + less than under the Gaussian (`huber_le_sq`). +* **Huber keeps clean inputs unchanged.** The boundary chain's `huber_kappa(ν) = min(3, √ν)` + is 3 on a clean intake (`ν = ∞`), where every residual is an inlier, so clean traces are + untouched. `√ν` is where the Student-t influence function `(ν+1)u/(ν+u²)` peaks. +* **Student-t loses the claim.** `σ²·ρ_ν(r/σ)` with `ρ_ν(u) = ((ν+1)/2)·ln(1 + u²/ν)` increases + with `σ`, towards the Gaussian's `(ν+1)r²/(2ν)`. The fit gain is a difference of two such + terms, so it can grow with `σ`. This happens when `M₁`'s extra coordinate explains an + outlier. +* **A counterexample for the t.** Take `ν = 4`, `k = 1`, `c = 0`, `a = 20`. `M₀` leaves one + residual of 5 px; `M₁` removes it at the price of two residuals of 1 px. The t-evidence + accepts the constraint at `σ = 0.10` (`B = +5.5`) and refuses it at `σ = 0.38` + (`B = −0.5`). The Gaussian and Huber refuse it at both. +* **Huber shares the failure, but only on outliers.** For an outlier, + `d/dσ[σ²ρ_H(r/σ)] = κ(|r| − κσ) > 0`, so Huber can fail the same way. Both failures need + `M₁` to fit an outlier, and that is the case the heavy tail exists to refuse. +* **The choice.** Chain R uses Huber, with `κ` from the boundary chain's noise model. + +**Consequence: a `web` trace should need no more parameters than the clean one.** Five +steps give it, with their limits: + +1. Each constraint is decided by its own evidence. +2. On the same geometry, `accept_monotone` makes the accepted set at the clean noise level a + subset of the accepted set on `web`. +3. The free-coordinate count is `n − rank` of the accepted constraints (R1.1), so it can only + fall. +4. Blur changes the geometry itself: detail below the PSF (a corner's tip, a hairline) is + lost. The honest description drops it, which lowers the count further. Restoring what + blur removed is the prior's job: corners under a cover (milestone 1 below) and the + design grid. +5. The argument is per constraint. It does not cover a greedy or joint search, it holds only + inside the regime, and it **needs an honest `σ`**. + +The last condition is the one that fails today. The engine reads one noise level per image, +while the codec's error at an edge is twenty times the interior's ([`noise.md`](noise.md)). +So the `χ²` term on `web` is inflated about 170×, constraints are refused for the wrong +reason, and the count rises. The measured web ratios below show exactly that. + +## R1. Constraints and free coordinates + +**Problem.** *In:* B4's map and a candidate structure (element kinds, segment kinds). *Out:* +a vocabulary of design constraints; for any set of them, the number of free coordinates, +a minimal parametrisation, and which constraints are redundant or contradictory. + +**The vocabulary**, with the number of coordinates each removes (its codimension) when +independent: + +| constraint | equation | removes | +|---|---|---| +| tie | `x_i = x_j` (also `y`, radii, widths, rx) | 1 | +| axis alignment | `y_a = y_b` or `x_a = x_b` for a line | 1 | +| 45° | `x_b − x_a = ±(y_b − y_a)` | 1 | +| on the design grid | `x_i ∈ o + gℤ` | 1 continuous, replaced by a discrete label | +| incidence | point on a curve; point = point is the map's topology | 1 | +| G1 join | tangents parallel at a join | 1 | +| parallel, perpendicular | direction cross or dot product zero | 1 | +| equal radius, concentric | `r_i = r_j`; `c_i = c_j` | 1; 2 | +| mirror symmetry | points paired across an axis (axis: 2 numbers) | R1.5 | +| repetition | a copy is the original translated by `t` (2 numbers) | R1.5 | +| one stroke width | ties among widths | 1 each | +| primitive | a closed boundary is a circle, ellipse, rounded rectangle | its outline's count minus 3, 4 (5 rotated), 4 (5 rounded) | + +### R1.1 Claim: linear constraints are counted exactly, and ties by components + +**Claim.** For constraints `Ax = b` (ties, axis alignment, 45° with a known sign, mirror +pairs about a known axis, translated copies with a known offset, concentricity), the +solutions form an affine subspace of dimension `n − rank A`. For ties alone, `rank A = +n − c` where `c` is the number of connected components of the graph whose edges are the ties, +so the free coordinates are the tie classes. A grid label fixes one class to a grid value. + +**Proof.** Rank–nullity. The incidence matrix of a graph with `n` vertices and `c` +components has rank `n − c` (its null space is spanned by the components' indicator +vectors). ∎ + +Because the coefficients are 0 and ±1, the rank is computed exactly over the rationals: +no tolerance decides it. Most of what the corpus shows artists doing (R3) is in this class. + +### R1.2 Claim: nonlinear constraints are counted at the fitted point, with a certified margin + +**Claim.** (a) If the constraint map `g` has Jacobian of constant rank `r` near a solution +`x*`, the solutions near `x*` form a manifold of dimension `n − r`; a minimal +parametrisation is `n − r` of the raw coordinates, chosen by column pivoting, with the +others implicit functions of them (the *derived* coordinates). (b) Computed at the fitted +point `x̂` instead of `x*`, with `‖Dg(x̂) − Dg(x*)‖ ≤ η`, the number of singular values of +`Dg(x̂)` above `η` equals `r` whenever the smallest nonzero singular value of `Dg(x*)` +exceeds `2η`. + +**Proof.** (a) The constant rank theorem (e.g. Lee, *Introduction to Smooth Manifolds*, +Thm. 4.12); the implicit function theorem gives the derived coordinates. (b) Weyl's +inequality for singular values: `|σ_i(Dg(x̂)) − σ_i(Dg(x*))| ≤ η`. ∎ + +`η` comes from B4's precision of `x̂` times the Lipschitz constant of `Dg`. Designs are not +generic: tangent circles, concurrent lines and symmetric tangencies sit exactly where ranks +drop. **Gap:** at such a point the gap condition of (b) fails by construction; the count is +then taken at nearby regular points (the generic rank) and the point is flagged, which is +right for counting but leaves the local solution set's shape unproved. + +The derived coordinates of (a) are what the corpus calls derived points (R3.2): where two of +lucide's arcs meet, the corner is the intersection of two circles whose centres and radii +are on the grid; the artist wrote it rounded to two decimals, and only 27 % of such numbers +are on the grid. They are written, but they are not free. + +### R1.3 Claim: the joins of an open boundary are independent; a closed one loses at most three + +**Claim.** Order a boundary's segments `s₁ … s_m` and let each join constraint (G1, +incidence of the next segment's start) involve a parameter of the outgoing segment that no +earlier constraint involves (its start tangent for G1). Then the join constraints of an +open boundary have full row rank. On a closed boundary, constraints invariant under rigid +motions (angles, lengths, tangency) can lose at most `dim SE(2) = 3` ranks to the closure. + +**Proof.** Ordered by segment, the Jacobian is block lower-triangular with a nonzero entry +on each constraint's own new parameter, so it has full row rank. A closed chain imposes +that the composition of its segments' relative rigid motions is the identity, three +equations; a set of motion-invariant constraints that determines all relative motions but +one is dependent through these three at most. ∎ The bound is stated, not sharp: the +rectangle's four right angles lose one rank (total turning), not three; R1.2 computes the +actual rank on the ring's small block. + +### R1.4 Claim: redundancy and equivalence + +**Claim.** Two constraint sets define the same design near `x*` exactly when their +Jacobians have the same row space there (for linear constraints: the same affine subspace). +A constraint whose row is in the span of the accepted ones removes no coordinate (`Δk = +0`): it earns no Occam credit in R0.2 and is recorded only for the encoder (an `H` instead of +an `L` whose two `y` are already tied). + +**Proof.** For linear constraints, the solution set is determined by the row space and one +solution. For the nonlinear regular case, the local solution sets are manifolds whose +tangent spaces are the null spaces of the Jacobians (R1.2a). ∎ + +### R1.5 Claim: under a symmetry group the free coordinates are the average character + +**Claim.** Let a finite group `G` (a mirror, a half turn, a rotation of order `m`) act on the +coordinate space `V` by permuting points and applying its isometry to each. The +configurations it fixes form a subspace of dimension + +```text +dim V^G = (1/|G|) · Σ_{g ∈ G} tr ρ(g), +``` + +plus the group's own parameters (a mirror axis 2, a centre 2). For a mirror: `dim = n/2` +whatever the number of points on the axis (each pair keeps one point's two coordinates; a +point on the axis keeps one). For a half turn: `n/2 − 1` if a point sits at the centre. A +copy translated by `t` keeps only `t`. + +**Proof.** The averaging operator `P = (1/|G|) Σ_g ρ(g)` is a projection onto `V^G` (it fixes +`V^G` and `P² = P`), and the trace of a projection is its rank. For a mirror, `ρ(σ)` permutes +points and negates one coordinate of each image, so its trace is the sum over fixed points +of `tr diag(−1, 1) = 0`, and `dim V^G = (n + 0)/2`. ∎ + +Classical representation theory; its use to count an icon's free coordinates is *not from +the literature*. `mirror_fit.rs` already fits a self-mirrored boundary on its fundamental +domain, which is this count made into a parametrisation. + +### R1.6 The gate's count is not the free-coordinate count + +| element | free coordinates (start given) | gate's count | numbers typed | +|---|---|---|---| +| line | 2 | 2 | 2 | +| line, axis-aligned | 1 | 2 | 1 (`H`/`V`) | +| cubic | 6 | 6 | 6 | +| cubic, G1 at its start | 5 | 6 | 6 (4 as `S` when the handle is also mirrored) | +| circular arc | 3 (end, radius; flags discrete) | 7 | 7 | +| elliptical arc | 5 | 7 | 7 | +| subpath start | 2 | 0 | 2 | +| `` | 3 | 3 | 3 | +| `` (axis-aligned; rounded) | 4; 5 | 6 | 4–6 | +| `` (axis-aligned; rotated) | 4; 5 | 4 | 4; 7 with `rotate(a cx cy)` | +| `` of a translated copy | 2 | 6 | 2–3 | +| stroke width | 1 | 0 | 1 | + +The gate over-counts arcs, rectangles and copies and under-counts starts and widths. +Measured on the artists' files, the numbers typed are 0.90 of the gate's count for material +(its `H`, `V` and 582 `S` commands) and 1.07 for lucide (its subpath starts). So the +objective (R0) counts free coordinates, which is what "the same design" means and what the +evidence prices, and the encoder (R4.6) separately writes each design with the fewest +gate-counted numbers; R0.6 connects the two where the design is recovered. + +## R2. Which constraints hold + +**Problem.** *In:* candidate constraints from cheap detectors (near-equal values, near-axis +directions, near-tangent joins, near-mirror pairs, repeated shapes), B4's likelihood (as an +evaluator of any constrained design), R3's prior. *Out:* the accepted constraints, the +tie classes, the grid and each coordinate's grid label, and the constrained fit. + +### R2.1 Claim: the test + +**Claim.** Imposing a constraint `c` that removes `Δk` free coordinates raises the posterior +of the design exactly when + +```text +½ Δχ²_c < Σ_{removed j} ln( W_j / (√(2π)·σ_j) ) + ln( π_c / (1 − π_c) ) =: τ_c, +``` + +where `Δχ²_c` is the rise in the best fit's `χ²` when `c` is imposed (the rest unchanged), +`σ_j` the posterior standard deviations along the removed directions, `W_j` their prior +ranges and `π_c` the prior probability of `c` in its context (R3). Two discrete special cases: + +* **grid label**, coordinate at offset `z·σ` from the nearest point of a grid of pitch `g`: + `½ z² < ln( g / (√(2π)·σ) ) + ln( π_on / (1 − π_on) )`; +* **tie classes**, from the Chinese-restaurant prior with concentration `α` (R2.5): merging + two classes of sizes `m₁, m₂` is worth `ln(W/(√(2π)σ)) − ln α + ln(Γ(m₁+m₂)/(Γ(m₁)Γ(m₂))) + − ½ ln((m₁+m₂)/(m₁m₂))` against its `½Δχ²`. + +**Proof.** R0.2 applied to the two nested designs: the constrained one lacks the removed +coordinates' Occam terms and carries the constraint's prior `π_c` instead of `1 − π_c`. For a +grid label, the prior of a grid point is `π_on·g/W` per unit length against `(1 − π_on)/W` +for a free value, and the free value's Occam term is `ln(W/(√(2π)σ))`; for the tie classes, +the Gaussian integral of R2.5's cluster cost. ∎ + +### R2.2 Claim: error rates at a given resolution + +**Claim.** In the linear-Gaussian case, a true constraint's `Δχ²_c` is distributed as `χ²` +with `Δk` degrees of freedom, and a false one's as noncentral `χ²` with noncentrality `b²`, +`b` the violation in standard deviations of the removed direction. So `P(reject true) = +P(χ²_Δk > 2τ)` and `P(accept false) = P(χ²_Δk(b²) < 2τ)`: + +| τ (nats) | P(reject a true constraint) | violation accepted half the time | accepted 5 % of the time | +|---|---|---|---| +| 2 | 4.6·10⁻² | 2.0 σ | 3.6 σ | +| 4 | 4.7·10⁻³ | 2.8 σ | 4.5 σ | +| 6 | 5.3·10⁻⁴ | 3.5 σ | 5.1 σ | +| 8 | 6.3·10⁻⁵ | 4.0 σ | 5.6 σ | +| 10 | 7.7·10⁻⁶ | 4.5 σ | 6.1 σ | + +(`Δk = 1`.) For a coordinate the price alone is 6.2–9.9 nats over 128–512 px and σ = 0.1–0.01 +px, and 7–13 nats at the boundary chain's calibrated precisions; the prior odds move `τ` by +±2 nats (R3). + +**Proof.** `merge_chi2_increase`: the rise is the squared norm of the noise in the removed +directions (true constraint), plus the violation's projection (false one); Gaussian noise +makes these `χ²` and noncentral `χ²` variables. ∎ + +### R2.3 Claim: the test is consistent + +**Claim.** As the resolution grows, both error rates go to zero. + +**Proof.** `τ_c` grows as `β ln s` (R0.5), so `P(χ²_Δk > 2τ)` falls as a power of `s`. A false +constraint's violation in standard deviations grows as a power of `s` (its `σ` shrinks while +its violation in design units is fixed), faster than `√τ`, so `P(χ²_Δk(b²) < 2τ) → 0`. ∎ + +The corpus helps the test at every resolution: artists' constraints are exact or clearly +absent (R3.1), so few true violations sit near the threshold. + +### R2.4 Claim: accepting in order of evidence never produces a contradiction + +**Claim.** Test candidates in decreasing order of `τ_c − ½Δχ²_c`, each against the fit under +all constraints already accepted, and refit after each acceptance. Then (a) the accepted set +always has a solution; (b) a candidate contradicting the accepted set is rejected; (c) a +candidate implied by them is recorded but earns nothing; (d) the final `χ²` exceeds the free +fit's by the sum of the accepted rises, each below its threshold, so the design's cost `L` +never rises; (e) after a final pass that tries removing each accepted constraint, the set is +a local optimum of `L`: no single addition or removal lowers it. + +**Proof.** (a) The current constrained fit is a solution. (b) A contradiction leaves no +solution or a singular one with the observed data; the constrained `χ²` is then infinite or +the rise exceeds every threshold. (c) R1.4: `Δk = 0`. (d) The rises telescope: +`χ²_final − χ²_free = Σ Δχ²_c` and each accepted `½Δχ²_c < τ_c`. (e) By construction. ∎ + +**Gap.** Not a global optimum: choosing the best subset of constraints contains best-subset +selection, which is NP-hard (Natarajan 1995). When the removed directions are orthogonal in +the Fisher metric the rises are independent and the order does not matter; when they are +not (two ties sharing a coordinate) the tie dynamic program of R2.5 decides them jointly. + +### R2.5 Claim: ties are found exactly by a one-dimensional dynamic program + +**Setting.** Measured values `v₁ … v_n` of one kind (the `x` of every point, or every +radius), equal noise `σ`, a Chinese-restaurant prior on their partition into tie classes +(concentration `α`; Ewens 1972, Aldous 1985) with any base measure for the class values. + +**Claim.** The most probable partition together with class values has classes that are +contiguous in sorted order, so a dynamic program over the sorted values, +`best[b] = min_a best[a] + cost(a..b)`, finds it exactly in `O(n²)`, with + +```text +cost(m values, sum of squares S about their mean) = −ln α − ln Γ(m) + ln W + + ((m − 1)/2)·ln(2πσ²) + S/(2σ²) + ½ ln m. +``` + +**Proof.** The prior depends on the partition only through the class sizes. Take any +partition with class values `c₁ < c₂` and values `a < b` with `a` in the class of `c₂`, `b` +in the class of `c₁`. Swapping them keeps every size and changes the squared residual by +`(a − c₁)² + (b − c₂)² − (a − c₂)² − (b − c₁)² = −2(b − a)(c₂ − c₁) < 0`. So an optimum has no +such pair, which is contiguity. The cost is the Gaussian marginal of `m` values about a class +value uniform on `[0, W]`. ∎ + +Fisher (1958) proved contiguity for least-squares grouping with a fixed number of groups; +the extension to the Chinese-restaurant prior, where the number is chosen by the evidence, +is *not from the literature*. **Gap:** with unequal `σ_i` the exchange argument fails (it +needs the weights equal); the program then returns the best contiguous partition, an upper +bound, and the coupled correction is R2.4's. + +**Measured** (simulation on the artists' numbers, `--part ties_sim`): pairwise precision of +recovered equalities 0.98–1.00 and recall 1.00 in lucide and material at σ = 0.005 px +(0.94–1.00 and 0.99–1.00 at σ = 0.02–0.1 px), 128 and 512 px; over all families 0.83 and +0.99 at 128 px, 0.95 and 1.00 at 512 px. Where precision is lower (the emoji families at +128 px and at the larger σ, down to 0.25), the merged values are closer than about `2σ`: +the pixels cannot tell them apart, and merging them costs no fidelity (the positional error +does not rise, as R0.4 predicts for violations under a standard deviation). + +### R2.6 Claim: the grid is inferred from tie classes, not from coordinates + +**Claim.** In the hierarchical model (values → tie classes under the Chinese-restaurant +prior → class values drawn from a base measure that mixes a grid with a continuous +background), the grid's likelihood is a product over *classes*, each with noise +`σ/√m`, not over coordinates. + +**Proof.** A class's value is one draw from the base measure; its `m` members are +conditionally independent given it. ∎ Counting coordinates instead treats a value repeated +twenty times as twenty independent agreements with the grid. Measured over the eight +conditions of Table R2.8 (two resolutions, four noise levels): in the families without a +grid, the share of icons where a grid is found falls from 49–74 % to 31–65 % (simple-icons) +and from 32–75 % to 11–63 % (noto); wrong snaps fall to 23–77 % of their per-coordinate +rate over all families (to 5–40 % in noto). + +### R2.7 Claim: harmonics resolve themselves + +**Claim.** If all class values lie on a grid of pitch `g`, the posterior prefers `g` to `g/2` +by `n_on·ln 2` nats minus the prior difference (`n_on` the number of on-grid classes), and +prefers `g` to `2g` unless half of the classes happen to lie on `2g`. + +**Proof.** A class's likelihood ratio against the background is `π·g·φ(z) + (1 − π)`; halving +the pitch leaves `φ` unchanged for on-grid classes and halves the factor `g`. ∎ The grid that +explains the numbers with the coarsest pitch wins: a 24-unit icon is read on its unit or half +unit, not on a 1/8. + +### R2.8 Empirical Bayes without double counting, and the measurements + +**Claim.** Each coordinate's grid label, decided with the grid posterior computed from the +*other* classes (leave one out), is the exact Bayesian conditional; the plug-in decision +(grid estimated from all classes) differs from it only when the grid's posterior margin is +smaller than the largest single class's log likelihood ratio. + +**Proof.** The grid posterior is a product over classes; removing one class divides by its +factor, at most `ln(g/(√(2π)σ/√m)) + |ln π|` nats; if the margin between the best grid +hypothesis and the next exceeds that, the same hypothesis wins without the class. ∎ + +**Simulation.** `bench/theory/design_prior.py --part grid_sim` and `--part ties_sim`. The +artist's positions (every on-curve point and primitive centre or side, 1,408 files) at +128 and 512 px, Gaussian noise of σ px per position standing in for B4's precision (0.005 px +is the boundary chain's calibrated regime under 8×8 supersampling, `chain-boundary.md` B4.3; +0.05 px is `DEFAULT_SIGMA_MODEL`), hypotheses of pitch `s/V·2^{−k}` for 11 viewBox sizes `V` +and `k = 0…3`, prior halving per subdivision and ½ on "no grid". "Exact" counts positions +returned equal to the artist's number; "wrong" counts positions snapped to another value. + +| family | px | σ px | exact (per coordinate, one weight) | wrong | exact (hierarchical) | wrong | error after / before (hier.) | +|---|---|---|---|---|---|---|---| +| lucide | 128 | 0.005 | 0.727 | 0.006 | 0.728 | 0.003 | 0.232 | +| lucide | 512 | 0.005 | 0.728 | 0.001 | 0.729 | 0.000 | 0.227 | +| lucide | 128 | 0.05 | 0.716 | 0.045 | 0.719 | 0.036 | 0.235 | +| material | 128 | 0.005 | 0.732 | 0.000 | 0.739 | 0.000 | 0.220 | +| material | 512 | 0.005 | 0.744 | 0.000 | 0.752 | 0.000 | 0.221 | +| material | 128 | 0.05 | 0.722 | 0.020 | 0.722 | 0.025 | 0.273 | +| twemoji | 128 | 0.005 | 0.251 | 0.022 | 0.253 | 0.021 | 0.611 | +| noto-emoji | 128 | 0.005 | 0.057 | 0.004 | 0.052 | 0.002 | 0.921 | +| simple-icons | 128 | 0.005 | 0.048 | 0.020 | 0.043 | 0.014 | 0.834 | +| all | 128 | 0.005 | 0.164 | 0.010 | 0.162 | 0.008 | 0.584 | +| all | 512 | 0.005 | 0.178 | 0.004 | 0.179 | 0.003 | 0.567 | +| all | 128 | 0.05 | 0.132 | 0.030 | 0.127 | 0.016 | 0.639 | +| all | 512 | 0.05 | 0.156 | 0.017 | 0.153 | 0.011 | 0.600 | + +The share of lucide's and material's on-curve numbers on a dyadic grid (unit to quarter +unit) is 73–74 %, so the hierarchical model returns essentially every on-grid number +exactly, and cuts the mean positional error to between a fifth and a quarter. The wrong +snaps that remain are values within about `3σ` of a grid point that are not on it, at +the rate R2.2 predicts, falling with resolution and with σ: at σ = 0.005 px they are lucide's +derived points at 128 px (0.3 %) and, in twemoji and simple-icons, three- and four-decimal +numbers a thousandth of a unit from an integer, which 128 px cannot separate from it (0.01 +px) and 512 px mostly can. Moving such a number by under `3σ` costs nothing visible (R0.4). +The model knows only each point's role (construction or derived; R3.2); a representation +that writes a derived point as the intersection of its snapped construction (R1.2a) would +not snap it at all, which is the next refinement. + +### R2.9 Corners, junctions and continuations are constraints + +**Claim.** A corner is the absence of a G1 constraint at a join: the smooth join is the +nested model with one coordinate fewer (the outgoing tangent). A T-junction, where one face's +boundary runs straight through and another's ends against it, is a G1 (collinearity) +constraint between the through-face's two edges at the vertex. Both are decided by R2.1 +against B4's run terms and the vertex's window term. + +**Proof.** R1's vocabulary and R2.1; the window term is the likelihood of the local +configuration with or without the constraint. ∎ This is the boundary chain's shortening +proposal S1, accepted in the interface section: the decisions move to R; B3 supplies the +vertex's per-pixel terms. `occlusion.rs` already reads paint order from this collinearity; +here it becomes one more tested constraint, with an error rate. + +## R3. The human prior, small + +**Problem.** *In:* the artists' own files (`bench/data/corpus_svg`, the gate families, +1,408 files). *Out:* the prior odds of each constraint in each context, and the +document-level variables that change them, as a model of a few hundred numbers. + +**The model.** + +1. **Structure.** `P(element kind | closed shape class, style)`, `P(written segment kind | + geometric kind, style)`, `P(smooth | join kinds, style)`, `P(axis-aligned, 45° | line, + style)`, `P(stroke | style)`, `P(partly covered | style)`: Dirichlet-smoothed counts + (the Krichevsky–Trofimov estimator, add ½). +2. **Coordinates.** Per axis and per kind of number (positions, radii, widths), a + Chinese-restaurant process of concentration `α_style`, whose base measure mixes the + document's grid (weight `π_role,style`) with a continuous background, the weight + conditioned on the point's **role**: construction (line–line corner, open end, primitive + centre or side) or derived (a corner where a curve meets, a tangent point). +3. **Document variables.** The grid (a pitch from the raster size and a short list of + viewBox sizes and subdivisions), the style (a mixture over the corpus families), the + stroke width (a tie class of its own). + +About forty numbers per style, six styles, and the grid hypotheses' prior: a few hundred. + +### R3.1 The numbers + +Measured by `bench/theory/design_prior.py` on every file of the gate families (the 246-icon +screen set gives the same picture: axis-aligned lines 0.50, smooth curve joins 0.69, +repeated radii 0.58). + +**Lines and joins.** + +| family | gate count / icon | lines axis-aligned (exact) | within 0.5° of an axis, not exact | 45° | axis lines written `H`/`V` | curve joins smooth (< 2°) | turning 5–30° | corners > 30° | line–line joins collinear | +|---|---|---|---|---|---|---|---|---|---| +| lucide | 41.7 | 0.668 | 0.000 | 0.163 | 0.94 | 0.904 | 0.010 | 0.073 | 0.000 | +| material-icons | 96.5 | 0.723 | 0.005 | 0.123 | 0.98 | 0.771 | 0.006 | 0.207 | 0.006 | +| simple-icons | 253.2 | 0.463 | 0.020 | 0.018 | 0.92 | 0.713 | 0.046 | 0.167 | 0.023 | +| openmoji | 372.5 | 0.332 | 0.025 | 0.032 | 0.72 | 0.621 | 0.097 | 0.199 | 0.050 | +| twemoji | 451.4 | 0.564 | 0.008 | 0.030 | 0.95 | 0.758 | 0.026 | 0.197 | 0.014 | +| noto-emoji | 1137.0 | 0.279 | 0.039 | 0.009 | 0.88 | 0.655 | 0.094 | 0.167 | 0.100 | +| all | 444.9 | 0.452 | 0.021 | 0.040 | 0.92 | 0.687 | 0.071 | 0.177 | 0.045 | + +Constraints are exact or clearly absent: the near-miss columns are small, and the turning +at curve joins is bimodal (smooth or a real corner, with 7 % between). Where artists' +numbers violate a constraint slightly, it is rounding: lucide writes its arc endpoints to two +decimals, so 44 % of its arc–line joins turn by a small nonzero angle (under 2°) and 52 % are +exactly tangent; they were drawn tangent and written rounded. The written file is what was +rendered, so whether the test imposes the tangency depends on the resolution: a turn of a +tenth of a degree is within the noise of a short arm at 128 px and not of a long one at 512 +px (`chain-boundary.md` B4.3: 0.076° for a 10 px line under 8×8 supersampling), where the +trace keeps the artist's small kink, as the pixels show it. Noto's 10 % of line–line +vertices turning under 0.5° are, nearly all, points an export left on a straight run: a +place where the trace can be smaller than the artist's file. + +**Segment kinds.** + +| family | line | quadratic | cubic | arc | cubics that are circular arcs | circular geometry written as `A` | arcs ≤ 120° | +|---|---|---|---|---|---|---|---| +| lucide | 0.562 | 0.001 | 0.045 | 0.392 | 0.147 | 0.98 | 0.82 | +| material-icons | 0.670 | 0.000 | 0.302 | 0.028 | 0.826 | 0.10 | 0.85 | +| simple-icons | 0.329 | 0.015 | 0.469 | 0.188 | 0.241 | 0.62 | 0.95 | +| openmoji | 0.314 | 0.001 | 0.605 | 0.080 | 0.382 | 0.26 | 0.92 | +| twemoji | 0.256 | 0.000 | 0.717 | 0.027 | 0.294 | 0.12 | 0.80 | +| noto-emoji | 0.176 | 0.000 | 0.824 | 0.000 | 0.201 | 0.00 | – | + +Whether a circular arc is written `A` or as a cubic is a matter of style, not geometry: 98 % +`A` in lucide, 10 % in material, none in noto. The pixels cannot tell an arc from its cubic +approximation (a quarter circle's cubic is off by 0.03 % of the radius), so this choice is +the prior's alone, and the style variable must carry it. 11–20 % of arcs exceed the fitter's +120° cap. + +### R3.2 The grid governs construction points; derived points are not free + +Share of numbers on the half-unit grid, by the role of the point: + +| family | line–line corner | open end | primitive | corner where a curve meets | tangent point | icons with a grid (80 % of construction numbers) | +|---|---|---|---|---|---|---| +| lucide | 0.955 | 0.830 | 1.000 | 0.269 | 0.628 | 0.72 | +| material-icons | 0.797 | 0.715 | 0.816 | 0.289 | 0.768 | 0.57 | +| twemoji | 0.503 | 0.108 | 0.738 | 0.160 | 0.252 | 0.32 | +| openmoji | 0.211 | 0.165 | 0.378 | 0.107 | 0.140 | 0.10 | +| simple-icons | 0.083 | 0.155 | – | 0.015 | 0.042 | 0.01 | +| noto-emoji | 0.072 | 0.135 | 0.078 | 0.096 | 0.066 | 0.01 | + +The finding the prior is built on: in the grid families, the grid is where the artist chose +a point; where two curves meet, the point is computed (lucide's badge: eight arcs of radius +4 meeting at `(8.63, 3.85)`), and is written rounded. A prior that conditions on the role +snaps the first and leaves the second to its construction (R1.2a). Twemoji draws its circles +on the half-unit grid (74 %) and little else; noto and simple-icons have no grid (two-decimal +and four-decimal numbers throughout). + +### R3.3 Ties, radii, widths, and what the prior is worth + +| family | x values reused | y values reused | CRP α (x, y) | radii equal to another in the icon | stroke widths per stroked icon | nats per position under the prior (flat: 8.54) | +|---|---|---|---|---|---|---| +| lucide | 0.345 | 0.396 | 11.7, 9.0 | 0.814 | 1.00 | 5.29 | +| material-icons | 0.483 | 0.505 | 13.4, 12.0 | 0.401 | – | 5.30 | +| simple-icons | 0.171 | 0.209 | 208, 156 | 0.490 | – | 8.07 | +| openmoji | 0.307 | 0.399 | 108, 67 | 0.385 | 1.23 | 7.38 | +| twemoji | 0.246 | 0.347 | 178, 100 | 0.680 | – | 7.59 | +| noto-emoji | 0.230 | 0.335 | 661, 314 | 0.727 | 1.50 | 8.05 | + +The last column is the mean code length of the artists' own positions under the +hierarchical prior (reuse at the Chinese-restaurant odds; else, in an icon with a grid, the +grid at the family's on-grid weight; else the flat price inkvec charges at 512 px, +`ln(512/0.1)`; one weight per family here, the role-conditioned weights of R3.2 would lower +it further): the prior saves about 3.2 nats per position (38 %) in the grid families and +0.5–1.2 nats elsewhere. In +gate-count terms that is a third of a parameter per position, which is how much more +willing the fit should be to keep a point where the artist's style puts one. + +### R3.4 Layers, symmetry, repetition (geometry of the artists' files) + +| family | elements partly covered by another paint | artist's parameters in them | elements wholly hidden | elements self-symmetric | in a mirror pair | repeating another (translation) | icons mirror-symmetric (render) | +|---|---|---|---|---|---|---|---| +| lucide | 0.000 | 0.000 | 0.000 | 0.680 | 0.029 | 0.144 | 0.42 | +| material-icons | 0.000 | 0.000 | 0.000 | 0.458 | 0.000 | 0.021 | 0.38 | +| simple-icons | 0.000 | 0.000 | 0.000 | 0.166 | 0.000 | 0.000 | 0.13 | +| openmoji | 0.367 | 0.444 | 0.025 | 0.417 | 0.043 | 0.137 | 0.08 | +| twemoji | 0.563 | 0.473 | 0.005 | 0.483 | 0.035 | 0.099 | 0.20 | +| noto-emoji | 0.471 | 0.467 | 0.050 | 0.277 | 0.062 | 0.150 | 0.05 | + +Openmoji's fills sit under its line art: the median partly covered fill has 96 % of its +visible boundary borrowed from the strokes painted over it, so the fill's own outline is not +observable at all and only the prior can choose it (R4.2). Writing each repeated element as a +`` would save 2.4 % of the artist's gate count at the gate's price of 6 per use: the +value of repetition is in fidelity and editing (exact copies), not in the count. + +### R3.5 Claims about the estimate + +**R3.5a (estimation error).** The unit of independence is the icon, not the coordinate: +the numbers of one icon share its grid and its style. A frequency estimated from `N` icons +per style, across `C` contexts, is within `ε = √(ln(2C/δ)/(2N))` of its expectation for +every context with probability `1 − δ` (Hoeffding 1963 with a union bound). With `N ≈ 150` +to 310 icons per family and `C ≈ 50`, `ε ≈ 0.10–0.13` at `δ = 0.05`: about ±0.5 nats of log +odds for frequencies between 0.2 and 0.8. **Proof:** Hoeffding's inequality for the icon +means, union bound. ∎ This is the worst case; the per-context counts (hundreds to tens of +thousands of instances) make the typical error far smaller, but the bound is the one the +dependence within icons allows. + +**R3.5b (decisions are robust to the prior's error).** An error of `ε` nats in a log prior +odds changes a decision of R2.1 only when `½Δχ²_c` lies within `ε` of `τ_c`. For a true +constraint that probability is `P(χ²_Δk ∈ [2τ − 2ε, 2τ])`, under 10⁻³ for `τ ≥ 6`, `ε ≤ 1`, +`Δk = 1`. **Proof:** the decision is a threshold on `½Δχ²_c`; the density of `χ²₁` above 10 is +under 10⁻³. ∎ So at 512 px the prior's precision hardly matters for true constraints; it +matters for the near-threshold false ones, and at 128 px, where `τ` is smaller and the +violations closer. + +**R3.5c (calibration).** If the likelihood is calibrated and the prior is the corpus +frequency, the posterior probability that a number is on the grid, averaged over the corpus, +equals the corpus frequency (the law of total probability), and the decision's frequency +differs from it by at most the misclassification rate. **Proof:** `E[P(on | data)] = +P(on)`. ∎ Measured in the simulation of R2.8 at σ = 0.005 px: 72.8–75.2 % of lucide's and +material's positions returned exactly against 73–74 % of their on-curve numbers on a dyadic +grid in the files, wrong snaps 0–0.3 %. This is the check the chains page asks for ("the +decision rule reproduces the corpus's constraint frequencies on clean inputs"); on traced +output it becomes the gate's design-statistics axis (R4.8). + +**R3.5d (style).** The style is a document variable with a posterior from document-level +evidence (stroked or filled, a grid or none, layered or not, the arc–line ratio), and the +style-dependent probabilities are its posterior mixture. **Gap:** the accuracy of style +inference from pixels is not measured yet; the families are separable on these features in +the artists' files (lucide is 100 % stroked with one width and a grid; material is filled +with a grid; the emoji families are layered without one), but that is the easy direction. + +## R4. Structure and encoding + +**Problem.** *In:* B4's map and R2's constrained designs per face and boundary. *Out:* the +SVG: which faces are strokes, which shapes continue under which, which are primitives, +which repeat, and the text that writes them with the fewest numbers. + +### R4.1 Claim: given a paint order, layers decompose exactly + +**Setting.** The planar map's faces have pairwise disjoint visible regions `V₁ … V_m` (the +background's region `V₀` is painted by nothing). Elements `E₁ … E_m` (sets of the plane, one +per face, in that face's paint) are painted in the order `1 … m`, bottom to top. The region +where element `i` shows is `E_i \ ⋃_{j>i} E_j`. + +**Claim.** Every element shows exactly its face's visible region, and nothing covers the +background, if and only if for every `i` + +```text +V_i ⊆ E_i ⊆ V_i ∪ U_i, U_i = ⋃_{j>i} V_j. +``` + +The conditions involve the data `V` only, so given the order the choice of each `E_i` is +independent of every other. + +**Proof.** (⇐) By induction downward from the top, show that element `i` shows `V_i` and +that `⋃_{j≥i} E_j = V_i ∪ U_i`. For `i = m`, `U_m = ∅` so `E_m = V_m`. Assume +`⋃_{j>i} E_j = U_i`. Element `i` shows `E_i \ U_i`; from `E_i ⊆ V_i ∪ U_i` this lies in `V_i`, +and from `V_i ⊆ E_i` with `V_i ∩ U_i = ∅` it contains `V_i`. And `E_i ∪ U_i = V_i ∪ U_i`. Nothing +reaches `V₀`, which is disjoint from every `V_i ∪ U_i`. (⇒) If element `i` shows `V_i` for all +`i`, the same induction gives `⋃_{j>i} E_j = U_i`, and `E_i = (E_i \ U_i) ∪ (E_i ∩ U_i) ⊆ V_i ∪ +U_i` while `V_i = E_i \ U_i ⊆ E_i`. ∎ + +*Not from the literature* in this form (the painter's algorithm's set algebra is +elementary; its use as an exact decomposition of layered vectorisation is new as far as we +know). `docs/DESIGN.md` §2.4 rules out amodal *inpainting* as a correctness hazard because +it invents content; this claim is why completion is not that: every completion in the +interval paints exactly the same visible regions, so no visible pixel of the picture +changes and nothing is invented that can be seen. + +**R4.1b (completion removes the compositing seam).** Anti-aliased "over" compositing of +`E_i` and then `E_j` (`j` above) in a pixel `p` with area coverages `a_i, a_j` gives +`a_j c_j + (1 − a_j)(a_i c_i + (1 − a_i) c_bg)`. With `E_i = V_i` exactly, along an edge +between faces `i` and `j` with no background in the pixel, `a_i = 1 − a_j`, and the +background shows with weight `a_j(1 − a_j)`: the hairline seam `seams.rs` describes. With +`E_i` completed under `E_j` across the pixel, `a_i = 1`, and the result is the exact +`a_j c_j + (1 − a_j) c_i`. Where the pixel also holds background area `b` (a three-ink +junction), the remaining error is `a_j·b·(c_i − c_bg)`. **Proof:** substitute. ∎ So the +underlap of `seams.rs` (the lower face reaching a fraction of a pixel under the upper one, +which costs 1.8 % of the parameters over the screen set, [`optimal.md`](optimal.md) §4) is +the one-pixel special case of a completion, and a completion chosen by the prior removes +the seam while lowering the count. + +### R4.2 Claim: inside its interval, a face's shape is the prior's choice alone + +**Claim.** Given the order, the likelihood of the picture is the same for every `E_i` in +`[V_i, V_i ∪ U_i]` (up to the junction-pixel term of R4.1b), so the most probable `E_i` is the +most probable shape under the prior among those in the interval: the simplest shape that +contains the visible part and stays within what is painted over it. Every shape in the +interval has the *owned* boundary of `V_i` (the part of `∂V_i` not in the closure of `U_i`) +in its own boundary, so the cost of describing the owned boundary is a lower bound on the +cost of any completion. + +**Proof.** The first part is R4.1 and R0.2 with a constant likelihood. For the bound: near a +point of `∂V_i` outside the closure of `U_i`, every `E` in the interval coincides with `V_i` +(it contains `V_i` and adds only points of `U_i`), so the point is on `∂E`. ∎ + +**Candidates**, each checked for containment in the interval: primitives fitted to the owned +boundary (rectangle, circle, ellipse, rounded rectangle); the owned pieces continued +through `U_i` (lines extended to their intersection, arcs along their circle, a G1 cubic +bridge where neither, the continuation that Kellman & Shipley's (1991) relatability +describes); and the visible outline itself, which is always in the interval (today's +output). **Gap:** optimality over all shapes is not claimed, only over the candidates. + +The flag `openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F`: with the white triangles and the +black border above the blue, the blue face's interval contains the artist's rectangle (`x 5, +y 17, 62 × 38`), a `` of gate count 6, in place of the blue's visible outline; the +artist's whole file counts 20, today's trace 54. + +### R4.3 Claim: the paint order is the only coupling, and is searched with a bound + +**Claim.** The total cost is `Σ_i c_i(A_i)`, where `A_i` is the set of faces painted above +`i` that a completion of `i` can reach (in practice its neighbours: a shape continued from +`V_i` enters `U_i` through the faces it borders); it is to be minimised over the acyclic +orientations of the face adjacency graph. `Σ_i min_A c_i(A)` is +a lower bound for any orientation; branch and bound over the orientation of adjacent pairs, +started from the order the T-junctions read (R2.9, `occlusion.rs`), finds the optimum. + +**Proof.** R4.1 for the decomposition; the bound because each term is minimised separately. +∎ **Gap:** no polynomial algorithm is claimed (with general costs the problem contains a +linear-ordering problem); the search is exact for the small components of icons (tens of +faces, mostly in small connected groups) and is cut to a beam otherwise, with the bound +reporting how far from optimal the beam may be. + +### R4.4 Strokes, gradients and primitives are R0 decisions + +Stroke or fill (`ribbons.rs`), gradient or flat (on B1's statistics: the flat ink is the +nested model with the field's coefficients removed), primitive or path (`primitives.rs`, +`choice.rs`): each compares two designs of one face by `L` of R0.2, with the prior of the +style (100 % of lucide's icons are stroked with one width; 97 % of openmoji's have strokes; +none of material's). Nothing beyond R0 is claimed; the gain is that each decision now has +the evidence's precision term and the prior. + +### R4.5 Repetition and symmetry + +**Claim.** An exact repetition (a translated copy) or symmetry (a mirror, a half turn) is a +constraint of R1.5, decided by R2.1 like any other, and imposed whatever the encoding; it +is written as a `` of one element only when that lowers the gate's count: a copy whose +own count exceeds 6, a self-symmetric element whose half costs more than its mirror's +`` saves. **Proof:** R1.5 and the counting rules. ∎ Repetition and symmetry change +fidelity (an exact copy averages the noise of every instance, R0.4) and the geometric match +more than the count (2.4 % of the artist's count, R3.4); the search for them is the +equality-saturation search of Szalinski (Nandi et al. 2020) over translations, mirrors and +rotations. + +### R4.6 Claim: the encoder writes each design with the fewest gate-counted numbers + +**Claim.** For every element kind of the vocabulary, the encoding with the fewest +gate-counted numbers among SVG's encodings of exactly that geometry is: + +| design element | write | gate's count | the alternative | +|---|---|---|---| +| line | a path segment (`H`/`V` when axis-aligned) | 2 | ``: 4 | +| axis-aligned rectangle | ``; among siblings of its paint, a subpath of their compound path | 6 | path: 6 (a tie, broken toward fewer elements) | +| rounded rectangle | `` | 6 | path: 36 | +| circle | `` | 3 | two arcs: 14 | +| axis-aligned ellipse | `` | 4 | two arcs: 14 | +| circular arc | `A` or a cubic, by the style prior | 7 or 6 | – | +| smooth cubic with a mirrored handle | `S` | 6 | `C`: 6 | +| translated copy of an element costing more than 6 | `` | 6 | the copy | +| several subpaths of one paint | one compound path | their sum | separate paths: the same sum | + +**Proof.** By enumeration of the encodings against the counting rules of `svgmodel.py`. ∎ The +table is finite and decidable, so it is the first thing proved by computation in Lean +(Phase 2, `Encoding.lean`). +Two encoding choices are not about the count: `H`, `V` and `S` change no gate count but write +fewer numbers (artists write 92 % of their axis-aligned lines as `H`/`V`), and the +document's coordinates are written in the inferred **design unit** (the viewBox of the +grid hypothesis that won in R2.6), so on-grid numbers are the artist's own small integers +and halves. A derived or free coordinate is written to the decimals its precision warrants: +the step `q` whose rounding error `q/√12` stays under half the coordinate's `σ`. + +### R4.7 Claim: one picture, one file + +**Claim.** With the posterior's ties broken by a fixed order (prior, then gate count, then a +lexicographic order of the written numbers), the output is a function of the picture: two +traces of the same pixels write the same file. **Proof:** determinism of every step. ∎ This +is the "normal form" of [`optimal.md`](optimal.md) §5. + +### R4.8 What the gate should see + +Beyond the parameter ratio, dE00 and the geometric match `geom` (mean edge displacement by +symmetric-difference area, `bench/inkvec_bench/geomatch.py`), with corner precision and +recall and segment-type agreement: the design statistics of R3 on the trace against the +artist's files, family by family (axis-aligned share, smooth-join share, on-grid share by +role, tie share, layering share). By R3.5c, a calibrated chain R reproduces them; a gap +names the link that is off. + +## Interface proposal + +The boundary chain's interface proposal ([`chain-boundary.md`](chain-boundary.md), +"Interface proposal") answers what this chain needs: what R asked for (per graph-like run, +the column or row sums with their variances; per vertex, raw unmixed pixels with the exact +forward model) is the special case of its **window identity** (B2.1: summed over any set of +whole pixels, a face's unmixed weights are its exact area there), which scores *any* +description, layered or not, by areas. So chain R adopts B's `Evidence` (map, ink +candidates, runs of window observations, vertices, thin strips, noise) and its +`BoundaryLikelihood` trait (`chi2_run`, `residuals_run` with the Jacobian, `run_moments`, +`chi2_local`, `chi2`, `density`, `floor`, every call returning `(χ², M)` calibrated so that +`E χ² = M` at the truth) as the interface, with the amendments below. + +Two of B's results change this chain's numbers. Calibrated window variances put positions +at 0.0004–0.04 px (B4.3), well inside the 0.02–0.1 px this page's simulations first assumed; +at σ = 0.005 px the grid and the ties are recovered almost without error in the grid +families (Table R2.8). And the likelihood is sharp enough to separate a true arc from its +four-cubic approximation by about fifty standard deviations at 512 px, which makes the +forward model's agreement with the renderer a precondition of everything in R0 (amendment +A1). + +### Amendments chain R needs + +* **A1. Render as the corpus's renderer does, and calibrate at the artist's own file.** R0.5's + limit and R2.2's error rates hold only if the truth's `χ²` has its nominal distribution. + With variances this small, any difference between the evaluator's drawing of a candidate + and resvg's (its arc-to-Bézier conversion, its curve flattening, its stroker's offset + curves, 8× supersampling with a box filter as `bench/build_corpus_v2.py` renders) is a + misfit growing with resolution that R would pay for with extra segments. So: the + evaluator draws arcs, circles, ellipses and strokes by the renderer's own approximations; + and the calibration check is run on the artist's SVG itself, scored against the + `Evidence` of its own render (`χ²/M` near 1 per family and tier), not only on the + starting map's smooth runs. +* **A2. Pieces and descriptions.** `Piece` gains the elliptical arc (radii, rotation) and + `Description` gains strokes (centreline pieces, width, cap, join, drawn as the renderer + strokes them) and layers (elements in paint order, composited per layer as the renderer + composites; B3.2's open question). A fast path through the visible partition is exact + except at the pixels R4.1b names, so R uses it in the search and the per-layer + compositing to score a finished candidate. +* **A3. The floor as its own term, with its correlation.** The near-axis supersampling bias + (up to `1/(2n)` px) is shared by every window of one edge and differs between edges. R + adds it to the variance of every *absolute* position test (a grid label, a tie between + two edges) and leaves it out of tests *along* one edge (an angle, a G1 join): folded into + per-window variances it would be averaged down as if independent, and an exact grid + number on an axis-aligned edge would be rejected at `z ≈ 9`. So: the floor's per-edge + value and the rule "the same edge: fully correlated; different edges: independent". +* **A4. Junction reports.** Per junction node, the cyclic order of its arms and the pairs of + arms that may continue one another (collinear or G1 within a few standard deviations), + with their statistics: the input of R2.9 (continuation) and of R4.3 (paint order from + T-junctions). +* **A5. Topological alternatives.** Where B's topology is uncertain beyond what strips cover + (one junction or two corners close together; a vertex to merge or split), a small set of + local alternatives, each with its observations, so that R chooses with the prior. +* **A6. Nothing else about precision.** R computes the Fisher information of its own + parametrisation from `residuals_run`'s Jacobians (or `density`), and with it each free + coordinate's price `ln(W/(√(2π)σ))` (R0.2) and every Wald statistic. B need not return + `log det F` in a parametrisation of its own. + +### Answers to the boundary chain's questions + +1. **Window residuals.** Yes. R's dynamic program scores a segment by the window residuals + of `chi2_run` (prefix moments from `run_moments` where the family is linear as a graph + over the window axis, the closed-form integrals otherwise). Kinds the evaluator must + integrate exactly, as the renderer draws them: line, quadratic, cubic, circular and + elliptical arc; primitives (circle, ellipse, rectangle, rounded rectangle) through those + pieces; stroke bands (A2). +2. **Additivity.** Breakpoints at window borders followed by a continuous polish are + acceptable, with one rule: a candidate segment over windows `a..b` is charged only the + windows wholly its own, and a guard window at each end goes to the vertex term, scored in + the polish. The program's cost is then a lower bound on the polished cost, so its pruning + stays valid, and no window is ever charged to the wrong arm. Straddling windows do not + need to enter the program. +3. **The price of a parameter.** The refined description length of R0.2: `½χ²` plus, per + free coordinate, `ln(W/(√(2π)σ))` from `F`, plus the prior's `−ln P(T)`. Not the fidelity + constraint with a prior: R0.5 proves the constraint form is the high-resolution limit of + this objective, so it is kept as the search order and as an adequacy check (when no + candidate of the vocabulary reaches `χ² ≤ M − p + z√(2(M − p))`, the design is outside the + vocabulary or A1 is violated, and either should be reported, not fitted away). R computes + `log det F` itself (A6). With B's variances each free coordinate costs about 7–13 nats, + so `λ = ln(extent/precision)` is retired, not re-tuned. +4. **Tests.** Wald for screening and ordering every candidate constraint (cheap, no refit), + with the covariance updated after each acceptance (`F⁻¹ − F⁻¹Gᵀ(GF⁻¹Gᵀ)⁻¹GF⁻¹`), which + reproduces the refit's sequential increments for linear models (R2.4); a refit for the + final accepted set and for nonlinear constraints. Constraints spanning several edges' + windows: ties of positions, radii and widths (R2.5); the grid (R2.6); parallel and + perpendicular; concentricity and equal radii across elements; mirror pairs and + repetition across faces (R1.5); continuation through a junction (two edges at one + vertex). Since edges couple only through vertex and strip terms (B4.1), the Wald + statistic of a cross-edge constraint needs only the per-edge covariance blocks. +5. **Corners.** Yes: R owns corner, fillet and smooth-join decisions (S1). R tests G1 at every + breakpoint its program chooses, with the arms' fitted tangents, which detect a turn of a + few tenths of a degree (B4.3's angle precision) where the fourth-difference proposal + detects 1.6° (8-bit) or 14° (8×8). So proposals do not decide corners; they decide where + the band keeps per-pixel terms. By the window identity a missed proposal costs + information (the window sums two arms, B2.2), not correctness; a false one costs a little + time. Target recall at least 0.99 down to the detection limit, false proposals up to one + per ten windows. Starting tangents: the one-sided tangents on each side of each + proposal, with their variances. Fillets use B's boundary-of-parameter-space null + (`½χ²₀ + ½χ²₁`, threshold 5.41 at 1 %) for R2.2's error rates. +6. **Strokes and hidden geometry.** Accept a stroke directly (A2). For a hidden stroke, the + flat-bottomed likelihood itself, not only its interval: R's prior is multiplied by it, + and its soft edges matter at the noise level. For occluded parts nothing is needed: by + R4.1 the likelihood is exactly constant over a face's interval, except at the junction + pixels R4.1b names, which per-layer compositing scores (A2). +7. **Inks.** Yes: gradient or flat, and which gradient, is R's (S3), as nested models (flat + inside linear, flat inside radial) priced by R0 with the style's prior (noto draws + gradients in 165 of its 311 files; lucide, material and simple-icons never). +8. **Layers.** R hands the evaluator the layered description (elements in paint order) and + asks it to composite per layer; the visible partition is R's fast path (A2). +9. **The floor.** Separate, with its correlation (A3). +10. **Primitives.** Draw each exactly as the gate's renderer does (A1). The design's + geometric kind (a circle, a circular arc) and its written kind (``, `A`, cubics) + are separate parts of `T`: the evaluator scores each written kind as rendered, the + likelihood separates them only where the renderer's approximations differ (large radii at + 512 px), and elsewhere the style prior chooses (R3.1: circular geometry is written as `A` + 98 % of the time in lucide, 10 % in material, never in noto). So yes, offer "circle" in + every encoding the corpus uses. + +### The boundary chain's shortening proposals + +* **S1 (corners and junctions are R2's): accepted,** amended as in answer 5: R places a + vertex by fitting its arms jointly with the vertex terms, and the proposals' job is the + band's partition, not the decision. +* **S2 (continuation and tangency at junctions are R's constraints): accepted,** with A4: + continuation also orders the paint (R4.3), so the junction report must carry the + candidate continuations. +* **S3 (gradient or flat is R's): accepted.** +* **S4 (stroke or two edges, and a sub-pixel stroke's ink, are R's): accepted.** The ink of a + hidden stroke is fixed only up to width × contrast (B1.5); R's prior chooses it (one stroke + width per icon in lucide, 1.2–1.5 in openmoji and noto, R3.3). +* **S5 (points stop being the interface): accepted, with an order of work.** The point solve, + `K_KINK`, `K_ANCHOR`, `DEFAULT_SIGMA_MODEL` and the curvature inflation go once the + program scores windows and R1 guarantees that no segment has more parameters than windows + (B4.2), not before: until then the points remain the program's input and its priors stay. + `λ` is not re-derived as a constant but replaced by R0.2's per-coordinate terms. +* **S6 (B2 = the likelihood of any description; B4 = what the pixels can confirm): + accepted.** One amendment of scope: B4.4 states the tests' distributions (nested, Wald, + boundary of the parameter space); the decisions (thresholds with the Occam terms and the + prior, the order of acceptance) are R2's, so the two pages do not each own half a test. + +This chain's own shortening proposals are the same in substance (corners and continuations +as R2 decisions, R2.9; gradients as an R4 choice; thin strokes on B's strip terms; precision +computed by R for its parametrisation; the null space removed by never fitting more +parameters than windows), so the two chains agree on the cut. + +### Still open between the chains + +1. **The renderer floor on the corpus's actual intake** (resvg, 8× supersampled, box + filtered): B's per-image estimator exists; its value per family and tier, and the + calibration of A1, decide whether R2's error rates are the stated ones. +2. **Conflation at layered junction pixels** (B3.2's open question): R4.1b gives its size, + `a_j·b·|c_i − c_bg|` per pixel where a completed shape, the shape over it and the + background meet; the corpus measurement is phase 2 for both chains. +3. **Run coverage at 45°**: whether the switch between column and row windows leaves pixels + counted twice or not at all; B's partition rule (one boundary piece per window, single + pixels elsewhere) suggests neither, and R relies on it. + +### Agreed in phase 2 (with the boundary chain) + +1. **Item 1 above is settled by arbitration.** The engine does not replicate any renderer. + It uses exact geometry plus a floor calibrated per image (straight, curved and stroke + components, with a correlated part along each edge), so `χ²/M ≈ 1` whatever made the + input. Grid and position tests use that floor. +2. **`EdgeScorer`** (in `inkvec-core`, so `inkvec-fit` needs no `inkvec-trace`): + * It is built per edge from a `BoundaryLikelihood`. + * `windows_between_points(i, j)` takes point indices of `map.edges[e].points` and wraps + on a closed edge. Chain R maps its decimated and rotated indices back to these before + calling, and passes pieces in pixel coordinates (the fitter works in content units). + * The windows form a **partition**. Each window belongs to the span holding its centre and + is scored with that span's piece extended past the span's end. Windows given to corners + and junctions are a fixed set per edge. So the dynamic program's + `Σ chi2(span) + Σ chi2_local(corner)` covers a constant number of windows. + * `best_graph(r, degree)` is O(1) and feeds the inner loop. `chi2(r, pieces)` is + O(len r), used only to re-score each span's best few candidates. + * `weight_moments(r)` gives `Σ w·s^p` for `p ≤ 6`: the Fisher matrix of a graph of degree + at most 3, for the Occam term (A6). + * `Piece::from_svg_arc` converts an arc. +3. **`NoiseModel`** (`inkvec_core::noise`, on `ColorTrace::noise`): `sigma_flat`, + `sigma_edge` by distance band, `psf_radius`, `psf_mu2`, `nu`, `lossy`, `window_scale`. + * `NoiseModel::clean()` is today's behaviour bit for bit, and on a clean intake the + estimator does not run. + * The boundary chain folds `sigma_edge` and `window_scale` into each edge's point sigmas, + only when the model is not clean. The fitter divides by those sigmas and scales nothing + itself. + * `huber_kappa(nu) = min(3, √nu)`, one definition for both chains. + * `explained_by_psf(width, colour, ink_a, ink_b)` is the ringing null. + * `psf_mu2` belongs to the forward model (`left_area`), not to the noise. + * The PSF's first moment, a global shift, is not identifiable from one image and is not + carried. +4. **Where chain R reads the noise model.** + * The fitter's robust loss uses `huber_kappa(nu)`, together with the fold of the noise + into the edge sigmas (milestone 2, gated as one change). Tried and withdrawn: it + turned curves into polylines on the emoji families. See milestone 2. + * Extra prior weight comes only from measured noise, never from a flag (user directive). + * The completion stage reads none of it, for now. A junction zone was tried and + withdrawn; see milestone 1. + +## Phase 2: formal, code, measurement + +### Lean (`formal/InkvecTheory`, a new `Design/` directory) + +| file | lemma | statement | +|---|---|---| +| `BiasVariance.lean` | `constrained_fit_error` | `‖P_K y − s‖² = ‖P_K ε‖² + ‖s − P_K s‖²` for `s ∈ L`, every `ε` (R0.4); with `noise_absorbed`, a constraint helps iff the violation is under `dim L − dim K` | +| `Evidence.lean` | `gaussian_evidence_1d`, `bayes_factor_nested` | the one-direction Gaussian integral (from Mathlib's `integral_gaussian`) and the nested-model Bayes factor of R2.1 in closed form | +| `Limit.lean` | `eventually_lexicographic` | for costs `a·g(s) + b·ln s + c` with `g` growing faster than `ln`, the order is eventually lexicographic in `(a, b, c)` (R0.5's skeleton) | +| `Grid.lean` | `snap_threshold`, `harmonic_halving` | the grid-label rule of R2.1; the factor 2 per on-grid class of R2.7 | +| `Ties.lean` | `swap_reduces`, `optimal_partition_contiguous` | the exchange inequality and contiguity of R2.5 (finite sets) | +| `Rank.lean` | `tie_rank`, `involution_fixed_dim` | rank of a tie system `= n − components` (R1.1); `dim Fix(P) = (n + tr P)/2` for `P² = 1` (R1.5) | +| `Layers.lean` | `painter_interval_iff` | the iff of R4.1 for a finite family of sets | +| `Compositing.lean` | `completion_removes_seam` | the algebra of R4.1b | +| `Encoding.lean` | `encoder_optimal` | the table of R4.6, the gate's counting rules as a function, optimality by `decide` | + +### Rust + +* `crates/inkvec-fit/src/design/` (new): `evidence.rs` (R0.2: Occam terms from the Fisher + information of a constrained least-squares fit, the tangent-space determinant); + `constraints.rs` (R1: the vocabulary, exact rational rank for the linear layer, numerical + rank with the Weyl margin for the rest, the constrained Gauss–Newton refit); + `ties.rs` (R2.5); `grid.rs` (R2.6–R2.8, leave-one-out); `relations.rs` (detectors and the + R2.1 test for axis, 45°, parallel, perpendicular, G1, concentric, equal radius, mirror, + repetition); `prior.rs` (R3's table, generated). +* `multimodel.rs`: each segment's cost becomes `½χ² + Σ Occam(σ_i) − ln P(kind | style)`, + joins decided by R2.1 (G1 against a corner) instead of the `G1_BREAK_DEGREES` ramp. The + dynamic program keeps its form but indexes the boundary chain's windows instead of points + (`BoundaryLikelihood::run_moments` for lines and polynomials, `chi2_run` otherwise), with + breakpoints at window borders, guard windows charged to the vertex term, and a joint + polish of each vertex's end segments where corners, fillets and continuations are tested + (interface, answers 2 and 5). +* `merge.rs`, `ribbon/refine/merge.rs`, `mirror_fit.rs`, `harmonize.rs`, `editable.rs`: their + acceptance tests (`½Δχ² < λΔk`, IoU, `3σ + slack`) become R2.1, one rule for all. +* `crates/inkvec-cli`: a `layers` stage (R4.1–R4.3: order by T-junctions and bound, completion + by candidates) before stacking in `emit.rs`, replacing `seams.rs`'s underlap where a + completion exists; the encoder table of R4.6 and the design unit and decimals in + `pathdata.rs` and `post.rs`. + +### How Lean constrains the Rust + +1. **Generated vectors.** `#eval` in Lean writes `formal/InkvecTheory/vectors/*.json`: the + encoder table (R4.6), the snap and tie thresholds at a grid of `(σ, g, π, α)`, the optimal + tie partitions of small inputs found by exhaustive enumeration, layer-interval examples + with their verdicts. `cargo test` (`crates/inkvec-fit/tests/lean_vectors.rs`) reads them + and compares bit for bit (rationals) or to a stated tolerance (logarithms). +2. **Generated prior.** `bench/theory/design_prior.py --emit-rust` writes `prior.rs`; a test + recomputes its hash from the corpus so the table cannot drift from the counts. +3. **Debug assertions of the inequalities the proofs use.** A nested refit never fits better + (`Δχ² ≥ −ε`, `merge_chi2_increase`); `k = n − rank ≥ 0` and the Weyl gap holds where a + rank is decided; an accepted constraint's `½Δχ²` is under its `τ`; a completed shape lies + in its interval (checked on a raster in debug builds); the encoder's count never exceeds + an alternative's. + +### Measurement + +The gate (`bench/ci_gate.py`): parameter ratio per family toward 1.0 or below; dE00 +non-inferior within its margin; the gated geometric match `geom` +(`bench/inkvec_bench/geomatch.py`: mean edge displacement from the artist's file by +symmetric-difference area over the artist's boundary length, in input px; Quality today +0.056 px at 128 px, 0.093 at 512, 0.097 at 512 opaque) with its reported `geom_far`; corner +precision and recall and segment-type agreement where the gate reports them; and the design +statistics of R4.8. Where this chain should move `geom`: exact grid numbers and ties +(R2.5–R2.8) put construction points on the artist's own numbers (three quarters of the +positional error removed in the grid families, in the simulation); the right corners, +continuations and segment kinds (R2.9, the style prior) remove the structural part of the +displacement, which at today's 0.06–0.1 px is most of it; completion (R4.2) moves no visible +edge, so its gain is in the count, not in `geom`. The search/model diagnostic +(`bench/theory/oracle_cost.py`) re-run with `L` as the objective: at 128 px the share of +icons where the objective prefers the artist's file should rise from 129/246, the remaining +gaps becoming search errors that R4.3's search addresses. + +**Order of work, by the share of the artist's parameters each reaches:** (1) layers and +completion (R4.1–R4.3): 44–47 % of the emoji families' parameters are in partly covered +elements, and this needs nothing new from the boundary chain (the visible partition and +per-layer compositing at junction pixels); (2) ties, grid and axis constraints (R2.5–R2.8): +the exact numbers of the grid families, and `geom`; (3) the objective in the dynamic +program and merges (R0.2, R2.1), with the style prior on segment kinds, on the boundary +chain's window evaluator once it lands (the program over windows, answer 2 of the +interface); (4) the encoder (R4.6): design unit, `H`/`V`/`S`, primitives after snapping, +``; (5) the style variable (R3.5d). + +## Phase 2, milestone 1: layers and completion + +**What runs.** `crates/inkvec-cli/src/layers.rs`, in Quality mode between stacking and the +seams; `INKVEC_COMPLETION=0` is the A/B switch. Faces are visited from the top down. For +each opaque face with something painted over it, the stage proposes candidate shapes and +keeps the cheapest one the checker certifies. The candidates are: + +* a circle, ellipse or rectangle through the boundary the face owns, or round its lower + bound; +* the face's own rings with each covered run replaced: the corner of the owned lines either + side, a chord a margin under the cover, the run offset under the cover, a bulge, a + **corner cut**, or a **bridge**. + +The two newer replacements: + +* **Corner cut.** It drops a chamfer and extends the neighbouring lines to meet under the + cover. A blur removes the tip of an acute corner, the fit writes what is left as one more + segment, and under a cover the tip can be restored for free. +* **Bridge.** One G1 cubic from where the boundary goes under the cover to where it comes + out, tangent to the visible boundary at both ends. Its arms are set as the circular arc + between the two tangents would set them (also 0.8, 1.25 and 1.5 times that), or as the + cubics whose area and first moment match the run (`fit_cubic_moments`). + +Every candidate goes through the same check, and the description length picks among those +that pass. + +**The bounds.** + +* **Upper bound:** `H = V ∪ U` exactly (no margin). +* **Lower bound:** `L = V`, plus the half pixel under the cover that the underlap reached, + tapered over 12 px towards a third paint. +* **`V` includes the seam.** A stroke can be drawn narrower than the face above's region in + the map, and the lower face's underlap paints the gap between them today. So `V` counts + that gap as shown, but only where the underlap reached: the reach into the gap tapers + off towards any other face over 12 px, as the underlap's does, and at a junction of + three paints it is zero. +* **No junction zone.** A zone near junctions of a blurred input was tried, relaxing the + bounds within the blur (`psf_radius`, plus half a pixel of chroma on a lossy intake). + On `web` it let the cyan rectangle of the canary drop a visible wedge of cyan 1-2 px + wide, and `geom` rose 4 % on that icon. It was withdrawn. Deciding what the blur leaves + unidentified is the likelihood's job (the boundary chain's `EdgeScorer`), not a + geometric zone's. + +**What is certified, and what is trusted.** + +* **Checked.** The painter's interval is proved in Lean (`painter_interval_iff`, + `replace_in_interval`; the seam algebra in `seam_of_exact_outline` and + `junction_residue`). On every scan line the solver proposes, for each span of `L`, the + chain of spans of `E` that covers it, and for each span of `E` a chain of spans of `H`. + Each pair is accepted only by the generated interval kernels `span_within` and + `span_link` (`inkvec_verified::generated::design`), which are outward rounded and follow + `chain_cover` and `line_cover`. The slack is 0.1 px at each crossing. Neighbouring spans + may be bridged across a crack narrower than 0.2 px, which two regions computed from + different polygons leave where they meet. A refusal keeps the face as it was. +* **Trusted.** The scan conversion of shapes into spans (flattened within 0.02 px, lines + 0.25 px apart) and the region algebra that builds `V`, `U`, `L` and `H`. +* **Known limit.** A horizontal edge that moves less than a line spacing is not seen by the + check. That is why the rectangle candidate puts each side on the face's own vertices when + one lies that close, and falls back to the sampled box only when that fails. + +**Canary** (`openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F`, artist 20 parameters): + +| tier | completion off | completion on | +|---|---|---| +| 512ss | 54 | 20 | +| 512ssop | — | 26 (20, plus the white page as a `rect`) | +| web | 112 | 68 | +| web, sigma ×2 | 60 | 38 | + +On `web` the two triangles keep a chamfer at each acute corner. Under the honest `σ` the +fit writes each as a pentagon, two vertices more per corner. The corner cut would remove +them, but at those tips the blurred junction gave a sliver of the cyan face below to the +planar map. Completing the tip would paint over that sliver, so the exact interval refuses +it. Whether that sliver is the blur or a real wedge of cyan is for the likelihood to say +(above). + +**Canonical z-order: skipped.** Making paint order free between shapes that do not overlap +and fixed where they do would move elements, and so change bytes on every clean condition. + +**Never the page.** No completion may fill the canvas (the image's frame), to within 2 % +of its side on every edge. Which face is the page, and whether the artist drew one at all, is the emitter's +decision. Before this rule, an opaque intake of a logo that touches the frame +(`simple-icons/sagemath`, `premierleague`) was completed to a black canvas, with the white +page painted over it in pieces. That description is further from the artist's file, and on +`quality-512ssop` it was the one gated distance that rose (`turning_gap` +0.5 %, within +noise; simple-icons +34 %). + +**Against the artists' hidden geometry** (`bench/theory/amodal_eval.py`: the 121 emoji +icons of the screen set, noto, twemoji and openmoji, at 512ss). Each artist element is +rendered alone, so its full shape includes what later elements hide. Each face the stage +tried is matched to the element of its colour whose visible part it overlaps most, and its +shape before and after completion is scored by IoU against that element's full shape. + +* 673 faces were tried; 236 were completed and 437 refused (65 %). +* For a refused face, the artist hides a median 26 % of the element (quartiles 12 % and + 43 %), and the crescent's own IoU has median 0.67. + +| candidate | completed faces | IoU better | IoU worse | mean ΔIoU | IoU off (q1 / median / q3) | IoU on (q1 / median / q3) | +|---|---|---|---|---|---|---| +| bridge | 31 | 64.5 % | 32.3 % | +0.040 | 0.22 / 0.59 / 0.88 | 0.26 / 0.75 / 0.88 | +| chord | 135 | 71.1 % | 14.8 % | +0.026 | 0.12 / 0.49 / 0.80 | 0.13 / 0.50 / 0.87 | +| offset | 12 | 75.0 % | 0 % | +0.024 | 0.02 / 0.23 / 0.31 | 0.02 / 0.24 / 0.35 | +| primitive | 13 | 53.8 % | 46.2 % | +0.026 | 0.46 / 0.71 / 1.00 | 0.66 / 0.77 / 0.92 | +| bulge | 48 | 39.6 % | 14.6 % | +0.006 | 0.16 / 0.48 / 0.91 | 0.16 / 0.48 / 0.93 | +| corner cut | 13 | 30.8 % | 30.8 % | −0.003 | 0.15 / 0.77 / 0.98 | 0.15 / 0.77 / 0.97 | +| corner | 7 | 42.9 % | 57.1 % | −0.058 | 0.62 / 0.68 / 0.91 | 0.50 / 0.60 / 0.87 | +| all | 219 | 60.3 % | 19.2 % | +0.016 | 0.13 / 0.49 / 0.85 | 0.14 / 0.52 / 0.87 | + +A face completed with several kinds of replacement counts once under each. The table says +four things: + +* **Completion moves toward the hidden geometry three times as often as away.** It moves + little, because most completions are chords and offsets that reach a pixel under the + cover. +* **The bridge recovers the most.** It is the one candidate that continues the visible + boundary into the hidden part; its median IoU rises from 0.59 to 0.75. +* **The corner overshoots.** The intersection of the owned lines lies beyond the artist's + rounded or bevelled corner. +* **The refusals are the opportunity.** Two thirds of the tried faces have a quarter of + their element hidden, and nothing proposed for them passed the interval. Better + candidates (bridges across longer runs, the style prior's choice of continuation) are + where milestone 2's prior meets this stage. + +**The gate.** 246 icons, all 8 conditions, `--no-tighten`, against the baseline. Turning +and parameters are gated as distances from the artist's file. Changes are relative. + +| condition | dE00 | turning_gap | ratio_gap | geom | +|---|---|---|---|---| +| quality-128ss | −0.18 % | −8.61 % | −0.12 % | −0.07 % | +| quality-512ss | −0.94 % | −10.77 % | −3.64 % | −0.02 % | +| quality-512ssop | −1.51 % | −4.34 % | −8.66 % | −0.01 % | +| quality-web | −0.31 % | −3.84 % | −5.08 % | −0.00 % | +| fast, 4 conditions | identical | identical | identical | identical | + +Every point estimate is level or better. By family, these moved the wrong way: + +* **ratio_gap.** noto-emoji and twemoji at 128 px (+7.1 %, +9.3 %), whose traces already + write fewer numbers than their artists; noto-emoji +4.6 % at 512ssop and +7.2 % on `web`. +* **turning_gap at 512ssop.** simple-icons +6.2 %, openmoji +2.4 %, material-icons +1.6 %. + A completed shape's long straight edges dilute the turning per length. +* **dE00.** The 5 synthetic icons, +0.3 to +0.5 %. +* **geom at 128 px.** twemoji +0.06 %. + +**Human statistics with completion on against off** (`bench/human_stats.py`, the benchmark +battery, all 246 screen icons). The figure is the divergence from the artist's file per +statistic, family-macro mean, change on minus off: + +* **quality-512ssop.** The composite (geometric mean of after/before over 28 statistics) is + +0.2 %. + * Closer to the artist: stacking −11.1 %, nodes per subpath −8.7 %, axis lines −7.2 %, + segment lengths −4.7 %, smoothness −3.9 %. + * Further: primitives +24 %, collinear +5.9 %, half-pixel numbers +4.3 %, subpaths + +3.3 %, colours +3.0 %. +* **quality-web.** The composite is −0.2 %, with the same pattern: primitives +12.7 %, + stacking −7.5 %, nodes per subpath −8.7 %. + +So the completion's rectangles, circles and ellipses are written where the artists drew +paths. That agrees with the amodal evaluation, where primitives improve the IoU barely more +often than they worsen it (54 % against 46 %). They are the first candidate to put under the +style prior. + +**Design statistics before the battery** (246 screen icons, quality mode; the script that +counted them was absorbed into `bench/human_stats.py`): + +| | gate/icon | line | cubic | arc | axis exact | axis ≤ 0.5° | 45° | other angle | on design grid | half px | ties | +|---|---|---|---|---|---|---|---|---|---|---|---| +| artist | 367 | 0.290 | 0.669 | 0.040 | 0.504 | 0.019 | 0.039 | 0.423 | 0.184 | 0.140 | 0.533 | +| trace 512ssop | 373 | 0.608 | 0.198 | 0.194 | 0.100 | 0.084 | 0.005 | 0.795 | 0.100 | 0.169 | 0.456 | +| trace web | 415 | 0.717 | 0.211 | 0.072 | 0.045 | 0.077 | 0.001 | 0.863 | 0.059 | 0.121 | 0.508 | + +The angle shares are of lines. Primitive elements are 10 % of the artist's elements and 25 % +of a trace's. The traces are not yet written the way the artists draw: + +* **Angles.** The artists put half of their lines on an axis; a trace puts 10 %, and 4.5 % on + `web`. Another 8 % of a trace's lines lie within half a degree of an axis: these are the + axis constraints of milestone 2. +* **Grid.** A trace puts half as many numbers on the design grid as the artist, and a third + as many on `web`. +* **`web` against clean.** The gap widens on every count. The trace moves toward lines in + general directions, which is the noise-chasing of an under-estimated `σ` (R0.8). +* **Counts by family.** + * noto-emoji falls to 850 per icon on `web` from 1059 clean (artist 1066): the blur hides + detail. + * openmoji rises to 856 from 347 (artist 323). Its inks multiply on `web` (one icon has + 49 elements against 7 clean), which is the front end's palette under noise and belongs + to that agent. + * lucide rises to 72 from 54 (artist 40). + +## Phase 2, milestone 2: the noise fold, and the encoder + +### The fold and the Huber fit: a negative result + +Item 4 of "Agreed in phase 2" was built as one gated change: + +* **The fold.** The measured noise was added into each edge's point sigmas + (`σ² + extra`, `evidence.rs`, on when the model is not clean). +* **The Huber fit.** Two IRLS rounds were added to the boundary fit, at + `κ = huber_kappa(ν)`. Each residual beyond `κ` standard units was down-weighted to + `σ·√(u/κ)`. + +Clean intakes were unchanged by construction. On a quarter of `quality-web` (61 icons, the +gate's scorer), family-macro change against the build without either: + +| variant | dE00 | turning_gap | ratio_gap | geom | +|---|---|---|---|---| +| fold and Huber, `κ(ν)` | −5.0 % | −7.7 % | −6.5 % | −23 % | +| fold only | −6.9 % | −4.3 % | −3.1 % | −25 % | +| Huber only | −0.6 % | −6.8 % | −4.6 % | −6.3 % | +| fold at a quarter, `κ = 3` | +0.6 % | −5.0 % | −4.7 % | −2.2 % | +| Huber only, `κ = 3` | +1.3 % | −4.5 % | −3.7 % | +1.25 % | +| Huber on spikes only | +1.0 % | −1.4 % | −1.5 % | +0.8 % | + +The first row looks like a win, and it is not one: + +* **One icon.** `synthetic/prim_star5` alone carries the macro gain (geom 0.62 → 0.05). +* **The emoji families get worse.** Per family, fold and Huber read: + * openmoji: dE00 +11.4 %, geom +20 %; + * twemoji: +4.9 %, +16 %; + * noto-emoji: +5.7 %, +1.3 %. +* **The variants that spare the emoji give up the gain.** They lose dE00 and keep little else. + +What goes wrong is the same in every family: + +* **Curves become polylines.** A larger `σ` buys a cheaper description, so the fit takes it. + On `openmoji/1F38A` the cubics fell from 49 to 29 and the lines rose from 478 to 495. +* **Real features count as outliers.** A down-weighted residual is one the fit no longer + has to explain: a real corner of a small feature costs as little as a JPEG block step. + +R0.8 proves that a constraint accepted at `σ₁` stays accepted at `σ₂ ≥ σ₁`. It says +nothing about which description is cheapest once every price falls, and here the cheapest +is a polyline. + +Honest noise needs what this lacked: + +* the style prior, so that a larger `σ` buys the artist's segment kinds rather than lines; +* the windowed evidence objective, so that a residual is judged against the window it + sits in rather than as a point. + +So the change was reverted, and the fold waits on both. The front end's parked soft +same-ink exemption, which waited on it, waits too. The patch touched `multimodel.rs` +(`optimal_multimodel_robust`, `huber_reweight`), `pipeline.rs` and `evidence.rs`. It is +not in the tree; it went with the milestone's report. + +### The encoder: holes cut, one path per paint + +Two encoder oddities set the artists' files apart from the traces on the opaque tiers: + +* **No holes.** No trace had a nested subpath (a hole or island of a compound path). The + artists of material-icons have 42 % of theirs nested, and of simple-icons 25 %. +* **Too many elements.** A trace's counter was a page-coloured element painted over the + glyph: 47 % of material-icons' elements were painted over another, against the artists' + 0 %. And every rectangle was an element of its own: `material-icons/border_left` came + out as seventeen `` against the artist's one path. + +What runs now (`crates/inkvec-cli/src/emit/holes.rs`): + +* **Holes are cut** (stage 2b, `cut_ground_holes`). The page is the opaque face that + covers the frame. A face in exactly the page's colour that fills a hole of a glyph on + the page is dropped, and its outline is written into the glyph as a hole. + * The picture is unchanged by construction: the hole is the counter's own outline and + the page paints under it. Lean, `Design/Layers.lean`: + * `cut_hole`: painting `P` and then `C` in colour `k`, over a picture that is already + `k` across `C`, is `P \ C`; + * `cut_hole_pixel`: the same at an edge pixel. + * As under `--no-background`, only a glyph whose children are all page-coloured is + cut. A figure keeps its stacked eyes and buttons, as the emoji artists draw them. + * Nothing is cut where the counter's or the glyph's outline is written as a ``, + an ellipse or a rounded rectangle: in a path that outline costs 14 or 36 numbers, + against 3 to 6. +* **Square rectangles join their siblings' compound path** (`plain_rect`). Three lines are + the six numbers of a ``, so the tie in R4.6 is broken toward fewer elements. A + rectangle the completion stage produced joins the path as well. + +Tried and withdrawn: + +* **Faces of the page's colour sitting on the page, dropped.** The page paints there too, + but the neighbours' outlines are not the face's own, and without it they showed: + `openmoji/1F517` on `web` read dE00 +1.2 % in Fast mode. Dropping them also changed + which completions certify. On the bottle cap of `noto-emoji/emoji_u1f9d1_1f3fc_200d_1f37c`, + `#fdfefa` taken for a `#ffffff` page went white (geom 0.065 → 0.346); hence the exact + colour match. +* **A ring of two circles cut and written as one stroke.** A stroke's outline is the + renderer's offset of the centre line, not the two fitted circles: + * `material-icons/group_remove`: dE00 +20 % at 512 px; + * `lucide/app-window-mac` on `web`: dE00 +3 %, turning gap +37 %. +* **A same-paint island in a hole, joined to the ring around it.** It is the artist's + structure, but one path's anti-aliasing is not two elements', and it moved dE00 by a + sixteenth of coverage on a few pixels (`simple-icons/notion`, `cocos` at 128 px). + That is a renderer effect and no geometry, but it is a worse point estimate. +* **Holes cut over any painted ground.** The emoji artists stack there: the letters of + `openmoji/1F195` are strokes over a white tile, and cut out of it they moved its dE00 + by the renderer's rounding (+0.26 % at 512 px in Fast mode). + +**Regression gate** (246 icons, all 8 conditions, against this milestone's base, `--no-tighten`): + +| condition | dE00 | turning_gap | ratio_gap | geom | icons changed | +|---|---|---|---|---|---| +| quality-128ss | −0.0001 % | −0.00003 % | −0.049 % | 0 | 23 | +| quality-512ss | −0.0002 % | +0.00002 % | −0.060 % | 0 | 16 | +| quality-512ssop | −0.146 % | −0.063 % | −0.145 % | −0.0001 % | 50 | +| quality-web | −0.0008 % | −0.053 % | −0.096 % | 0 | 65 | +| fast-128ss | identical | identical | identical | identical | 0 | +| fast-512ss | identical | identical | identical | identical | 0 | +| fast-512ssop | −0.0087 % | 0 | 0 | +0.0003 % | 65 | +| fast-web | −0.0035 % | 0 | 0 | −0.0027 % | 67 | + +"Icons changed" counts the SVGs whose bytes changed. Every verdict is identical or +non-inferior. Two point estimates are worse, each from one icon: + +* **quality-512ss turning_gap (+3·10⁻⁷).** `material-icons/qr_code`: its bars joined one + path, so their paint ranks and with them one completion changed; a corner moved by + 0.01 px. +* **fast-512ssop geom (+7.8·10⁻⁷).** `material-icons/admin_panel_settings` (geom + +3.8 %): the shield's hole is the white face's own outline, but the renderer covers an + edge pixel of one path differently from the same edge in another. The pixels moved are + better in 618 places and worse in 355. Two lucide icons moved the other way + (−3.8·10⁻⁶). + +Per family, the axes that rose: + +* quality-512ssop, noto-emoji: dE00 +0.002 %, turning_gap +0.14 %, ratio_gap +0.05 %. + One icon, `emoji_u1f469_1f3fb_200d_1f52c`: a gradient test tube with its white stripes + cut out is no longer a completion candidate (faces with holes are not), and its + completed outline went back to the traced one. +* quality-512ss, material-icons: turning_gap +0.001 % (`qr_code`, above). +* fast-512ssop, material-icons: geom +0.14 % (`admin_panel_settings`, above). +* fast-web, simple-icons: dE00 +0.002 %. + +Completing a face with holes, its holes carried into the completed path, is the next +step for the first of these. + +**Human statistics** (`bench/human_stats.py`, all 246 icons, divergence from the artist's +file, family-macro, against the base): + +| statistic | quality-512ssop | quality-web | +|---|---|---| +| composite (28 statistics) | −3.1 % | −1.9 % | +| primitives | −24.7 % | −18.5 % | +| elements | −14.5 % | −11.1 % | +| colours | −16.9 % | −5.8 % | +| nested | −12.7 % | −11.2 % | +| stacked | −10.3 % | −10.4 % | +| subpaths | −3.3 % | −0.8 % (not significant) | + +* **Primitives.** The fall undoes the +24 % that milestone 1's completed rectangles added. +* **Further from the artist.** A few statistics moved the other way: + * on 512ssop, collinear +1.7 %; + * on `web`, stroked +4.5 %, line_axis +1.0 %, ties +0.8 % and extremum +0.4 %. + + These are shares, and their denominators fell with the elements and primitives taken + away. For example, the stroked share is strokes over elements, and the strokes are as + they were. +* **material-icons, 512ssop.** The nested share went 0 → 0.13 (artist 0.42), and the + stacked share 0.47 → 0.28 (artist 0). +* **What is left.** On material-icons at 512ssop, 21 elements in the page's colour are still + painted over another: 9 circles, 6 rectangles and 6 paths. A round counter stays painted + over by the cost rule above (a cut circle is 14 numbers against 3). + +## Where the present code stands + +| link | inkvec today | what changes | +|---|---|---| +| R0 | `½χ² + λ·P`, `λ = ln(extent/precision)` (`cost.rs`, `FitConfig`), used by the dynamic program, merges, strokes and mirrors | per-coordinate Occam terms from B4's precision; the prior | +| R1 | no constraint system; constraints imposed one at a time by the passes that need them (`mirror_fit.rs`'s fundamental domain, `merge::snap` in research builds) | one vocabulary, exact and certified ranks, derived coordinates | +| R2 | fixed tolerances: `editable.rs` (`3σ + slack`), `harmonize.rs` (mask IoU, then evidence), the G1 break ramp | one Bayes-factor test with error rates; ties and grid jointly | +| R3 | `editable.rs`'s measured handle-angle prior (29 % of artist handles within 0.05° of an axis) | the counted model of R3 | +| R4 | `ribbons.rs` (stroke or fill), `primitives.rs`/`choice.rs`, `emit.rs` stacking, `seams.rs` underlap, `occlusion.rs` T-junction order, `` from `harmonize`; fixed decimals | order and completion (R4.1–R4.3), the encoder table, the design unit | + +## References + +* Aldous, D. J. (1985). Exchangeability and related topics. *École d'Été de Probabilités de + Saint-Flour XIII*, Lecture Notes in Mathematics 1117. doi:10.1007/BFb0099421. +* Carlier, A., Danelljan, M., Alahi, A., Timofte, R. (2020). DeepSVG: a hierarchical + generative network for vector graphics animation. *NeurIPS*. +* Ellis, K., Ritchie, D., Solar-Lezama, A., Tenenbaum, J. B. (2018). Learning to infer + graphics programs from hand-drawn images. *NeurIPS*. +* Ewens, W. J. (1972). The sampling theory of selectively neutral alleles. *Theoretical + Population Biology* 3(1). doi:10.1016/0040-5809(72)90035-4. +* Fisher, W. D. (1958). On grouping for maximum homogeneity. *JASA* 53(284). + doi:10.1080/01621459.1958.10501479. +* Hoeffding, W. (1963). Probability inequalities for sums of bounded random variables. + *JASA* 58(301). doi:10.1080/01621459.1963.10500830. +* Igarashi, T., Matsuoka, S., Kawachiya, S., Tanaka, H. (1997). Interactive beautification: + a technique for rapid geometric design. *UIST*. doi:10.1145/263407.263525. +* Kass, R. E., Raftery, A. E. (1995). Bayes factors. *JASA* 90(430). + doi:10.1080/01621459.1995.10476572. +* Kellman, P. J., Shipley, T. F. (1991). A theory of visual interpolation in object + perception. *Cognitive Psychology* 23(2). doi:10.1016/0010-0285(91)90009-D. +* Krichevsky, R., Trofimov, V. (1981). The performance of universal encoding. *IEEE + Transactions on Information Theory* 27(2). doi:10.1109/TIT.1981.1056331. +* Lee, J. M. (2013). *Introduction to Smooth Manifolds*, 2nd ed. Springer. +* Li, Y., Wu, X., Chrysanthou, Y., Sharf, A., Cohen-Or, D., Mitra, N. J. (2011). GlobFit: + consistently fitting primitives by discovering global relations. *ACM TOG* 30(4). +* MacKay, D. J. C. (1992). Bayesian interpolation. *Neural Computation* 4(3). + doi:10.1162/neco.1992.4.3.415. +* Nandi, C., Willsey, M., Anderson, A., Wilcox, J. R., Darulova, E., Grossman, D., Tatlock, Z. + (2020). Synthesizing structured CAD models with equality saturation and inverse + transformations. *PLDI*. doi:10.1145/3385412.3386012. +* Natarajan, B. K. (1995). Sparse approximate solutions to linear systems. *SIAM Journal on + Computing* 24(2). doi:10.1137/S0097539792240406. +* Pavlidis, T., Van Wyk, C. J. (1985). An automatic beautifier for drawings and + illustrations. *SIGGRAPH*. doi:10.1145/325165.325240. +* Rissanen, J. (1978). Modeling by shortest data description. *Automatica* 14(5). + doi:10.1016/0005-1098(78)90005-5. +* Schwarz, G. (1978). Estimating the dimension of a model. *Annals of Statistics* 6(2). + doi:10.1214/aos/1176344136. +* Tierney, L., Kadane, J. B. (1986). Accurate approximations for posterior moments and + marginal densities. *JASA* 81(393). doi:10.1080/01621459.1986.10478240. +* Toro-Vizcarrondo, C., Wallace, T. D. (1968). A test of the mean square error criterion for + restrictions in linear regression. *JASA* 63(322). +* Wallace, C. S., Freeman, P. R. (1987). Estimation and inference by compact coding. *JRSS B* + 49(3). doi:10.1111/j.2517-6161.1987.tb01695.x. +* Weyl, H. (1912). Das asymptotische Verteilungsgesetz der Eigenwerte linearer partieller + Differentialgleichungen. *Mathematische Annalen* 71. doi:10.1007/BF01456804. diff --git a/docs/theory/chains.md b/docs/theory/chains.md new file mode 100644 index 00000000..4dd49f0a --- /dev/null +++ b/docs/theory/chains.md @@ -0,0 +1,160 @@ +# Two chains: from pixels to the fewest coordinates + +> The problem of [`optimal.md`](optimal.md), split into two chains of mathematical problems, +> each link taking the previous link's output as its input. One chain recovers the picture +> (boundary solving), the other writes it with the fewest coordinates a person would use +> (representation). Each link is a problem worth a proof, sized so that no link can be +> solved by an assumption a longer link would have to justify. The two chains meet at one +> interface, which their owners negotiate. + +## The goal + +Write the artist's design back with **the fewest coordinates**, as close to the artist's +own file as the pixels allow: the same shapes, the same kinds of segments, the same +constraints (a horizontal line is horizontal, two radii that are equal are equal, a point +on the design grid is on it), and so the same count of numbers or fewer. Fidelity is a +constraint, not a currency: the description must explain the pixels within their noise; +among those that do, the fewest free coordinates win; among equals, the most human. + +Judged three ways (`bench/ci_gate.py`): colour error against the artist's render (dE00), +parameters against the artist's file, and geometric match to the artist's file (edge +displacement by area, corner and segment-type agreement), the last being the most direct +measure of "the same design". + +## Chain B: boundary solving (pixels → a likelihood over curves) + +**B1. Inks and mixtures.** *In:* the raster. *Out:* the inks (flat colours; linear or radial +colour fields) and, per pixel, the mixture weights of the at most two inks it mixes (three at +a junction pixel). *Claims to prove:* the palette is identifiable from interior pixels; given +it, the two-ink weights are unique and unbiased, with an error bound under 8-bit quantisation; +a junction pixel's three weights are identifiable only with geometry from its neighbours (so +B3 needs B1's two-ink pixels around it, not the junction pixel itself); a gradient ink's field +is identifiable from its interior and edge pixels unmix against the field's value there. +*Known:* `coverage.rs`, `bench/theory/attribution.py` (interior colour error is ~0 for flat +inks; gradients are the main interior error). + +**B2. A likelihood for any curve.** *In:* B1's weights along a two-ink run. *Out:* the exact +likelihood of an arbitrary candidate boundary curve, not of extracted points. *Claims to +prove:* under the box filter and independent quantisation noise, the column (or row) sums +of one ink's weights are a sufficient statistic for the boundary within the run +(`column_sum_eq_average`); the log-likelihood of any curve `f` is a quadratic in the +differences `S_col − ∫_col f`, with known variances, so `χ²(curve)` is computable in time +linear in the run's columns; its Fisher information per unit length bounds the precision of +any curve parameter (Cramér–Rao). *Known:* `planar/strip.rs`, `Coverage`, `Noise`, +`Supersampling`. + +**B3. Where runs end: corners, junctions, thin strokes.** *In:* B1's weights near a point +where B2's assumptions fail (a tangent discontinuity, three inks, a feature under two pixels +wide). *Out:* a local parametric model fitted to the raw weights (a wedge: two rays and a +vertex; a junction: `k` rays and a vertex; a thin stroke: a centreline and a width), with its +posterior. *Claims to prove:* each model is identifiable from the pixels within a stated +radius; the estimator's bias and variance, against the Cramér–Rao bound; when the model +should be refused (curvature within the radius). *Known:* `planar/junctions.rs`, +`ThinStroke`, `LevelSetBias` (the ½-crossing rounds corners), `bench/theory/attribution.py` +(corners ~4 %, junctions ~1 % of colour error, but visually first). + +**B4. The planar map as one likelihood.** *In:* B2's runs and B3's vertices. *Out:* a planar +map whose total log-likelihood is a sum of local terms, one per run and one per vertex, with +the coupling between a vertex and the runs that meet it made explicit. *Claims to prove:* the +decomposition is exact up to stated cross terms (pixels shared between a vertex model and a +run); the box filter's null space (`polyline_kernel`) is a property of the parametrisation, +not of the data, and vanishes for curves with no more coefficients than columns +(`polynomial_boundary_determined`); the precision of every coordinate the representation +might write. *This is the interface:* what chain R evaluates every description against. + +## Chain R: representation (a likelihood → the fewest human coordinates) + +**R1. Constraints and degrees of freedom.** *In:* B4's map and likelihood. *Out:* a +vocabulary of design constraints (incidence, G1 tangency, axis alignment, parallel and +perpendicular, equal length and radius, concentricity, mirror and rotational symmetry, +repetition by translation, a lattice or design grid, one stroke width) and, for any set of +them, the free coordinates that remain. *Claims to prove:* at a regular point the free +coordinates are the raw coordinates minus the rank of the constraint Jacobian; how to compute +the rank and a minimal parametrisation for the constraint graphs icons produce (decomposition +into rigid clusters); when two constraint sets give the same design (redundancy). + +**R2. Which constraints hold.** *In:* R1's candidates, B4's likelihood, R3's prior. *Out:* the +accepted constraint set. *Claims to prove:* a constraint is a nested model, so imposing a true +one never moves the fit away from the truth (`natural_model_closer`) and raises `χ²` by a +`χ²_Δk` variable (`merge_chi2_increase`); the test "accept when the evidence ratio times the +prior odds exceeds one" is consistent (a false constraint's `Δχ²` grows with the boundary +length, a true one's does not) and has stated error rates at a given resolution; accepting +constraints in order of evidence and re-solving keeps the accepted set consistent (no two +accepted constraints contradict). + +**R3. The human prior, small.** *In:* the artists' own files in the corpus. *Out:* prior odds +for each constraint in each context (segment kinds on either side, element kind, family), and +the document-level latent variables that change them (a design grid and its unit; one stroke +width; a symmetry axis), as a model of a few hundred numbers counted from the files, not a +neural network. *Claims to prove:* the estimate's error (Dirichlet smoothing, a +generalisation bound over icons); empirical Bayes for the document variables (a grid +inferred from some coordinates raises the prior of the rest, without double counting); that +the resulting decision rule reproduces the corpus's constraint frequencies on clean inputs +(calibration). + +**R4. Structure and encoding.** *In:* R2's constrained geometry. *Out:* the SVG. *Claims to +prove:* the choice between structures (stroke or fill, layers completed behind what covers +them, primitives, repetition by ``) decomposes per face up to stated couplings and can +be searched with bounds (a free-coordinate lower bound prunes); the encoder that writes a +constrained element with the fewest numbers the gate counts is optimal over its alternatives +(``, ``, a stroke, `H`/`V`, arcs, ``); and the objective itself: +lexicographic (fit within tolerance, then fewest free coordinates, then the prior) against +description length, with the conditions under which they agree. + +## The interface, and what may move across it + +B4's output is R's input: a map, a likelihood any curve can be evaluated against, and the +precision of each coordinate. Two things may move: + +* **Vertices.** If R's constraints (incidence, tangency, a corner as two lines meeting) can be + evaluated against B2's likelihood plus raw-pixel terms near the vertex, B3 shrinks to + providing those terms, and corners become R2 decisions. +* **Gradients.** Whether a fill is a gradient, and which kind, is a representation choice + (R4) on B1's evidence. + +The owners negotiate these, and anything else that shortens a chain without hiding a +problem in an assumption. + +## As negotiated (phase 1) + +The owners' write-ups are [`chain-boundary.md`](chain-boundary.md) and +[`chain-representation.md`](chain-representation.md). What they agreed: + +* **The interface is areas, not points.** Summed over any window of pixels, a face's mixture + weights equal its exact area there, so any description (curves, primitives, strokes, + layers) is scored against the pixels by areas, and at the truth `χ²/M` is 1.00 (exact + area) and 1.01 (8×8 supersampling). Chain B delivers an `Evidence` object and a + `BoundaryLikelihood` evaluator (`chain-boundary.md`, "Interface proposal"); the fitter's + per-point residual becomes a per-window one, and points, `DEFAULT_SIGMA_MODEL`, the kink + and anchor priors and the curvature inflation stop being the interface. +* **Chain B, re-cut.** B1 inks and mixtures; B2 the likelihood of any description (the window + identity and the exact decomposition into edge, vertex and thin-stroke terms); B3 vertex + proposals and thin features (high-recall proposals, per-pixel terms, flat-bottomed + likelihoods where the data are flat); B4 what the pixels can confirm (precision, and the + distributions of the tests). +* **Chain R gains a link and four decisions.** R0, the objective: the negative log posterior + of the discrete design with its free coordinates integrated out (the Laplace / + Wallace-Freeman evidence), which prices each coordinate by its own precision and each + constraint by its prior odds; today's `½χ² + λ·k` is its special case with one precision + and a flat prior. R2 now decides corners, fillets, smooth joins, tangency and continuation + through junctions (B proposes, R's arms place the vertex); R4 now decides gradient or + flat, a stroke or two edges, and the layers (each shape completed behind what covers it, + exactly within the interval the painted picture allows). +* **Amendments chain B accepted to deliver:** an evaluator that draws exactly as the gate's + renderer does (A1, checked on the artists' own files); elliptical arcs, strokes and + per-layer compositing (A2); the renderer floor as its own correlated term (A3); junction + arms in cyclic order with candidate continuations (A4); local topological alternatives + (A5). Precision and `log det F` are computed on R's side from Jacobians (A6). +* **Open measurements for chain B:** the renderer floor on the corpus's own intake per + family and tier; the size of the per-layer compositing term; that windows at 45° neither + count a pixel twice nor drop one. + +## Formal, then code + +Each link: an informal statement and proof first (`chain-boundary.md`, +`chain-representation.md`); the load-bearing lemmas then in Lean +(`formal/InkvecTheory`); then code bound to them by the rule of +[`verification.md`](verification.md): solvers are free (floats, heuristics, any algorithm), +and every result a theorem speaks about is accepted only by a checker generated from the +Lean definition the theorem is about, on a certificate the solver emits, in exact +arithmetic or rigorous intervals. diff --git a/docs/theory/noise.md b/docs/theory/noise.md new file mode 100644 index 00000000..d3118bff --- /dev/null +++ b/docs/theory/noise.md @@ -0,0 +1,133 @@ +# Noisy inputs + +> The theory so far reads exact renders: box-filtered, rounded to 8 bits, nothing else. The +> files people send have been resampled and compressed on the way. This page says what that +> adds, measured; what of the theory survives it; what has to change; and how the gate +> holds the engine to it. + +## What arrives + +A logo usually reaches a tracer as a screenshot or a download: drawn at one size, resized to +another with a bicubic or Lanczos kernel, and saved as a JPEG, often with the colour stored at +half resolution (4:2:0). Each step leaves its mark at the edges: blur and overshoot from the +resampling kernel, 8×8 block quantisation and ringing from the codec, colour bleeding a pixel +or two across every edge from the subsampled chroma. Zhang, Liang, Van Gool and Timofte +(2021), *Designing a practical degradation model for deep blind image super-resolution*, ICCV, +arXiv 2103.14006, model real degradations as exactly this chain. + +The gate's `web` tier fixes it at one realistic setting: each of the 246 screen icons at +512 px, flattened onto white, resized to 400 px (bicubic) and saved at JPEG quality 80 with +4:2:0 chroma (`bench/build_web_tier.py`). `quality-web` and `fast-web` are gated like the +other six conditions. + +## Where the noise sits + +`bench/theory/noise_profile.py`, 41 icons, the `web` raster against the exact box-filtered +raster at 400 px, RMS in 8-bit levels by distance to the nearest exact edge: + +| distance to an edge | share of pixels | resampling (luma) | JPEG (luma) | JPEG (chroma) | +|---|---|---|---|---| +| under 1 px | 4.7 % | 7.9 | 4.5 | 6.5 | +| 1-2 px | 3.7 % | 0.3 | 3.1 | 2.7 | +| 2-3 px | 3.6 % | 0.05 | 2.3 | 1.6 | +| 3-5 px | 5.5 % | 0.05 | 1.7 | 1.3 | +| 5-8 px | 8.1 % | 0.05 | 0.95 | 1.05 | +| 8 px and more | 74 % | 0.03 | 0.20 | 0.35 | + +Two facts follow. The resampling's error is deterministic and confined to the edge pixel: a +blur, which a forward model reproduces, not noise. The codec's error is noise, and it is not +stationary: twenty times larger at an edge than in the flat interior three quarters of the +image is made of. One noise level per image is wrong wherever it is read. The engine's +estimate (`coverage::estimate_noise`, a low quantile of the Laplacian, so flat regions) +returns its floor of 0.5 levels on every one of these images; its measured replacement on a +lossy intake (`regularize::residual_sigma`, the larger of an interior and an edge median) +returns the edge's 4-5 levels and applies them to the interiors too. The first lets ringing +halos through as inks; the second lets two flat regions a few levels apart pass for one +gradient. + +## What survives: area windows are unbiased + +A column window's sum is the area of a face in that column (the window identity, +`window_sum_eq_area`). Under a blur kernel `k` whose weights over the outputs sum to one for +every input position, Fubini gives, for a window that covers the blurred transition, + + Σ_{y ∈ W} (f ∗ k)(x, y) = (A ∗ k_x)(x) + Δ · m_y + +where `A` is the column-area profile, `k_x` the kernel's horizontal marginal, `Δ` the step +between the two plateaus and `m_y` the kernel's vertical first moment. A centred kernel has +`m_y = 0`, so vertical blur, overshoot and ringing vanish from a column window entirely, and +horizontal blur is a one-dimensional convolution of the area profile, the identity on a +straight edge and `½ μ₂ A''` on a curved one. The measured means agree: over 38 826 windows +the sums stay within 0.0004 px of area of the exact ones on the 8-bit, the resampled and the +`web` rasters alike, and growing the windows only adds noise. + +What changes is the spread: 0.005 px of area on an exact render, 0.039 once resampled +(Pillow normalises its weights per output pixel, so at a non-integer factor an edge's sum +ripples with its phase against the output grid; the same 0.041 from an exact 512 px render), +0.066 on `web`. The tails grow with it: the 95th percentile is 1.2 times the RMS on the exact +render and 1.9 times on `web`. + +This is why reading areas is the right primitive for noisy input. A tracer that thresholds, +or reads the half-coverage crossing, has an error that grows with the blur; the window's sum +does not move, it only becomes less precise, and its precision can be measured from the +image itself. + +## What has to change + +1. **A noise model per image and per place, not one number.** Interior and edge noise + measured separately, the edge's as a function of distance; a window's variance from the + windows themselves (the fourth difference of consecutive windows reads it without knowing + the geometry). Each decision takes the noise of the pixels it reads: an ink or a gradient + from interiors, a boundary from its edge band. +2. **Heavy tails.** A Student-t or Huber likelihood, which is χ² for small residuals (exact + renders keep their behaviour) and does not let one block step or ringing lobe overrule a + constraint. +3. **A forward model with the blur in it.** Score a candidate's area profile convolved with + `k_x` rather than the profile itself; `k`'s width from the edge profiles + (`softness::ramp_evidence` already measures it). On an exact render the kernel is the + identity and nothing changes. +4. **Colour from luma.** With 4:2:0 the chroma is at half resolution and bleeds across edges; + the coverage between two inks is read from luma wherever their lumas differ, and inks are + robust (median) estimates of interiors. +5. **Halos are not faces.** A band narrower than the kernel along an edge, whose colour lies + on the line through the two inks it separates but beyond them (overshoot), or off it by + the chroma's bleed, is explained by the edge; a face must beat that explanation by its own + description length. + +## Noise makes the prior matter more + +For nested descriptions `M₀ ⊂ M₁`, `M₁` adding `k` parameters (or dropping a tie), the +evidence for `M₀` grows with the noise when the fit `M₁` buys is within it: the likelihood +flattens and the prior's preference for the shorter description carries more of the +posterior (`chain-representation.md`). On noisy input the honest result snaps more to the +grid, ties more coordinates and writes fewer segments, not more; detail finer than the blur +was never in the pixels, and the shortest description that fits drops it. A trace whose +parameter count rises on noisy input is fitting the noise. The gate's `ratio` axis on `web` +reads it. + +## Where the engine stands (2026-10-10) + +Against the opaque 512 px tier, on the gate's 246 icons: + +| | Quality `web` | Quality `512ssop` | Fast `web` | Fast `512ssop` | +|---|---|---|---|---| +| dE00 | 0.202 | 0.040 | 0.213 | 0.080 | +| geom (px) | 0.347 | 0.097 | 0.354 | 0.282 | +| geom_far (px) | 0.145 | 0.019 | 0.136 | 0.142 | +| parameters / artist's | 2.16 | 1.41 | 7.22 | 3.51 | + +Fast takes ringing halos for inks (a two-colour flag comes back with four and 215 faces: +the halo colours lie 0.08-0.09 sRGB from the line between the two inks, twice the blend +tolerance, because 4:2:0 moves chroma independently of luma) and its parameters explode on +the colour families (openmoji 13×, twemoji 8.9×). Quality loses inks instead: on a soft +intake the palette treats colours within 5 dE00 as one ink, to keep ramp colours out, and +that also folds real neighbouring inks together (the mosaic's 37 fills come back as 26 +inks and 25 faces, five of them gradients, where the clean raster gives 34 and 59 flat +ones); the interior residual then reads palette bias (4.5 levels on the mosaic, where the +codec's interior noise is 0.2), so splitting the noise level by population alone does not +help. Gradients are not the culprit on balance: tracing `web` without them raises dE00 by +62 % and `geom` by 139 %. What separates a ramp colour from an ink is where it sits (within +the blur's reach of an edge, or with an interior of its own), not how far it is from its +neighbour. The boundary chain owns items 1-4 +above (`chain-boundary.md`), the representation chain item 5 and the prior's side +(`chain-representation.md`). diff --git a/docs/theory/optimal.md b/docs/theory/optimal.md new file mode 100644 index 00000000..a6ed69b4 --- /dev/null +++ b/docs/theory/optimal.md @@ -0,0 +1,331 @@ +# The optimal vectorizer, informally + +> What the best possible raster-to-vector tracer would compute, whether anyone has found +> it, how far inkvec is from it stage by stage, and which approximations to make next. +> Informal on purpose: the claims that are theorems are proved in +> [`formal/InkvecTheory`](../../formal/InkvecTheory/README.md) and named here; the rest is +> argument, with the measurement that would test it. + +## Summary + +* **Nobody has found or proved an optimal algorithm for the general problem**, and none + can exist in general: the problem contains NP-hard segmentation, and with an + unrestricted prior it is the uncomputable problem of finding the shortest program that + draws an image. But the *optimum itself* can be stated exactly: the most probable SVG + given the pixels, under the exact rendering model and a model of how people write SVG + (§2). +* **For clean artwork the problem splits in two.** The *picture* (where the boundaries + are, what colour the fills are) is determined by the pixels down to the anti-aliasing + and quantisation floor, and inkvec is already near that floor (§3, §4). The *program* + is not: many SVGs draw the same picture (strokes or fills, one arc or three, a rectangle + under two triangles or two cut-out shapes), and pixels cannot choose between them. Only a + prior over human SVGs can (§5). +* So the remaining distance to the optimum is almost entirely **representation**: the + prior, and the search over structures it ranks. That is what "naturality" means, and why + cutting parameters has lowered colour error rather than raised it: among descriptions + that draw the truth, the one with the fewest parameters is the most faithful + (`natural_model_closer`, proved). +* **Measured:** a diagnostic splits each icon's gap into *search error* (our own objective + ranks the artist's file first and the search missed it) and *model error* (the + objective prefers something else) (§6). At 512 px it is search on 85-88 % of the icons; + at 128 px the objective prefers the trace on about half, where the prior must decide. +* **Plan:** build the optimum as a slow reference ("oracle mode") and measure every fast + stage by its gap to it; add the moves the search lacks (layers completed behind what + covers them, merges for filled outlines, more than one hypothesis per structural + choice); then a code-length prior that reproduces the artists' statistics, whose most + probable output is a canonical "normal form" (§5, §7). + +## 1. The problem + +An artist writes an SVG document `S`: shapes, their paint, their order. A renderer draws +it, anti-aliases it (exactly: each pixel gets the area of each shape inside it; in +practice 8×8 or 16×16 supersampling, or analytic coverage), and the result is quantised to +8 bits, perhaps compressed. We see the raster `R` and must write `Ŝ`. + +Three things make `Ŝ` good, and the gate measures all three: + +1. **Fidelity.** `Ŝ` draws the same picture as `S`, at any resolution (the gate renders + both at 1024 px and compares by CIEDE2000). +2. **Compactness.** `Ŝ` uses about as many numbers as `S` (the gate's parameter ratio). +3. **Naturalness.** `Ŝ` is written the way a person writes SVG: a line where they drew a + line, a stroke where they used a pen, a circle where they used a circle, layers where + they layered. This is what makes an SVG editable, and it is what "clean" means. + +`S` cannot be recovered in general, for two separate reasons: + +* **Picture ambiguity.** Different pictures give identical pixels. The box filter has a + null space: zigzags along a pixel border, sub-pixel ripples, anything that moves area + within a column without changing the column's total (`sine_ripple_invisible`, + `polyline_kernel`, `column_fiber`). Detail below the pixel is gone. +* **Program ambiguity.** Different SVGs give identical pictures. A ring is a stroked circle + or a black disc under a white one; a 270° arc is one arc or three; a flag's background + is a rectangle under two triangles or the complement of the triangles. + +Picture ambiguity is resolved by a prior on *shapes* (smoothness, few segments). Program +ambiguity is resolved only by a prior on *programs*: how people write SVG. + +## 2. The optimum + +Bayes' rule says what the best decision is. With a likelihood `P(R | S)` (how probable these +pixels are if the artist wrote `S`), a prior `P(S)` (how probable it is that a person writes +`S`), and a loss `ℓ(Ŝ, S)` (what a wrong answer costs), the optimal output minimises the +expected loss under the posterior: + +``` +Ŝ* = argmin over Ŝ of Σ_S P(S | R) · ℓ(Ŝ, S), P(S | R) ∝ P(R | S) · P(S) +``` + +For clean art the posterior over *pictures* is sharply peaked (§3), so this is very nearly +the most probable description (MAP). Taking logarithms: + +``` +Ŝ* ≈ argmin over S of ½ χ²(R, raster(S)) + CodeLength(S) +``` + +* `½ χ²` is the likelihood: the squared difference between the pixels and the pixels `S` + would make, in units of the noise (8-bit quantisation is ±½ level, a standard deviation of + 0.11 % of full scale; the renderer's own anti-aliasing differs from the artist's by more, + and that mismatch is the real noise floor). +* `CodeLength(S) = −log P(S)` is the prior, in nats: how surprising this SVG would be from a + person. + +That is the minimum description length principle (Rissanen 1978), and it is the objective +inkvec already optimises, with two differences that matter: + +1. **inkvec measures `χ²` on boundary points**, extracted from the pixels first, not on the + pixels themselves. Where extraction is exact (smooth edges between two fills, the + column-sum theorem) nothing is lost. Where it is not (corners, junctions, strokes under + two pixels, three colours in one pixel) the two-step estimate is a worse estimator than + the pixels allow. +2. **inkvec's prior is flat:** `CodeLength = λ · (number of parameters)`, every parameter + priced the same, `λ = ln(extent / precision)`. That price is not arbitrary. It is the + Laplace approximation of the code length of a real number known to within `precision` + in a range `extent` (Rissanen's optimal precision), so it is the right price for a + coordinate a person picks uniformly at random. People do not: they put points on a grid, + draw lines at 0°, 45° and 90°, reuse coordinates, repeat radii, mirror halves. A prior + that knows this charges a point on the design grid `log(grid points)` instead of + `log(extent / precision)`, a horizontal line one number instead of two, a repeated + radius almost nothing. Under such a prior the MAP *is* the canonical form (§5). + +## 3. What is known + +| Question | Answer | Where | +|---|---|---| +| Is the forward model known? | Exactly: a pixel's coverage is the area of the shape in it; a column of coverages sums to the boundary's mean height over that column, whatever its slope or curvature | `column_sum_eq_average`; Puckett (1991), Trujillo-Pino et al. (2013) | +| Can sub-pixel detail be recovered? | No: the box filter's null space is exactly the zigzag (for one vertex per pixel border) and any area-preserving rearrangement within a column | `polyline_kernel`, `column_fiber` | +| Is a clean boundary determined by its pixels? | Yes: a polynomial boundary of degree `< n` is fixed by `n` columns; a line by two; a cubic by four | `polynomial_boundary_determined`, `strip_reading_exact` | +| How precisely? | Per column, 8-bit quantisation alone allows about 0.001 px; 8×8 supersampling allows up to 1/16 px of bias; a ½-crossing reading is biased up to 0.086 px; thresholding first, up to ½ px | `quantize_minimax`, `ss_column_sum_close`, `levelSetBias_max`, `binarize_minimax` | +| Is optimal segmentation tractable? | Along one chain with fixed candidate breakpoints, yes: an exact dynamic program (Kolesnikov 2012), which inkvec runs per edge. Over a whole image with a region prior, no: Potts energy minimisation is NP-hard (Boykov, Veksler, Zabih 2001) | `inkvec_fit::multimodel` | +| Is the shortest program computable? | Not under an unrestricted prior (Kolmogorov complexity). Under a fixed grammar (SVG's elements) and a fixed prior it is a finite, if large, search | — | +| Does fewer parameters mean less fidelity? | Not when the smaller model still draws the truth: its least-squares fit is closer to the truth for every noise, by exactly the noise in the dropped directions; each surplus parameter costs one `σ²` of squared error | `natural_model_closer`, `natural_model_gain`, `noise_absorbed` | +| What do people judge a vectorisation by? | Accuracy, simplicity, continuity and regularity (straight, parallel, symmetric, axis-aligned), measured in user studies | Hoshyari, Dominici, Sheffer, Carr, Wang, Ceylan, Shen (2018), *Perception-driven semi-structured boundary vectorization*, SIGGRAPH; Favreau, Lafarge, Bousseau (2016) | +| Has anyone optimised SVGs against the pixels directly? | Yes, locally, without a prior on programs: DiffVG (Li et al. 2020), LIVE (Ma et al. 2022). They fit, but the output is not what a person would write | — | +| Has anyone learned the human prior? | Yes, as generators: DeepSVG (Carlier et al. 2020), Im2Vec (Reddy et al. 2021), StarVector (Rodriguez et al., 2023 onward). They write in a human style but do not match the pixels to sub-pixel precision | — | + +No published method combines the exact likelihood, a prior over human programs, and a +global search over structure, and that combination is the optimum of §2. Each piece +exists separately. + +## 4. How far inkvec is from the optimum + +Measured on the gate's 246 icons (Quality, stroke detection on, after this round's +merges), against the artist's own files: + +| Stage | What the optimum does | What inkvec does | Gap | +|---|---|---|---| +| Palette, regions | The fewest flat colours (or gradients) that explain every pixel as a mixture of at most two (three at a junction) | Palette walk, unmixing, gradient fits | Small: interior fill colour is exact for most families; gradients (noto-emoji) are the main interior error (`bench/theory/attribution.py`) | +| Boundary points | The best unbiased estimate from the pixels | Column sums where two fills meet (unbiased, variance `k·σ²`); probes elsewhere | At the floor on smooth edges: equivalent displacement about 0.025 source px at 512 px, the 8×8 supersampling floor. Not at corners, junctions, thin strokes | +| Curves per edge | MAP segmentation under the human prior | Exact dynamic program under the flat prior; arcs at most 120° | The prior, and the 120° cap | +| Structure | MAP over strokes vs fills, layering, primitives, symmetry, repetition | Greedy moves verified by description length: strokes, merges, primitives, mirrors, harmonisation | Greedy search, and moves it does not have (amodal completion, continuation through a junction, shared coordinates) | +| Emission | The canonical form of the MAP | Fixed decimals, faces in paint order | No canonicalisation | + +What the numbers say: 83-92 % of the remaining colour error lies within one source pixel +of a smooth edge, at the measurement floor; corners hold about 4 % and junctions 1 %. The +parameter ratio is 0.95 at 128 px, 1.17 at 512 px and 1.41 on opaque 512 px logos. The +remaining distance is in representation, not in fitting. + +The gate already shows the theorems at work. Writing stroke-drawn faces as strokes, and +merging what the solve split, *raised* the trace's residual against its own input +(`self_res` +2.5 % to +3.5 %) while *lowering* its error against the artist's file (dE00 +−8 % to −11 %). That is `merge_chi2_increase` and `natural_model_closer` side by side: the +smaller true model fits the pixels a little worse, because it no longer absorbs their +noise, and the truth better, for the same reason. A tracer tuned to its own residual alone +would have refused both changes. + +Two concrete examples of representation the search cannot reach today: + +* `openmoji/1F3F4-E0069-E0074-E0062-E0061-E007F` (a flag): the artist drew a blue + rectangle and two white triangles over it (20 parameters). inkvec draws the blue *visible + part*, a complicated polygon, and the triangles (54). The move missing is **amodal + completion**: a face cut by the faces painted over it is the simplest shape that + continues behind them. +* `synthetic/mosaic_grid6`: every corner of a cell where two cells sit side by side gains + a 6 px taper, which is the underlap that hides anti-aliasing seams (`crates/inkvec-cli/src/seams.rs`). + It costs 1.8 % of the parameters over the screen set, a choice made for the renderer, not + for the picture. + +## 5. The prior: writing SVG the way a person does + +A prior over SVG programs is a code: frequent choices get short codewords. The MAP under +it is the description a person would most probably have written. A sharp enough prior +makes that choice deterministic, so the same picture always comes back as the same file: +a single normal form. This is the "mode collapse to one clean format" asked for, and it is +a feature here: two traces of one logo should be the same file. + +What the prior has to know, all measurable on the artists' files in the corpus: + +* **Elements.** Line sets are strokes of one width; circles, ellipses and rounded + rectangles are written as such; emoji are layered shapes. +* **Segments.** Lines where straight, circular arcs where circular (of any sweep), cubics + otherwise, joined smoothly (G1) where smooth. +* **Numbers.** Coordinates on the design grid when there is one (lucide and material: + a 24-unit grid with half-unit steps); angles of 0°, 45°, 90°; coordinates shared between + points (a vertical edge shares its x); radii and widths from a short list; halves that + mirror exactly; repeated parts identical. +* **Layers.** Shapes completed behind the shapes that cover them, back to front. + +As a code length: a coordinate on a detected grid costs `log(grid points)`; a coordinate +equal to one already written costs `log(how many have been written)`; a free one costs +`log(extent / precision)` as now; an axis-aligned line costs one number; an arc's sweep is +free (SVG's flags). The grid itself is a parameter of the document, paid once, and is only +used when it pays for itself, so an icon not designed on a grid loses nothing. + +**The inkvec normal form**, which the MAP under that prior produces: + +1. Back-to-front layers, each shape completed behind the shapes over it. +2. A primitive where the shape is one; a stroke where the face is a pen line of one width. +3. Lines, arcs and cubics as above, the fewest that fit; smooth joins written smooth. +4. Coordinates snapped to the document's grid and axes wherever that is within the + measurement's own error; exact symmetry and exact repetition where the drawing has them. +5. One deterministic writing order and number format. + +**Keeping the statistics the same.** The prior can be checked without any icon's ground +truth: the distribution of these features over inkvec's output should match their +distribution over the artists' files (element kinds, segment kinds, angle histogram, +fraction of coordinates on a grid, symmetry rate). A distance between the two histograms +belongs in the gate as a reported axis, next to the parameter ratio, which is the first +of these statistics. + +**Hand-written or learned.** Start hand-written: each rule above is a few lines, can be +tested alone, and is priced in the same currency as everything else. A learned model of +SVG syntax (a small sequence model over path commands) is the later step, used only to +*score* candidate descriptions, never to generate them, so the pixels keep the last word. + +## 6. Search error or model error: the diagnostic that decides + +For each icon, compute the objective of §2 twice: on inkvec's output, and on the artist's +own file fitted to the same pixels (its structure kept, its numbers refined). + +* **The artist's file scores better** (lower cost): a better description exists and the + search did not find it. That is a **search error**: add moves, widen the search. +* **inkvec's output scores better, but the artist's file is better on the gate**: the + objective prefers the wrong description. That is a **model error**: fix the prior or the + loss. +* **Both agree**: the icon is at the optimum of this objective. + +The split is standard in machine-translation decoding, where it decides whether to +improve the search or the model. Here it turns "where is the remaining gap" from a guess +into a per-icon count (`bench/theory/oracle_cost.py`). + +**Measured (2026-10-10, Quality, stroke detection on).** The fit is the squared difference +from the input's pixels with each file rendered at the input's size (over white and black, +so transparency counts; over white only for the opaque tier), in units of the artist +file's own per-pixel residual, the renderer floor; a parameter costs inkvec's `λ`. The +artist's file is the truth, so it always fits to the floor; the question is whether the +objective *prefers* it. + +| tier | objective prefers the artist's file | prefers the trace | the trace is larger and fits worse | +|---|---|---|---| +| 128 px | 129 / 246 | 117 | 64 | +| 512 px | 208 / 246 | 38 | 128 | +| 512 px, opaque | 216 / 246 | 30 | 165 | + +At 512 px the objective already ranks the artist's description first on 85-88 % of the +icons, and the trace did not find it: those gaps are **search errors**, and they stay the +majority with the noise scale taken 16 times larger (159 of 246). Most are wrong structure +rather than wrong numbers: the trace is both larger and further from the pixels on 128 +icons (noto-emoji's shaded emoji lead, 1.5-2× the artist's parameters at several times +its residual), which is what a missing representation (a gradient, a layer, a completed +shape) looks like. At 128 px the pixels say less, and the objective prefers the trace on +nearly half the icons: there the choice between descriptions is the prior's, which is the +case for a prior that knows how people draw (§5). So the order of work follows: search +moves first for 512 px and above, the prior for small rasters. + +## 7. From the optimum to fast approximations + +The optimum is too slow to run on every trace, but it can run once, as a reference: an +**oracle mode** that searches much harder (several structural hypotheses kept at each +choice, pixel-space refinement at corners and junctions, every merge and completion +tried), slow enough for minutes per icon. Then every fast stage is judged by its distance +to that reference rather than to the artist's file, which separates "the fast stage +approximates badly" from "the objective is wrong". + +Ranked by expected gain against cost: + +1. **The search/model diagnostic** (§6), now measured: at 512 px the gap is mostly search. + Run it on every change that claims a structural gain. +2. **A grid-, axis- and repetition-aware code length, with snapping.** The prior of §5, + hand-written. Expected: naturalness and editability directly; fidelity where a snapped + value is the artist's exact one; fewer parameters where a shared value replaces a free + one. +3. **Amodal completion.** A face cut by faces painted over it is offered as the simplest + shape continuing behind them, and kept when the description length falls. The largest + remaining parameter cost in opaque logos and emoji (the flag: 54 → about 20). +4. **Merges for filled outlines.** The stroke solve's merges (this round) applied to + outlines: arcs beyond 120°, collinear lines, straight cubics; 1.5-5 % of the + parameters in the filled families, where the naturality count finds them. +5. **Search beyond greedy.** Keep a few hypotheses at each structural choice (stroke or + fill, layer order, which merge first) instead of one: a beam. Split and merge moves are + already the moves of reversible-jump MCMC (Green 1995) taken at zero temperature; a beam + or annealing is the next step toward the optimum. +6. **Pixel-space polish where extraction fails.** At corners, junctions and strokes under + two pixels, fit the local geometry to the pixels themselves, with exact coverage as the + forward model. These are 5 % of today's error, but they are where a person looks first. +7. **Perceptual precision.** An edge between two similar colours needs less positional + precision than an edge between black and white: its displaced area costs `contrast × + area` in colour error. Pricing each edge's parameters at its own precision (`λ_edge = + ln(extent / precision_edge)`, `precision_edge` at a just-noticeable difference over its + contrast) spends the parameters where a viewer would see them. + +## 8. Can the optimum be found? + +For a fixed grammar (SVG's elements and segments), a fixed prior and a fixed perceptual +loss, the optimum is a well-defined finite search, and on icon-sized inputs a slow +exhaustive-enough search is feasible: that is the oracle mode. What cannot be had is a +proof that any *fast* algorithm reaches it on every input, because the general problem is +NP-hard. The workable notion of "optimal" is therefore empirical and measurable: the fast +tracer's gap to the oracle, per icon, should be zero on most icons and small on the rest, +and the oracle's own choices should match the artists' files wherever the pixels allow. + +The theorems settle what can be: the picture is recoverable down to the floor, and a +true simplification never costs fidelity. Everything else is the prior, which the +artists' own files measure. + +## References + +* Rissanen, J. (1978). Modeling by shortest data description. *Automatica* 14(5). + doi:10.1016/0005-1098(78)90005-5. +* Boykov, Y., Veksler, O., Zabih, R. (2001). Fast approximate energy minimization via graph + cuts. *IEEE TPAMI* 23(11). doi:10.1109/34.969114. (Potts energy minimisation is NP-hard.) +* Kolesnikov, A. (2012). Segmentation and multi-model approximation of digital curves. + *Pattern Recognition Letters* 33(9). doi:10.1016/j.patrec.2012.01.021. +* Green, P. J. (1995). Reversible jump Markov chain Monte Carlo computation and Bayesian + model determination. *Biometrika* 82(4). doi:10.1093/biomet/82.4.711. +* Hoshyari, S., Dominici, E. A., Sheffer, A., Carr, N., Wang, Z., Ceylan, D., Shen, I.-C. + (2018). Perception-driven semi-structured boundary vectorization. *ACM TOG* 37(4). + doi:10.1145/3197517.3201312. +* Favreau, J.-D., Lafarge, F., Bousseau, A. (2016). Fidelity vs. simplicity: a global + approach to line drawing vectorization. *ACM TOG* 35(4). doi:10.1145/2897824.2925946. +* Li, T.-M., Lukáč, M., Gharbi, M., Ragan-Kelley, J. (2020). Differentiable vector + graphics rasterization for editing and learning. *ACM TOG* 39(6). + doi:10.1145/3414685.3417871. +* Ma, X., Zhou, Y., Xu, X., Sun, B., Filev, V., Orlov, N., Fu, Y., Shi, H. (2022). Towards + layer-wise image vectorization (LIVE). *CVPR*. +* Carlier, A., Danelljan, M., Alahi, A., Timofte, R. (2020). DeepSVG: a hierarchical + generative network for vector graphics animation. *NeurIPS*. +* Reddy, P., Gharbi, M., Lukáč, M., Mitra, N. J. (2021). Im2Vec: synthesizing vector + graphics without vector supervision. *CVPR*. +* Rodriguez, J. A., et al. StarVector: generating scalable vector graphics code from + images and text (2023 onward). +* Puckett, E. G. (1991); Trujillo-Pino, A., et al. (2013): see the theory page, + [`README.md`](README.md) §2. diff --git a/docs/theory/verification.md b/docs/theory/verification.md new file mode 100644 index 00000000..5dc7b1ab --- /dev/null +++ b/docs/theory/verification.md @@ -0,0 +1,91 @@ +# Keeping the proofs and the code from drifting apart + +> A decision record. The theorems in [`formal/InkvecTheory`](../../formal/InkvecTheory/README.md) +> are about mathematical objects; the engine is Rust. Tests and CI checks run beside the +> code but do not link it to the proofs: they sample. This page compares the ways of linking +> them so that a divergence is a build failure, and chooses one. + +## The requirement + +1. **No drift.** A change to the code that breaks what a theorem promises must fail the + build, not wait for a test to sample it. +2. **No limit on algorithms.** Solvers, searches and approximations stay free to change, + in any style, with floating point. +3. **Speed.** No runtime or portability cost that the WebAssembly, Python, Go and other + bindings would carry. + +## The options + +| | How proof and code are linked | Floats and fast approximations | Algorithms allowed | Runtime cost | Proof effort | Tooling | +|---|---|---|---|---|---|---| +| **A. Tests only** (until now) | Not linked; tests sample | Yes | Any | None | None | In place | +| **B. Lean is the source, Rust generated** | The Rust file is generated; a hand edit fails CI | No (exact arithmetic or rigorous intervals only) | Straight-line formulas, small exact kernels | Small kernels only | Moderate | No new tools | +| **C. Lean compiled to C, linked into Rust** | The proved function is the running function | Yes, but proofs about floats are impractical | Any, written in Lean | 2-10× slower than Rust (an estimate); the Lean runtime in every binding | Moderate to high | The Lean runtime in WebAssembly, Python and Go: very hard | +| **D. Aeneas** (Rust translated to Lean) | Proofs about the actual Rust; a change breaks them | Floats allowed but opaque to the proofs | A subset of Rust in verified functions | None (it is the Rust) | High | OCaml, a pinned Lean and Mathlib (~8 GB), access to its repository | +| **E. Verus** (proofs inside the Rust) | The compiler checks code and proof together | Weak float support | The Verus dialect in verified functions | None | Moderate for integer logic; real analysis impractical | One more toolchain | +| **F. Certified results** (free solvers, a proved checker) | Every result is checked by proved code before it is used | Yes, anywhere in the solvers | Any | One exact check per accepted result | Low to moderate (checking is easier than solving) | No new tools (the checker by B) | + +F is the method of *certifying algorithms*: a solver returns its answer with a certificate, +and a small checker, proved correct once, decides whether the answer is accepted. McConnell, +Mehlhorn, Näher, Schweitzer (2011), Certifying algorithms, *Computer Science Review* 5(2), +doi:10.1016/j.cosrev.2010.09.009; with verified checkers, Alkassar, Böhme, Mehlhorn, +Rizkallah (2014), A framework for the verification of certifying computations, *Journal of +Automated Reasoning* 52, doi:10.1007/s10817-013-9289-2. + +## The evaluation + +Scores 1-5; a link of at least 4 is required, since it is the point. + +| Criterion (weight) | A | B | C | D | E | **F, checker by B** | F, checker by D | +|---|---|---|---|---|---|---|---| +| Proof and code cannot drift (25) | 1 | 5 | 5 | 5 | 5 | 4 | 4.5 | +| Any algorithm (20) | 5 | 2 | 3 | 3 | 3 | **5** | 5 | +| Speed, floats (20) | 5 | 3 | 2 | 5 | 5 | **5** | 5 | +| Proof effort (15) | 5 | 4 | 3 | 2 | 3 | **4** | 3 | +| Tooling and portability (10) | 5 | 4 | 1 | 2 | 3 | **4** | 2 | +| Reuses the Lean theorems (10) | 1 | 5 | 5 | 4 | 1 | **5** | 5 | +| **Weighted, of 100** | fails the link | 75 | 66 | 75 | 74 | **90** | 86 | + +## The decision: F, with checkers generated from Lean + +* **Solvers are free.** Fitting, the dynamic programs, the stroke solve, the searches: any + algorithm, floating point, heuristics, approximations. +* **Results are not.** Every result a theorem speaks about (a constraint accepted, a merge + kept, a shape completed behind another, a coordinate snapped, a description scored) is + used only if a checker accepts it, on a certificate the solver emits. +* **Checkers are generated from Lean.** A checker is a Lean definition in a small + expression language that Lean can both reason about and print as Rust; the theorem is + about that definition, and the Rust is generated from it into files marked as generated, + which CI regenerates and compares. A hand edit cannot survive. +* **Checkers are exact.** The pixels are 8-bit integers, so window sums are exact + integers; every `f64` is an exact rational, so the areas of lines and cubics are exact + polynomials in a solver's numbers; square roots and angles (arcs) are bounded by interval + arithmetic with outward rounding. The one trusted assumption, stated as an axiom in Lean, + is IEEE 754's: each floating-point operation returns the correctly rounded result, so its + value widened by one unit in the last place on each side contains the exact one. + +What this guarantees: every result the engine uses satisfies what the theorems say, so a +solver change cannot break a proved property; at worst a result is refused. What it does +not: that the solver finds the best result. That is the gate's job. + +A side effect: decisions made in exact arithmetic are the same on every platform. Linux and +Windows outputs differ today on 7 of the 12 cross-language contract cases, from floating +point. + +Option D can be added later for hand-written Rust kernels, where a proof about the code +itself is worth its toolchain. + +## In place (2026-10-10) + +* `formal/InkvecTheory/InkvecTheory/Gen/`: the expression language `Expr` with its real, + rational and interval semantics and their soundness theorems (`evalQ_sound`, + `evalI_sound`, `nonneg_of_evalI`); the Rust printer; `Emit.lean`, which writes the + generated files. +* `crates/inkvec-verified`: no dependencies; the runtime (`iv.rs`, outward-rounded + intervals; `q.rs`, checked `i128` rationals with an overflow-free exact comparison) and + the generated kernels. The `formal` CI job regenerates them and fails on any difference. +* The first kernels (`Gen/Strip.lean`): `strip.rs`'s cubic stencil is now the generated one, + bit for bit the formula it replaced (output unchanged on 120 traces in both modes), and + every vertex the strip reading moves is accepted only if the generated interval checker + proves it lies on the cubic the column sums determine to 1e-9 px + (`stripResidual_on_cubic`); a refusal sends the vertex to the probes. diff --git a/formal/InkvecTheory/.gitignore b/formal/InkvecTheory/.gitignore new file mode 100644 index 00000000..bfb30ec8 --- /dev/null +++ b/formal/InkvecTheory/.gitignore @@ -0,0 +1 @@ +/.lake diff --git a/formal/InkvecTheory/InkvecTheory.lean b/formal/InkvecTheory/InkvecTheory.lean new file mode 100644 index 00000000..dc8e6dc6 --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory.lean @@ -0,0 +1,30 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import InkvecTheory.Basic +import InkvecTheory.Coverage +import InkvecTheory.NullSpace +import InkvecTheory.Identifiability +import InkvecTheory.Deconvolution +import InkvecTheory.LevelSetBias +import InkvecTheory.Quantization +import InkvecTheory.ThinStroke +import InkvecTheory.Rank +import InkvecTheory.Noise +import InkvecTheory.Supersampling +import InkvecTheory.Naturality +import InkvecTheory.Gen.Expr +import InkvecTheory.Gen.Rust +import InkvecTheory.Gen.Strip +import InkvecTheory.Design.Layers +import InkvecTheory.Design.Noise +import InkvecTheory.Gen.Design +import InkvecTheory.Windows +import InkvecTheory.Gen.Evidence + +/-! +# Inkvec theory: inverting box-filter rasterisation + +Machine-checked theorems behind inkvec's coverage-first design. `README.md` maps each +theorem to the code it bears on; `Audit.lean` prints the axioms each depends on. +-/ diff --git a/formal/InkvecTheory/InkvecTheory/Audit.lean b/formal/InkvecTheory/InkvecTheory/Audit.lean new file mode 100644 index 00000000..3f20d6c6 --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Audit.lean @@ -0,0 +1,89 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). + +# Axiom audit + +`lake build InkvecTheory.Audit` prints, for every headline theorem, the axioms its proof +depends on. Every line must read `[propext, Classical.choice, Quot.sound]`: Lean's three +standard axioms, on which all of Mathlib's real analysis rests. No `sorry`, and no axiom of +this library's own, appears anywhere. +-/ +import InkvecTheory + +open Inkvec + +#print axioms coverage_subgraph +#print axioms column_sum_eq_average +#print axioms invisible_perturbation +#print axioms sine_ripple_invisible +#print axioms rasterization_not_injective +#print axioms polyline_zigzag_invisible +#print axioms polyline_kernel +#print axioms column_fiber +#print axioms zeros_of_zero_averages +#print axioms poly_eq_of_averages +#print axioms polynomial_boundary_determined +#print axioms line_from_two_columns +#print axioms cubic_point_from_means +#print axioms quartic_defect +#print axioms boundary_point_from_pixels +#print axioms levelSet_reading +#print axioms levelSetBias_le +#print axioms levelSetBias_max +#print axioms column_sum_reading +#print axioms binarize_minimax +#print axioms quantize_minimax +#print axioms coverage_band +#print axioms straddle_inversion +#print axioms hidden_stroke_invisible +#print axioms centroid_bias +#print axioms centroid_bias_worst +#print axioms width_contrast_ambiguity +#print axioms flat_directions +#print axioms histopolate_cubic +#print axioms face_value_cubic +#print axioms side_stencil_cubic +#print axioms strip_reading_exact +#print axioms strip_unbiased +#print axioms strip_variance +#print axioms face_value_noise +#print axioms point_from_means_noise +#print axioms subCount_close +#print axioms ss_column_sum_close +#print axioms natural_model_closer +#print axioms natural_model_gain +#print axioms merge_chi2_increase +#print axioms noise_absorbed +#print axioms Inkvec.Gen.Expr.evalQ_sound +#print axioms Inkvec.Gen.Expr.evalI_sound +#print axioms Inkvec.Gen.Expr.nonneg_of_evalI +#print axioms Inkvec.Gen.histopolateK_eq +#print axioms Inkvec.Gen.stripResidualK_eq +#print axioms Inkvec.Gen.stripResidual_on_cubic +#print axioms Inkvec.Design.above_eq_of_interval +#print axioms Inkvec.Design.painter_interval_iff +#print axioms Inkvec.Design.replace_in_interval +#print axioms Inkvec.Design.seam_of_exact_outline +#print axioms Inkvec.Design.no_seam_of_completion +#print axioms Inkvec.Design.junction_residue +#print axioms Inkvec.Design.cut_hole +#print axioms Inkvec.Design.cut_hole_pixel +#print axioms Inkvec.Design.accept_monotone +#print axioms Inkvec.Design.huber_eq_sq +#print axioms Inkvec.Design.inlier_of_le +#print axioms Inkvec.Design.huber_le_sq +#print axioms Inkvec.Gen.spanWithinK_eq +#print axioms Inkvec.Gen.spanWithin_meaning +#print axioms Inkvec.Gen.spanLinkK_eq +#print axioms Inkvec.Gen.chain_cover +#print axioms Inkvec.Gen.line_cover +#print axioms Inkvec.window_sum_eq_area +#print axioms Inkvec.trapezoid_integral +#print axioms Inkvec.window_sum_resampled +#print axioms Inkvec.blur_affine_profile +#print axioms Inkvec.blur_quadratic_profile +#print axioms Inkvec.Gen.trapezoidK_integral +#print axioms Inkvec.Gen.windowTermK_eq +#print axioms Inkvec.Gen.fourthDiff_cubic +#print axioms Inkvec.Gen.fourthDiff_side +#print axioms Inkvec.Gen.cornerExcessK_eq diff --git a/formal/InkvecTheory/InkvecTheory/Basic.lean b/formal/InkvecTheory/InkvecTheory/Basic.lean new file mode 100644 index 00000000..fcec5df7 --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Basic.lean @@ -0,0 +1,82 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import Mathlib + +/-! +# The unit clamp + +A pixel of height one cut by a boundary at height `t` above its bottom is covered by +`clamp01 t = min 1 (max 0 t)` of its height. Everything about box-filter coverage of a +boundary that is a graph reduces to this function, and its one structural fact is that it is +a difference of two ramps (`clamp01_eq_ramp_sub`), so stacked cells telescope +(`sum_clamp01`). +-/ + +namespace Inkvec + +open Finset + +/-- The share of a unit cell lying below height `t` measured from the cell's bottom. -/ +noncomputable def clamp01 (t : ℝ) : ℝ := min 1 (max 0 t) + +/-- The ramp `t ↦ max 0 t`. -/ +noncomputable def ramp (t : ℝ) : ℝ := max 0 t + +lemma clamp01_nonneg (t : ℝ) : 0 ≤ clamp01 t := + le_min zero_le_one (le_max_left _ _) + +lemma clamp01_le_one (t : ℝ) : clamp01 t ≤ 1 := min_le_left _ _ + +lemma clamp01_of_mem {t : ℝ} (h0 : 0 ≤ t) (h1 : t ≤ 1) : clamp01 t = t := by + unfold clamp01; rw [max_eq_right h0, min_eq_right h1] + +lemma clamp01_of_nonpos {t : ℝ} (h : t ≤ 0) : clamp01 t = 0 := by + unfold clamp01; rw [max_eq_left h, min_eq_right zero_le_one] + +lemma clamp01_of_one_le {t : ℝ} (h : 1 ≤ t) : clamp01 t = 1 := by + unfold clamp01; rw [max_eq_right (le_trans zero_le_one h), min_eq_left h] + +lemma continuous_clamp01 : Continuous clamp01 := by + unfold clamp01; fun_prop + +lemma continuous_ramp : Continuous ramp := by + unfold ramp; fun_prop + +/-- **Layer-cake decomposition.** The unit clamp is a difference of two ramps one unit +apart. -/ +lemma clamp01_eq_ramp_sub (t : ℝ) : clamp01 t = ramp t - ramp (t - 1) := by + unfold clamp01 ramp + rcases le_total t 0 with h | h + · rw [max_eq_left h, max_eq_left (by linarith), min_eq_right zero_le_one]; ring + · rcases le_total t 1 with h' | h' + · rw [max_eq_right h, max_eq_left (by linarith), min_eq_right h']; ring + · rw [max_eq_right h, max_eq_right (by linarith), min_eq_left h']; ring + +/-- **Telescoping.** `n` stacked unit cells below height `t` hold `ramp t - ramp (t - n)`. -/ +lemma sum_clamp01 (t : ℝ) (n : ℕ) : + ∑ k ∈ range n, clamp01 (t - k) = ramp t - ramp (t - n) := by + induction n with + | zero => simp + | succ n ih => + rw [sum_range_succ, ih, clamp01_eq_ramp_sub] + have : t - (n : ℝ) - 1 = t - ((n + 1 : ℕ) : ℝ) := by push_cast; ring + rw [this]; ring + +/-- When the boundary height lies within the `n` stacked cells, the cells hold exactly `t`. -/ +lemma sum_clamp01_of_mem {t : ℝ} {n : ℕ} (h0 : 0 ≤ t) (h1 : t ≤ n) : + ∑ k ∈ range n, clamp01 (t - k) = t := by + rw [sum_clamp01]; unfold ramp + rw [max_eq_right h0, max_eq_left (by linarith)]; ring + +/-- The cells from index `k` upwards of a stack of `n` hold `ramp (t - k)` when the boundary +lies below the top of the stack. -/ +lemma sum_Ico_clamp01 {t : ℝ} {k n : ℕ} (hkn : k ≤ n) (h1 : t ≤ n) : + ∑ m ∈ Ico k n, clamp01 (t - m) = ramp (t - k) := by + have hsplit := sum_range_add_sum_Ico (fun m : ℕ => clamp01 (t - m)) hkn + rw [sum_clamp01, sum_clamp01] at hsplit + have htop : ramp (t - n) = 0 := by unfold ramp; exact max_eq_left (by linarith) + rw [htop] at hsplit + linarith + +end Inkvec diff --git a/formal/InkvecTheory/InkvecTheory/Coverage.lean b/formal/InkvecTheory/InkvecTheory/Coverage.lean new file mode 100644 index 00000000..b7c403c4 --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Coverage.lean @@ -0,0 +1,136 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import InkvecTheory.Basic + +/-! +# Box-filter coverage, from Lebesgue measure + +The image formation model inkvec inverts (`crates/inkvec-trace/src/coverage.rs`): a pixel's +value is the *area* of the shape inside the pixel's unit square. Here that area is the +Lebesgue measure of `Ω ∩ pixel i j` in `ℝ²`; nothing about it is assumed. + +For a shape whose boundary is the graph of a continuous `f` (the shape lies below it), +`coverage_subgraph` turns the 2-D area into a 1-D integral of the unit clamp, and +`column_sum` stacks a column of pixels: + + Σ_{rows} coverage = ∫_{column} (f x - j₀) dx (when the boundary stays in the rows) + +so the sum of a column's coverages is **exactly** the column average of the boundary +height, whatever the boundary's slope or curvature. The identity is the one volume-of-fluid +interface reconstruction rests on (E. G. Puckett (2010), CAMCoS 5(1), eq. (11)) and the +"partial area effect" edge detector of A. Trujillo-Pino et al. (2013), Image and Vision +Computing 31(1); here it is derived from Lebesgue measure for every continuous graph and any +number of rows, and machine-checked. + +Conventions: pixel `(i, j)` is the open square `(i, i+1) × (j, j+1)`; its centre is +`(i + ½, j + ½)`. (inkvec's code puts pixel centres on integers; shift by ½.) +-/ + +namespace Inkvec + +open Set MeasureTheory Finset + +/-- The open unit pixel whose lower-left corner is `(i, j)`. -/ +def pixel (i j : ℤ) : Set (ℝ × ℝ) := Ioo (i : ℝ) (i + 1) ×ˢ Ioo (j : ℝ) (j + 1) + +/-- **Box-filter coverage**: the Lebesgue area of `Ω` inside pixel `(i, j)`. An anti-aliased +renderer that computes exact area coverage (libart, FreeType's smooth rasteriser, font-rs, +inkvec's own `boundary_opt/band.rs`) writes this number, times the ink contrast, into the +pixel. -/ +noncomputable def coverage (Ω : Set (ℝ × ℝ)) (i j : ℤ) : ℝ := (volume (Ω ∩ pixel i j)).toReal + +/-- The region strictly below the graph of `f`. -/ +def subgraph (f : ℝ → ℝ) : Set (ℝ × ℝ) := {p | p.2 < f p.1} + +lemma subgraph_inter_pixel (f : ℝ → ℝ) (i j : ℤ) : + subgraph f ∩ pixel i j = + regionBetween (fun _ => (j : ℝ)) (fun x => j + clamp01 (f x - j)) (Ioo (i : ℝ) (i + 1)) := by + ext ⟨x, y⟩ + simp only [subgraph, pixel, regionBetween, Set.mem_inter_iff, Set.mem_ofPred_eq, Set.mem_prod, Set.mem_Ioo, + clamp01] + constructor + · rintro ⟨hy, ⟨hx0, hx1⟩, hy0, hy1⟩ + refine ⟨⟨hx0, hx1⟩, hy0, ?_⟩ + have : y - j < min 1 (max 0 (f x - j)) := + lt_min (by linarith) (lt_max_of_lt_right (by linarith)) + linarith + · rintro ⟨⟨hx0, hx1⟩, hy0, hy⟩ + have h' : y - j < min 1 (max 0 (f x - j)) := by linarith + rcases lt_min_iff.mp h' with ⟨h1, h2⟩ + rcases lt_max_iff.mp h2 with h3 | h3 + · exact absurd h3 (by linarith) + · exact ⟨by linarith, ⟨hx0, hx1⟩, hy0, by linarith⟩ + +/-- **Coverage of a graph boundary.** The area of the subgraph of a continuous `f` inside +pixel `(i, j)` is the integral over the pixel's column of the unit clamp of the boundary's +height above the pixel's bottom. -/ +theorem coverage_subgraph (f : ℝ → ℝ) (hf : Continuous f) (i j : ℤ) : + coverage (subgraph f) i j = ∫ x in (i : ℝ)..(i + 1), clamp01 (f x - j) := by + have hg : Continuous fun x => clamp01 (f x - j) := + continuous_clamp01.comp (hf.sub continuous_const) + have hle : (i : ℝ) ≤ i + 1 := by linarith + have hint : IntegrableOn (fun x => (j : ℝ) + clamp01 (f x - j)) (Ioo (i : ℝ) (i + 1)) := + ((continuous_const.add hg).integrableOn_Icc).mono_set Ioo_subset_Icc_self + unfold coverage + rw [subgraph_inter_pixel, Measure.volume_eq_prod, + volume_regionBetween_eq_integral (integrableOn_const (by simp) (by simp)) hint measurableSet_Ioo + (fun x _ => le_add_of_nonneg_right (clamp01_nonneg _))] + have hfun : ((fun x => (j : ℝ) + clamp01 (f x - j)) - fun _ => (j : ℝ)) = + fun x => clamp01 (f x - j) := by + funext x; simp + rw [hfun, ENNReal.toReal_ofReal (setIntegral_nonneg measurableSet_Ioo + (fun x _ => clamp01_nonneg _)), + intervalIntegral.integral_of_le hle, integral_Ioc_eq_integral_Ioo] + +/-- Each coverage is a genuine fraction. -/ +lemma coverage_subgraph_mem (f : ℝ → ℝ) (hf : Continuous f) (i j : ℤ) : + 0 ≤ coverage (subgraph f) i j ∧ coverage (subgraph f) i j ≤ 1 := by + have hg : Continuous fun x => clamp01 (f x - j) := + continuous_clamp01.comp (hf.sub continuous_const) + have hle : (i : ℝ) ≤ i + 1 := by linarith + rw [coverage_subgraph f hf] + constructor + · exact intervalIntegral.integral_nonneg hle (fun x _ => clamp01_nonneg _) + · calc ∫ x in (i : ℝ)..(i + 1), clamp01 (f x - j) + ≤ ∫ _ in (i : ℝ)..(i + 1), (1 : ℝ) := + intervalIntegral.integral_mono_on hle (hg.intervalIntegrable _ _) + intervalIntegrable_const (fun x _ => clamp01_le_one _) + _ = 1 := by simp + +/-- A column of `n` pixels stacked from row `j₀` holds the integral of the boundary's height +above `j₀`, clamped to the column's height `n`. -/ +theorem column_sum (f : ℝ → ℝ) (hf : Continuous f) (i j₀ : ℤ) (n : ℕ) : + ∑ k ∈ range n, coverage (subgraph f) i (j₀ + k) = + ∫ x in (i : ℝ)..(i + 1), (ramp (f x - j₀) - ramp (f x - j₀ - n)) := by + have hc : ∀ k ∈ range n, IntervalIntegrable (fun x => clamp01 (f x - ((j₀ + k : ℤ) : ℝ))) + volume (i : ℝ) (i + 1) := fun k _ => + (continuous_clamp01.comp (hf.sub continuous_const)).intervalIntegrable _ _ + simp_rw [coverage_subgraph f hf] + rw [← intervalIntegral.integral_finsetSum hc] + congr 1; funext x + have := sum_clamp01 (f x - j₀) n + simp only [Int.cast_add, Int.cast_natCast] + rw [← this] + refine sum_congr rfl (fun k _ => ?_) + congr 1; ring + +/-- **Column-sum theorem (exact strip average).** If the boundary stays within rows +`j₀ … j₀ + n` over column `i`, the column's coverages sum to the column average of the +boundary height above `j₀`. No slope, curvature or normal direction enters. -/ +theorem column_sum_eq_average (f : ℝ → ℝ) (hf : Continuous f) (i j₀ : ℤ) (n : ℕ) + (hlo : ∀ x ∈ Icc (i : ℝ) (i + 1), (j₀ : ℝ) ≤ f x) + (hhi : ∀ x ∈ Icc (i : ℝ) (i + 1), f x ≤ j₀ + n) : + ∑ k ∈ range n, coverage (subgraph f) i (j₀ + k) = (∫ x in (i : ℝ)..(i + 1), f x) - j₀ := by + have hle : (i : ℝ) ≤ i + 1 := by linarith + rw [column_sum f hf] + have hcongr : ∫ x in (i : ℝ)..(i + 1), (ramp (f x - j₀) - ramp (f x - j₀ - n)) = + ∫ x in (i : ℝ)..(i + 1), (f x - j₀) := by + refine intervalIntegral.integral_congr (fun x hx => ?_) + rw [uIcc_of_le hle] at hx + have h1 := hlo x hx; have h2 := hhi x hx + unfold ramp; rw [max_eq_right (by linarith), max_eq_left (by linarith)]; ring + rw [hcongr, intervalIntegral.integral_sub (hf.intervalIntegrable _ _) intervalIntegrable_const] + simp + +end Inkvec diff --git a/formal/InkvecTheory/InkvecTheory/Deconvolution.lean b/formal/InkvecTheory/InkvecTheory/Deconvolution.lean new file mode 100644 index 00000000..d58c2cae --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Deconvolution.lean @@ -0,0 +1,217 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import InkvecTheory.Coverage + +/-! +# From column sums to boundary points, exactly + +`column_sum_eq_average` gives each pixel column's *mean* boundary height. A mean is not a +point: for a curved boundary it is off the height at the column centre by `f''/24` plus +higher terms. The finite-volume correction + + f(c) = A(c) - (A(c+1) - 2·A(c) + A(c-1)) / 24 + +(cell averages to point values, as in high-order finite-volume schemes) removes that, and +`cubic_point_from_means` proves it is **exact for every cubic**, not merely fourth-order +accurate. `quartic_defect` pins the first term it misses: `-3/640 · f''''`. + +`boundary_point_from_pixels` chains it with the column-sum theorem: from the raw pixel areas +of three adjacent columns, the boundary height at the middle column's centre, exact for any +cubic boundary and with no normal direction, threshold or iteration involved. The correction +is the fourth-order finite-volume one (McCorquodale & Colella 2011) and Trujillo-Pino et al.'s +(2013) centre coefficient; what this file adds is the machine-checked chain from pixel areas +to the point, and to the constants of `strip.rs`. +-/ + +namespace Inkvec + +open Set MeasureTheory Finset + +/-- A cubic, written out. -/ +def cubic (c₀ c₁ c₂ c₃ : ℝ) (x : ℝ) : ℝ := c₀ + c₁ * x + c₂ * x ^ 2 + c₃ * x ^ 3 + +/-- Its antiderivative. -/ +noncomputable def cubicPrim (c₀ c₁ c₂ c₃ : ℝ) (x : ℝ) : ℝ := + c₀ * x + c₁ * x ^ 2 / 2 + c₂ * x ^ 3 / 3 + c₃ * x ^ 4 / 4 + +lemma continuous_cubic (c₀ c₁ c₂ c₃ : ℝ) : Continuous (cubic c₀ c₁ c₂ c₃) := by + unfold cubic; fun_prop + +lemma hasDerivAt_cubicPrim (c₀ c₁ c₂ c₃ x : ℝ) : + HasDerivAt (cubicPrim c₀ c₁ c₂ c₃) (cubic c₀ c₁ c₂ c₃ x) x := by + have h := ((((hasDerivAt_id x).const_mul c₀).add + (((hasDerivAt_pow 2 x).const_mul c₁).div_const 2)).add + (((hasDerivAt_pow 3 x).const_mul c₂).div_const 3)).add + (((hasDerivAt_pow 4 x).const_mul c₃).div_const 4) + unfold cubicPrim cubic + convert h using 1 + · funext y; simp + · simp; ring + +lemma integral_cubic (c₀ c₁ c₂ c₃ a b : ℝ) : + ∫ x in a..b, cubic c₀ c₁ c₂ c₃ x = cubicPrim c₀ c₁ c₂ c₃ b - cubicPrim c₀ c₁ c₂ c₃ a := + intervalIntegral.integral_eq_sub_of_hasDerivAt (fun x _ => hasDerivAt_cubicPrim c₀ c₁ c₂ c₃ x) + ((continuous_cubic c₀ c₁ c₂ c₃).intervalIntegrable _ _) + +/-- The mean of `f` over the unit cell centred at `c`. -/ +noncomputable def cellMean (f : ℝ → ℝ) (c : ℝ) : ℝ := ∫ x in (c - 1 / 2)..(c + 1 / 2), f x + +/-- The cell-mean-to-point correction. -/ +noncomputable def pointFromMeans (Aₗ A Aᵣ : ℝ) : ℝ := A - (Aᵣ - 2 * A + Aₗ) / 24 + +/-- **Exact for cubics.** The cell-mean-to-point correction returns the value at the centre of +any cubic, at any centre. -/ +theorem cubic_point_from_means (c₀ c₁ c₂ c₃ c : ℝ) : + pointFromMeans (cellMean (cubic c₀ c₁ c₂ c₃) (c - 1)) (cellMean (cubic c₀ c₁ c₂ c₃) c) + (cellMean (cubic c₀ c₁ c₂ c₃) (c + 1)) = cubic c₀ c₁ c₂ c₃ c := by + unfold pointFromMeans cellMean + rw [integral_cubic, integral_cubic, integral_cubic] + unfold cubicPrim cubic + ring + +/-- The plain cell mean is off by the curvature: `f''(c)/24` for a cubic. -/ +theorem cubic_mean_bias (c₀ c₁ c₂ c₃ c : ℝ) : + cellMean (cubic c₀ c₁ c₂ c₃) c - cubic c₀ c₁ c₂ c₃ c = (2 * c₂ + 6 * c₃ * c) / 24 := by + unfold cellMean + rw [integral_cubic] + unfold cubicPrim cubic + ring + +/-- **The first term the correction misses.** For `x⁴` (fourth derivative 24) at centre 0 +the correction is off by `-9/80 = -(3/640)·24`: the method's error constant is `3/640` +times the fourth derivative, about `0.0047 · f''''`. -/ +theorem quartic_defect : + pointFromMeans (cellMean (fun x => x ^ 4) (-1)) (cellMean (fun x => x ^ 4) 0) + (cellMean (fun x => x ^ 4) 1) - (0 : ℝ) ^ 4 = -(3 / 640) * 24 := by + unfold pointFromMeans cellMean + simp only [integral_pow] + norm_num + +/-- **Boundary point from raw pixel areas.** Let a cubic boundary stay within rows +`j₀ … j₀+m` over columns `i-1, i, i+1`, and let `Sₖ` be the sum of the box-filter coverages +of column `k` over those rows. Then the boundary passes through +`(i + ½, j₀ + Sᵢ - (Sᵢ₊₁ - 2·Sᵢ + Sᵢ₋₁)/24)`, exactly. -/ +theorem boundary_point_from_pixels (c₀ c₁ c₂ c₃ : ℝ) (i j₀ : ℤ) (m : ℕ) + (hlo : ∀ x ∈ Icc ((i : ℝ) - 1) (i + 2), (j₀ : ℝ) ≤ cubic c₀ c₁ c₂ c₃ x) + (hhi : ∀ x ∈ Icc ((i : ℝ) - 1) (i + 2), cubic c₀ c₁ c₂ c₃ x ≤ j₀ + m) : + let S := fun k : ℤ => ∑ r ∈ range m, coverage (subgraph (cubic c₀ c₁ c₂ c₃)) k (j₀ + r) + cubic c₀ c₁ c₂ c₃ (i + 1 / 2) = j₀ + pointFromMeans (S (i - 1)) (S i) (S (i + 1)) := by + intro S + have hc := continuous_cubic c₀ c₁ c₂ c₃ + have hS : ∀ k : ℤ, (i : ℝ) - 1 ≤ k → (k : ℝ) + 1 ≤ i + 2 → + S k = cellMean (cubic c₀ c₁ c₂ c₃) (k + 1 / 2) - j₀ := by + intro k hk1 hk2 + have := column_sum_eq_average _ hc k j₀ m + (fun x hx => hlo x ⟨by linarith [hx.1], by linarith [hx.2]⟩) + (fun x hx => hhi x ⟨by linarith [hx.1], by linarith [hx.2]⟩) + unfold cellMean + rw [show (k : ℝ) + 1 / 2 - 1 / 2 = k by ring, show (k : ℝ) + 1 / 2 + 1 / 2 = k + 1 by ring] + exact this + rw [hS (i - 1) (by push_cast; linarith) (by push_cast; linarith), + hS i (by linarith) (by linarith), hS (i + 1) (by push_cast; linarith) (by push_cast; linarith)] + have key := cubic_point_from_means c₀ c₁ c₂ c₃ ((i : ℝ) + 1 / 2) + push_cast + rw [show (i : ℝ) - 1 + 1 / 2 = (i : ℝ) + 1 / 2 - 1 by ring, + show (i : ℝ) + 1 + 1 / 2 = (i : ℝ) + 1 / 2 + 1 by ring] + unfold pointFromMeans at key ⊢ + linarith + +end Inkvec + +/-! ### The constants of `crates/inkvec-trace/src/planar/strip.rs` -/ + +namespace Inkvec + +/-- `strip.rs`'s `histopolate`: the cubic coefficients from the means over the cells +`[-2,-1]`, `[-1,0]`, `[0,1]`, `[1,2]`, with the code's rational constants. -/ +noncomputable def histopolate (m₀ m₁ m₂ m₃ : ℝ) : ℝ × ℝ × ℝ × ℝ := + ((-m₀ + 7 * m₁ + 7 * m₂ - m₃) / 12, + (m₀ - 15 * m₁ + 15 * m₂ - m₃) / 12, + (m₀ - m₁ - m₂ + m₃) / 4, + (-m₀ + 3 * m₁ - 3 * m₂ + m₃) / 6) + +/-- The mean of `f` over the unit cell `[k, k+1]`. -/ +noncomputable def cellMean' (f : ℝ → ℝ) (k : ℝ) : ℝ := ∫ x in k..(k + 1), f x + +/-- **`strip.rs`'s constants are exact.** Fed the four cell means of any cubic, `histopolate` +returns that cubic's coefficients. With `poly_eq_of_averages` this is the whole correctness +argument of the strip reading on a cubic boundary: the column sums are the cell means +(`column_sum_eq_average`), and the cubic rebuilt from them is the boundary. -/ +theorem histopolate_cubic (c₀ c₁ c₂ c₃ : ℝ) : + histopolate (cellMean' (cubic c₀ c₁ c₂ c₃) (-2)) (cellMean' (cubic c₀ c₁ c₂ c₃) (-1)) + (cellMean' (cubic c₀ c₁ c₂ c₃) 0) (cellMean' (cubic c₀ c₁ c₂ c₃) 1) = (c₀, c₁, c₂, c₃) := by + unfold histopolate cellMean' + simp only [integral_cubic] + unfold cubicPrim + refine Prod.ext ?_ (Prod.ext ?_ (Prod.ext ?_ ?_)) <;> simp <;> ring + +/-- The constant term alone is the classical fourth-order face value +`(7(m₁ + m₂) - (m₀ + m₃))/12`: the boundary's height at the pixel border between the two +middle cells. -/ +theorem face_value_cubic (c₀ c₁ c₂ c₃ : ℝ) : + (7 * (cellMean' (cubic c₀ c₁ c₂ c₃) (-1) + cellMean' (cubic c₀ c₁ c₂ c₃) 0) - + (cellMean' (cubic c₀ c₁ c₂ c₃) (-2) + cellMean' (cubic c₀ c₁ c₂ c₃) 1)) / 12 = + cubic c₀ c₁ c₂ c₃ 0 := by + unfold cellMean' + simp only [integral_cubic] + unfold cubicPrim cubic + ring + +/-- The one-sided stencils of `strip.rs`'s corner test agree with the central one on every +cubic: the cubic histopolated from cells `[-3,-2] … [0,1]`, read one cell to the right of its +own origin, is the same cubic's value at `0`. (The right-hand stencil is the mirror image.) -/ +theorem side_stencil_cubic (c₀ c₁ c₂ c₃ : ℝ) : + let h := histopolate (cellMean' (cubic c₀ c₁ c₂ c₃) (-3)) + (cellMean' (cubic c₀ c₁ c₂ c₃) (-2)) (cellMean' (cubic c₀ c₁ c₂ c₃) (-1)) + (cellMean' (cubic c₀ c₁ c₂ c₃) 0) + cubic h.1 h.2.1 h.2.2.1 h.2.2.2 1 = cubic c₀ c₁ c₂ c₃ 0 := by + intro h + simp only [h, histopolate, cellMean', integral_cubic] + unfold cubicPrim cubic + ring + +end Inkvec + +namespace Inkvec + +open Set MeasureTheory Finset + +/-- **The strip reading is exact, end to end.** Let a cubic boundary, written in coordinates +local to the pixel border `x = X₀` as `y = cubic c₀ c₁ c₂ c₃ (x - X₀)`, stay within rows +`j₀ … j₀+m` over the four columns `X₀-2 … X₀+1`. Sum each column's box-filter coverages over +those rows, add back `j₀`, and feed the four results to `strip.rs`'s `histopolate`: out come +the boundary's own coefficients. The vertex `strip.rs` then slides onto this cubic is on the +boundary. -/ +theorem strip_reading_exact (c₀ c₁ c₂ c₃ : ℝ) (X₀ j₀ : ℤ) (m : ℕ) + (hlo : ∀ x ∈ Icc ((X₀ : ℝ) - 2) (X₀ + 2), (j₀ : ℝ) ≤ cubic c₀ c₁ c₂ c₃ (x - X₀)) + (hhi : ∀ x ∈ Icc ((X₀ : ℝ) - 2) (X₀ + 2), cubic c₀ c₁ c₂ c₃ (x - X₀) ≤ j₀ + m) : + let S := fun k : ℤ => + (j₀ : ℝ) + ∑ r ∈ range m, coverage (subgraph fun x => cubic c₀ c₁ c₂ c₃ (x - X₀)) (X₀ + k) (j₀ + r) + histopolate (S (-2)) (S (-1)) (S 0) (S 1) = (c₀, c₁, c₂, c₃) := by + intro S + have hc : Continuous fun x => cubic c₀ c₁ c₂ c₃ (x - X₀) := + (continuous_cubic c₀ c₁ c₂ c₃).comp (continuous_id.sub continuous_const) + have hS : ∀ k : ℤ, -2 ≤ k → k ≤ 1 → S k = cellMean' (cubic c₀ c₁ c₂ c₃) k := by + intro k hk1 hk2 + have hk1' : (-2 : ℝ) ≤ k := by exact_mod_cast hk1 + have hk2' : (k : ℝ) ≤ 1 := by exact_mod_cast hk2 + have h := column_sum_eq_average _ hc (X₀ + k) j₀ m + (fun x hx => hlo x ⟨by push_cast at hx; linarith [hx.1], by push_cast at hx; linarith [hx.2]⟩) + (fun x hx => hhi x ⟨by push_cast at hx; linarith [hx.1], by push_cast at hx; linarith [hx.2]⟩) + show (j₀ : ℝ) + _ = _ + rw [h] + unfold cellMean' + have hsub := intervalIntegral.integral_comp_sub_right (cubic c₀ c₁ c₂ c₃) + (a := ((X₀ + k : ℤ) : ℝ)) (b := ((X₀ + k : ℤ) : ℝ) + 1) (X₀ : ℝ) + rw [hsub] + push_cast + rw [show (X₀ : ℝ) + k - X₀ = k by ring, show (X₀ : ℝ) + k + 1 - X₀ = k + 1 by ring] + ring + rw [hS (-2) (by norm_num) (by norm_num), hS (-1) (by norm_num) (by norm_num), + hS 0 (by norm_num) (by norm_num), hS 1 (by norm_num) (by norm_num)] + have := histopolate_cubic c₀ c₁ c₂ c₃ + push_cast at this ⊢ + exact this + +end Inkvec diff --git a/formal/InkvecTheory/InkvecTheory/Design/Layers.lean b/formal/InkvecTheory/InkvecTheory/Design/Layers.lean new file mode 100644 index 00000000..7719c7b0 --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Design/Layers.lean @@ -0,0 +1,185 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import Mathlib.Data.Set.Lattice.Disjoint +import Mathlib.Data.Set.Lattice.Indexed +import Mathlib.Order.Interval.Finset.Nat +import Mathlib.Tactic + +/-! +# Layers: the painter's interval + +`docs/theory/chain-representation.md`, R4.1 and R4.1b; the code is +`crates/inkvec-cli/src/layers.rs`. + +Elements `E 0, …, E (m-1)` (regions of the plane) are painted in that order, each over the +ones before it. Element `i` *shows* what it covers and nothing painted later covers: +`shows E m i = E i \ above E m i`. A planar map gives each face a visible region `V i`, +pairwise disjoint. Which shapes `E` paint exactly those regions? + +* `painter_interval_iff`: element `i` shows `V i` for every `i` exactly when + `V i ⊆ E i ⊆ V i ∪ above V m i` for every `i`. The condition on `E i` names no other + element's shape, only the data `V`: given the paint order, each face is completed on its + own, and any shape in its interval paints the same picture. +* `above_eq_of_interval`: under those conditions, what the elements above `i` cover is + what the faces above `i` show. + +The compositing identities of R4.1b, for one pixel with exact area coverages: + +* `seam_of_exact_outline`: a lower face drawn exactly to its visible region, under an upper + face of coverage `a`, lets the ground show with weight `a (1 − a)`: the seam. +* `no_seam_of_completion`: completed across the pixel, the lower face shows exactly its + share; and `junction_residue`: where the pixel also holds ground area `b` (a junction of + three paints) the residue is `a·b·(c_i − c_bg)`. + +Holes cut, not painted over (R4.6b; `crates/inkvec-cli/src/emit/holes.rs`): + +* `cut_hole`: a face painted over its parent in the colour already under the parent paints + what the parent with the face cut out of it paints; `cut_hole_pixel`: so does an edge + pixel, with area coverages. +-/ + +namespace Inkvec.Design + +open Set + +variable {α : Type*} + +/-- What the elements painted after `i` (and before `m`) cover. -/ +def above (E : ℕ → Set α) (m i : ℕ) : Set α := ⋃ j ∈ Finset.Ioo i m, E j + +/-- What element `i` shows when `E 0, …, E (m - 1)` are painted in that order. -/ +def shows (E : ℕ → Set α) (m i : ℕ) : Set α := E i \ above E m i + +theorem mem_above {E : ℕ → Set α} {m i : ℕ} {x : α} : + x ∈ above E m i ↔ ∃ j, i < j ∧ j < m ∧ x ∈ E j := by + simp [above, Finset.mem_Ioo, and_assoc] + +/-- Under the interval conditions, the elements above `i` cover what the faces above `i` +show. -/ +theorem above_eq_of_interval {V E : ℕ → Set α} {m : ℕ} + (h : ∀ j < m, V j ⊆ E j ∧ E j ⊆ V j ∪ above V m j) (i : ℕ) : + above E m i = above V m i := by + ext x + simp only [mem_above] + constructor + · rintro ⟨j, hij, hjm, hx⟩ + rcases (h j hjm).2 hx with hv | hu + · exact ⟨j, hij, hjm, hv⟩ + · obtain ⟨k, hjk, hkm, hk⟩ := mem_above.mp hu + exact ⟨k, hij.trans hjk, hkm, hk⟩ + · rintro ⟨j, hij, hjm, hx⟩ + exact ⟨j, hij, hjm, (h j hjm).1 hx⟩ + +/-- **The painter's interval.** With pairwise disjoint visible regions `V`, every element +shows exactly its face's region if and only if each lies between that region and that +region together with what the faces above it show. -/ +theorem painter_interval_iff {V E : ℕ → Set α} {m : ℕ} + (hV : ∀ i j, i ≠ j → Disjoint (V i) (V j)) : + (∀ i < m, shows E m i = V i) ↔ (∀ i < m, V i ⊆ E i ∧ E i ⊆ V i ∪ above V m i) := by + constructor + · intro hs i him + refine ⟨fun x hx => ?_, fun x hx => ?_⟩ + · rw [← hs i him] at hx + exact hx.1 + · classical + -- The last element at or above `i` that covers `x` shows it. + let S := (Finset.Ico i m).filter (fun j => x ∈ E j) + have hS : S.Nonempty := ⟨i, Finset.mem_filter.mpr ⟨Finset.mem_Ico.mpr ⟨le_rfl, him⟩, hx⟩⟩ + obtain ⟨j, hjS, hjmax⟩ : ∃ j ∈ S, ∀ k ∈ S, k ≤ j := + ⟨S.max' hS, S.max'_mem hS, fun k hk => S.le_max' k hk⟩ + obtain ⟨hjr, hxj⟩ := Finset.mem_filter.mp hjS + obtain ⟨hij, hjm⟩ := Finset.mem_Ico.mp hjr + have hshow : x ∈ shows E m j := by + refine ⟨hxj, fun ha => ?_⟩ + obtain ⟨k, hjk, hkm, hk⟩ := mem_above.mp ha + have hkS : k ∈ S := + Finset.mem_filter.mpr ⟨Finset.mem_Ico.mpr ⟨hij.trans hjk.le, hkm⟩, hk⟩ + exact absurd (hjmax k hkS) (not_le.mpr hjk) + rw [hs j hjm] at hshow + rcases eq_or_lt_of_le hij with heq | hlt + · rw [← heq] at hshow + exact Or.inl hshow + · exact Or.inr (mem_above.mpr ⟨j, hlt, hjm, hshow⟩) + · intro h i him + rw [shows, above_eq_of_interval h i] + ext x + constructor + · rintro ⟨hx, hna⟩ + rcases (h i him).2 hx with hv | hu + · exact hv + · exact absurd hu hna + · intro hx + refine ⟨(h i him).1 hx, fun ha => ?_⟩ + obtain ⟨j, hij, _, hj⟩ := mem_above.mp ha + exact Set.disjoint_left.mp (hV i j hij.ne) hx hj + +/-- **Each face on its own.** Given the order, whether element `i` is acceptable depends on +`E i` and the data `V` alone: replacing `E i` by any `E'` in the same interval keeps every +element showing its region. -/ +theorem replace_in_interval {V E : ℕ → Set α} {m : ℕ} + (hV : ∀ i j, i ≠ j → Disjoint (V i) (V j)) + (h : ∀ i < m, shows E m i = V i) (k : ℕ) (E' : Set α) + (hlo : V k ⊆ E') (hhi : E' ⊆ V k ∪ above V m k) : + ∀ i < m, shows (Function.update E k E') m i = V i := by + rw [painter_interval_iff hV] at h ⊢ + intro i him + by_cases hik : i = k + · subst hik + simpa using And.intro hlo hhi + · simpa [Function.update_of_ne hik] using h i him + +/-! ### One pixel: the compositing of R4.1b + +`a` is the upper face's area coverage of the pixel, `c_j` its colour; `c_i` the lower +face's, `c_bg` the ground's. "Over" compositing paints the lower face with its own coverage +first, then the upper one. -/ + +/-- The lower face drawn to its visible region exactly (coverage `1 − a`) leaves the ground +showing with weight `a (1 − a)`. -/ +theorem seam_of_exact_outline (a ci cj cbg : ℝ) : + (a * cj + (1 - a) * ((1 - a) * ci + a * cbg)) - (a * cj + (1 - a) * ci) = + a * (1 - a) * (cbg - ci) := by + ring + +/-- Completed across the pixel (coverage 1) the lower face shows exactly its share. -/ +theorem no_seam_of_completion (a ci cj cbg : ℝ) : + (a * cj + (1 - a) * (1 * ci + 0 * cbg)) - (a * cj + (1 - a) * ci) = 0 := by + ring + +/-- With ground area `b` in the pixel too (a junction of three paints), the completed face +covers `1 − b` and the residue is `a · b · (c_i − c_bg)`. -/ +theorem junction_residue (a b ci cj cbg : ℝ) : + (a * cj + (1 - a) * ((1 - b) * ci + b * cbg)) - (a * cj + (1 - a - b) * ci + b * cbg) = + a * b * (ci - cbg) := by + ring + +/-! ### Holes cut, not painted over (R4.6b) + +The code is `crates/inkvec-cli/src/emit/holes.rs`. A picture is a colour per point; +`paintOver b R c` paints region `R` in colour `c` over the picture `b`. -/ + +open Classical in +/-- Region `R` painted in colour `c` over the picture `b`. -/ +noncomputable def paintOver {κ : Type*} (b : α → κ) (R : Set α) (c : κ) : α → κ := + fun x => if x ∈ R then c else b x + +/-- **A hole cut.** Painting `P` and then `C` in colour `k` over it paints the same picture as +`P` with `C` cut out, wherever the picture under `P` is already `k` across `C`: the +counter of a glyph in the colour of the page it sits on. -/ +theorem cut_hole {κ : Type*} (b : α → κ) (P C : Set α) (cp k : κ) + (hb : ∀ x ∈ C, b x = k) : + paintOver (paintOver b P cp) C k = paintOver b (P \ C) cp := by + funext x + by_cases hx : x ∈ C + · simp [paintOver, hx, hb x hx] + · by_cases hp : x ∈ P <;> simp [paintOver, hx, hp] + +/-- The same at an edge pixel with area coverages: `P` covering the pixel and `C` a share +`a` of it, over ground `k`, composite as `P` covering `1 − a` with the ground showing in +the rest. -/ +theorem cut_hole_pixel (a cp k : ℝ) : + a * k + (1 - a) * (1 * cp + 0 * k) = (1 - a) * cp + (1 - (1 - a)) * k := by + ring + +end Inkvec.Design diff --git a/formal/InkvecTheory/InkvecTheory/Design/Noise.lean b/formal/InkvecTheory/InkvecTheory/Design/Noise.lean new file mode 100644 index 00000000..e2535eb3 --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Design/Noise.lean @@ -0,0 +1,105 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import Mathlib.Analysis.SpecialFunctions.Log.Basic +import Mathlib.Tactic + +/-! +# Noise and constraints: a constraint accepted on clean input stays accepted on noisier input + +`docs/theory/chain-representation.md`, R0.4 (noise). A description `M₀` (a tie, a snap to the +design grid, a dropped coordinate) is nested in `M₁`, which has `k` more free coordinates. +With the free coordinates integrated out (Laplace), the log posterior odds of `M₀` over `M₁` +at noise scale `σ` are + + `logOdds k Δ a c σ = c − Δ / (2σ²) + k · log (a / σ)`, + +where `Δ ≥ 0` is the misfit the constraint costs (in px², the drop in the residual sum of +squares `M₁` buys), `k · log (a / σ)` the Occam factor of the `k` coordinates (`a / σ` is the +ratio of a coordinate's prior width to its posterior width; `a = W / (√(2π) g)` for a range +`W` and a geometry factor `g`), and `c` the log prior odds of the constraint (the design prior). + +* `accept_monotone`: for a fixed misfit `Δ`, if the constraint is accepted at `σ₁` it is + accepted at every `σ₂ ≥ σ₁`, as long as at `σ₂` the coordinates still cost at least half a + nat each beyond the prior odds (`k / 2 ≤ c + k · log (a / σ₂)`, the regime in which the + Laplace approximation is meaningful). On noisy input a tie or a snap costs less fit, and + the description falls back on the design prior. +* `huber_eq_sq`: the Huber loss with threshold `κ` is the Gaussian `u² / 2` on residuals + within `κ` standard units, so on such residuals `accept_monotone` holds for it verbatim. +-/ + +namespace Inkvec.Design + +open Real + +/-- Log posterior odds of the constrained description over the free one (see the module +docs). -/ +noncomputable def logOdds (k Δ a c σ : ℝ) : ℝ := c - Δ / (2 * σ ^ 2) + k * Real.log (a / σ) + +/-- **Accepted once, accepted at more noise.** -/ +theorem accept_monotone {k Δ a c σ₁ σ₂ : ℝ} (hk : 0 ≤ k) (ha : 0 < a) + (h₁ : 0 < σ₁) (h₁₂ : σ₁ ≤ σ₂) + (hacc : 0 ≤ logOdds k Δ a c σ₁) (hreg : k / 2 ≤ c + k * Real.log (a / σ₂)) : + 0 ≤ logOdds k Δ a c σ₂ := by + have h₂ : 0 < σ₂ := lt_of_lt_of_le h₁ h₁₂ + unfold logOdds at * + by_cases hcase : k * σ₂ ^ 2 ≤ Δ + · -- The misfit is still significant at `σ₂`: the odds have only risen. + have ht : 0 < σ₂ / σ₁ := div_pos h₂ h₁ + have hlog : Real.log (a / σ₁) - Real.log (a / σ₂) ≤ ((σ₂ / σ₁) ^ 2 - 1) / 2 := by + have e : Real.log (a / σ₁) - Real.log (a / σ₂) = Real.log (σ₂ / σ₁) := by + rw [← Real.log_div (div_pos ha h₁).ne' (div_pos ha h₂).ne'] + congr 1 + field_simp + rw [e] + have hl := Real.log_le_sub_one_of_pos (pow_pos ht 2) + rw [Real.log_pow] at hl + push_cast at hl + linarith + have hsq : 0 ≤ σ₂ ^ 2 - σ₁ ^ 2 := by nlinarith + have key : k * (((σ₂ / σ₁) ^ 2 - 1) / 2) ≤ Δ / (2 * σ₁ ^ 2) - Δ / (2 * σ₂ ^ 2) := by + have e1 : Δ / (2 * σ₁ ^ 2) - Δ / (2 * σ₂ ^ 2) = + Δ * (σ₂ ^ 2 - σ₁ ^ 2) / (2 * σ₁ ^ 2 * σ₂ ^ 2) := by + field_simp + have e2 : k * (((σ₂ / σ₁) ^ 2 - 1) / 2) = + k * σ₂ ^ 2 * (σ₂ ^ 2 - σ₁ ^ 2) / (2 * σ₁ ^ 2 * σ₂ ^ 2) := by + field_simp + rw [e1, e2] + apply div_le_div_of_nonneg_right _ (by positivity) + exact mul_le_mul_of_nonneg_right hcase hsq + nlinarith [mul_le_mul_of_nonneg_left hlog hk] + · -- The misfit is within noise at `σ₂`: the prices alone carry the constraint. + push Not at hcase + have : Δ / (2 * σ₂ ^ 2) < k / 2 := by + rw [div_lt_iff₀ (by positivity)] + nlinarith + linarith + +/-- The Huber loss of a residual `u` in standard units, threshold `κ`. -/ +noncomputable def huber (κ u : ℝ) : ℝ := if |u| ≤ κ then u ^ 2 / 2 else κ * |u| - κ ^ 2 / 2 + +/-- **Huber is Gaussian on inliers**: within `κ` standard units the robust cost is the +squared one, so clean inputs (every residual within `κ`) keep their behaviour and +`accept_monotone` applies to them unchanged. -/ +theorem huber_eq_sq {κ u : ℝ} (h : |u| ≤ κ) : huber κ u = u ^ 2 / 2 := by + simp [huber, h] + +/-- An inlier at `σ₁` stays an inlier at any larger noise scale. -/ +theorem inlier_of_le {κ r σ₁ σ₂ : ℝ} (h₁ : 0 < σ₁) (h₁₂ : σ₁ ≤ σ₂) + (h : |r / σ₁| ≤ κ) : |r / σ₂| ≤ κ := by + have h₂ : 0 < σ₂ := lt_of_lt_of_le h₁ h₁₂ + rw [abs_div, abs_of_pos h₂] + rw [abs_div, abs_of_pos h₁, div_le_iff₀ h₁] at h + rw [div_le_iff₀ h₂] + have hκ : 0 ≤ κ := by nlinarith [abs_nonneg r] + nlinarith [mul_le_mul_of_nonneg_left h₁₂ hκ] + +/-- The Huber loss never exceeds the Gaussian one: an outlier costs less evidence. -/ +theorem huber_le_sq (κ u : ℝ) : huber κ u ≤ u ^ 2 / 2 := by + unfold huber + split_ifs with h + · exact le_rfl + · push Not at h + nlinarith [abs_nonneg u, sq_abs u] + +end Inkvec.Design diff --git a/formal/InkvecTheory/InkvecTheory/Gen/Design.lean b/formal/InkvecTheory/InkvecTheory/Gen/Design.lean new file mode 100644 index 00000000..8d89b578 --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Gen/Design.lean @@ -0,0 +1,113 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import InkvecTheory.Gen.Rust +import InkvecTheory.Design.Layers + +/-! +# The representation chain's kernels (`crates/inkvec-cli/src/layers/check.rs`) + +The painter's interval (`InkvecTheory.Design.Layers.painter_interval_iff`) is checked on scan +lines: on each line, every span of the lower region must lie in a span of the completed +shape, and every span of the shape in a span of the upper region, within a slack `s`. The +solver (the layers stage) computes the spans and proposes, for each span, the span that +covers it: the certificate. The checker decides each pair with `spanWithinK`. + +* `spanWithinK`: for `x = [a₀, a₁, b₀, b₁, s]`, the outputs `a₀ − b₀ + s` and + `b₁ − a₁ + s`. `spanWithinK_eq` says what they are; `spanWithin_meaning`: both + non-negative means `[a₀, a₁] ⊆ [b₀ − s, b₁ + s]`. +* `spanLinkK`: for `x = [p₁, q₀, s]`, the output `p₁ − q₀ + 2s`: non-negative exactly when + a span ending at `p₁` and the next starting at `q₀`, each widened by `s`, touch. Two + regions computed from different polygons can leave a crack of a thousandth of a pixel + between spans that meet; a chain of linked spans covers what lies between its ends + (`chain_cover`). +* `line_cover`: the fold the checker performs over one line's spans. If every span of a + list is certified within a chain of linked spans of another (`span_within` against the + chain's first start and last end, `span_link` between neighbours), the union of the first + lies within the union of the second, each widened by `s`. +-/ + +namespace Inkvec.Gen + +open Inkvec.Gen.Expr + +/-- `[a₀ − b₀ + s, b₁ − a₁ + s]` over `x = [a₀, a₁, b₀, b₁, s]`. -/ +def spanWithinOuts : List Expr := + [add (sub (var 0) (var 2)) (var 4), add (sub (var 3) (var 1)) (var 4)] + +def spanWithinK : Kernel where + name := "span_within" + doc := "For `x = [a₀, a₁, b₀, b₁, s]`: `[a₀ − b₀ + s, b₁ − a₁ + s]`, both non-negative \ + exactly when the span `[a₀, a₁]` lies in `[b₀ − s, b₁ + s]` (`spanWithin_meaning`); \ + the per-span check of the painter's interval (`painter_interval_iff`)." + arity := 5 + outs := spanWithinOuts + +/-- The kernel's outputs. -/ +theorem spanWithinK_eq (x : ℕ → ℝ) : + spanWithinK.outs.map (evalR x) = [x 0 - x 2 + x 4, x 3 - x 1 + x 4] := by + simp [spanWithinK, spanWithinOuts, evalR] + +/-- **What the checker certifies for one span.** -/ +theorem spanWithin_meaning (a₀ a₁ b₀ b₁ s : ℝ) (h₀ : 0 ≤ a₀ - b₀ + s) (h₁ : 0 ≤ b₁ - a₁ + s) : + Set.Icc a₀ a₁ ⊆ Set.Icc (b₀ - s) (b₁ + s) := by + intro y hy + exact ⟨by linarith [hy.1], by linarith [hy.2]⟩ + +/-- `p₁ − q₀ + 2s` over `x = [p₁, q₀, s]`. -/ +def spanLinkOuts : List Expr := + [add (sub (var 0) (var 1)) (add (var 2) (var 2))] + +def spanLinkK : Kernel where + name := "span_link" + doc := "For `x = [p₁, q₀, s]`: `p₁ − q₀ + 2s`, non-negative exactly when a span ending at \ + `p₁` and the next one starting at `q₀`, each widened by `s`, touch (`chain_cover`)." + arity := 3 + outs := spanLinkOuts + +/-- The kernel's output. -/ +theorem spanLinkK_eq (x : ℕ → ℝ) : + spanLinkK.outs.map (evalR x) = [x 0 - x 1 + (x 2 + x 2)] := by + simp [spanLinkK, spanLinkOuts, evalR] + +/-- Consecutive spans of a chain, each widened by `s`, touch. -/ +def Linked (s : ℝ) : List (ℝ × ℝ) → Prop + | b :: c :: cs => 0 ≤ b.2 - c.1 + (s + s) ∧ Linked s (c :: cs) + | _ => True + +/-- The end of a chain's last span. -/ +def lastHi : ℝ × ℝ → List (ℝ × ℝ) → ℝ + | b, [] => b.2 + | _, c :: cs => lastHi c cs + +/-- **A chain of linked spans covers what lies between its ends.** -/ +theorem chain_cover (s y : ℝ) : ∀ (b : ℝ × ℝ) (bs : List (ℝ × ℝ)), + Linked s (b :: bs) → b.1 - s ≤ y → y ≤ lastHi b bs + s → + ∃ c ∈ b :: bs, c.1 - s ≤ y ∧ y ≤ c.2 + s + | b, [], _, h₀, h₁ => ⟨b, List.mem_singleton_self _, h₀, h₁⟩ + | b, c :: cs, hl, h₀, h₁ => by + by_cases hy : y ≤ b.2 + s + · exact ⟨b, List.mem_cons_self .., h₀, hy⟩ + · obtain ⟨hbc, hcs⟩ := hl + obtain ⟨d, hd, hd'⟩ := chain_cover s y c cs hcs (by linarith) h₁ + exact ⟨d, List.mem_cons_of_mem _ hd, hd'⟩ + +/-- **One scan line.** If each span of `A` is certified within a chain of linked spans of +`B` (`span_within` against the chain's first start and last end, `span_link` between +neighbours), the union of `A`'s spans lies in the union of `B`'s, each widened by `s`. -/ +theorem line_cover (A B : List (ℝ × ℝ)) (s : ℝ) + (h : ∀ a ∈ A, ∃ b bs, (∀ c ∈ b :: bs, c ∈ B) ∧ Linked s (b :: bs) ∧ + 0 ≤ a.1 - b.1 + s ∧ 0 ≤ lastHi b bs - a.2 + s) : + (⋃ a ∈ A, Set.Icc a.1 a.2) ⊆ ⋃ b ∈ B, Set.Icc (b.1 - s) (b.2 + s) := by + intro y hy + simp only [Set.mem_iUnion] at hy ⊢ + obtain ⟨a, ha, hya⟩ := hy + obtain ⟨b, bs, hmem, hl, h₀, h₁⟩ := h a ha + obtain ⟨c, hc, hc'⟩ := + chain_cover s y b bs hl (by linarith [hya.1]) (by linarith [hya.2]) + exact ⟨c, hmem c hc, hc'⟩ + +/-- The kernels of `generated/design.rs`. -/ +def designKernels : List Kernel := [spanWithinK, spanLinkK] + +end Inkvec.Gen diff --git a/formal/InkvecTheory/InkvecTheory/Gen/Emit.lean b/formal/InkvecTheory/InkvecTheory/Gen/Emit.lean new file mode 100644 index 00000000..db0a69f6 --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Gen/Emit.lean @@ -0,0 +1,46 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import InkvecTheory.Gen.Strip +import InkvecTheory.Gen.Design +import InkvecTheory.Gen.Evidence + +/-! +# Writing the generated Rust + +Run from `formal/InkvecTheory`: + + lake build InkvecTheory && lake env lean InkvecTheory/Gen/Emit.lean + +It writes every module of `generatedModules` to `crates/inkvec-verified/src/generated/`. CI +runs it and fails when the files it writes differ from the committed ones, so the Rust +cannot drift from the definitions the theorems are about. Not imported by the library: a +build has no side effects. +-/ + +namespace Inkvec.Gen + +/-- Each generated module: file stem, the Lean declarations it comes from, its kernels. -/ +def generatedModules : List (String × String × List Kernel) := + [("strip", "InkvecTheory.Gen.Strip (stripKernels)", stripKernels), + ("design", "InkvecTheory.Gen.Design (designKernels)", designKernels), + ("evidence", "InkvecTheory.Gen.Evidence (evidenceKernels)", evidenceKernels)] + +/-- The generated directory's `mod.rs`. Each module is `#[rustfmt::skip]`: it is compared +byte for byte with what this file prints, so no formatter may touch it. -/ +def modRs : String := + "// @generated by `lake env lean InkvecTheory/Gen/Emit.lean` (formal/InkvecTheory). Do not edit. +//! Kernels generated from the Lean definitions their theorems are about. + +" ++ String.intercalate "" (generatedModules.map (fun (n, _, _) => s!"#[rustfmt::skip]\npub mod {n};\n")) + +end Inkvec.Gen + +open Inkvec.Gen in +#eval show IO Unit from do + let dir : System.FilePath := "../../crates/inkvec-verified/src/generated" + IO.FS.createDirAll dir + IO.FS.writeFile (dir / "mod.rs") modRs + for (n, src, ks) in generatedModules do + IO.FS.writeFile (dir / s!"{n}.rs") (module src ks) + IO.println s!"wrote {generatedModules.length} generated module(s) to {dir}" diff --git a/formal/InkvecTheory/InkvecTheory/Gen/Evidence.lean b/formal/InkvecTheory/InkvecTheory/Gen/Evidence.lean new file mode 100644 index 00000000..a8d138ee --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Gen/Evidence.lean @@ -0,0 +1,136 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import InkvecTheory.Windows +import InkvecTheory.Deconvolution +import InkvecTheory.Gen.Rust + +/-! +# The boundary evidence's kernels (`crates/inkvec-trace/src/evidence.rs`) + +A candidate description is scored against window areas (`Windows.lean`). Its checker takes +a certificate from the solver: the candidate cut at the window's strip and ends into straight +pieces, each labelled inside the window, above it or below it. The kernels: + +* `trapezoidK`: the area a straight piece inside the window contributes, + `(ub − ua)((va − vlo) + (vb − vlo))/2`; `trapezoidK_integral` says it is the integral of the + piece's height above `vlo` (`trapezoid_integral`). +* `windowTermK`: one window's `χ²` term `(S − A)²/V` and its residual. +* `fourthDiffK`: the fourth difference `h₀ − 4h₁ + 6h₂ − 4h₃ + h₄` of five consecutive window + means. `fourthDiff_cubic`: it vanishes on the cell means of every cubic, so on a smooth run + it reads only noise and the quartic term. `fourthDiff_side`: it is twelve times the + disagreement `strip.rs`'s corner test measures (the one-sided cubic at the pixel border + against the central one). +* `cornerExcessK`: `D² − z²·Σ wᵢ² Vᵢ`; certified non-negative (`nonneg_of_evalI`), it says the + fourth difference is at least `z` of its standard deviations: a corner proposal. +-/ + +namespace Inkvec.Gen + +open Inkvec.Gen.Expr + +/-- `x[i]` as an expression. -/ +abbrev ev (i : ℕ) : Expr := var i +/-- A literal. -/ +abbrev el (q : ℚ) : Expr := lit q + +/-- Inputs `x = [ua, va, ub, vb, vlo]`. -/ +def trapezoidOut : Expr := + div (mul (sub (ev 2) (ev 0)) (add (sub (ev 1) (ev 4)) (sub (ev 3) (ev 4)))) (el 2) + +def trapezoidK : Kernel where + name := "trapezoid" + doc := "The area `(ub − ua)((va − vlo) + (vb − vlo))/2` a straight piece from `(ua, va)` to \ + `(ub, vb)` inside a window adds above its end `vlo`, `x = [ua, va, ub, vb, vlo]` \ + (`trapezoidK_integral`)." + arity := 5 + outs := [trapezoidOut] + +theorem trapezoidK_eq (x : ℕ → ℝ) : + evalR x trapezoidOut = (x 2 - x 0) * ((x 1 - x 4) + (x 3 - x 4)) / 2 := by + simp [trapezoidOut, evalR] + +/-- **What the trapezoid certifies.** It is the integral of the piece's height above `vlo` +over the piece's extent across the strip. -/ +theorem trapezoidK_integral (x : ℕ → ℝ) (h : x 0 ≠ x 2) : + evalR x trapezoidOut = + ∫ u in (x 0)..(x 2), (x 1 + (u - x 0) / (x 2 - x 0) * (x 3 - x 1) - x 4) := by + rw [trapezoidK_eq, trapezoid_integral _ _ _ _ _ h] + +/-- Inputs `x = [S, A, V]`: the measured window sum, the candidate's area, the variance. -/ +def windowTermOuts : List Expr := + [ div (mul (sub (ev 0) (ev 1)) (sub (ev 0) (ev 1))) (ev 2), sub (ev 0) (ev 1) ] + +def windowTermK : Kernel where + name := "window_term" + doc := "One window's `χ²` term `(S − A)²/V` and its residual `S − A`, `x = [S, A, V]`." + arity := 3 + outs := windowTermOuts + +theorem windowTermK_eq (x : ℕ → ℝ) : + windowTermK.outs.map (evalR x) = [(x 0 - x 1) ^ 2 / x 2, x 0 - x 1] := by + simp [windowTermK, windowTermOuts, evalR, sq] + +/-- `h₀ − 4h₁ + 6h₂ − 4h₃ + h₄` from `x[0..5]`. -/ +def fourthDiffOut : Expr := + add (sub (add (sub (ev 0) (mul (el 4) (ev 1))) (mul (el 6) (ev 2))) (mul (el 4) (ev 3))) (ev 4) + +def fourthDiffK : Kernel where + name := "fourth_difference" + doc := "The fourth difference `h₀ − 4h₁ + 6h₂ − 4h₃ + h₄` of five consecutive window means \ + (`fourthDiff_cubic`: zero on every cubic; `fourthDiff_side`: twelve times `strip.rs`'s \ + one-sided disagreement)." + arity := 5 + outs := [fourthDiffOut] + +theorem fourthDiffK_eq (x : ℕ → ℝ) : + evalR x fourthDiffOut = x 0 - 4 * x 1 + 6 * x 2 - 4 * x 3 + x 4 := by + simp [fourthDiffOut, evalR] + +/-- **The fourth difference vanishes on every cubic.** Fed the means of a cubic over five +consecutive unit cells, it is zero: on a smooth run it reads only noise and the quartic term +(`quartic_defect`). -/ +theorem fourthDiff_cubic (c₀ c₁ c₂ c₃ k : ℝ) : + let f := cubic c₀ c₁ c₂ c₃ + cellMean' f (k - 2) - 4 * cellMean' f (k - 1) + 6 * cellMean' f k - 4 * cellMean' f (k + 1) + + cellMean' f (k + 2) = 0 := by + intro f + simp only [f, cellMean', integral_cubic] + unfold cubicPrim + ring + +/-- **`strip.rs`'s corner test is the fourth difference.** The cubic through the four left +means, read at the pixel border one cell on, less the face value of the four central means, is +the fourth difference of the five over twelve. -/ +theorem fourthDiff_side (m₀ m₁ m₂ m₃ m₄ : ℝ) : + let l := histopolate m₀ m₁ m₂ m₃ + let c := histopolate m₁ m₂ m₃ m₄ + cubic l.1 l.2.1 l.2.2.1 l.2.2.2 1 - c.1 = (m₀ - 4 * m₁ + 6 * m₂ - 4 * m₃ + m₄) / 12 := by + simp only [histopolate, cubic] + ring + +/-- `D² − z²·(V₀ + 16V₁ + 36V₂ + 16V₃ + V₄)` from `x = [h₀..h₄, V₀..V₄, z²]`. -/ +def cornerExcessOut : Expr := + let d := fourthDiffOut + let varD := add (add (add (add (ev 5) (mul (el 16) (ev 6))) (mul (el 36) (ev 7))) + (mul (el 16) (ev 8))) (ev 9) + sub (mul d d) (mul (ev 10) varD) + +def cornerExcessK : Kernel where + name := "corner_excess" + doc := "`D² − z²·Var D` for the fourth difference `D` of five window means with variances \ + `V₀..V₄`, `x = [h₀..h₄, V₀..V₄, z²]`: non-negative exactly when `|D|` is at least `z` of its \ + standard deviations (a corner proposal)." + arity := 11 + outs := [cornerExcessOut] + +theorem cornerExcessK_eq (x : ℕ → ℝ) : + evalR x cornerExcessOut = + (x 0 - 4 * x 1 + 6 * x 2 - 4 * x 3 + x 4) ^ 2 - + x 10 * (x 5 + 16 * x 6 + 36 * x 7 + 16 * x 8 + x 9) := by + simp [cornerExcessOut, fourthDiffOut, evalR, sq] + +/-- The kernels of `generated/evidence.rs`. -/ +def evidenceKernels : List Kernel := [trapezoidK, windowTermK, fourthDiffK, cornerExcessK] + +end Inkvec.Gen diff --git a/formal/InkvecTheory/InkvecTheory/Gen/Expr.lean b/formal/InkvecTheory/InkvecTheory/Gen/Expr.lean new file mode 100644 index 00000000..39f6fa0e --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Gen/Expr.lean @@ -0,0 +1,294 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import Mathlib.Analysis.SpecialFunctions.Pow.Real +import Mathlib.Analysis.SpecialFunctions.Sqrt + +/-! +# Checkers generated from the definitions the theorems are about + +The engine's solvers are free (floating point, heuristics, any algorithm); a result a theorem +speaks about is used only if a checker accepts it (`docs/theory/verification.md`). This file +is the bridge: a small expression language that Lean can reason about and print as Rust. + +* `Expr`: straight-line arithmetic over numbered inputs (`+ − × ÷`, `√`, rational + literals). A kernel is an `Expr`; its theorem is about `Expr.evalR`. +* `Expr.evalQ`: exact rational evaluation, for inputs that are integers or rationals (sums + of 8-bit pixels, rational stencils). Agrees with `evalR` wherever it returns a value + (`evalQ_sound`). +* `Expr.evalI`: interval evaluation through any implementation of the interval operations + that encloses the exact ones (`Enclosing`). Whatever it returns contains the true value + (`evalI_sound`): the checker's interval holds the real number the theorem is about. + +The Rust runtime (`crates/inkvec-verified`) implements the interval operations in `f64` +with each result widened outward by one unit in the last place. That it satisfies +`Enclosing` is the one trusted assumption, IEEE 754's: `+ − × ÷ √` return the correctly +rounded result, which lies within half a unit in the last place of the exact one, so the +neighbouring floats on either side bracket it. It is stated here as a hypothesis of +`evalI_sound`, not as an axiom of the library, so the audit stays at Lean's three. +-/ + +namespace Inkvec.Gen + +/-- Straight-line arithmetic over the inputs `x 0, x 1, …`. -/ +inductive Expr where + | lit (q : ℚ) + | var (i : ℕ) + | neg (a : Expr) + | add (a b : Expr) + | sub (a b : Expr) + | mul (a b : Expr) + | div (a b : Expr) + | sqrt (a : Expr) + deriving Inhabited + +namespace Expr + +/-- The real value: what the theorems are about. -/ +noncomputable def evalR (x : ℕ → ℝ) : Expr → ℝ + | lit q => q + | var i => x i + | neg a => -evalR x a + | add a b => evalR x a + evalR x b + | sub a b => evalR x a - evalR x b + | mul a b => evalR x a * evalR x b + | div a b => evalR x a / evalR x b + | sqrt a => Real.sqrt (evalR x a) + +/-- The exact rational value, or `none` for a division by zero or a square root (which the +rational checker refuses). -/ +def evalQ (x : ℕ → ℚ) : Expr → Option ℚ + | lit q => some q + | var i => some (x i) + | neg a => (evalQ x a).map (fun u => -u) + | add a b => do let u ← evalQ x a; let v ← evalQ x b; pure (u + v) + | sub a b => do let u ← evalQ x a; let v ← evalQ x b; pure (u - v) + | mul a b => do let u ← evalQ x a; let v ← evalQ x b; pure (u * v) + | div a b => do + let u ← evalQ x a + let v ← evalQ x b + if v = 0 then none else pure (u / v) + | sqrt _ => none + +/-- **The rational checker computes the real value.** -/ +theorem evalQ_sound (x : ℕ → ℚ) : + ∀ (e : Expr) (q : ℚ), evalQ x e = some q → (q : ℝ) = evalR (fun i => (x i : ℝ)) e := by + intro e + induction e with + | lit r => intro q h; simp [evalQ] at h; simp [evalR, h] + | var i => intro q h; simp [evalQ] at h; simp [evalR, h] + | neg a ha => + intro q h + simp only [evalQ, Option.map_eq_some_iff] at h + obtain ⟨u, hu, rfl⟩ := h + simp [evalR, ha u hu] + | add a b ha hb => + intro q h + simp only [evalQ, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.pure_def, + Option.some.injEq] at h + obtain ⟨u, hu, v, hv, rfl⟩ := h + simp [evalR, ha u hu, hb v hv] + | sub a b ha hb => + intro q h + simp only [evalQ, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.pure_def, + Option.some.injEq] at h + obtain ⟨u, hu, v, hv, rfl⟩ := h + simp [evalR, ha u hu, hb v hv] + | mul a b ha hb => + intro q h + simp only [evalQ, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.pure_def, + Option.some.injEq] at h + obtain ⟨u, hu, v, hv, rfl⟩ := h + simp [evalR, ha u hu, hb v hv] + | div a b ha hb => + intro q h + simp only [evalQ, Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨u, hu, v, hv, h⟩ := h + by_cases hv0 : v = 0 + · simp [hv0] at h + · simp only [hv0, ite_false, Option.pure_def, Option.some.injEq] at h + subst h + simp [evalR, ha u hu, hb v hv] + | sqrt a _ => intro q h; simp [evalQ] at h + +end Expr + +/-! ### Intervals -/ + +/-- A closed interval of reals; a checker's enclosure of a value. -/ +structure Iv where + lo : ℝ + hi : ℝ + +namespace Iv + +/-- `v` lies in `I`. -/ +def Mem (I : Iv) (v : ℝ) : Prop := I.lo ≤ v ∧ v ≤ I.hi + +/-- `I` lies inside `J`. -/ +def Sub (I J : Iv) : Prop := J.lo ≤ I.lo ∧ I.hi ≤ J.hi + +theorem Mem.of_sub {I J : Iv} {v : ℝ} (h : I.Mem v) (s : I.Sub J) : J.Mem v := + ⟨s.1.trans h.1, h.2.trans s.2⟩ + +/-- The exact interval operations. -/ +def neg (I : Iv) : Iv := ⟨-I.hi, -I.lo⟩ +def add (I J : Iv) : Iv := ⟨I.lo + J.lo, I.hi + J.hi⟩ +def sub (I J : Iv) : Iv := ⟨I.lo - J.hi, I.hi - J.lo⟩ +noncomputable def mul (I J : Iv) : Iv := + ⟨min (min (I.lo * J.lo) (I.lo * J.hi)) (min (I.hi * J.lo) (I.hi * J.hi)), + max (max (I.lo * J.lo) (I.lo * J.hi)) (max (I.hi * J.lo) (I.hi * J.hi))⟩ +/-- The reciprocal, for an interval that excludes zero. -/ +noncomputable def recip (I : Iv) : Iv := ⟨1 / I.hi, 1 / I.lo⟩ +/-- The square root, for an interval of non-negative numbers. -/ +noncomputable def sqrt (I : Iv) : Iv := ⟨Real.sqrt I.lo, Real.sqrt I.hi⟩ + +theorem mem_neg {I : Iv} {a : ℝ} (h : I.Mem a) : (neg I).Mem (-a) := + ⟨by simp [neg]; linarith [h.2], by simp [neg]; linarith [h.1]⟩ + +theorem mem_add {I J : Iv} {a b : ℝ} (ha : I.Mem a) (hb : J.Mem b) : (add I J).Mem (a + b) := + ⟨by simp [add]; linarith [ha.1, hb.1], by simp [add]; linarith [ha.2, hb.2]⟩ + +theorem mem_sub {I J : Iv} {a b : ℝ} (ha : I.Mem a) (hb : J.Mem b) : (sub I J).Mem (a - b) := + ⟨by simp [sub]; linarith [ha.1, hb.2], by simp [sub]; linarith [ha.2, hb.1]⟩ + +/-- `a·b` lies between the least and greatest product of the endpoints. -/ +theorem mem_mul {I J : Iv} {a b : ℝ} (ha : I.Mem a) (hb : J.Mem b) : (mul I J).Mem (a * b) := by + obtain ⟨ha1, ha2⟩ := ha + obtain ⟨hb1, hb2⟩ := hb + -- For fixed `b`, `t ↦ t·b` is monotone one way or the other, so `a·b` lies between + -- `lo·b` and `hi·b`; each of those lies between the products with `J`'s endpoints. + have key : ∀ t, I.lo ≤ t → t ≤ I.hi → ∀ s, J.lo ≤ s → s ≤ J.hi → + min (min (I.lo * J.lo) (I.lo * J.hi)) (min (I.hi * J.lo) (I.hi * J.hi)) ≤ t * s ∧ + t * s ≤ max (max (I.lo * J.lo) (I.lo * J.hi)) (max (I.hi * J.lo) (I.hi * J.hi)) := by + intro t ht1 ht2 s hs1 hs2 + have e1 : min (I.lo * s) (I.hi * s) ≤ t * s ∧ t * s ≤ max (I.lo * s) (I.hi * s) := by + rcases le_total 0 s with h0 | h0 + · exact ⟨(min_le_left _ _).trans (mul_le_mul_of_nonneg_right ht1 h0), + (mul_le_mul_of_nonneg_right ht2 h0).trans (le_max_right _ _)⟩ + · exact ⟨(min_le_right _ _).trans (mul_le_mul_of_nonpos_right ht2 h0), + (mul_le_mul_of_nonpos_right ht1 h0).trans (le_max_left _ _)⟩ + have e2 : ∀ u, min (u * J.lo) (u * J.hi) ≤ u * s ∧ u * s ≤ max (u * J.lo) (u * J.hi) := by + intro u + rcases le_total 0 u with h0 | h0 + · exact ⟨(min_le_left _ _).trans (mul_le_mul_of_nonneg_left hs1 h0), + (mul_le_mul_of_nonneg_left hs2 h0).trans (le_max_right _ _)⟩ + · exact ⟨(min_le_right _ _).trans (mul_le_mul_of_nonpos_left hs2 h0), + (mul_le_mul_of_nonpos_left hs1 h0).trans (le_max_left _ _)⟩ + obtain ⟨l1, u1⟩ := e2 I.lo + obtain ⟨l2, u2⟩ := e2 I.hi + constructor + · refine le_trans ?_ e1.1 + rcases min_choice (I.lo * s) (I.hi * s) with h | h <;> rw [h] + · exact (min_le_left _ _).trans l1 + · exact (min_le_right _ _).trans l2 + · refine e1.2.trans ?_ + rcases max_choice (I.lo * s) (I.hi * s) with h | h <;> rw [h] + · exact u1.trans (le_max_left _ _) + · exact u2.trans (le_max_right _ _) + exact key a ha1 ha2 b hb1 hb2 + +/-- The reciprocal of a number in an interval that excludes zero. -/ +theorem mem_recip {I : Iv} {b : ℝ} (hb : I.Mem b) (h0 : 0 < I.lo ∨ I.hi < 0) : + (recip I).Mem (1 / b) := by + obtain ⟨h1, h2⟩ := hb + rcases h0 with hp | hn + · have hb0 : 0 < b := lt_of_lt_of_le hp h1 + exact ⟨one_div_le_one_div_of_le hb0 h2, one_div_le_one_div_of_le hp h1⟩ + · have hb0 : b < 0 := lt_of_le_of_lt h2 hn + exact ⟨one_div_le_one_div_of_neg_of_le hn h2, one_div_le_one_div_of_neg_of_le hb0 h1⟩ + +theorem mem_sqrt {I : Iv} {a : ℝ} (ha : I.Mem a) : (sqrt I).Mem (Real.sqrt a) := + ⟨Real.sqrt_le_sqrt ha.1, Real.sqrt_le_sqrt ha.2⟩ + +end Iv + +/-- An implementation of the interval operations, as the Rust runtime provides: each may +refuse (`none`: an overflow, a divisor interval that does not exclude zero, a square root of +an interval reaching below zero, a non-finite endpoint), and what it returns encloses the +exact operation on its arguments. -/ +structure Enclosing where + lit : ℚ → Option Iv + neg : Iv → Option Iv + add : Iv → Iv → Option Iv + sub : Iv → Iv → Option Iv + mul : Iv → Iv → Option Iv + div : Iv → Iv → Option Iv + sqrt : Iv → Option Iv + lit_ok : ∀ q K, lit q = some K → K.Mem q + neg_ok : ∀ I K, neg I = some K → (Iv.neg I).Sub K + add_ok : ∀ I J K, add I J = some K → (Iv.add I J).Sub K + sub_ok : ∀ I J K, sub I J = some K → (Iv.sub I J).Sub K + mul_ok : ∀ I J K, mul I J = some K → (Iv.mul I J).Sub K + div_ok : ∀ I J K, div I J = some K → + (0 < J.lo ∨ J.hi < 0) ∧ (Iv.mul I (Iv.recip J)).Sub K + sqrt_ok : ∀ I K, sqrt I = some K → 0 ≤ I.lo ∧ (Iv.sqrt I).Sub K + +namespace Expr + +/-- Interval evaluation through the implementation `E`, from enclosures `X` of the inputs. -/ +def evalI (E : Enclosing) (X : ℕ → Iv) : Expr → Option Iv + | lit q => E.lit q + | var i => some (X i) + | neg a => (evalI E X a).bind E.neg + | add a b => do let I ← evalI E X a; let J ← evalI E X b; E.add I J + | sub a b => do let I ← evalI E X a; let J ← evalI E X b; E.sub I J + | mul a b => do let I ← evalI E X a; let J ← evalI E X b; E.mul I J + | div a b => do let I ← evalI E X a; let J ← evalI E X b; E.div I J + | sqrt a => (evalI E X a).bind E.sqrt + +/-- **The interval checker encloses the real value.** Whenever the interval evaluation +returns an interval, the real value the theorems are about lies in it, given enclosures of +the inputs. -/ +theorem evalI_sound (E : Enclosing) (X : ℕ → Iv) (x : ℕ → ℝ) (hx : ∀ i, (X i).Mem (x i)) : + ∀ (e : Expr) (K : Iv), evalI E X e = some K → K.Mem (evalR x e) := by + intro e + induction e with + | lit q => intro K h; exact E.lit_ok q K h + | var i => intro K h; simp [evalI] at h; subst h; exact hx i + | neg a ha => + intro K h + simp only [evalI, Option.bind_eq_some_iff] at h + obtain ⟨I, hI, hK⟩ := h + exact (Iv.mem_neg (ha I hI)).of_sub (E.neg_ok I K hK) + | add a b ha hb => + intro K h + simp only [evalI, Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨I, hI, J, hJ, hK⟩ := h + exact (Iv.mem_add (ha I hI) (hb J hJ)).of_sub (E.add_ok I J K hK) + | sub a b ha hb => + intro K h + simp only [evalI, Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨I, hI, J, hJ, hK⟩ := h + exact (Iv.mem_sub (ha I hI) (hb J hJ)).of_sub (E.sub_ok I J K hK) + | mul a b ha hb => + intro K h + simp only [evalI, Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨I, hI, J, hJ, hK⟩ := h + exact (Iv.mem_mul (ha I hI) (hb J hJ)).of_sub (E.mul_ok I J K hK) + | div a b ha hb => + intro K h + simp only [evalI, Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨I, hI, J, hJ, hK⟩ := h + obtain ⟨h0, hs⟩ := E.div_ok I J K hK + have hm := Iv.mem_mul (ha I hI) (Iv.mem_recip (hb J hJ) h0) + simp only [evalR] + rw [div_eq_mul_one_div] + exact hm.of_sub hs + | sqrt a ha => + intro K h + simp only [evalI, Option.bind_eq_some_iff] at h + obtain ⟨I, hI, hK⟩ := h + obtain ⟨_, hs⟩ := E.sqrt_ok I K hK + exact (Iv.mem_sqrt (ha I hI)).of_sub hs + +/-- **A checker's verdict.** If the interval evaluation of `e` returns an interval whose +lower end is at least zero, the real value is at least zero: a condition `e ≥ 0` a theorem +needs holds. A straddling interval is no verdict, and the checker refuses. -/ +theorem nonneg_of_evalI (E : Enclosing) (X : ℕ → Iv) (x : ℕ → ℝ) (hx : ∀ i, (X i).Mem (x i)) + (e : Expr) (K : Iv) (h : evalI E X e = some K) (hlo : 0 ≤ K.lo) : 0 ≤ evalR x e := + hlo.trans (evalI_sound E X x hx e K h).1 + +end Expr + +end Inkvec.Gen diff --git a/formal/InkvecTheory/InkvecTheory/Gen/Rust.lean b/formal/InkvecTheory/InkvecTheory/Gen/Rust.lean new file mode 100644 index 00000000..e506fe4a --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Gen/Rust.lean @@ -0,0 +1,127 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import InkvecTheory.Gen.Expr + +/-! +# Printing kernels as Rust + +A `Kernel` is a named list of `Expr` outputs over `arity` inputs. Each is printed three ways +into `crates/inkvec-verified/src/generated/`: + +* `_f64`: the formula in `f64`, fully parenthesised so Rust evaluates it in exactly + the order of the `Expr` (the solvers' fast path; the same formula the theorem is about, + rounded). +* `_iv`: `Expr.evalI` through the runtime's outward-rounded intervals (`iv.rs`); what it + returns contains the real value (`Expr.evalI_sound`). +* `_q`: `Expr.evalQ` through the runtime's checked `i128` rationals (`q.rs`); what it + returns is the real value (`Expr.evalQ_sound`). + +The printer is trusted, as a compiler is: it maps each constructor to one runtime call or +one Rust operator, and nothing else. +-/ + +namespace Inkvec.Gen + +/-- A generated kernel. -/ +structure Kernel where + /-- The Rust function stem. -/ + name : String + /-- One line on what it computes, and the Lean declaration its theorem is about. -/ + doc : String + /-- Number of inputs `x[0..arity]`. -/ + arity : Nat + /-- The outputs. -/ + outs : List Expr + +namespace Expr + +/-- A rational literal as Rust `f64` source. -/ +def litF64 (q : ℚ) : String := + let n := if q.num < 0 then s!"(-{q.num.natAbs}.0)" else s!"{q.num.natAbs}.0" + if q.den = 1 then n else s!"({n} / {q.den}.0)" + +/-- The `f64` formula, fully parenthesised. -/ +def rustF64 : Expr → String + | lit q => litF64 q + | var i => s!"x[{i}]" + | neg a => s!"(-{rustF64 a})" + | add a b => s!"({rustF64 a} + {rustF64 b})" + | sub a b => s!"({rustF64 a} - {rustF64 b})" + | mul a b => s!"({rustF64 a} * {rustF64 b})" + | div a b => s!"({rustF64 a} / {rustF64 b})" + | sqrt a => s!"{rustF64 a}.sqrt()" + +/-- A literal's numerator and denominator as Rust `i128` arguments. -/ +def litArgs (q : ℚ) : String := s!"{q.num}, {q.den}" + +/-- The interval evaluation: one runtime call per constructor, `?` on each refusal. -/ +def rustIv : Expr → String + | lit q => s!"iv::lit({litArgs q})?" + | var i => s!"x[{i}]" + | neg a => s!"iv::neg({rustIv a})?" + | add a b => s!"iv::add({rustIv a}, {rustIv b})?" + | sub a b => s!"iv::sub({rustIv a}, {rustIv b})?" + | mul a b => s!"iv::mul({rustIv a}, {rustIv b})?" + | div a b => s!"iv::div({rustIv a}, {rustIv b})?" + | sqrt a => s!"iv::sqrt({rustIv a})?" + +/-- The exact rational evaluation: one runtime call per constructor, `?` on each refusal +(an overflow, a division by zero, a square root). -/ +def rustQ : Expr → String + | lit q => s!"q::lit({litArgs q})?" + | var i => s!"x[{i}]" + | neg a => s!"q::neg({rustQ a})?" + | add a b => s!"q::add({rustQ a}, {rustQ b})?" + | sub a b => s!"q::sub({rustQ a}, {rustQ b})?" + | mul a b => s!"q::mul({rustQ a}, {rustQ b})?" + | div a b => s!"q::div({rustQ a}, {rustQ b})?" + | sqrt _ => "None?" + +end Expr + +namespace Kernel + +private def joinOuts (f : Expr → String) (outs : List Expr) : String := + String.intercalate ",\n " (outs.map f) + +/-- The three Rust functions of a kernel. -/ +def rust (k : Kernel) : String := + let n := k.outs.length + s!"/// {k.doc} +#[inline] +pub fn {k.name}_f64(x: &[f64; {k.arity}]) -> [f64; {n}] \{ + [ + {joinOuts Expr.rustF64 k.outs}, + ] +} + +/// [`{k.name}_f64`] as an enclosure: contains the exact value, or `None` (a refusal). +pub fn {k.name}_iv(x: &[Iv; {k.arity}]) -> Option<[Iv; {n}]> \{ + Some([ + {joinOuts Expr.rustIv k.outs}, + ]) +} + +/// [`{k.name}_f64`] exactly, or `None` (an overflow, a division by zero, a square root). +pub fn {k.name}_q(x: &[Q; {k.arity}]) -> Option<[Q; {n}]> \{ + Some([ + {joinOuts Expr.rustQ k.outs}, + ]) +} +" + +end Kernel + +/-- A generated Rust module: its header and kernels. -/ +def module (source : String) (kernels : List Kernel) : String := + s!"// @generated by `lake env lean InkvecTheory/Gen/Emit.lean` (formal/InkvecTheory) from +// `{source}`. Do not edit: CI regenerates this file and fails on any difference. +#![allow(clippy::all, unused_parens, unused_variables, missing_docs)] + +use crate::iv::\{self, Iv}; +use crate::q::\{self, Q}; + +" ++ String.intercalate "\n" (kernels.map Kernel.rust) + +end Inkvec.Gen diff --git a/formal/InkvecTheory/InkvecTheory/Gen/Strip.lean b/formal/InkvecTheory/InkvecTheory/Gen/Strip.lean new file mode 100644 index 00000000..6ef91c8a --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Gen/Strip.lean @@ -0,0 +1,99 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import InkvecTheory.Deconvolution +import InkvecTheory.Gen.Rust + +/-! +# The strip reading's kernels (`crates/inkvec-trace/src/planar/strip.rs`) + +* `histopolateK`: the cubic from the means of four unit cells, in the operation order of the + code it replaces; `histopolateK_eq` says it is `histopolate`, whose constants are exact on + every cubic (`histopolate_cubic`, `strip_reading_exact`). +* `stripResidualK`: where the normal line from a vertex meets that cubic, as the residual + `q(s₀ + t·n_u) − t·n_v` of a shift `t`. `stripResidualK_eq` says it is that residual for the + cubic `histopolate` returns, so (with `strip_reading_exact`) a shift whose residual + vanishes puts the vertex on the boundary the column sums determine, and on the boundary + itself wherever the boundary is a cubic. The engine's Newton iteration is the solver; the + interval kernel is its checker. +-/ + +namespace Inkvec.Gen + +open Inkvec.Gen.Expr + +/-- `x[i]` as an expression. -/ +abbrev v (i : ℕ) : Expr := var i +/-- A literal. -/ +abbrev c (q : ℚ) : Expr := lit q + +/-- The four coefficients, written as `strip.rs` writes them. -/ +def histopolateOuts : List Expr := + [ div (sub (add (add (neg (v 0)) (mul (c 7) (v 1))) (mul (c 7) (v 2))) (v 3)) (c 12), + div (sub (add (sub (v 0) (mul (c 15) (v 1))) (mul (c 15) (v 2))) (v 3)) (c 12), + div (add (sub (sub (v 0) (v 1)) (v 2)) (v 3)) (c 4), + div (add (sub (add (neg (v 0)) (mul (c 3) (v 1))) (mul (c 3) (v 2))) (v 3)) (c 6) ] + +def histopolateK : Kernel where + name := "histopolate" + doc := "The cubic `c₀ + c₁s + c₂s² + c₃s³` whose means over the cells `[-2,-1] … [1,2]` are \ + `x[0..4]` (`Inkvec.histopolate`; exact on every cubic: `histopolate_cubic`)." + arity := 4 + outs := histopolateOuts + +/-- The kernel computes `histopolate`. -/ +theorem histopolateK_eq (x : ℕ → ℝ) : + histopolateK.outs.map (evalR x) = + let h := histopolate (x 0) (x 1) (x 2) (x 3) + [h.1, h.2.1, h.2.2.1, h.2.2.2] := by + simp [histopolateK, histopolateOuts, evalR, histopolate] + +/-- Horner's form of a cubic with coefficients `cs` at `s`, as `strip.rs`'s `eval`. -/ +def horner (c₀ c₁ c₂ c₃ s : Expr) : Expr := add c₀ (mul s (add c₁ (mul s (add c₂ (mul s c₃))))) + +/-- Inputs: `x[0..4]` the cell means, `x[4]` = `s₀`, `x[5]` = `n_u`, `x[6]` = `n_v`, `x[7]` = `t`. -/ +def stripResidualOut : Expr := + match histopolateOuts with + | [c₀, c₁, c₂, c₃] => + sub (horner c₀ c₁ c₂ c₃ (add (v 4) (mul (v 7) (v 5)))) (mul (v 7) (v 6)) + | _ => lit 0 + +def stripResidualK : Kernel where + name := "strip_residual" + doc := "`q(s₀ + t·n_u) − t·n_v` for the cubic `q` of [`histopolate_f64`] and \ + `x = [m₀, m₁, m₂, m₃, s₀, n_u, n_v, t]`: zero where the normal line meets the cubic \ + (`stripResidualK_eq`)." + arity := 8 + outs := [stripResidualOut] + +/-- The residual kernel is the cubic `histopolate` returns, at `s₀ + t·n_u`, minus `t·n_v`. -/ +theorem stripResidualK_eq (x : ℕ → ℝ) : + evalR x stripResidualOut = + let h := histopolate (x 0) (x 1) (x 2) (x 3) + cubic h.1 h.2.1 h.2.2.1 h.2.2.2 (x 4 + x 7 * x 5) - x 7 * x 6 := by + simp only [stripResidualOut, histopolateOuts, horner, evalR, histopolate, cubic] + ring + +/-- **What the checker certifies.** For a cubic boundary `q`, fed its four cell means, the +residual kernel is `q(s₀ + t·n_u) − t·n_v`: zero exactly when the vertex moved by `t` along +the normal lies on `q`. -/ +theorem stripResidual_on_cubic (c₀ c₁ c₂ c₃ s₀ nu nv t : ℝ) : + let x : ℕ → ℝ := fun i => match i with + | 0 => cellMean' (cubic c₀ c₁ c₂ c₃) (-2) + | 1 => cellMean' (cubic c₀ c₁ c₂ c₃) (-1) + | 2 => cellMean' (cubic c₀ c₁ c₂ c₃) 0 + | 3 => cellMean' (cubic c₀ c₁ c₂ c₃) 1 + | 4 => s₀ + | 5 => nu + | 6 => nv + | _ => t + evalR x stripResidualOut = cubic c₀ c₁ c₂ c₃ (s₀ + t * nu) - t * nv := by + intro x + rw [stripResidualK_eq] + simp only [x] + rw [histopolate_cubic] + +/-- The kernels of `generated/strip.rs`. -/ +def stripKernels : List Kernel := [histopolateK, stripResidualK] + +end Inkvec.Gen diff --git a/formal/InkvecTheory/InkvecTheory/Identifiability.lean b/formal/InkvecTheory/InkvecTheory/Identifiability.lean new file mode 100644 index 00000000..bdc88068 --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Identifiability.lean @@ -0,0 +1,156 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import InkvecTheory.Coverage + +/-! +# What box-filter coverage does determine + +`NullSpace.lean` shows a free-form boundary is not determined by its pixels. This file shows +the other half of the dichotomy: a boundary drawn from a *finite-dimensional model* is +determined, exactly, by as many pixel columns as the model has coefficients. + +* `exists_zero_of_integral_eq_zero`, `zeros_of_zero_averages`: a continuous function whose + mean vanishes on `n` consecutive unit cells has `n` distinct zeros, one inside each cell. +* `poly_eq_of_averages`: two polynomials of degree `< n` with the same means on `n` + consecutive cells are equal (histopolation is unisolvent). +* `polynomial_boundary_determined`: two polynomial boundaries of degree `< n` that render to + the same pixels on `n` consecutive columns are the same boundary. Combined with + `column_sum_eq_average`, the model order a curve can be identified at is bounded by the + number of pixel columns its span covers: a line needs 2, a cubic graph 4. +* `line_from_two_columns`: the closed form for a straight edge. + +This is the theorem behind fitting with a *model* (inkvec's MDL dynamic program over lines, +arcs and cubics) rather than optimising free points: within a model class of dimension at +most the number of columns covered, the data term has a unique zero. +-/ + +namespace Inkvec + +open Set MeasureTheory Finset Polynomial + +/-- A continuous function with zero mean on `[a, b]` vanishes somewhere strictly inside. -/ +theorem exists_zero_of_integral_eq_zero {f : ℝ → ℝ} (hf : Continuous f) {a b : ℝ} (hab : a < b) + (h0 : ∫ x in a..b, f x = 0) : ∃ r ∈ Ioo a b, f r = 0 := by + by_contra hne + push Not at hne + set m := (a + b) / 2 with hm_def + have hm : m ∈ Ioo a b := ⟨by linarith, by linarith⟩ + -- `f` keeps the sign it has at the midpoint throughout `(a, b)`. + have keep : ∀ g : ℝ → ℝ, Continuous g → (∀ r ∈ Ioo a b, g r ≠ 0) → 0 < g m → + ∀ x ∈ Ioo a b, 0 < g x := by + intro g hg hgne hgm x hx + by_contra hx' + push Not at hx' + have hlt : g x < 0 := lt_of_le_of_ne hx' (hgne x hx) + obtain ⟨r, hr, hr0⟩ := isPreconnected_Ioo.intermediate_value hx hm hg.continuousOn + (show (0 : ℝ) ∈ Icc (g x) (g m) from ⟨hlt.le, hgm.le⟩) + exact hgne r hr hr0 + rcases lt_or_gt_of_ne (hne m hm) with hneg | hpos + · have hpos' := keep (fun x => -f x) hf.neg (fun r hr h => hne r hr (by linarith)) + (by linarith) + have := intervalIntegral.intervalIntegral_pos_of_pos_on (f := fun x => -f x) + (hf.neg.intervalIntegrable a b) hpos' hab + rw [intervalIntegral.integral_neg, h0, neg_zero] at this + exact lt_irrefl _ this + · have := intervalIntegral.intervalIntegral_pos_of_pos_on (hf.intervalIntegrable a b) + (keep f hf hne hpos) hab + rw [h0] at this + exact lt_irrefl _ this + +/-- **Zero averages force zeros.** If a continuous `f` has zero mean on each of the `n` +consecutive unit cells starting at `a`, it has a zero inside each, and these are `n` +distinct points. -/ +theorem zeros_of_zero_averages {f : ℝ → ℝ} (hf : Continuous f) (a : ℝ) (n : ℕ) + (h0 : ∀ k < n, ∫ x in (a + k)..(a + k + 1), f x = 0) : + ∃ r : Fin n → ℝ, StrictMono r ∧ ∀ k, f (r k) = 0 := by + have hex : ∀ k : Fin n, ∃ r ∈ Ioo (a + k) (a + k + 1), f r = 0 := fun k => + exists_zero_of_integral_eq_zero hf (by linarith) (h0 k k.isLt) + choose r hr hr0 using hex + refine ⟨r, fun k l hkl => ?_, hr0⟩ + have hkl' : (k : ℝ) + 1 ≤ l := by exact_mod_cast (Fin.lt_def.mp hkl) + linarith [(hr k).2, (hr l).1] + +/-- **Histopolation is unisolvent.** A polynomial of degree `< n` whose means vanish on `n` +consecutive unit cells is zero. -/ +theorem poly_eq_zero_of_zero_averages (p : ℝ[X]) (a : ℝ) (n : ℕ) (hdeg : p.natDegree < n) + (h0 : ∀ k < n, ∫ x in (a + k)..(a + k + 1), p.eval x = 0) : p = 0 := by + obtain ⟨r, hr, hr0⟩ := zeros_of_zero_averages p.continuous a n h0 + exact p.eq_zero_of_natDegree_lt_card_of_eval_eq_zero hr.injective hr0 (by simpa using hdeg) + +/-- Two polynomials of degree `< n` with equal means on `n` consecutive cells are equal. -/ +theorem poly_eq_of_averages (p q : ℝ[X]) (a : ℝ) (n : ℕ) (hp : p.natDegree < n) + (hq : q.natDegree < n) + (h : ∀ k < n, ∫ x in (a + k)..(a + k + 1), p.eval x = ∫ x in (a + k)..(a + k + 1), q.eval x) : + p = q := by + have hd : (p - q).natDegree < n := lt_of_le_of_lt (natDegree_sub_le p q) (max_lt hp hq) + have := poly_eq_zero_of_zero_averages (p - q) a n hd (fun k hk => by + simp only [eval_sub] + rw [intervalIntegral.integral_sub (p.continuous.intervalIntegrable _ _) + (q.continuous.intervalIntegrable _ _), h k hk, sub_self]) + exact sub_eq_zero.mp this + +/-- **Polynomial boundaries are determined by their pixels.** Let two polynomial boundaries +of degree `< n` stay within rows `j₀ … j₀+m` over the `n` columns starting at column `a`. If +the two shapes below them have the same box-filter coverage at every one of those +`n × m` pixels, the boundaries are the same polynomial. -/ +theorem polynomial_boundary_determined (p q : ℝ[X]) (a j₀ : ℤ) (n m : ℕ) (hp : p.natDegree < n) + (hq : q.natDegree < n) + (hpb : ∀ k < n, ∀ x ∈ Icc ((a + k : ℤ) : ℝ) ((a + k : ℤ) + 1), + (j₀ : ℝ) ≤ p.eval x ∧ p.eval x ≤ j₀ + m) + (hqb : ∀ k < n, ∀ x ∈ Icc ((a + k : ℤ) : ℝ) ((a + k : ℤ) + 1), + (j₀ : ℝ) ≤ q.eval x ∧ q.eval x ≤ j₀ + m) + (hcov : ∀ k < n, ∀ r < m, + coverage (subgraph fun x => p.eval x) (a + k) (j₀ + r) = + coverage (subgraph fun x => q.eval x) (a + k) (j₀ + r)) : + p = q := by + refine poly_eq_of_averages p q a n hp hq (fun k hk => ?_) + have ep := column_sum_eq_average (fun x => p.eval x) p.continuous (a + k) j₀ m + (fun x hx => (hpb k hk x hx).1) (fun x hx => (hpb k hk x hx).2) + have eq := column_sum_eq_average (fun x => q.eval x) q.continuous (a + k) j₀ m + (fun x hx => (hqb k hk x hx).1) (fun x hx => (hqb k hk x hx).2) + have hsum : ∑ r ∈ range m, coverage (subgraph fun x => p.eval x) (a + k) (j₀ + r) = + ∑ r ∈ range m, coverage (subgraph fun x => q.eval x) (a + k) (j₀ + r) := + sum_congr rfl (fun r hr => hcov k hk r (mem_range.mp hr)) + rw [ep, eq] at hsum + have hcast : ((a + k : ℤ) : ℝ) = (a : ℝ) + k := by push_cast; ring + rw [hcast] at hsum + linarith + +/-- The column mean of a straight boundary is its height at the column centre. -/ +lemma integral_affine_column (s b a : ℝ) : + ∫ x in a..(a + 1), (s * x + b) = s * (a + 1 / 2) + b := by + rw [intervalIntegral.integral_add (f := fun x => s * x) (g := fun _ => b) + ((continuous_const.mul continuous_id).intervalIntegrable _ _) intervalIntegrable_const, + intervalIntegral.integral_const_mul, integral_id, intervalIntegral.integral_const, + smul_eq_mul] + ring + +/-- **A straight edge from two column sums, in closed form.** If the boundary `y = s·x + b` +stays within rows `j₀ … j₀+m` over columns `i` and `i+1`, with column sums `S₀`, `S₁`, then +`s = S₁ - S₀` and `b = S₀ + j₀ - s·(i + ½)`. No normal, no threshold, no iteration. -/ +theorem line_from_two_columns (s b : ℝ) (i j₀ : ℤ) (m : ℕ) + (hlo : ∀ x ∈ Icc (i : ℝ) (i + 2), (j₀ : ℝ) ≤ s * x + b) + (hhi : ∀ x ∈ Icc (i : ℝ) (i + 2), s * x + b ≤ j₀ + m) : + let S₀ := ∑ r ∈ range m, coverage (subgraph fun x => s * x + b) i (j₀ + r) + let S₁ := ∑ r ∈ range m, coverage (subgraph fun x => s * x + b) (i + 1) (j₀ + r) + s = S₁ - S₀ ∧ b = S₀ + j₀ - s * (i + 1 / 2) := by + intro S₀ S₁ + have hc : Continuous fun x : ℝ => s * x + b := by fun_prop + have e0 := column_sum_eq_average _ hc i j₀ m + (fun x hx => hlo x ⟨hx.1, by linarith [hx.2]⟩) (fun x hx => hhi x ⟨hx.1, by linarith [hx.2]⟩) + have e1 := column_sum_eq_average _ hc (i + 1) j₀ m + (fun x hx => hlo x ⟨by push_cast at hx; linarith [hx.1], by push_cast at hx; linarith [hx.2]⟩) + (fun x hx => hhi x ⟨by push_cast at hx; linarith [hx.1], by push_cast at hx; linarith [hx.2]⟩) + rw [integral_affine_column] at e0 + push_cast at e1 + rw [integral_affine_column] at e1 + have hS0 : S₀ = s * (i + 1 / 2) + b - j₀ := e0 + have hS1 : S₁ = s * ((i : ℝ) + 1 + 1 / 2) + b - j₀ := by + have : S₁ = ∑ r ∈ range m, coverage (subgraph fun x => s * x + b) (i + 1) (j₀ + r) := rfl + rw [this, e1] + constructor + · rw [hS0, hS1]; ring + · rw [hS0]; ring + +end Inkvec diff --git a/formal/InkvecTheory/InkvecTheory/LevelSetBias.lean b/formal/InkvecTheory/InkvecTheory/LevelSetBias.lean new file mode 100644 index 00000000..21945ef5 --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/LevelSetBias.lean @@ -0,0 +1,97 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import InkvecTheory.Coverage + +/-! +# The bias of reading an edge as the ½-crossing of interpolated coverage + +Most sub-pixel tracers (and inkvec's own bilevel contour, `contour.rs`, and its +`root_find_half` fallback in `planar.rs`) put the boundary where the *linear interpolation* +of pixel-centre coverages crosses ½. Even on the easiest input there is, a straight +axis-aligned step edge with no noise, that reading is biased: + +* `levelSet_reading`: an edge `δ` above the centre of its pixel is read at + `δ/(½+δ)` instead of `δ`; +* `levelSetBias_le`, `levelSetBias_max`: the error is at most `3/2 - √2 ≈ 0.0858 px`, and + that bound is attained (at `δ = (√2-1)/2`). + +`column_sum_reading` is the alternative this theory recommends: the column sum reads the +same edge exactly, for every `δ`. + +`docs/algorithm/02-coverage.md` measures "roughly 0.05 px" for level-set extraction on +analytic circles and makes it `DEFAULT_SIGMA_MODEL`; this file shows that floor is a +property of the reading, not of the data. +-/ + +namespace Inkvec + +open Set MeasureTheory Finset Real + +/-- The coverage of a horizontal edge at height `e` in pixel `(i, j)` is `clamp01 (e - j)`. -/ +lemma coverage_flat (e : ℝ) (i j : ℤ) : + coverage (subgraph fun _ => e) i j = clamp01 (e - j) := by + rw [coverage_subgraph _ continuous_const, intervalIntegral.integral_const, smul_eq_mul] + ring + +/-- The error of the ½-crossing reading of an edge `δ` above its pixel's centre. -/ +noncomputable def levelSetBias (δ : ℝ) : ℝ := δ / (1 / 2 + δ) - δ + +/-- **What the ½-crossing reads.** Let the edge sit at `e = j + ½ + δ`, `0 ≤ δ ≤ ½`, inside +pixel row `j` (centre `j + ½`). Pixel `j` reads `½ + δ` and pixel `j+1` reads `0`; the linear +interpolation between their centres crosses ½ at `e + levelSetBias δ`. -/ +theorem levelSet_reading (e : ℝ) (i j : ℤ) (h0 : (j : ℝ) + 1 / 2 ≤ e) (h1 : e ≤ j + 1) : + let a₀ := coverage (subgraph fun _ => e) i j + let a₁ := coverage (subgraph fun _ => e) i (j + 1) + ((j : ℝ) + 1 / 2) + (a₀ - 1 / 2) / (a₀ - a₁) = e + levelSetBias (e - (j + 1 / 2)) := by + intro a₀ a₁ + have ha₀ : a₀ = e - j := by + show coverage _ i j = _ + rw [coverage_flat, clamp01_of_mem (by linarith) (by linarith)] + have ha₁ : a₁ = 0 := by + show coverage _ i (j + 1) = _ + rw [coverage_flat, clamp01_of_nonpos (by push_cast; linarith)] + rw [ha₀, ha₁] + unfold levelSetBias + have hne : e - (j : ℝ) ≠ 0 := by linarith + rw [show (1 : ℝ) / 2 + (e - (j + 1 / 2)) = e - j by ring, sub_zero] + field_simp + ring + +/-- The ½-crossing reading is never below the edge in this configuration, and never more than +`3/2 - √2` px above it. -/ +theorem levelSetBias_le (δ : ℝ) (h0 : 0 ≤ δ) (h1 : δ ≤ 1 / 2) : + 0 ≤ levelSetBias δ ∧ levelSetBias δ ≤ 3 / 2 - √2 := by + unfold levelSetBias + have hu : (0 : ℝ) < 1 / 2 + δ := by linarith + have hs : √2 ^ 2 = 2 := sq_sqrt (by norm_num) + have hs0 : 0 ≤ √2 := sqrt_nonneg 2 + constructor + · rw [sub_nonneg, le_div_iff₀ hu]; nlinarith + · rw [sub_le_iff_le_add, div_le_iff₀ hu] + nlinarith [sq_nonneg (1 / 2 + δ - √2 / 2)] + +/-- **The bound is sharp.** At `δ = (√2 - 1)/2` the ½-crossing is `3/2 - √2 ≈ 0.0858` px off. -/ +theorem levelSetBias_max : levelSetBias ((√2 - 1) / 2) = 3 / 2 - √2 := by + unfold levelSetBias + have hs : √2 ^ 2 = 2 := sq_sqrt (by norm_num) + have hpos : (0 : ℝ) < √2 := by positivity + rw [show (1 : ℝ) / 2 + (√2 - 1) / 2 = √2 / 2 by ring] + field_simp + nlinarith + +/-- `3/2 - √2` lies between `0.0857` and `0.0858`. -/ +lemma levelSetBias_max_approx : 0.0857 < 3 / 2 - √2 ∧ 3 / 2 - √2 < 0.0858 := by + have hs : √2 ^ 2 = 2 := sq_sqrt (by norm_num) + have h0 : 0 ≤ √2 := sqrt_nonneg 2 + constructor <;> nlinarith + +/-- **The column sum reads the same edge exactly.** For an edge anywhere inside rows +`j₀ … j₀+m`, `j₀ + Σ coverages = e`. -/ +theorem column_sum_reading (e : ℝ) (i j₀ : ℤ) (m : ℕ) (h0 : (j₀ : ℝ) ≤ e) (h1 : e ≤ j₀ + m) : + (j₀ : ℝ) + ∑ r ∈ range m, coverage (subgraph fun _ => e) i (j₀ + r) = e := by + rw [column_sum_eq_average _ continuous_const i j₀ m (fun _ _ => h0) (fun _ _ => h1), + intervalIntegral.integral_const, smul_eq_mul] + ring + +end Inkvec diff --git a/formal/InkvecTheory/InkvecTheory/Naturality.lean b/formal/InkvecTheory/InkvecTheory/Naturality.lean new file mode 100644 index 00000000..ee33c4f3 --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Naturality.lean @@ -0,0 +1,133 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import Mathlib.Analysis.InnerProductSpace.Projection.Basic +import Mathlib.Analysis.InnerProductSpace.Trace +import Mathlib.LinearAlgebra.Trace + +/-! +# Naturality: the smaller true description is the more accurate one + +A trace is a least-squares fit of a model to measured boundary points. Write the measurement +as `y = s + ε`: the true boundary `s` plus noise. Locally (about the fitted curve) the curves a +segmentation can draw form a linear space of the dimension of its parameter count, and the fit +is the orthogonal projection of `y` onto it. Merging two segments into one (two arcs on one +circle into one arc, two collinear lines into one) passes to a *subspace*: every curve the +merged description can draw, the split one can draw too. + +The question this file answers is whether a merge that keeps the truth drawable can cost +fidelity. It cannot, for any noise at all, and what it gains is exactly the noise the extra +parameters had absorbed: + +* `natural_model_closer`: if `s ∈ K ≤ L`, the fit onto `K` is at least as close to `s` as + the fit onto `L`, for every noise `ε`: pointwise, not in expectation. +* `natural_model_gain`: the two squared errors differ by exactly `‖P_L ε - P_K ε‖²`, the + noise lying in the directions `L` has and `K` lacks. +* `merge_chi2_increase`: the merge raises the fit's residual `‖y - P y‖²` by that same + amount. So the description-length test the stroke solve's merges apply + (`½·Δχ² < λ·Δk`, `crates/inkvec-trace/src/ribbon/refine/merge.rs`) reads the noise in the + removed directions and nothing else when the merge is true. +* `noise_absorbed`: averaged over the directions of any orthonormal basis, a model of + dimension `k` keeps `k` units of noise: `Σᵢ ‖P_K bᵢ‖² = dim K`. For isotropic noise of + variance `σ²` per coordinate the expected squared error of the fit is therefore `σ²·dim K`, + and every parameter a trace spends beyond the truth's costs `σ²` of squared error, while + the merge test sees `Δχ²/σ²` with mean `Δk`, against a price of `2λ·Δk` (`λ ≈ 8` nats at + 512 px). + +That is the formal content of "naturality": among the descriptions that draw the truth, the +one with the fewest parameters is the most faithful, and an MDL test with `λ > ½` accepts it +(in expectation) whenever it draws the truth. The nonlinear curve families inkvec fits are +covered to first order, about the fitted curve; the theorems themselves are exact. +-/ + +namespace Inkvec + +open Submodule +open scoped InnerProductSpace + +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + +/-- The fit onto `K` minus the truth is the projected noise, when the truth lies in `K`. -/ +lemma fit_error_eq {K : Submodule ℝ E} [K.HasOrthogonalProjection] {s : E} (hs : s ∈ K) + (ε : E) : K.starProjection (s + ε) - s = K.starProjection ε := by + rw [map_add, starProjection_eq_self_iff.mpr hs, add_sub_cancel_left] + +/-- **The natural model is closer, for every noise.** Least squares onto `K ≤ L` of a +measurement `s + ε` whose truth `s` lies in `K` is at least as close to `s` as least squares +onto `L`. -/ +theorem natural_model_closer {K L : Submodule ℝ E} [K.HasOrthogonalProjection] + [L.HasOrthogonalProjection] (hKL : K ≤ L) {s : E} (hs : s ∈ K) (ε : E) : + ‖K.starProjection (s + ε) - s‖ ≤ ‖L.starProjection (s + ε) - s‖ := by + rw [fit_error_eq hs, fit_error_eq (hKL hs)] + have h : K.starProjection (L.starProjection ε) = K.starProjection ε := by + have := congrArg (fun f => f ε) (starProjection_comp_starProjection_of_le hKL) + simpa using this + rw [← h] + exact norm_starProjection_apply_le _ _ + +/-- **The gain is the noise in the removed directions.** With `s ∈ K ≤ L`, the larger model's +squared error is the smaller one's plus `‖P_L ε - P_K ε‖²`. -/ +theorem natural_model_gain {K L : Submodule ℝ E} [K.HasOrthogonalProjection] + [L.HasOrthogonalProjection] (hKL : K ≤ L) {s : E} (hs : s ∈ K) (ε : E) : + ‖L.starProjection (s + ε) - s‖ ^ 2 = + ‖K.starProjection (s + ε) - s‖ ^ 2 + + ‖L.starProjection ε - K.starProjection ε‖ ^ 2 := by + rw [fit_error_eq hs, fit_error_eq (hKL hs)] + set v := L.starProjection ε + have hK : K.starProjection v = K.starProjection ε := by + have := congrArg (fun f => f ε) (starProjection_comp_starProjection_of_le hKL) + simpa using this + -- `v = P_K v + (v - P_K v)` with the two parts orthogonal. + have hperp : ⟪K.starProjection v, v - K.starProjection v⟫_ℝ = 0 := by + rw [real_inner_comm] + exact starProjection_inner_eq_zero v _ (starProjection_apply_mem K v) + have := norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero + (K.starProjection v) (v - K.starProjection v) hperp + rw [add_sub_cancel] at this + rw [← hK] + simpa [sq] using this + +/-- **The merge's price in residual.** With `s ∈ K ≤ L` and `y = s + ε`, the residual of the +fit onto `K` exceeds the residual onto `L` by `‖P_L ε - P_K ε‖²`: the description-length +test of a true merge reads only the noise in the directions it removes. -/ +theorem merge_chi2_increase {K L : Submodule ℝ E} [K.HasOrthogonalProjection] + [L.HasOrthogonalProjection] (hKL : K ≤ L) {s : E} (hs : s ∈ K) (ε : E) : + ‖(s + ε) - K.starProjection (s + ε)‖ ^ 2 = + ‖(s + ε) - L.starProjection (s + ε)‖ ^ 2 + + ‖L.starProjection ε - K.starProjection ε‖ ^ 2 := by + set y := s + ε + -- `y - P_K y = (y - P_L y) + (P_L y - P_K y)`, the first part orthogonal to `L ⊇ K`. + have hK : K.starProjection (L.starProjection y) = K.starProjection y := by + have := congrArg (fun f => f y) (starProjection_comp_starProjection_of_le hKL) + simpa using this + have hdiff : L.starProjection y - K.starProjection y = + L.starProjection ε - K.starProjection ε := by + simp only [y, map_add, starProjection_eq_self_iff.mpr hs, + starProjection_eq_self_iff.mpr (hKL hs)] + abel + have hperp : ⟪y - L.starProjection y, L.starProjection y - K.starProjection y⟫_ℝ = 0 := by + apply starProjection_inner_eq_zero + exact L.sub_mem (starProjection_apply_mem L y) (hKL (starProjection_apply_mem K y)) + have := norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero + (y - L.starProjection y) (L.starProjection y - K.starProjection y) hperp + rw [sub_add_sub_cancel] at this + rw [← hdiff] + simpa [sq] using this + +/-- **Each dimension keeps one unit of noise.** For any orthonormal basis `b` of a +finite-dimensional space, `Σᵢ ‖P_K bᵢ‖² = dim K`. With isotropic noise `ε = Σᵢ ξᵢ bᵢ` +(uncorrelated `ξᵢ` of variance `σ²`) the fit's expected squared error is `σ²` times this. -/ +theorem noise_absorbed [FiniteDimensional ℝ E] {ι : Type*} [Fintype ι] (K : Submodule ℝ E) + (b : OrthonormalBasis ι ℝ E) : + ∑ i, ‖K.starProjection (b i)‖ ^ 2 = (Module.finrank ℝ K : ℝ) := by + have hproj : LinearMap.IsProj K (K.starProjection : E →ₗ[ℝ] E) := + ⟨fun x => starProjection_apply_mem K x, + fun x hx => starProjection_eq_self_iff.mpr hx⟩ + rw [← hproj.trace, LinearMap.trace_eq_sum_inner _ b] + refine Finset.sum_congr rfl (fun i _ => ?_) + have := re_inner_starProjection_eq_normSq (K := K) (b i) + simp only [RCLike.re_to_real] at this + rw [real_inner_comm, ContinuousLinearMap.coe_coe, this, starProjection_apply, + norm_coe] + +end Inkvec diff --git a/formal/InkvecTheory/InkvecTheory/Noise.lean b/formal/InkvecTheory/InkvecTheory/Noise.lean new file mode 100644 index 00000000..6013a903 --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Noise.lean @@ -0,0 +1,94 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import InkvecTheory.Basic +import Mathlib.Probability.Moments.Variance + +/-! +# The strip reading under pixel noise + +A column sum is linear in the pixels, so pixel noise passes through it without bias and with +a variance that adds up; the cell-mean-to-point and face-value corrections are linear too. A +½-crossing reading is a ratio of noisy pixels and has neither property. This file proves the +linear half: + +* `strip_unbiased`: zero-mean noise on each pixel leaves the column sum's mean exact. +* `strip_variance`: `k` pixels with independent noise of variance `σ²` give the sum variance + `k·σ²`. +* `weighted_variance`, `face_value_noise`: a fixed linear combination of independent column + sums has variance `Σ wᵢ²·V`; for the face value of `strip.rs` that is `25/36·V`, less than + one column's own variance, and for the cell-mean-to-point correction `113/96·V`. + +The noise model is explicit and minimal: integrable, zero-mean, pairwise independent, +square-integrable where variances are claimed. Nothing about Gaussianity is assumed. +-/ + +namespace Inkvec + +open MeasureTheory ProbabilityTheory Finset + +variable {Ω : Type*} [MeasurableSpace Ω] {μ : Measure Ω} [IsProbabilityMeasure μ] + +/-- **The column sum is unbiased.** If pixel `i` of a window reads its true coverage `a i` plus +zero-mean noise `ε i`, the expected column sum is the true column sum, hence (by +`column_sum_eq_average`) the boundary's column mean. -/ +theorem strip_unbiased (k : ℕ) (a : Fin k → ℝ) (ε : Fin k → Ω → ℝ) + (hint : ∀ i, Integrable (ε i) μ) (h0 : ∀ i, ∫ ω, ε i ω ∂μ = 0) : + ∫ ω, ∑ i, (a i + ε i ω) ∂μ = ∑ i, a i := by + have h := integral_finsetSum (μ := μ) univ (f := fun i ω => a i + ε i ω) + (fun i _ => (integrable_const _).add (hint i)) + rw [h] + refine sum_congr rfl (fun i _ => ?_) + rw [integral_add (integrable_const _) (hint i), integral_const, h0 i] + simp + +omit [IsProbabilityMeasure μ] in +/-- **Variance of a weighted sum of independent readings.** -/ +theorem weighted_variance {ι : Type*} (s : Finset ι) (w : ι → ℝ) (X : ι → Ω → ℝ) + (hL2 : ∀ i ∈ s, MemLp (X i) 2 μ) (hind : Set.Pairwise ↑s fun i j => X i ⟂ᵢ[μ] X j) : + variance (fun ω => ∑ i ∈ s, w i * X i ω) μ = ∑ i ∈ s, w i ^ 2 * variance (X i) μ := by + have hsum : (fun ω => ∑ i ∈ s, w i * X i ω) = ∑ i ∈ s, (fun ω => w i * X i ω) := by + funext ω; simp [Finset.sum_apply] + rw [hsum, IndepFun.variance_sum (fun i hi => (hL2 i hi).const_mul (w i)) + (fun i hi j hj hij => (hind hi hj hij).comp (measurable_const_mul (w i)) + (measurable_const_mul (w j)))] + exact sum_congr rfl (fun i _ => variance_const_mul (w i) (X i) μ) + +/-- **Variance of the column sum.** `k` pixels with pairwise independent noise of variance +`σ²` each give the column sum the variance `k·σ²`. -/ +theorem strip_variance (k : ℕ) (a : Fin k → ℝ) (ε : Fin k → Ω → ℝ) (σ : ℝ) + (hL2 : ∀ i, MemLp (ε i) 2 μ) (hind : Pairwise fun i j => ε i ⟂ᵢ[μ] ε j) + (hvar : ∀ i, variance (ε i) μ = σ ^ 2) : + variance (fun ω => ∑ i, (a i + ε i ω)) μ = k * σ ^ 2 := by + have hshift : (fun ω => ∑ i, (a i + ε i ω)) = fun ω => (∑ i, 1 * ε i ω) + ∑ i, a i := by + funext ω; rw [sum_add_distrib]; simp [add_comm] + have hmeas : AEStronglyMeasurable (fun ω => ∑ i, 1 * ε i ω) μ := + Finset.aestronglyMeasurable_fun_sum _ (fun i _ => ((hL2 i).const_mul 1).aestronglyMeasurable) + rw [hshift, variance_add_const hmeas, + weighted_variance univ (fun _ => 1) ε (fun i _ => hL2 i) + (fun i _ j _ hij => hind hij)] + simp [hvar] + +omit [IsProbabilityMeasure μ] in +/-- **The face value averages noise down.** With the four column sums of `strip.rs`'s +`histopolate` carrying pairwise independent errors of equal variance `V`, the boundary height +read at the pixel border, `(7(S₁ + S₂) - (S₀ + S₃))/12`, has error variance `25/36·V`. -/ +theorem face_value_noise (X : Fin 4 → Ω → ℝ) (V : ℝ) (hL2 : ∀ i, MemLp (X i) 2 μ) + (hind : Pairwise fun i j => X i ⟂ᵢ[μ] X j) (hvar : ∀ i, variance (X i) μ = V) : + variance (fun ω => ∑ i, ![-1 / 12, 7 / 12, 7 / 12, -1 / 12] i * X i ω) μ = 25 / 36 * V := by + rw [weighted_variance univ _ X (fun i _ => hL2 i) (fun i _ j _ hij => hind hij)] + simp [Fin.sum_univ_four, hvar] + ring + +omit [IsProbabilityMeasure μ] in +/-- The cell-mean-to-point correction `A - (A₊ - 2A + A₋)/24` of `Deconvolution.lean`, with +weights `-1/24, 13/12, -1/24` on three pairwise independent means of variance `V`, has error +variance `((1/24)² + (13/12)² + (1/24)²)·V = 113/96·V`. -/ +theorem point_from_means_noise (X : Fin 3 → Ω → ℝ) (V : ℝ) (hL2 : ∀ i, MemLp (X i) 2 μ) + (hind : Pairwise fun i j => X i ⟂ᵢ[μ] X j) (hvar : ∀ i, variance (X i) μ = V) : + variance (fun ω => ∑ i, ![-1 / 24, 13 / 12, -1 / 24] i * X i ω) μ = 113 / 96 * V := by + rw [weighted_variance univ _ X (fun i _ => hL2 i) (fun i _ j _ hij => hind hij)] + simp [Fin.sum_univ_three, hvar] + ring + +end Inkvec diff --git a/formal/InkvecTheory/InkvecTheory/NullSpace.lean b/formal/InkvecTheory/InkvecTheory/NullSpace.lean new file mode 100644 index 00000000..736de00e --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/NullSpace.lean @@ -0,0 +1,276 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import InkvecTheory.Coverage + +/-! +# What box-filter coverage cannot see + +`docs/algorithm/08-boundary-solve.md` ("The sawtooth") records that the boundary solve can +"wander into that null space and return a row of triangular teeth that render almost as +well as a straight edge". This file proves that the null space is real, characterises it, +and shows the teeth are not "almost" invisible but *exactly* invisible: + +* `invisible_perturbation`: any perturbation with zero mean over a pixel column, that keeps + the boundary inside one row of pixels there, leaves every pixel of that column unchanged. +* `rasterization_not_injective`: two different shapes with identical coverage at every + pixel of the plane (a sine ripple of any frequency `k ≥ 1`). +* `polyline_zigzag_invisible` and `polyline_kernel`: for a polyline with one vertex per + pixel border (the parametrisation `planar::build` produces and `boundary_opt` moves), + the alternating zigzag `δ·(-1)^k` is invisible, and it is the *only* invisible + deformation of the vertex heights: the null space is exactly one-dimensional. +* `coverage_layer_cake`, `column_fiber`: in general a column's coverages determine, and are + determined by, the integrated distribution function `t ↦ ∫ (f - t)₊` at integer `t`. + Rearranging the boundary inside a column without changing that function is invisible. +-/ + +namespace Inkvec + +open Set MeasureTheory Finset Real + +/-- **Invisible perturbations.** If `f` and `f + h` both stay within row `j` over column `i` +and `h` has zero mean over the column, every pixel of column `i` has the same coverage. -/ +theorem invisible_perturbation (f h : ℝ → ℝ) (hf : Continuous f) (hh : Continuous h) (i j : ℤ) + (hband : ∀ x ∈ Icc (i : ℝ) (i + 1), + (j : ℝ) ≤ f x ∧ f x ≤ j + 1 ∧ (j : ℝ) ≤ f x + h x ∧ f x + h x ≤ j + 1) + (hzero : ∫ x in (i : ℝ)..(i + 1), h x = 0) (j' : ℤ) : + coverage (subgraph (f + h)) i j' = coverage (subgraph f) i j' := by + have hle : (i : ℝ) ≤ i + 1 := by linarith + rw [coverage_subgraph _ (hf.add hh), coverage_subgraph _ hf] + rcases lt_trichotomy j' j with hlt | heq | hgt + · -- rows below the boundary's row are full on both sides + have hj : (j' : ℝ) + 1 ≤ j := by exact_mod_cast hlt + refine intervalIntegral.integral_congr (fun x hx => ?_) + rw [uIcc_of_le hle] at hx + obtain ⟨h1, -, h3, -⟩ := hband x hx + simp only [Pi.add_apply] + rw [clamp01_of_one_le (by linarith), clamp01_of_one_le (by linarith)] + · subst heq + have e1 : ∫ x in (i : ℝ)..(i + 1), clamp01 ((f + h) x - j') = + ∫ x in (i : ℝ)..(i + 1), ((f x - j') + h x) := by + refine intervalIntegral.integral_congr (fun x hx => ?_) + rw [uIcc_of_le hle] at hx + obtain ⟨-, -, h3, h4⟩ := hband x hx + simp only [Pi.add_apply] + rw [clamp01_of_mem (by linarith) (by linarith)]; ring + have e2 : ∫ x in (i : ℝ)..(i + 1), clamp01 (f x - j') = + ∫ x in (i : ℝ)..(i + 1), (f x - j') := by + refine intervalIntegral.integral_congr (fun x hx => ?_) + rw [uIcc_of_le hle] at hx + obtain ⟨h1, h2, -, -⟩ := hband x hx + rw [clamp01_of_mem (by linarith) (by linarith)] + rw [e1, e2, intervalIntegral.integral_add (f := fun x => f x - (j' : ℝ)) (g := h) + ((hf.sub continuous_const).intervalIntegrable _ _) (hh.intervalIntegrable _ _), hzero, + add_zero] + · -- rows above are empty on both sides + have hj : (j : ℝ) + 1 ≤ j' := by exact_mod_cast hgt + refine intervalIntegral.integral_congr (fun x hx => ?_) + rw [uIcc_of_le hle] at hx + obtain ⟨-, h2, -, h4⟩ := hband x hx + simp only [Pi.add_apply] + rw [clamp01_of_nonpos (by linarith), clamp01_of_nonpos (by linarith)] + +/-- Different boundaries bound different shapes: a statement about sets, not functions. -/ +lemma subgraph_ne_of_ne {f g : ℝ → ℝ} (hfg : f ≠ g) : subgraph f ≠ subgraph g := by + intro hs + obtain ⟨x, hx⟩ := Function.ne_iff.mp hfg + rcases lt_or_gt_of_ne hx with h | h + · have : ((x, f x) : ℝ × ℝ) ∈ subgraph g := h + rw [← hs] at this; exact absurd (show f x < f x from this) (lt_irrefl _) + · have : ((x, g x) : ℝ × ℝ) ∈ subgraph f := h + rw [hs] at this; exact absurd (show g x < g x from this) (lt_irrefl _) + +/-- A whole-period ripple has zero mean over every pixel column. -/ +lemma integral_sin_ripple (k : ℕ) (hk : 0 < k) (i : ℤ) : + ∫ x in (i : ℝ)..(i + 1), sin (2 * π * k * x) = 0 := by + have hc : (2 * π * k : ℝ) ≠ 0 := by positivity + rw [intervalIntegral.integral_comp_mul_left (fun x => sin x) hc, integral_sin] + have : 2 * π * (k : ℝ) * ((i : ℝ) + 1) = 2 * π * k * i + (k : ℕ) * (2 * π) := by ring + rw [this, cos_add_nat_mul_two_pi]; simp + +/-- **The box filter is not injective, at every frequency.** A horizontal edge inside row +`j` and the same edge carrying a ripple `ε sin(2πkx)` of any whole frequency `k ≥ 1` and any +amplitude that keeps it inside the row have identical coverage at every pixel of the plane, +yet bound different shapes. The invisible ripples span an infinite-dimensional space, so no +amount of data-term optimisation can choose among them: only a prior can. -/ +theorem sine_ripple_invisible (c ε : ℝ) (j : ℤ) (k : ℕ) (hk : 0 < k) + (hlo : (j : ℝ) + |ε| ≤ c) (hhi : c + |ε| ≤ j + 1) (i j' : ℤ) : + coverage (subgraph (fun x => c + ε * sin (2 * π * k * x))) i j' = + coverage (subgraph (fun _ => c)) i j' := by + have hrw : (fun x => c + ε * sin (2 * π * k * x)) = + (fun _ : ℝ => c) + (fun x => ε * sin (2 * π * k * x)) := rfl + rw [hrw] + refine invisible_perturbation _ _ continuous_const (by fun_prop) i j (fun x _ => ?_) ?_ j' + · have hs := abs_le.mp (show |ε * sin (2 * π * k * x)| ≤ |ε| by + rw [abs_mul]; exact mul_le_of_le_one_right (abs_nonneg _) (abs_sin_le_one _)) + have he := abs_nonneg ε + refine ⟨by linarith, by linarith, by linarith [hs.1], by linarith [hs.2]⟩ + · rw [intervalIntegral.integral_const_mul, integral_sin_ripple k hk, mul_zero] + +theorem rasterization_not_injective : + ∃ Ω₁ Ω₂ : Set (ℝ × ℝ), Ω₁ ≠ Ω₂ ∧ ∀ i j, coverage Ω₁ i j = coverage Ω₂ i j := by + refine ⟨subgraph (fun x => 1 / 2 + 1 / 4 * sin (2 * π * (1 : ℕ) * x)), + subgraph (fun _ => 1 / 2), subgraph_ne_of_ne ?_, fun i j' => + sine_ripple_invisible (1 / 2) (1 / 4) 0 1 one_pos (by norm_num [abs_of_pos]) + (by norm_num [abs_of_pos]) i j'⟩ + intro h + have := congrFun h (1 / 4) + have hs : sin (2 * π * ((1 : ℕ) : ℝ) * (1 / 4)) = 1 := by + rw [show 2 * π * ((1 : ℕ) : ℝ) * (1 / 4) = π / 2 by push_cast; ring, sin_pi_div_two] + rw [hs] at this; norm_num at this + +/-! ### Polylines with a vertex on every pixel border -/ + +/-- The unit hat function, the piecewise-linear interpolation basis. -/ +noncomputable def hat (t : ℝ) : ℝ := max 0 (1 - |t|) + +lemma continuous_hat : Continuous hat := by unfold hat; fun_prop + +/-- The polyline through `(k, y k)` for `k = 0 … n`. -/ +noncomputable def polyline (y : ℕ → ℝ) (n : ℕ) (x : ℝ) : ℝ := + ∑ k ∈ range (n + 1), y k * hat (x - k) + +lemma continuous_polyline (y : ℕ → ℝ) (n : ℕ) : Continuous (polyline y n) := by + unfold polyline + exact continuous_finsetSum _ (fun k _ => + continuous_const.mul (continuous_hat.comp (continuous_id.sub continuous_const))) + +lemma polyline_add (y z : ℕ → ℝ) (n : ℕ) : + polyline (y + z) n = polyline y n + polyline z n := by + funext x; simp only [polyline, Pi.add_apply, add_mul, sum_add_distrib] + +/-- On column `i` the polyline is the chord between its two vertices. -/ +lemma polyline_on_column (y : ℕ → ℝ) (n i : ℕ) (hi : i < n) {x : ℝ} + (hx : x ∈ Icc (i : ℝ) (i + 1)) : + polyline y n x = y i + (y (i + 1) - y i) * (x - i) := by + obtain ⟨hx0, hx1⟩ := hx + unfold polyline + have hsub : ({i, i + 1} : Finset ℕ) ⊆ range (n + 1) := by + intro k hk; simp only [Finset.mem_insert, Finset.mem_singleton] at hk + rcases hk with rfl | rfl <;> simp <;> omega + rw [← sum_subset hsub (fun k _ hk => ?_)] + · rw [sum_pair (by omega)] + unfold hat + have e1 : |x - (i : ℕ)| = x - i := abs_of_nonneg (by simp; linarith) + have e2 : |x - ((i + 1 : ℕ) : ℝ)| = i + 1 - x := by + rw [abs_of_nonpos (by push_cast; linarith)]; push_cast; ring + rw [e1, e2, max_eq_right (by linarith), max_eq_right (by linarith)]; ring + · simp only [Finset.mem_insert, Finset.mem_singleton, not_or] at hk + unfold hat + rcases Nat.lt_or_gt_of_ne hk.1 with h | h + · have hk' : (k : ℝ) + 1 ≤ i := by exact_mod_cast h + rw [max_eq_left (by rw [abs_of_nonneg (by linarith)]; linarith), mul_zero] + · have hk' : (i : ℝ) + 2 ≤ k := by + have : i + 2 ≤ k := by omega + exact_mod_cast this + rw [max_eq_left (by rw [abs_of_nonpos (by linarith)]; linarith), mul_zero] + +/-- The column mean of a polyline is the mean of its two vertex heights (the trapezoid). -/ +lemma integral_polyline_column (y : ℕ → ℝ) (n i : ℕ) (hi : i < n) : + ∫ x in (i : ℝ)..(i + 1), polyline y n x = (y i + y (i + 1)) / 2 := by + have hle : (i : ℝ) ≤ i + 1 := by linarith + rw [intervalIntegral.integral_congr (g := fun x => y i + (y (i + 1) - y i) * (x - i)) + (fun x hx => polyline_on_column y n i hi (by rwa [uIcc_of_le hle] at hx))] + have hs := intervalIntegral.integral_comp_sub_right + (fun x => y i + (y (i + 1) - y i) * x) (a := (i : ℝ)) (b := (i : ℝ) + 1) (i : ℝ) + rw [hs, sub_self, add_sub_cancel_left, + intervalIntegral.integral_add (f := fun _ => y i) (g := fun x => (y (i + 1) - y i) * x) + intervalIntegrable_const ((continuous_const.mul continuous_id).intervalIntegrable _ _), + intervalIntegral.integral_const_mul, integral_id] + simp; ring + +/-- The alternating zigzag of amplitude `δ` on the vertices. -/ +noncomputable def zigzag (δ : ℝ) (k : ℕ) : ℝ := δ * (-1) ^ k + +/-- **The sawtooth is exactly invisible.** Adding the vertex zigzag `δ·(-1)^k` to a polyline +with a vertex on every pixel border changes no pixel of any column where both polylines stay +inside one row. This is the "row of triangular teeth" of `08-boundary-solve.md`. -/ +theorem polyline_zigzag_invisible (y : ℕ → ℝ) (δ : ℝ) (n i : ℕ) (hi : i < n) (j : ℤ) + (hband : ∀ x ∈ Icc (i : ℝ) (i + 1), + (j : ℝ) ≤ polyline y n x ∧ polyline y n x ≤ j + 1 ∧ + (j : ℝ) ≤ polyline (y + zigzag δ) n x ∧ polyline (y + zigzag δ) n x ≤ j + 1) (j' : ℤ) : + coverage (subgraph (polyline (y + zigzag δ) n)) (i : ℤ) j' = + coverage (subgraph (polyline y n)) (i : ℤ) j' := by + rw [polyline_add] + refine invisible_perturbation _ _ (continuous_polyline y n) (continuous_polyline _ n) + (i : ℤ) j (fun x hx => ?_) ?_ j' + · have := hband x (by simpa using hx) + rw [polyline_add] at this; simpa using this + · have := integral_polyline_column (zigzag δ) n i hi + simp only [Int.cast_natCast] + rw [this]; unfold zigzag; rw [pow_succ]; ring + +/-- **The zigzag is the whole null space.** If every column mean of a polyline vanishes +(the linearised coverage change of a vertex perturbation inside one row of pixels), its +vertex heights are an alternating zigzag. With one vertex per pixel border and motion only +across the boundary, the data term therefore has exactly one flat direction per boundary +run, and a prior has to fix exactly that one. -/ +theorem polyline_kernel (z : ℕ → ℝ) (n : ℕ) + (hz : ∀ i < n, ∫ x in (i : ℝ)..(i + 1), polyline z n x = 0) : + ∀ k ≤ n, z k = zigzag (z 0) k := by + intro k hk + induction k with + | zero => simp [zigzag] + | succ k ih => + have h := hz k (by omega) + rw [integral_polyline_column z n k (by omega)] at h + rw [show z (k + 1) = -z k by linarith, ih (by omega)] + unfold zigzag; rw [pow_succ]; ring + +/-! ### The layer cake: exactly what a column of coverages determines -/ + +/-- The integrated distribution function of the boundary heights over column `i`. -/ +noncomputable def layer (f : ℝ → ℝ) (i : ℤ) (t : ℝ) : ℝ := ∫ x in (i : ℝ)..(i + 1), ramp (f x - t) + +theorem coverage_layer_cake (f : ℝ → ℝ) (hf : Continuous f) (i j : ℤ) : + coverage (subgraph f) i j = layer f i j - layer f i (j + 1) := by + unfold layer + have h1 : IntervalIntegrable (fun x => ramp (f x - j)) volume (i : ℝ) (i + 1) := + (continuous_ramp.comp (hf.sub continuous_const)).intervalIntegrable _ _ + have h2 : IntervalIntegrable (fun x => ramp (f x - (j + 1))) volume (i : ℝ) (i + 1) := + (continuous_ramp.comp (hf.sub continuous_const)).intervalIntegrable _ _ + rw [coverage_subgraph f hf, ← intervalIntegral.integral_sub h1 h2] + refine intervalIntegral.integral_congr (fun x _ => ?_) + rw [clamp01_eq_ramp_sub, show f x - j - 1 = f x - (j + 1) by ring] + +/-- Above the boundary the layer function vanishes. -/ +lemma layer_eq_sum (f : ℝ → ℝ) (hf : Continuous f) (i j₀ : ℤ) (n k : ℕ) (hkn : k ≤ n) + (hhi : ∀ x ∈ Icc (i : ℝ) (i + 1), f x ≤ j₀ + n) : + layer f i (j₀ + k) = ∑ m ∈ Finset.Ico k n, coverage (subgraph f) i (j₀ + m) := by + have hle : (i : ℝ) ≤ i + 1 := by linarith + have hc : ∀ m ∈ Finset.Ico k n, IntervalIntegrable (fun x => clamp01 (f x - ((j₀ + m : ℤ) : ℝ))) + volume (i : ℝ) (i + 1) := fun m _ => + (continuous_clamp01.comp (hf.sub continuous_const)).intervalIntegrable _ _ + simp_rw [coverage_subgraph f hf] + rw [← intervalIntegral.integral_finsetSum hc] + unfold layer + refine intervalIntegral.integral_congr (fun x hx => ?_) + rw [uIcc_of_le hle] at hx + have h := sum_Ico_clamp01 (t := f x - j₀) hkn (by linarith [hhi x hx]) + simp only [Int.cast_add, Int.cast_natCast] + rw [show f x - ((j₀ : ℝ) + k) = f x - j₀ - k by ring, ← h] + refine sum_congr rfl (fun m _ => ?_) + congr 1; ring + +/-- **Fibre of the box filter on one column.** Two boundaries below the top of rows +`j₀ … j₀+n` give the same coverages in those rows exactly when their layer functions agree at +every integer level from `j₀` to `j₀+n`. The pixels see a boundary only through how much of +it lies above each integer height, never through where along the column it does so. -/ +theorem column_fiber (f g : ℝ → ℝ) (hf : Continuous f) (hg : Continuous g) (i j₀ : ℤ) (n : ℕ) + (hfh : ∀ x ∈ Icc (i : ℝ) (i + 1), f x ≤ j₀ + n) + (hgh : ∀ x ∈ Icc (i : ℝ) (i + 1), g x ≤ j₀ + n) : + (∀ k < n, coverage (subgraph f) i (j₀ + k) = coverage (subgraph g) i (j₀ + k)) ↔ + (∀ k ≤ n, layer f i (j₀ + k) = layer g i (j₀ + k)) := by + constructor + · intro hcov k hk + rw [layer_eq_sum f hf i j₀ n k hk hfh, layer_eq_sum g hg i j₀ n k hk hgh] + exact sum_congr rfl (fun m hm => hcov m (Finset.mem_Ico.mp hm).2) + · intro hlay k hk + rw [coverage_layer_cake f hf, coverage_layer_cake g hg] + have h1 := hlay k hk.le + have h2 := hlay (k + 1) hk + have e : ((j₀ + (k : ℤ) : ℤ) : ℝ) + 1 = (j₀ : ℝ) + ((k + 1 : ℕ) : ℝ) := by push_cast; ring + have e' : ((j₀ + (k : ℤ) : ℤ) : ℝ) = (j₀ : ℝ) + (k : ℝ) := by push_cast; ring + rw [e, e', h1, h2] + +end Inkvec diff --git a/formal/InkvecTheory/InkvecTheory/Quantization.lean b/formal/InkvecTheory/InkvecTheory/Quantization.lean new file mode 100644 index 00000000..7a68ce0a --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Quantization.lean @@ -0,0 +1,138 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import InkvecTheory.LevelSetBias + +/-! +# What a tracer that quantises coverage first can never recover + +A tracer that thresholds the image (Potrace) or clusters it into flat colours before finding +boundaries (VTracer and most colour tracers) reads each pixel through a quantiser before any +geometry is decided. Those tracers cannot recover what the quantiser removed, whatever +happens afterwards; there is no tunable stage left to recover it (the `thin_features` case +of `docs/M0-BASELINE.md`). This file makes that a lower bound, against an exact upper bound +for coverage: + +* `binarize_minimax`: every estimator of an edge's position that reads only the thresholded + pixels is off by at least `½ - η` px on some edge, for every `η > 0`. +* `quantize_minimax`: every estimator reading pixels through *any* `L`-level quantiser is off + by at least `δ/2` on some edge, for every `δ < 1/L`. For 8-bit coverage that floor is + `1/512 px`. +* `column_sum_reading` (in `LevelSetBias.lean`) reads every such edge with error `0`. + +The bounds are over the simplest family of shapes there is, a horizontal edge, so they bind +on every richer family that contains it. +-/ + +namespace Inkvec + +open Set MeasureTheory Finset + +lemma half_le_clamp01_iff (t : ℝ) : 1 / 2 ≤ clamp01 t ↔ 1 / 2 ≤ t := by + constructor + · intro h + by_contra ht + push Not at ht + have : clamp01 t ≤ max 0 t := min_le_right _ _ + have : max 0 t < 1 / 2 := max_lt (by norm_num) ht + linarith + · intro h + rcases le_total t 1 with h1 | h1 + · rw [clamp01_of_mem (by linarith) h1]; exact h + · rw [clamp01_of_one_le h1]; norm_num + +/-- The thresholded column under a horizontal edge at height `e`. -/ +noncomputable def binarized (e : ℝ) : ℤ → Bool := + fun j => decide (1 / 2 ≤ coverage (subgraph fun _ => e) 0 j) + +/-- **Binarisation costs half a pixel.** For any estimator `φ` of the edge height from the +thresholded column and any `η ∈ (0, 1)`, some edge is read at least `(1 - η)/2` px off. -/ +theorem binarize_minimax (φ : (ℤ → Bool) → ℝ) (η : ℝ) (hη0 : 0 < η) (hη1 : η < 1) : + ∃ e : ℝ, (1 - η) / 2 ≤ |φ (binarized e) - e| := by + set e₁ : ℝ := 1 / 2 + set e₂ : ℝ := 3 / 2 - η + have hsame : binarized e₁ = binarized e₂ := by + funext j + unfold binarized + rw [coverage_flat, coverage_flat] + apply decide_eq_decide.mpr + rw [half_le_clamp01_iff, half_le_clamp01_iff] + constructor + · intro h + have : (j : ℝ) ≤ 0 := by simp only [e₁] at h; linarith + simp only [e₂]; linarith + · intro h + have hj : (j : ℝ) < 1 := by simp only [e₂] at h; linarith + have hj' : j ≤ 0 := by + have : j < 1 := by exact_mod_cast hj + omega + have : (j : ℝ) ≤ 0 := by exact_mod_cast hj' + simp only [e₁]; linarith + by_contra hall + push Not at hall + have h1 := hall e₁ + have h2 := hall e₂ + rw [hsame] at h1 + have := abs_sub_le e₂ (φ (binarized e₂)) e₁ + rw [abs_sub_comm e₂ (φ (binarized e₂))] at this + have hd : |e₂ - e₁| = 1 - η := by + simp only [e₁, e₂]; rw [abs_of_pos (by linarith)]; ring + linarith + +/-- The column under a horizontal edge at height `e`, read through a per-pixel quantiser. -/ +noncomputable def quantized {L : ℕ} (q : ℝ → Fin L) (e : ℝ) : ℤ → Fin L := + fun j => q (coverage (subgraph fun _ => e) 0 j) + +/-- **Any quantiser costs at least half a level.** For any per-pixel quantiser to `L` levels +(any function at all, not necessarily monotone or uniform), any estimator `φ` reading the +quantised column, and any `δ > 0` with `δ·L < 1`, some edge is read at least `δ/2` px off. -/ +theorem quantize_minimax (L : ℕ) (q : ℝ → Fin L) (φ : (ℤ → Fin L) → ℝ) (δ : ℝ) (hδ : 0 < δ) + (hδL : δ * L < 1) : ∃ e : ℝ, δ / 2 ≤ |φ (quantized q e) - e| := by + -- `L + 1` edges `kδ` inside one pixel; two of them quantise alike. + obtain ⟨k₁, k₂, hne, hq⟩ := Fintype.exists_ne_map_eq_of_card_lt + (fun k : Fin (L + 1) => q ((k : ℝ) * δ)) (by simp) + have hin : ∀ k : Fin (L + 1), 0 ≤ (k : ℝ) * δ ∧ (k : ℝ) * δ < 1 := by + intro k + have hk : (k : ℝ) ≤ L := by exact_mod_cast Nat.lt_succ_iff.mp k.isLt + exact ⟨by positivity, by nlinarith⟩ + have hsame : quantized q ((k₁ : ℝ) * δ) = quantized q ((k₂ : ℝ) * δ) := by + funext j + unfold quantized + rw [coverage_flat, coverage_flat] + obtain ⟨a1, b1⟩ := hin k₁ + obtain ⟨a2, b2⟩ := hin k₂ + rcases lt_trichotomy j 0 with hj | rfl | hj + · have : (j : ℝ) ≤ -1 := by exact_mod_cast (show j ≤ -1 by omega) + rw [clamp01_of_one_le (by linarith), clamp01_of_one_le (by linarith)] + · simp only [Int.cast_zero, sub_zero] + rw [clamp01_of_mem a1 b1.le, clamp01_of_mem a2 b2.le] + exact hq + · have : (1 : ℝ) ≤ j := by exact_mod_cast (show 1 ≤ j by omega) + rw [clamp01_of_nonpos (by linarith), clamp01_of_nonpos (by linarith)] + have hgap : δ ≤ |(k₁ : ℝ) * δ - (k₂ : ℝ) * δ| := by + rw [← sub_mul, abs_mul, abs_of_pos hδ] + have : (1 : ℝ) ≤ |(k₁ : ℝ) - (k₂ : ℝ)| := by + have hk : (k₁ : ℕ) ≠ (k₂ : ℕ) := fun h => hne (Fin.ext h) + rcases Nat.lt_or_gt_of_ne hk with h | h + · have : (k₁ : ℝ) + 1 ≤ k₂ := by exact_mod_cast h + rw [abs_of_neg (by linarith)]; linarith + · have : (k₂ : ℝ) + 1 ≤ k₁ := by exact_mod_cast h + rw [abs_of_pos (by linarith)]; linarith + nlinarith + by_contra hall + push Not at hall + have h1 := hall ((k₁ : ℝ) * δ) + have h2 := hall ((k₂ : ℝ) * δ) + rw [hsame] at h1 + have := abs_sub_le ((k₁ : ℝ) * δ) (φ (quantized q ((k₂ : ℝ) * δ))) ((k₂ : ℝ) * δ) + have h3 : |(k₁ : ℝ) * δ - φ (quantized q ((k₂ : ℝ) * δ))| = + |φ (quantized q ((k₂ : ℝ) * δ)) - (k₁ : ℝ) * δ| := abs_sub_comm _ _ + linarith + +/-- **Coverage reads every edge exactly.** The estimator `e ↦ j₀ + Σ coverages` has error `0` +on every edge inside rows `j₀ … j₀+m`. -/ +theorem coverage_reading_exact (j₀ : ℤ) (m : ℕ) (e : ℝ) (h0 : (j₀ : ℝ) ≤ e) (h1 : e ≤ j₀ + m) : + |((j₀ : ℝ) + ∑ r ∈ range m, coverage (subgraph fun _ => e) 0 (j₀ + r)) - e| = 0 := by + rw [column_sum_reading e 0 j₀ m h0 h1, sub_self, abs_zero] + +end Inkvec diff --git a/formal/InkvecTheory/InkvecTheory/Rank.lean b/formal/InkvecTheory/InkvecTheory/Rank.lean new file mode 100644 index 00000000..5d16449d --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Rank.lean @@ -0,0 +1,46 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import Mathlib + +/-! +# Counting flat directions + +The boundary solve (`crates/inkvec-trace/src/boundary_opt.rs`) gives every boundary point +two unknowns, `x` and `y`. Linearised, its data term is a linear map from `2N` point +coordinates to the `M` band pixels' values; rank–nullity then forces at least `2N - M` flat +directions on it, whatever the image. `polyline_kernel` (in `NullSpace.lean`) shows the +smallest case exactly: `n + 1` vertices moving across an `n`-column run inside one pixel row +leave precisely one flat direction, the zigzag. + +The remedy the theory gives is not a heavier prior but fewer unknowns than measurements, +in a family the measurements identify: `polynomial_boundary_determined` (in +`Identifiability.lean`) is the statement that a curve model of dimension at most the number +of columns it spans has no flat direction at all. +-/ + +namespace Inkvec + +/-- **Rank–nullity for the boundary solve.** Any linear map from `N` free points of the plane +to `M` pixel values has a kernel of dimension at least `2N - M`. -/ +theorem flat_directions (N M : ℕ) (J : (Fin N → ℝ × ℝ) →ₗ[ℝ] (Fin M → ℝ)) : + 2 * N ≤ M + Module.finrank ℝ (LinearMap.ker J) := by + have h := LinearMap.finrank_range_add_finrank_ker J + have hr : Module.finrank ℝ (LinearMap.range J) ≤ M := by + have := Submodule.finrank_le (LinearMap.range J) + simpa using this + have hd : Module.finrank ℝ (Fin N → ℝ × ℝ) = 2 * N := by + rw [Module.finrank_pi_fintype]; simp [Module.finrank_prod]; ring + omega + +/-- The same count with motion along a fixed normal only (one unknown per point). -/ +theorem flat_directions_normal (N M : ℕ) (J : (Fin N → ℝ) →ₗ[ℝ] (Fin M → ℝ)) : + N ≤ M + Module.finrank ℝ (LinearMap.ker J) := by + have h := LinearMap.finrank_range_add_finrank_ker J + have hr : Module.finrank ℝ (LinearMap.range J) ≤ M := by + have := Submodule.finrank_le (LinearMap.range J) + simpa using this + simp at h + omega + +end Inkvec diff --git a/formal/InkvecTheory/InkvecTheory/Supersampling.lean b/formal/InkvecTheory/InkvecTheory/Supersampling.lean new file mode 100644 index 00000000..8cba772b --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Supersampling.lean @@ -0,0 +1,147 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import InkvecTheory.Basic + +/-! +# Renderers that supersample instead of integrating + +The other files assume exact area coverage (`Coverage.lean`). Many renderers instead +point-sample an `n × n` grid inside each pixel and write the fraction of samples inside the +shape; inkvec's own regression corpus is rendered that way at `n = 8` +(`bench/ci_gate.py`). What does a column sum read then? + +* `subCount_close`: of the `N` sub-rows of a column, the number whose centre lies below a + height `h` is `n·h` to within one half. +* `ss_column_sum_close`: the column sum of `n × n` supersampled coverage equals the + `n`-point midpoint rule of the boundary height across the column to within `1/(2n)` px, + whatever the boundary. + +So on an 8x8 corpus the strip reading's error is at most `1/16` px of quantisation above the +midpoint rule's, which is why it is measured at 0.008 px mean error on 8x8 renders against +0.001 px on exact ones (`bench/theory`). On a boundary aligned with the sample grid the +pixels themselves cannot do better: no sample changes until the boundary crosses a sample +row (an informal remark; `quantize_minimax` in `Quantization.lean` is the formal bound for +quantised coverage). +-/ + +namespace Inkvec + +open Finset + +/-- How many of the `N` sub-row centres `(u + ½)/n`, `u < N`, lie below height `h`. -/ +noncomputable def subCount (n N : ℕ) (h : ℝ) : ℝ := + ∑ u ∈ range N, if ((u : ℝ) + 1 / 2) / n < h then 1 else 0 + +/-- **Counting sub-rows reads a height to within half a sub-row.** -/ +theorem subCount_close (n N : ℕ) (hn : 0 < n) (h : ℝ) (h0 : 0 ≤ h) (h1 : h * n ≤ N) : + |subCount n N h / n - h| ≤ 1 / (2 * n) := by + have hnr : (0 : ℝ) < n := by exact_mod_cast hn + set H := h * n with hH + have hH0 : 0 ≤ H := by positivity + -- the indicator in terms of `H` + have hind : ∀ u : ℕ, (((u : ℝ) + 1 / 2) / n < h) ↔ ((u : ℝ) + 1 / 2 < H) := by + intro u; rw [div_lt_iff₀ hnr] + -- the exact count `Σ clamp01 (H - u) = H`, and the per-sub-row differences + have hexact : ∑ u ∈ range N, clamp01 (H - u) = H := sum_clamp01_of_mem hH0 h1 + set d : ℕ → ℝ := fun u => (if ((u : ℝ) + 1 / 2) / n < h then 1 else 0) - clamp01 (H - u) + have hsum : subCount n N h - H = ∑ u ∈ range N, d u := by + unfold subCount; simp only [d, sum_sub_distrib, hexact] + set a := ⌊H⌋₊ + have ha0 : (a : ℝ) ≤ H := Nat.floor_le hH0 + have ha1 : H < a + 1 := Nat.lt_floor_add_one H + have hzero : ∀ b : ℕ, b ≠ a → d b = 0 := by + intro b hb + simp only [d] + rcases Nat.lt_or_gt_of_ne hb with hlt | hgt + · have : (b : ℝ) + 1 ≤ a := by exact_mod_cast hlt + have hc : ((b : ℝ) + 1 / 2) / n < h := (hind b).mpr (by linarith) + simp only [hc, ↓reduceIte]; rw [clamp01_of_one_le (by linarith)]; ring + · have : (a : ℝ) + 1 ≤ b := by exact_mod_cast hgt + have hc : ¬ (((b : ℝ) + 1 / 2) / n < h) := fun h' => by have := (hind b).mp h'; linarith + simp only [hc, ↓reduceIte]; rw [clamp01_of_nonpos (by linarith)] + ring + have hda : |d a| ≤ 1 / 2 := by + simp only [d] + rw [clamp01_of_mem (by linarith) (by linarith)] + by_cases hc : ((a : ℝ) + 1 / 2) / n < h + · simp only [hc, ↓reduceIte]; have := (hind a).mp hc + rw [abs_le]; constructor <;> linarith + · simp only [hc, ↓reduceIte]; have : ¬ ((a : ℝ) + 1 / 2 < H) := fun h' => hc ((hind a).mpr h') + rw [abs_le]; constructor <;> linarith + have hsingle : ∑ u ∈ range N, d u = if a ∈ range N then d a else 0 := by + split_ifs with hmem + · exact sum_eq_single a (fun b _ hb => hzero b hb) (fun h' => absurd hmem h') + · exact sum_eq_zero (fun b hb => hzero b (fun h' => hmem (h' ▸ hb))) + have hbound : |subCount n N h - H| ≤ 1 / 2 := by + rw [hsum, hsingle]; split_ifs + · exact hda + · simp + have : subCount n N h / n - h = (subCount n N h - H) / n := by + rw [hH]; field_simp + rw [this, abs_div, abs_of_pos hnr, div_le_div_iff₀ hnr (by positivity)] + nlinarith [hbound] + +/-- The abscissa of the `s`-th sample column of pixel column `i` under `n × n` sampling. -/ +noncomputable def sampleX (n : ℕ) (i : ℤ) (s : ℕ) : ℝ := i + ((s : ℝ) + 1 / 2) / n + +/-- `n × n` point-supersampled coverage of the region below the graph of `f` in pixel +`(i, j)`: the fraction of the sample points `(i + (s+½)/n, j + (t+½)/n)` below the graph. -/ +noncomputable def ssCoverage (n : ℕ) (f : ℝ → ℝ) (i j : ℤ) : ℝ := + (∑ s ∈ range n, ∑ t ∈ range n, + if (j : ℝ) + ((t : ℝ) + 1 / 2) / n < f (sampleX n i s) then 1 else 0) / (n : ℝ) ^ 2 + +lemma sum_range_mul_add (G : ℕ → ℝ) (n : ℕ) : + ∀ m : ℕ, ∑ r ∈ range m, ∑ t ∈ range n, G (r * n + t) = ∑ u ∈ range (m * n), G u + | 0 => by simp + | m + 1 => by + rw [sum_range_succ, sum_range_mul_add G n m, Nat.succ_mul, sum_range_add] + +/-- The column sum of supersampled coverage, reorganised as sub-row counts per sample column. -/ +lemma ss_column_sum (n m : ℕ) (hn : 0 < n) (f : ℝ → ℝ) (i j₀ : ℤ) : + ∑ r ∈ range m, ssCoverage n f i (j₀ + r) = + (∑ s ∈ range n, subCount n (m * n) (f (sampleX n i s) - j₀)) / (n : ℝ) ^ 2 := by + have hnr : (0 : ℝ) < n := by exact_mod_cast hn + unfold ssCoverage subCount + rw [← sum_div, sum_comm] + congr 1 + refine sum_congr rfl (fun s _ => ?_) + rw [← sum_range_mul_add + (fun u => if ((u : ℝ) + 1 / 2) / n < f (sampleX n i s) - j₀ then (1 : ℝ) else 0) n m] + refine sum_congr rfl (fun r _ => sum_congr rfl (fun t _ => ?_)) + have : ((j₀ + r : ℤ) : ℝ) + ((t : ℝ) + 1 / 2) / n < f (sampleX n i s) ↔ + (((r * n + t : ℕ) : ℝ) + 1 / 2) / n < f (sampleX n i s) - j₀ := by + push_cast + rw [show ((r : ℝ) * n + t + 1 / 2) / n = r + (t + 1 / 2) / n by field_simp; ring] + constructor <;> intro h <;> linarith + simp only [this] + +/-- **The supersampled column sum is the midpoint rule, to within `1/(2n)`.** If at each of +the column's `n` sample abscissae the boundary lies within rows `j₀ … j₀+m`, the column sum of +`n × n` supersampled coverage is within `1/(2n)` px of the mean boundary height at those +abscissae (above `j₀`). -/ +theorem ss_column_sum_close (n m : ℕ) (hn : 0 < n) (f : ℝ → ℝ) (i j₀ : ℤ) + (hlo : ∀ s < n, (j₀ : ℝ) ≤ f (sampleX n i s)) + (hhi : ∀ s < n, f (sampleX n i s) ≤ j₀ + m) : + |∑ r ∈ range m, ssCoverage n f i (j₀ + r) - + (∑ s ∈ range n, (f (sampleX n i s) - j₀)) / n| ≤ 1 / (2 * n) := by + have hnr : (0 : ℝ) < n := by exact_mod_cast hn + rw [ss_column_sum n m hn f i j₀] + have key : (∑ s ∈ range n, subCount n (m * n) (f (sampleX n i s) - j₀)) / (n : ℝ) ^ 2 - + (∑ s ∈ range n, (f (sampleX n i s) - j₀)) / n = + (∑ s ∈ range n, (subCount n (m * n) (f (sampleX n i s) - j₀) / n - + (f (sampleX n i s) - j₀))) / n := by + conv_rhs => rw [sum_sub_distrib, ← sum_div] + field_simp + rw [key, abs_div, abs_of_pos hnr, div_le_iff₀ hnr] + calc |∑ s ∈ range n, (subCount n (m * n) (f (sampleX n i s) - j₀) / n - (f (sampleX n i s) - j₀))| + ≤ ∑ s ∈ range n, |subCount n (m * n) (f (sampleX n i s) - j₀) / n - (f (sampleX n i s) - j₀)| := + abs_sum_le_sum_abs _ _ + _ ≤ ∑ _s ∈ range n, 1 / (2 * (n : ℝ)) := by + refine sum_le_sum (fun s hs => subCount_close n (m * n) hn _ ?_ ?_) + · have := hlo s (mem_range.mp hs); linarith + · have := hhi s (mem_range.mp hs); push_cast + nlinarith + _ = 1 / (2 * n) * n := by rw [sum_const, card_range, nsmul_eq_mul]; ring + +end Inkvec diff --git a/formal/InkvecTheory/InkvecTheory/ThinStroke.lean b/formal/InkvecTheory/InkvecTheory/ThinStroke.lean new file mode 100644 index 00000000..6ea7428b --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/ThinStroke.lean @@ -0,0 +1,163 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import InkvecTheory.LevelSetBias + +/-! +# Strokes thinner than a pixel + +A stroke is the region between two boundaries `lo ≤ hi`. When it is thinner than a pixel, +its pixels never read full coverage, and `planar::ridge_offset` reads it from its coverage +centroid and integrated width (`bench/cases` `ribbon_w1`, `docs/algorithm/07-subpixel.md`). +This file settles exactly what such a stroke's pixels determine: + +* `coverage_band`: a stroke's coverage is the difference of its two boundaries' coverages + (Lebesgue measure, no assumption). +* `straddle_inversion`: when the stroke crosses a pixel border along a whole column, the two + pixels it touches give its mean centre line and mean width **exactly**: + `centre = j + 1 + (aHi - aLo)/2`, `width = aLo + aHi`. +* `hidden_stroke_invisible`: when it lies inside one pixel row, every position inside that + row gives the same pixels. The position is undetermined within `1 - w` px, and only a prior + can place it (the minimax choice is the pixel centre). +* `centroid_bias`: in the straddling case the centroid reading `ridge_offset` uses is off by + `(1 - w)(aHi/w - ½)`, which reaches `(1 - w)/2`: as bad as not knowing the position at all, + in exactly the case where it is known. +* `width_contrast_ambiguity`: a hidden stroke's pixels fix only the product of its width + and its ink contrast (`coverage.rs`: "A 0.3px black stroke and a 1px grey stroke produce + the same pixels"). +-/ + +namespace Inkvec + +open Set MeasureTheory Finset + +/-- The region between two boundaries. -/ +def band (lo hi : ℝ → ℝ) : Set (ℝ × ℝ) := subgraph hi \ subgraph lo + +lemma measurableSet_subgraph {f : ℝ → ℝ} (hf : Continuous f) : MeasurableSet (subgraph f) := + measurableSet_lt measurable_snd (hf.measurable.comp measurable_fst) + +lemma volume_pixel_lt_top (i j : ℤ) : volume (pixel i j) < ⊤ := by + unfold pixel + rw [Measure.volume_eq_prod, Measure.prod_prod] + simp [Real.volume_Ioo] + +/-- **A stroke's coverage is a difference of two edges' coverages.** -/ +theorem coverage_band (lo hi : ℝ → ℝ) (hlo : Continuous lo) (hle : ∀ x, lo x ≤ hi x) + (i j : ℤ) : coverage (band lo hi) i j = coverage (subgraph hi) i j - coverage (subgraph lo) i j := by + unfold coverage band + have hsub : subgraph lo ∩ pixel i j ⊆ subgraph hi ∩ pixel i j := + fun p hp => ⟨lt_of_lt_of_le hp.1 (hle p.1), hp.2⟩ + have hmeas : MeasurableSet (subgraph lo ∩ pixel i j) := + (measurableSet_subgraph hlo).inter (measurableSet_Ioo.prod measurableSet_Ioo) + have hfin : volume (subgraph hi ∩ pixel i j) ≠ ⊤ := + ((measure_mono inter_subset_right).trans_lt (volume_pixel_lt_top i j)).ne + have hset : (subgraph hi \ subgraph lo) ∩ pixel i j = + (subgraph hi ∩ pixel i j) \ (subgraph lo ∩ pixel i j) := by + ext p + constructor + · rintro ⟨⟨h1, h2⟩, h3⟩; exact ⟨⟨h1, h3⟩, fun h => h2 h.1⟩ + · rintro ⟨⟨h1, h3⟩, h2⟩; exact ⟨⟨h1, fun h => h2 ⟨h, h3⟩⟩, h3⟩ + rw [hset, measure_sdiff hsub hmeas.nullMeasurableSet + (ne_top_of_le_ne_top hfin (measure_mono hsub)), ENNReal.toReal_sub_of_le (measure_mono hsub) hfin] + +/-- **Exact inversion of a straddling stroke.** If over column `i` the stroke's lower edge +stays in row `j` and its upper edge in row `j+1`, the two pixels read +`aLo = j + 1 - mean lo` and `aHi = mean hi - (j + 1)`, so the column mean of the centre line is +`j + 1 + (aHi - aLo)/2` and the column mean of the width is `aLo + aHi`, exactly. -/ +theorem straddle_inversion (lo hi : ℝ → ℝ) (hlo : Continuous lo) (hhi : Continuous hi) + (hle : ∀ x, lo x ≤ hi x) (i j : ℤ) + (hlo_row : ∀ x ∈ Icc (i : ℝ) (i + 1), (j : ℝ) ≤ lo x ∧ lo x ≤ j + 1) + (hhi_row : ∀ x ∈ Icc (i : ℝ) (i + 1), (j : ℝ) + 1 ≤ hi x ∧ hi x ≤ j + 2) : + let aLo := coverage (band lo hi) i j + let aHi := coverage (band lo hi) i (j + 1) + let mlo := ∫ x in (i : ℝ)..(i + 1), lo x + let mhi := ∫ x in (i : ℝ)..(i + 1), hi x + aLo = j + 1 - mlo ∧ aHi = mhi - (j + 1) ∧ + (mlo + mhi) / 2 = j + 1 + (aHi - aLo) / 2 ∧ mhi - mlo = aLo + aHi := by + intro aLo aHi mlo mhi + have hI : (i : ℝ) ≤ i + 1 := by linarith + have congr_on : ∀ {F G : ℝ → ℝ}, (∀ x ∈ Icc (i : ℝ) (i + 1), F x = G x) → + ∫ x in (i : ℝ)..(i + 1), F x = ∫ x in (i : ℝ)..(i + 1), G x := fun h => + intervalIntegral.integral_congr (fun x hx => h x (by rwa [uIcc_of_le hI] at hx)) + have hm : aLo = j + 1 - mlo := by + show coverage _ i j = _ + rw [coverage_band lo hi hlo hle, coverage_subgraph hi hhi, coverage_subgraph lo hlo, + congr_on (G := fun _ => (1 : ℝ)) (fun x hx => clamp01_of_one_le (by linarith [hhi_row x hx])), + congr_on (G := fun x => lo x - j) (fun x hx => clamp01_of_mem + (by linarith [hlo_row x hx]) (by linarith [hlo_row x hx])), + intervalIntegral.integral_sub (hlo.intervalIntegrable _ _) intervalIntegrable_const] + simp [mlo]; ring + have hp : aHi = mhi - (j + 1) := by + show coverage _ i (j + 1) = _ + rw [coverage_band lo hi hlo hle, coverage_subgraph hi hhi, coverage_subgraph lo hlo, + congr_on (G := fun x => hi x - ((j + 1 : ℤ) : ℝ)) (fun x hx => clamp01_of_mem + (by push_cast; linarith [hhi_row x hx]) (by push_cast; linarith [hhi_row x hx])), + congr_on (G := fun _ => (0 : ℝ)) (fun x hx => clamp01_of_nonpos + (by push_cast; linarith [hlo_row x hx])), + intervalIntegral.integral_sub (hhi.intervalIntegrable _ _) intervalIntegrable_const] + simp [mhi] + refine ⟨hm, hp, ?_, ?_⟩ <;> rw [hm, hp] <;> ring + +/-- **A stroke inside one pixel row is invisible to position.** Two strokes of the same +width `w`, both lying inside row `j`, have the same coverage at every pixel. -/ +theorem hidden_stroke_invisible (c c' w : ℝ) (j : ℤ) (hw : 0 ≤ w) + (hc : (j : ℝ) ≤ c - w / 2 ∧ c + w / 2 ≤ j + 1) + (hc' : (j : ℝ) ≤ c' - w / 2 ∧ c' + w / 2 ≤ j + 1) (i j' : ℤ) : + coverage (band (fun _ => c - w / 2) (fun _ => c + w / 2)) i j' = + coverage (band (fun _ => c' - w / 2) (fun _ => c' + w / 2)) i j' := by + rw [coverage_band _ _ continuous_const (fun _ => by linarith), + coverage_band _ _ continuous_const (fun _ => by linarith), + coverage_flat, coverage_flat, coverage_flat, coverage_flat] + rcases lt_trichotomy j' j with h | rfl | h + · have : (j' : ℝ) + 1 ≤ j := by exact_mod_cast h + rw [clamp01_of_one_le (by linarith), clamp01_of_one_le (by linarith), + clamp01_of_one_le (by linarith), clamp01_of_one_le (by linarith)] + · rw [clamp01_of_mem (by linarith) (by linarith), clamp01_of_mem (by linarith) (by linarith), + clamp01_of_mem (by linarith) (by linarith), clamp01_of_mem (by linarith) (by linarith)] + ring + · have : (j : ℝ) + 1 ≤ j' := by exact_mod_cast h + rw [clamp01_of_nonpos (by linarith), clamp01_of_nonpos (by linarith), + clamp01_of_nonpos (by linarith), clamp01_of_nonpos (by linarith)] + +/-- **The centroid's bias on a straddling stroke.** With the two pixels' coverages +`aLo = j + 1 - lo` and `aHi = hi - (j + 1)` of a stroke `[lo, hi]` of width `w = hi - lo > 0`, +the coverage centroid of the two pixel centres is off the stroke's centre by +`(1 - w)·(aHi/w - ½)`. -/ +theorem centroid_bias (lo hi : ℝ) (j : ℤ) (hw : 0 < hi - lo) : + let aLo := (j : ℝ) + 1 - lo + let aHi := hi - (j + 1) + let w := hi - lo + (aLo * (j + 1 / 2) + aHi * (j + 3 / 2)) / (aLo + aHi) - (lo + hi) / 2 = + (1 - w) * (aHi / w - 1 / 2) := by + intro aLo aHi w + have hs : aLo + aHi = w := by simp only [aLo, aHi, w]; ring + rw [hs] + have hw' : w ≠ 0 := ne_of_gt hw + field_simp + simp only [aLo, aHi, w] + ring + +/-- The centroid's bias reaches `(1 - w)/2` while the stroke still straddles: put a stroke of +width `w < 1` with its upper edge exactly on the border (`aHi = 0`). -/ +theorem centroid_bias_worst (w : ℝ) (j : ℤ) (hw0 : 0 < w) : + let lo := (j : ℝ) + 1 - w + let hi := (j : ℝ) + 1 + ((j + 1 - lo) * (j + 1 / 2) + (hi - (j + 1)) * (j + 3 / 2)) / ((j + 1 - lo) + (hi - (j + 1))) + - (lo + hi) / 2 = -(1 - w) / 2 := by + intro lo hi + have hw' : w ≠ 0 := ne_of_gt hw0 + have hden : ((j : ℝ) + 1 - lo) + (hi - ((j : ℝ) + 1)) = w := by simp only [lo, hi]; ring + rw [hden] + simp only [lo, hi] + field_simp + ring + +/-- **Width and contrast trade off.** A hidden stroke of width `w` in ink `F` on ground `B` +writes `B + w·(F - B)` into its pixel; so does width `w'` in ink `B + (w/w')·(F - B)`. -/ +theorem width_contrast_ambiguity (B F w w' : ℝ) (hw' : w' ≠ 0) : + B + w * (F - B) = B + w' * ((B + (w / w') * (F - B)) - B) := by + field_simp + ring + +end Inkvec diff --git a/formal/InkvecTheory/InkvecTheory/Windows.lean b/formal/InkvecTheory/InkvecTheory/Windows.lean new file mode 100644 index 00000000..6f63ce93 --- /dev/null +++ b/formal/InkvecTheory/InkvecTheory/Windows.lean @@ -0,0 +1,121 @@ +/- +Copyright (c) 2026 LogoLabs. Released under the Apache 2.0 licence (see LICENSE). +-/ +import InkvecTheory.ThinStroke + +/-! +# Windows: any set of whole pixels measures an area + +The boundary chain scores a candidate description against the pixels by windows +(`docs/theory/chain-boundary.md`, B2.1; `crates/inkvec-trace/src/evidence.rs`): + +* `window_sum_eq_area`: summed over any finite set of pixels, a region's coverages are its + area inside their union, for every measurable region. No graph, slope or threshold enters; + `column_sum_eq_average` is the case of a graph and one column. +* `trapezoid_integral`: the integral of the straight piece from `(ua, va)` to `(ub, vb)`, + measured from a level `vlo`, is the trapezoid `(ub − ua)((va − vlo) + (vb − vlo))/2`: the + per-piece area the window checker sums (`Gen/Evidence.lean`, `trapezoidK`). +-/ + +namespace Inkvec + +open Set MeasureTheory Finset + +lemma measurableSet_pixel (i j : ℤ) : MeasurableSet (pixel i j) := + measurableSet_Ioo.prod measurableSet_Ioo + +lemma disjoint_Ioo_int {i i' : ℤ} (h : i ≠ i') : + Disjoint (Ioo (i : ℝ) (i + 1)) (Ioo (i' : ℝ) (i' + 1)) := by + rw [Set.disjoint_left] + intro x hx hx' + rcases lt_or_gt_of_ne h with hl | hl + · have : (i : ℝ) + 1 ≤ i' := by exact_mod_cast hl + linarith [hx.2, hx'.1] + · have : (i' : ℝ) + 1 ≤ i := by exact_mod_cast hl + linarith [hx.1, hx'.2] + +/-- Distinct pixels are disjoint. -/ +lemma disjoint_pixel {p q : ℤ × ℤ} (h : p ≠ q) : Disjoint (pixel p.1 p.2) (pixel q.1 q.2) := by + unfold pixel + by_cases h1 : p.1 = q.1 + · have h2 : p.2 ≠ q.2 := fun h2 => h (Prod.ext h1 h2) + exact Set.disjoint_prod.mpr (Or.inr (disjoint_Ioo_int h2)) + · exact Set.disjoint_prod.mpr (Or.inl (disjoint_Ioo_int h1)) + +/-- **The window identity.** Summed over any finite set `W` of pixels, the coverages of a +measurable region are its area inside the pixels' union. -/ +theorem window_sum_eq_area (Ω : Set (ℝ × ℝ)) (hΩ : MeasurableSet Ω) (W : Finset (ℤ × ℤ)) : + ∑ p ∈ W, coverage Ω p.1 p.2 = (volume (Ω ∩ ⋃ p ∈ W, pixel p.1 p.2)).toReal := by + have hfin : ∀ p ∈ W, volume (Ω ∩ pixel p.1 p.2) ≠ ⊤ := fun p _ => + ((measure_mono inter_subset_right).trans_lt (volume_pixel_lt_top p.1 p.2)).ne + unfold coverage + rw [← ENNReal.toReal_sum hfin, Set.inter_iUnion₂, measure_biUnion_finset] + · intro p _ q _ hpq + exact (disjoint_pixel hpq).mono inter_subset_right inter_subset_right + · intro p _ + exact hΩ.inter (measurableSet_pixel _ _) + +/-- **A straight piece's area above a level.** The integral of the affine interpolant from +`(ua, va)` to `(ub, vb)`, less `vlo`, is the trapezoid. -/ +theorem trapezoid_integral (ua va ub vb vlo : ℝ) (h : ua ≠ ub) : + ∫ u in ua..ub, (va + (u - ua) / (ub - ua) * (vb - va) - vlo) = + (ub - ua) * ((va - vlo) + (vb - vlo)) / 2 := by + have hd : ub - ua ≠ 0 := sub_ne_zero.mpr (Ne.symm h) + set k := (vb - va) / (ub - ua) with hk + have hf : ∀ u : ℝ, va + (u - ua) / (ub - ua) * (vb - va) - vlo = (va - vlo - ua * k) + u * k := by + intro u; rw [hk]; field_simp; ring + simp_rw [hf] + have h1 : IntervalIntegrable (fun _ : ℝ => va - vlo - ua * k) volume ua ub := + intervalIntegrable_const + have h2 : IntervalIntegrable (fun u : ℝ => u * k) volume ua ub := + (continuous_id.mul continuous_const).intervalIntegrable _ _ + rw [intervalIntegral.integral_add h1 h2, intervalIntegral.integral_const, + intervalIntegral.integral_mul_const, integral_id, smul_eq_mul, hk] + field_simp + ring + +/-! ## Window sums under a blur or a resampling + +A resized or blurred intake's pixel `y` reads `Σ_s w(y, s) c(s)` of the exact image's pixels +`c` (`docs/theory/noise.md`, `chain-boundary.md` "Blur"). Summed over a window, the window +identity survives whenever every input pixel the window draws on gives the window its whole +weight (`window_sum_resampled`): an integer-ratio box filter does, a general resampler only +on average over phase, and what it leaves is its phase ripple. Along the strip a centred +kernel leaves a straight edge's area profile alone (`blur_affine_profile`) and moves a +curved one by exactly half its second moment times the profile's second derivative +(`blur_quadratic_profile`): the forward model's correction, not noise. -/ + +/-- **Mass preservation over a window.** If every input pixel `s ∈ S` gives the window `Y` +its whole weight (`Σ_{y∈Y} w y s = 1`), the window's resampled sum is the inputs' sum. -/ +theorem window_sum_resampled (Y S : Finset ℤ) (w : ℤ → ℤ → ℝ) (c : ℤ → ℝ) + (hw : ∀ s ∈ S, ∑ y ∈ Y, w y s = 1) : + ∑ y ∈ Y, ∑ s ∈ S, w y s * c s = ∑ s ∈ S, c s := by + rw [Finset.sum_comm] + refine Finset.sum_congr rfl fun s hs => ?_ + rw [← Finset.sum_mul, hw s hs, one_mul] + +/-- **A centred kernel leaves an affine profile alone.** For weights `k` on a finite set of +offsets with `Σ k = 1` and `Σ k i · i = 0`, the blurred profile of `A x = α + β x` is `A`. -/ +theorem blur_affine_profile (I : Finset ℤ) (k : ℤ → ℝ) (hk : ∑ i ∈ I, k i = 1) + (hm : ∑ i ∈ I, k i * i = 0) (α β x : ℝ) : + ∑ i ∈ I, k i * (α + β * (x - i)) = α + β * x := by + have e : ∀ i ∈ I, k i * (α + β * (x - i)) = (α + β * x) * k i - β * (k i * i) := by + intro i _; ring + rw [Finset.sum_congr rfl e, Finset.sum_sub_distrib, ← Finset.mul_sum, ← Finset.mul_sum, hk, + hm] + ring + +/-- **A centred kernel moves a curved profile by `½ μ₂ A''`.** With `μ₂ = Σ k i · i²`, the +blurred profile of `A x = α + β x + γ x²` is `A x + γ μ₂`, and `A'' = 2γ`. -/ +theorem blur_quadratic_profile (I : Finset ℤ) (k : ℤ → ℝ) (hk : ∑ i ∈ I, k i = 1) + (hm : ∑ i ∈ I, k i * i = 0) (α β γ x : ℝ) : + ∑ i ∈ I, k i * (α + β * (x - i) + γ * (x - i) ^ 2) = + α + β * x + γ * x ^ 2 + (1 / 2) * (∑ i ∈ I, k i * (i : ℝ) ^ 2) * (2 * γ) := by + have e : ∀ i ∈ I, k i * (α + β * (x - i) + γ * (x - i) ^ 2) = + (α + β * x + γ * x ^ 2) * k i - (β + 2 * γ * x) * (k i * i) + γ * (k i * (i : ℝ) ^ 2) := by + intro i _; ring + rw [Finset.sum_congr rfl e, Finset.sum_add_distrib, Finset.sum_sub_distrib, ← Finset.mul_sum, + ← Finset.mul_sum, ← Finset.mul_sum, hk, hm] + ring + +end Inkvec diff --git a/formal/InkvecTheory/README.md b/formal/InkvecTheory/README.md new file mode 100644 index 00000000..264598ed --- /dev/null +++ b/formal/InkvecTheory/README.md @@ -0,0 +1,129 @@ +# InkvecTheory — machine-checked theory of inverting box-filter rasterisation + +A Lean 4 / Mathlib library proving what an anti-aliased raster does and does not determine +about the shapes drawn into it, and what that implies for a tracer. Every result is proved +from Lebesgue measure on `ℝ²` or from first principles. **The library has no `sorry`, and no +axiom of its own.** `Audit.lean` prints the axioms each headline theorem uses; every line +reads `[propext, Classical.choice, Quot.sound]`, Lean's three standard axioms. + +The prose companion, with the literature survey, the comparison against prior work and the +measured effect on inkvec, is [`docs/theory/README.md`](../../docs/theory/README.md). + +## Build + +```bash +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh | sh -s -- -y --default-toolchain none +cd formal/InkvecTheory +lake exe cache get # prebuilt Mathlib (about 5 GB); skips hours of compiling +lake build # the library: about a minute and a half on four cores +lake build InkvecTheory.Audit # prints the axiom audit +``` + +Toolchain and Mathlib are pinned in `lean-toolchain` and `lake-manifest.json` +(Lean 4.34.1, Mathlib `v4.34.1`). + +## The model, stated once + +* **Pixel** `(i, j)` is the open square `(i, i+1) × (j, j+1)`; inkvec's code puts pixel + centres on integers, so its coordinates are these minus ½. +* **Box-filter coverage** `coverage Ω i j` is the Lebesgue area of `Ω ∩ pixel i j` + (`Coverage.lean`). This is what exact-area renderers write (libart, FreeType's smooth + rasteriser, font-rs, inkvec's own `boundary_opt/band.rs`). Point-supersampling renderers + are treated separately (`Supersampling.lean`). +* A **boundary** is, locally, the graph of a continuous function over one axis: the shape is + `subgraph f = {(x, y) | y < f x}`. Every orientation reduces to this one by symmetry, and + the hypotheses say exactly where the graph must lie. +* Two-colour **unmixing** (`coverage.rs`: `a = (P − B)·(F − B)/|F − B|²`) is taken as given: + the theorems are about the coverage `a`. + +## Theorems, and the code each bears on + +| file | theorem | statement | inkvec code | +|---|---|---|---| +| `Coverage` | `coverage_subgraph` | the area of a graph's subgraph in a pixel is `∫ clamp01 (f x − j)` over the pixel's column | the model every stage assumes (`coverage.rs`) | +| `Coverage` | `column_sum_eq_average` | **a column's coverages sum to the column mean of the boundary height**, for every continuous graph, whatever its slope or curvature | `planar/strip.rs` `line_mean` | +| `NullSpace` | `invisible_perturbation` | a zero-mean perturbation that keeps the boundary in one pixel row changes no pixel | the sawtooth of `boundary_opt` (`08-boundary-solve.md`) | +| `NullSpace` | `sine_ripple_invisible`, `rasterization_not_injective` | two different shapes with identical coverage at every pixel of the plane, at every frequency | why the boundary solve needs a prior | +| `NullSpace` | `polyline_zigzag_invisible`, `polyline_kernel` | with one vertex per pixel border, the zigzag `δ(−1)ᵏ` is invisible and is the **only** invisible deformation: the null space is exactly one-dimensional | `boundary_opt.rs` priors (`K_KINK`) | +| `NullSpace` | `coverage_layer_cake`, `column_fiber` | a column's coverages determine, and are determined by, `t ↦ ∫ (f − t)₊` at integer `t`: rearranging the boundary inside a column is invisible | — | +| `Identifiability` | `zeros_of_zero_averages` | zero means on `n` cells force `n` distinct zeros | — | +| `Identifiability` | `poly_eq_of_averages` | a polynomial of degree `< n` is determined by its means on `n` cells (histopolation is unisolvent) | `strip.rs` `histopolate` | +| `Identifiability` | `polynomial_boundary_determined` | **polynomial boundaries of degree `< n` are determined by their pixels on `n` columns** | `inkvec-fit` model selection | +| `Identifiability` | `line_from_two_columns` | closed form: `s = S₁ − S₀`, `b = S₀ + j₀ − s(i + ½)` | — | +| `Deconvolution` | `cubic_point_from_means` | `A − (A₊ − 2A + A₋)/24` is the centre value of **every cubic** | — | +| `Deconvolution` | `quartic_defect` | the first missed term is `−(3/640)·f''''` | — | +| `Deconvolution` | `boundary_point_from_pixels` | from raw pixel areas of three columns, the exact boundary point of a cubic boundary | `strip.rs` | +| `Deconvolution` | `strip_reading_exact` | **end to end: from the raw pixel areas of four columns, `strip.rs`'s `histopolate` returns the boundary cubic's own coefficients** | `strip.rs` `strip_along` | +| `Deconvolution` | `histopolate_cubic`, `face_value_cubic`, `side_stencil_cubic` | **the rational constants in `strip.rs` are exact**: its `histopolate` returns any cubic's coefficients from its four cell means; the face value `(7(m₁+m₂) − (m₀+m₃))/12`; the one-sided stencils of its corner test agree on every cubic | `strip.rs` `histopolate`, `SIDE_TOL` test | +| `LevelSetBias` | `levelSet_reading`, `levelSetBias_le`, `levelSetBias_max` | reading an edge at the ½-crossing of interpolated coverage is off by up to **`3/2 − √2 ≈ 0.0858 px` on a straight noiseless step, and the bound is attained** | `contour.rs`, `planar::root_find_half`, `DEFAULT_SIGMA_MODEL` | +| `LevelSetBias` | `column_sum_reading` | the column sum reads the same edges exactly | `strip.rs` | +| `Quantization` | `binarize_minimax` | **any** estimator reading thresholded pixels is off by ≥ ½ − η px on some edge | Potrace-, VTracer-class tracers | +| `Quantization` | `quantize_minimax` | any `L`-level quantiser (any function at all) costs ≥ `δ/2` for every `δ < 1/L` | — | +| `ThinStroke` | `coverage_band` | a stroke's coverage is the difference of its edges' coverages | — | +| `ThinStroke` | `straddle_inversion` | a sub-pixel stroke straddling a pixel border is read **exactly**: centre `j + 1 + (a₊ − a₋)/2`, width `a₋ + a₊` | `planar::ridge_offset` | +| `ThinStroke` | `hidden_stroke_invisible` | inside one pixel its position is undetermined within `1 − w` | — | +| `ThinStroke` | `centroid_bias`, `centroid_bias_worst` | the coverage centroid is off by `(1 − w)(a₊/w − ½)`, up to `(1 − w)/2` | `planar::ridge_offset` | +| `ThinStroke` | `width_contrast_ambiguity` | a hidden stroke fixes only width × contrast | `coverage.rs` `saturation` | +| `Rank` | `flat_directions` | `N` free points against `M` pixels leave ≥ `2N − M` flat directions | `boundary_opt.rs` unknowns | +| `Noise` | `strip_unbiased`, `strip_variance` | zero-mean pixel noise leaves the column sum unbiased, variance `k·σ²` | `strip.rs` | +| `Noise` | `face_value_noise`, `point_from_means_noise` | the face value has noise gain `25/36`, the point correction `113/96` | `strip.rs` | +| `Supersampling` | `subCount_close`, `ss_column_sum_close` | under `n × n` point supersampling the column sum is the `n`-point midpoint rule of the boundary to within `1/(2n)` px | the 8x8 corpus of `bench/ci_gate.py` | +| `Gen.Expr` | `evalQ_sound`, `evalI_sound`, `nonneg_of_evalI` | a generated checker's exact rational value is the real value; its outward-rounded interval contains the real value; an interval with a non-negative lower end certifies a condition `e ≥ 0` | `crates/inkvec-verified` (`q.rs`, `iv.rs`) | +| `Gen.Strip` | `histopolateK_eq`, `stripResidualK_eq`, `stripResidual_on_cubic` | the generated stencil is `histopolate`; the generated residual vanishes exactly where the vertex, moved along its normal, lies on the cubic the column sums determine | `strip.rs` `histopolate`, `certified` | +| `Windows` | `window_sum_eq_area` | **any finite set of pixels measures an area**: a measurable region's coverages summed over the set are its area inside their union | `evidence.rs` run windows, `chi2_run` | +| `Windows` | `trapezoid_integral` | a straight piece's integral above a level is the trapezoid | `evidence/checks.rs` | +| `Windows` | `window_sum_resampled` | **a blurred or resampled window sums to its inputs** whenever every input pixel gives the window its whole weight (`Σ_y w(y, s) = 1`): the window identity survives resampling; what a resampler normalised per output pixel leaves is its phase ripple | `evidence/noise.rs`, `docs/theory/noise.md` | +| `Windows` | `blur_affine_profile`, `blur_quadratic_profile` | a centred kernel leaves a straight edge's area profile alone and moves a curved one by exactly `½ μ₂ A''` | `RenderModel::window_area` | +| `Gen.Evidence` | `trapezoidK_integral`, `windowTermK_eq`, `fourthDiff_cubic`, `fourthDiff_side`, `cornerExcessK_eq` | the generated window checker sums exact piece areas into `(S − A)²/V`; the fourth difference vanishes on every cubic and is `12×` `strip.rs`'s one-sided test; a corner proposal is certified when `D² − z² Σ wᵢ² Vᵢ ≥ 0` | `evidence/checks.rs`, `evidence/reports.rs` `corners` | +| `Design.Layers` | `painter_interval_iff`, `above_eq_of_interval`, `replace_in_interval` | **the painter's interval**: with the paint order fixed, every element shows exactly its face's visible region iff `V_i ⊆ E_i ⊆ V_i ∪ above V i`; each face is completed on its own | `inkvec-cli` `layers.rs` | +| `Design.Layers` | `seam_of_exact_outline`, `no_seam_of_completion`, `junction_residue` | the hairline seam `a(1−a)(c_bg − c_i)` of an exact outline, gone under a completion; the junction residue `a·b·(c_i − c_bg)` | `seams.rs`, `layers.rs` | +| `Design.Layers` | `cut_hole`, `cut_hole_pixel` | **holes cut, not painted over**: painting a face over its parent in the colour already under the parent paints the parent with the face cut out; an edge pixel composites the same | `emit/holes.rs` | +| `Gen.Design` | `spanWithinK_eq`, `spanWithin_meaning`, `spanLinkK_eq`, `chain_cover`, `line_cover` | the generated span checker: a span certified within a chain of linked spans lies in their union; per scan line, the union of certified spans lies in the widened union | `layers/check.rs` `check_cover` | +| `Design.Noise` | `accept_monotone` | **a constraint accepted at one noise level stays accepted at more noise**, while each coordinate costs at least half a nat (Laplace evidence) | chain R's constraint tests | +| `Design.Noise` | `huber_eq_sq`, `inlier_of_le`, `huber_le_sq` | Huber is the Gaussian on inliers, inliers stay inliers as noise grows, outliers cost less | the fitter's robust loss | +| `Naturality` | `natural_model_closer`, `natural_model_gain` | **a merge that keeps the truth drawable never costs fidelity**: least squares onto `K ≤ L` with the truth in `K` is at least as close to it for every noise, by exactly the noise in the removed directions | `ribbon/refine/merge.rs` | +| `Naturality` | `merge_chi2_increase`, `noise_absorbed` | the merge raises the residual by that noise and nothing else; each model dimension keeps one unit of noise variance (`Σᵢ ‖P bᵢ‖² = dim K`), so every surplus parameter costs `σ²` of squared error | the description-length price `λ` per parameter | + +## What is new, and what is not + +The identity behind `column_sum_eq_average` is classical: volume-of-fluid interface +reconstruction rests on it (Puckett 2010, eq. 11), and Trujillo-Pino et al. (2013) built a +sub-pixel edge detector on it. Histopolation unisolvence and the `1/24` cell-average +correction are textbook finite-volume facts (Shu 1997; McCorquodale & Colella 2011). What +this library adds, as far as the survey in `docs/theory/README.md` could establish: + +* **the first machine-checked proofs** of any of it: no formalisation of rasterisation + coverage, anti-aliasing or sub-pixel recovery was found in Lean, Coq, Isabelle or HOL Light; +* the **exact null space**: the layer-cake fibre of a column (`column_fiber`) and the + one-dimensional zigzag kernel of the border-vertex polyline (`polyline_kernel`), where the + literature has the binary analogues (Havelock's locales, Dorst–Smeulders domains); +* the **sharp bias constant** `3/2 − √2` of the ½-crossing reading; +* the end-to-end chain from Lebesgue pixel areas to boundary points and to the code's own + constants (`strip_reading_exact`, `histopolate_cubic`); the cubic exactness of the + correction itself is classical (fourth-order finite-volume reconstruction); +* the **supersampled** version of the column-sum theorem with its `1/(2n)` floor. + +It does **not** prove that inkvec is the best tracer, and no theorem could: "best" is an +empirical claim about real inputs and a chosen metric. What it does establish is narrower +and checkable: within the box-filter model, which readings are exact, which are biased and +by how much, what no estimator can recover, and that the parts of inkvec built on these +theorems compute what the theorems say. + +## Generated checkers + +The engine's solvers are free; a result a theorem speaks about is used only if a checker +generated from the definition the theorem is about accepts it +([`docs/theory/verification.md`](../../docs/theory/verification.md)). `InkvecTheory/Gen/` holds +the bridge: `Expr`, a straight-line expression language with a real semantics (what theorems +are about), an exact rational one and an interval one, with their soundness theorems; a +printer to Rust; and the kernels (`Gen/Strip.lean`). To regenerate: + +```bash +lake build InkvecTheory && lake env lean InkvecTheory/Gen/Emit.lean +``` + +which writes `crates/inkvec-verified/src/generated/`. CI runs it and fails on any difference +from the committed files, so the Rust cannot drift from the definitions. The trusted base is +stated in `Gen/Expr.lean`: the Rust runtime (`iv.rs`, `q.rs`) implements the operations +`Enclosing` and ℚ model (IEEE 754's correctly rounded `+ − × ÷ √`, widened one float outward), +and the printer maps each constructor to one runtime call. diff --git a/formal/InkvecTheory/lake-manifest.json b/formal/InkvecTheory/lake-manifest.json new file mode 100644 index 00000000..67573936 --- /dev/null +++ b/formal/InkvecTheory/lake-manifest.json @@ -0,0 +1,96 @@ +{"version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": + [{"url": "https://github.com/leanprover-community/mathlib4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.1", + "inherited": false, + "configFile": "lakefile.lean"}, + {"url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean"}, + {"url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml"}], + "name": "InkvecTheory", + "lakeDir": ".lake", + "fixedToolchain": false} diff --git a/formal/InkvecTheory/lakefile.toml b/formal/InkvecTheory/lakefile.toml new file mode 100644 index 00000000..64be1391 --- /dev/null +++ b/formal/InkvecTheory/lakefile.toml @@ -0,0 +1,18 @@ +name = "InkvecTheory" +version = "0.1.0" +keywords = ["math"] +defaultTargets = ["InkvecTheory"] + +[leanOptions] +pp.unicode.fun = true # pretty-prints `fun a ↦ b` +relaxedAutoImplicit = false +weak.linter.mathlibStandardSet = false +maxSynthPendingDepth = 3 + +[[require]] +name = "mathlib" +scope = "leanprover-community" +rev = "v4.34.1" + +[[lean_lib]] +name = "InkvecTheory" diff --git a/formal/InkvecTheory/lean-toolchain b/formal/InkvecTheory/lean-toolchain new file mode 100644 index 00000000..ba8ebf2d --- /dev/null +++ b/formal/InkvecTheory/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.34.1 diff --git a/packages/dotnet/README.md b/packages/dotnet/README.md index 0fcf7787..9d3ecc98 100644 --- a/packages/dotnet/README.md +++ b/packages/dotnet/README.md @@ -140,7 +140,7 @@ value -- an unknown name is an error, not a silent no-op. | `harmonize_threshold` | number | `0.92` | >= 0 and <= 1 | Shape-equivalence threshold for harmonization: the outline similarity (IoU after affine normalisation) above which two marks count as the same shape. | | `mode` | string | `"quality"` | - | Which engine traces the image. "quality" (the default) is the full engine: the best fidelity and the fewest parameters, at about half a second for a 512 px logo. "fast" is a Potrace-class fit on the same palette, planar map and emitter, with a one-pass gradient check in place of gradient recovery: several times faster (tens of milliseconds at 512 px), a little less faithful, with somewhat more parameters. Options that only steer quality stages (precision, content_units, harmonize, harmonize_threshold, time_budget) are ignored in fast mode. "balanced" (opt-in) is fast plus eight iterations of quality's boundary solve and a fit with tolerances a quarter finer: in between the two in fidelity and time, on rasters up to 1024 px on the longer side; a larger raster is traced exactly as in fast mode. It ignores the same options as fast. | | `hypotheses` | bool | `false` | - | Also trace three structural alternatives -- blend absorption off, a matte instead of native alpha, and a merge distance of 0.020 -- and keep the trace whose render explains the input in the fewest nats (its squared error at the input's resolution against the best one's, plus a price per parameter). Quality colour mode only; up to four traces, about 3.6 times the trace time at 512 px. Measured on the 246-icon screen set: 6 % closer to the artist's file at 128 px, 1 % at 512 px (9 % on the hardest tenth). Off by default. | -| `detect_strokes` | bool | `false` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count. Quality mode only; off by default. | +| `detect_strokes` | bool | `true` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count, and a ring on a plain page as one stroke over the page rather than two discs. Quality mode only; on by default. | | `merge_colors` | string | `""` | - | Colour groups: fills to draw as one, so the shapes between them join rather than being recoloured. Empty (the default) changes nothing. Groups are separated by ';' and members by ','; a member is a colour '#rrggbb' as it appears in a trace of the same image, or a gradient written as its stop colours joined by '>'. An optional '=' says what the group becomes: '=#rrggbb' a flat colour, '=@n' its n-th member (1-based; a gradient there is refitted over the whole group); without it, the member covering the most of the image. Example: '#c0392b,#e74c3c;#f00>#00f,#0a0=@1'. A group costs one extra trace. | diff --git a/packages/dotnet/src/LogoLabs.Inkvec/InkvecOptions.generated.cs b/packages/dotnet/src/LogoLabs.Inkvec/InkvecOptions.generated.cs index 22deea4c..2c588689 100644 --- a/packages/dotnet/src/LogoLabs.Inkvec/InkvecOptions.generated.cs +++ b/packages/dotnet/src/LogoLabs.Inkvec/InkvecOptions.generated.cs @@ -192,8 +192,9 @@ public sealed class InkvecOptions /// width, with round or butt caps and round or miter joins -- and write each as a stroked path /// (fill none, one stroke-width) where that describes the face's measured boundary in fewer /// numbers than its filled outline, at a fit as good within the measurement noise. Line icons - /// come back at about the artist's own parameter count. Quality mode only; off by default. - /// The tracer's default is false; leave this null to use it. + /// come back at about the artist's own parameter count, and a ring on a plain page as one + /// stroke over the page rather than two discs. Quality mode only; on by default. + /// The tracer's default is true; leave this null to use it. /// public bool? DetectStrokes { get; set; } diff --git a/packages/go/README.md b/packages/go/README.md index 1ab4d840..0ae96a67 100644 --- a/packages/go/README.md +++ b/packages/go/README.md @@ -96,7 +96,7 @@ option added to the tracer after this struct was generated can be passed with `T | `harmonize_threshold` | number | `0.92` | >= 0 and <= 1 | Shape-equivalence threshold for harmonization: the outline similarity (IoU after affine normalisation) above which two marks count as the same shape. | | `mode` | string | `"quality"` | - | Which engine traces the image. "quality" (the default) is the full engine: the best fidelity and the fewest parameters, at about half a second for a 512 px logo. "fast" is a Potrace-class fit on the same palette, planar map and emitter, with a one-pass gradient check in place of gradient recovery: several times faster (tens of milliseconds at 512 px), a little less faithful, with somewhat more parameters. Options that only steer quality stages (precision, content_units, harmonize, harmonize_threshold, time_budget) are ignored in fast mode. "balanced" (opt-in) is fast plus eight iterations of quality's boundary solve and a fit with tolerances a quarter finer: in between the two in fidelity and time, on rasters up to 1024 px on the longer side; a larger raster is traced exactly as in fast mode. It ignores the same options as fast. | | `hypotheses` | bool | `false` | - | Also trace three structural alternatives -- blend absorption off, a matte instead of native alpha, and a merge distance of 0.020 -- and keep the trace whose render explains the input in the fewest nats (its squared error at the input's resolution against the best one's, plus a price per parameter). Quality colour mode only; up to four traces, about 3.6 times the trace time at 512 px. Measured on the 246-icon screen set: 6 % closer to the artist's file at 128 px, 1 % at 512 px (9 % on the hardest tenth). Off by default. | -| `detect_strokes` | bool | `false` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count. Quality mode only; off by default. | +| `detect_strokes` | bool | `true` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count, and a ring on a plain page as one stroke over the page rather than two discs. Quality mode only; on by default. | | `merge_colors` | string | `""` | - | Colour groups: fills to draw as one, so the shapes between them join rather than being recoloured. Empty (the default) changes nothing. Groups are separated by ';' and members by ','; a member is a colour '#rrggbb' as it appears in a trace of the same image, or a gradient written as its stop colours joined by '>'. An optional '=' says what the group becomes: '=#rrggbb' a flat colour, '=@n' its n-th member (1-based; a gradient there is refitted over the whole group); without it, the member covering the most of the image. Example: '#c0392b,#e74c3c;#f00>#00f,#0a0=@1'. A group costs one extra trace. | diff --git a/packages/go/options_generated.go b/packages/go/options_generated.go index 258cc452..647fb247 100644 --- a/packages/go/options_generated.go +++ b/packages/go/options_generated.go @@ -162,10 +162,11 @@ type Options struct { // width, with round or butt caps and round or miter joins -- and write each as a stroked // path (fill none, one stroke-width) where that describes the face's measured boundary in // fewer numbers than its filled outline, at a fit as good within the measurement noise. - // Line icons come back at about the artist's own parameter count. Quality mode only; off - // by default. + // Line icons come back at about the artist's own parameter count, and a ring on a plain + // page as one stroke over the page rather than two discs. Quality mode only; on by + // default. // - // Default: false. + // Default: true. DetectStrokes *bool `json:"detect_strokes,omitempty"` // Colour groups: fills to draw as one, so the shapes between them join rather than being diff --git a/packages/java/README.md b/packages/java/README.md index 889eb054..c715db3f 100644 --- a/packages/java/README.md +++ b/packages/java/README.md @@ -140,7 +140,7 @@ you set. | `harmonize_threshold` | number | `0.92` | >= 0 and <= 1 | Shape-equivalence threshold for harmonization: the outline similarity (IoU after affine normalisation) above which two marks count as the same shape. | | `mode` | string | `"quality"` | - | Which engine traces the image. "quality" (the default) is the full engine: the best fidelity and the fewest parameters, at about half a second for a 512 px logo. "fast" is a Potrace-class fit on the same palette, planar map and emitter, with a one-pass gradient check in place of gradient recovery: several times faster (tens of milliseconds at 512 px), a little less faithful, with somewhat more parameters. Options that only steer quality stages (precision, content_units, harmonize, harmonize_threshold, time_budget) are ignored in fast mode. "balanced" (opt-in) is fast plus eight iterations of quality's boundary solve and a fit with tolerances a quarter finer: in between the two in fidelity and time, on rasters up to 1024 px on the longer side; a larger raster is traced exactly as in fast mode. It ignores the same options as fast. | | `hypotheses` | bool | `false` | - | Also trace three structural alternatives -- blend absorption off, a matte instead of native alpha, and a merge distance of 0.020 -- and keep the trace whose render explains the input in the fewest nats (its squared error at the input's resolution against the best one's, plus a price per parameter). Quality colour mode only; up to four traces, about 3.6 times the trace time at 512 px. Measured on the 246-icon screen set: 6 % closer to the artist's file at 128 px, 1 % at 512 px (9 % on the hardest tenth). Off by default. | -| `detect_strokes` | bool | `false` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count. Quality mode only; off by default. | +| `detect_strokes` | bool | `true` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count, and a ring on a plain page as one stroke over the page rather than two discs. Quality mode only; on by default. | | `merge_colors` | string | `""` | - | Colour groups: fills to draw as one, so the shapes between them join rather than being recoloured. Empty (the default) changes nothing. Groups are separated by ';' and members by ','; a member is a colour '#rrggbb' as it appears in a trace of the same image, or a gradient written as its stop colours joined by '>'. An optional '=' says what the group becomes: '=#rrggbb' a flat colour, '=@n' its n-th member (1-based; a gradient there is refitted over the whole group); without it, the member covering the most of the image. Example: '#c0392b,#e74c3c;#f00>#00f,#0a0=@1'. A group costs one extra trace. | diff --git a/packages/java/src/main/java/com/logolabs/inkvec/InkvecOptions.java b/packages/java/src/main/java/com/logolabs/inkvec/InkvecOptions.java index 845fbb15..4e9708e6 100644 --- a/packages/java/src/main/java/com/logolabs/inkvec/InkvecOptions.java +++ b/packages/java/src/main/java/com/logolabs/inkvec/InkvecOptions.java @@ -299,9 +299,10 @@ public boolean hypotheses() { * width, with round or butt caps and round or miter joins -- and write each as a stroked path * (fill none, one stroke-width) where that describes the face's measured boundary in fewer * numbers than its filled outline, at a fit as good within the measurement noise. Line icons - * come back at about the artist's own parameter count. Quality mode only; off by default. + * come back at about the artist's own parameter count, and a ring on a plain page as one + * stroke over the page rather than two discs. Quality mode only; on by default. * - * @default false + * @default true */ public boolean detectStrokes() { return detectStrokes; @@ -421,7 +422,7 @@ public static final class Builder { private double harmonizeThreshold = 0.92; private String mode = "quality"; private boolean hypotheses = false; - private boolean detectStrokes = false; + private boolean detectStrokes = true; private String mergeColors = ""; private Builder() { @@ -677,9 +678,10 @@ public Builder hypotheses(boolean hypotheses) { * width, with round or butt caps and round or miter joins -- and write each as a stroked path * (fill none, one stroke-width) where that describes the face's measured boundary in fewer * numbers than its filled outline, at a fit as good within the measurement noise. Line icons - * come back at about the artist's own parameter count. Quality mode only; off by default. + * come back at about the artist's own parameter count, and a ring on a plain page as one + * stroke over the page rather than two discs. Quality mode only; on by default. * - * @default false + * @default true */ public Builder detectStrokes(boolean detectStrokes) { this.detectStrokes = detectStrokes; diff --git a/packages/npm/README.md b/packages/npm/README.md index d2c526cc..5a93787d 100644 --- a/packages/npm/README.md +++ b/packages/npm/README.md @@ -138,7 +138,7 @@ every value -- an unknown name is an error, not a silent no-op. | `harmonize_threshold` | number | `0.92` | >= 0 and <= 1 | Shape-equivalence threshold for harmonization: the outline similarity (IoU after affine normalisation) above which two marks count as the same shape. | | `mode` | string | `"quality"` | - | Which engine traces the image. "quality" (the default) is the full engine: the best fidelity and the fewest parameters, at about half a second for a 512 px logo. "fast" is a Potrace-class fit on the same palette, planar map and emitter, with a one-pass gradient check in place of gradient recovery: several times faster (tens of milliseconds at 512 px), a little less faithful, with somewhat more parameters. Options that only steer quality stages (precision, content_units, harmonize, harmonize_threshold, time_budget) are ignored in fast mode. "balanced" (opt-in) is fast plus eight iterations of quality's boundary solve and a fit with tolerances a quarter finer: in between the two in fidelity and time, on rasters up to 1024 px on the longer side; a larger raster is traced exactly as in fast mode. It ignores the same options as fast. | | `hypotheses` | bool | `false` | - | Also trace three structural alternatives -- blend absorption off, a matte instead of native alpha, and a merge distance of 0.020 -- and keep the trace whose render explains the input in the fewest nats (its squared error at the input's resolution against the best one's, plus a price per parameter). Quality colour mode only; up to four traces, about 3.6 times the trace time at 512 px. Measured on the 246-icon screen set: 6 % closer to the artist's file at 128 px, 1 % at 512 px (9 % on the hardest tenth). Off by default. | -| `detect_strokes` | bool | `false` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count. Quality mode only; off by default. | +| `detect_strokes` | bool | `true` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count, and a ring on a plain page as one stroke over the page rather than two discs. Quality mode only; on by default. | | `merge_colors` | string | `""` | - | Colour groups: fills to draw as one, so the shapes between them join rather than being recoloured. Empty (the default) changes nothing. Groups are separated by ';' and members by ','; a member is a colour '#rrggbb' as it appears in a trace of the same image, or a gradient written as its stop colours joined by '>'. An optional '=' says what the group becomes: '=#rrggbb' a flat colour, '=@n' its n-th member (1-based; a gradient there is refitted over the whole group); without it, the member covering the most of the image. Example: '#c0392b,#e74c3c;#f00>#00f,#0a0=@1'. A group costs one extra trace. | diff --git a/packages/npm/src/options.generated.ts b/packages/npm/src/options.generated.ts index 4cb17119..4b2c319c 100644 --- a/packages/npm/src/options.generated.ts +++ b/packages/npm/src/options.generated.ts @@ -192,10 +192,11 @@ export interface Options { * one width, with round or butt caps and round or miter joins -- and write each as a * stroked path (fill none, one stroke-width) where that describes the face's measured * boundary in fewer numbers than its filled outline, at a fit as good within the - * measurement noise. Line icons come back at about the artist's own parameter count. - * Quality mode only; off by default. + * measurement noise. Line icons come back at about the artist's own parameter count, and + * a ring on a plain page as one stroke over the page rather than two discs. Quality mode + * only; on by default. * - * @default false + * @default true */ detect_strokes?: boolean; /** diff --git a/packages/php/README.md b/packages/php/README.md index 6e8a5af8..e6275df0 100644 --- a/packages/php/README.md +++ b/packages/php/README.md @@ -206,7 +206,7 @@ an unknown name is an error, not a silent no-op. | `harmonize_threshold` | number | `0.92` | >= 0 and <= 1 | Shape-equivalence threshold for harmonization: the outline similarity (IoU after affine normalisation) above which two marks count as the same shape. | | `mode` | string | `"quality"` | - | Which engine traces the image. "quality" (the default) is the full engine: the best fidelity and the fewest parameters, at about half a second for a 512 px logo. "fast" is a Potrace-class fit on the same palette, planar map and emitter, with a one-pass gradient check in place of gradient recovery: several times faster (tens of milliseconds at 512 px), a little less faithful, with somewhat more parameters. Options that only steer quality stages (precision, content_units, harmonize, harmonize_threshold, time_budget) are ignored in fast mode. "balanced" (opt-in) is fast plus eight iterations of quality's boundary solve and a fit with tolerances a quarter finer: in between the two in fidelity and time, on rasters up to 1024 px on the longer side; a larger raster is traced exactly as in fast mode. It ignores the same options as fast. | | `hypotheses` | bool | `false` | - | Also trace three structural alternatives -- blend absorption off, a matte instead of native alpha, and a merge distance of 0.020 -- and keep the trace whose render explains the input in the fewest nats (its squared error at the input's resolution against the best one's, plus a price per parameter). Quality colour mode only; up to four traces, about 3.6 times the trace time at 512 px. Measured on the 246-icon screen set: 6 % closer to the artist's file at 128 px, 1 % at 512 px (9 % on the hardest tenth). Off by default. | -| `detect_strokes` | bool | `false` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count. Quality mode only; off by default. | +| `detect_strokes` | bool | `true` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count, and a ring on a plain page as one stroke over the page rather than two discs. Quality mode only; on by default. | | `merge_colors` | string | `""` | - | Colour groups: fills to draw as one, so the shapes between them join rather than being recoloured. Empty (the default) changes nothing. Groups are separated by ';' and members by ','; a member is a colour '#rrggbb' as it appears in a trace of the same image, or a gradient written as its stop colours joined by '>'. An optional '=' says what the group becomes: '=#rrggbb' a flat colour, '=@n' its n-th member (1-based; a gradient there is refitted over the whole group); without it, the member covering the most of the image. Example: '#c0392b,#e74c3c;#f00>#00f,#0a0=@1'. A group costs one extra trace. | diff --git a/packages/php/src/Options.php b/packages/php/src/Options.php index 54e02334..cd042674 100644 --- a/packages/php/src/Options.php +++ b/packages/php/src/Options.php @@ -140,8 +140,9 @@ final class Options * -- and write each as a stroked path (fill none, one stroke-width) where that describes * the face's measured boundary in fewer numbers than its filled outline, at a fit as good * within the measurement noise. Line icons come back at about the artist's own parameter - * count. Quality mode only; off by default. The tracer's default is false; leave it null - * to use that. + * count, and a ring on a plain page as one stroke over the page rather than two discs. + * Quality mode only; on by default. The tracer's default is true; leave it null to use + * that. * * @param string|null $mergeColors Colour groups: fills to draw as one, so the shapes * between them join rather than being recoloured. Empty (the default) changes nothing. diff --git a/packages/swift/README.md b/packages/swift/README.md index 534e9ff7..4062696a 100644 --- a/packages/swift/README.md +++ b/packages/swift/README.md @@ -134,7 +134,7 @@ is `InkvecError.invalidOptions`, not a silent no-op. | `harmonize_threshold` | number | `0.92` | >= 0 and <= 1 | Shape-equivalence threshold for harmonization: the outline similarity (IoU after affine normalisation) above which two marks count as the same shape. | | `mode` | string | `"quality"` | - | Which engine traces the image. "quality" (the default) is the full engine: the best fidelity and the fewest parameters, at about half a second for a 512 px logo. "fast" is a Potrace-class fit on the same palette, planar map and emitter, with a one-pass gradient check in place of gradient recovery: several times faster (tens of milliseconds at 512 px), a little less faithful, with somewhat more parameters. Options that only steer quality stages (precision, content_units, harmonize, harmonize_threshold, time_budget) are ignored in fast mode. "balanced" (opt-in) is fast plus eight iterations of quality's boundary solve and a fit with tolerances a quarter finer: in between the two in fidelity and time, on rasters up to 1024 px on the longer side; a larger raster is traced exactly as in fast mode. It ignores the same options as fast. | | `hypotheses` | bool | `false` | - | Also trace three structural alternatives -- blend absorption off, a matte instead of native alpha, and a merge distance of 0.020 -- and keep the trace whose render explains the input in the fewest nats (its squared error at the input's resolution against the best one's, plus a price per parameter). Quality colour mode only; up to four traces, about 3.6 times the trace time at 512 px. Measured on the 246-icon screen set: 6 % closer to the artist's file at 128 px, 1 % at 512 px (9 % on the hardest tenth). Off by default. | -| `detect_strokes` | bool | `false` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count. Quality mode only; off by default. | +| `detect_strokes` | bool | `true` | - | Detect the faces of the colour trace that were drawn as strokes -- a centreline and one width, with round or butt caps and round or miter joins -- and write each as a stroked path (fill none, one stroke-width) where that describes the face's measured boundary in fewer numbers than its filled outline, at a fit as good within the measurement noise. Line icons come back at about the artist's own parameter count, and a ring on a plain page as one stroke over the page rather than two discs. Quality mode only; on by default. | | `merge_colors` | string | `""` | - | Colour groups: fills to draw as one, so the shapes between them join rather than being recoloured. Empty (the default) changes nothing. Groups are separated by ';' and members by ','; a member is a colour '#rrggbb' as it appears in a trace of the same image, or a gradient written as its stop colours joined by '>'. An optional '=' says what the group becomes: '=#rrggbb' a flat colour, '=@n' its n-th member (1-based; a gradient there is refitted over the whole group); without it, the member covering the most of the image. Example: '#c0392b,#e74c3c;#f00>#00f,#0a0=@1'. A group costs one extra trace. | diff --git a/packages/swift/Sources/Inkvec/InkvecOptions.generated.swift b/packages/swift/Sources/Inkvec/InkvecOptions.generated.swift index 9c9056f8..3c5e2354 100644 --- a/packages/swift/Sources/Inkvec/InkvecOptions.generated.swift +++ b/packages/swift/Sources/Inkvec/InkvecOptions.generated.swift @@ -163,10 +163,11 @@ public struct InkvecOptions: Codable, Hashable, Sendable { /// width, with round or butt caps and round or miter joins -- and write each as a stroked /// path (fill none, one stroke-width) where that describes the face's measured boundary in /// fewer numbers than its filled outline, at a fit as good within the measurement noise. - /// Line icons come back at about the artist's own parameter count. Quality mode only; off - /// by default. + /// Line icons come back at about the artist's own parameter count, and a ring on a plain + /// page as one stroke over the page rather than two discs. Quality mode only; on by + /// default. /// - /// Default: `false`. + /// Default: `true`. public var detectStrokes: Bool? /// Colour groups: fills to draw as one, so the shapes between them join rather than being diff --git a/studio/core/src/options.rs b/studio/core/src/options.rs index 5611e9b7..245caac1 100644 --- a/studio/core/src/options.rs +++ b/studio/core/src/options.rs @@ -302,7 +302,7 @@ impl Settings { bilevel: black_and_white, monochrome, native_alpha: trace_transparency, - restore: clean_up_damage.restore(), + restore: Some(clean_up_damage.restore()), harmonize: match_repeated_shapes, harmonize_threshold: match_threshold, content_units: fewer_paths, diff --git a/studio/core/src/trace.rs b/studio/core/src/trace.rs index 560aabb6..cc2dccce 100644 --- a/studio/core/src/trace.rs +++ b/studio/core/src/trace.rs @@ -1095,7 +1095,7 @@ fn trace_pipeline( drop(kept); let size = Some((source.width as usize, source.height as usize)); let out = match external_denoiser() { - Some(denoise) if args.restore != inkvec_restore::Mode::Off => { + Some(denoise) if args.restore_mode() != inkvec_restore::Mode::Off => { trace_denoised(img, args, size, denoise)? } _ => inkvec_cli::trace_image_sized(img, args, size)?, @@ -1186,8 +1186,8 @@ fn trace_denoised( denoise: ExternalDenoiser, ) -> Result> { let mut intake = inkvec_cli::intake(img, args, size); - let mode = intake.args.restore; - intake.args.restore = inkvec_restore::Mode::Off; + let mode = intake.args.restore_mode(); + intake.args.restore = Some(inkvec_restore::Mode::Off); let mut note = String::new(); if mode == inkvec_restore::Mode::Auto { let mut probe = inkvec_cli::trace_prepared(intake.clone())?; diff --git a/tools/build_site.py b/tools/build_site.py index 79fbc777..94381c8e 100644 --- a/tools/build_site.py +++ b/tools/build_site.py @@ -98,6 +98,8 @@ "code-of-conduct.html": ("CODE_OF_CONDUCT.md", "Code of conduct"), "algorithm/index.html": ("docs/algorithm/README.md", "How inkvec works"), "algorithm/constants.html": ("docs/algorithm/constants.md", "Constants"), + "theory.html": ("docs/theory/README.md", "Theory"), + "theory-optimal.html": ("docs/theory/optimal.md", "The optimal vectorizer"), } # The Studio user guide: (page, sidebar label), in reading order. Page "x" is @@ -144,7 +146,9 @@ def studio_source(page: str) -> str: ("Studio tutorials", [(f"studio/{p}.html", label) for p, label in STUDIO_TUTORIALS]), ("How it works", [("algorithm/index.html", "The series")] + [(f"algorithm/{slug}.html", label) for slug, label in STAGES] - + [("algorithm/constants.html", "Constants and thresholds")]), + + [("algorithm/constants.html", "Constants and thresholds")] + + [("theory.html", "Theory: inverting the box filter")] + + [("theory-optimal.html", "Theory: the optimal vectorizer")]), ("Reference", [("design.html", "Design"), ("bindings.html", "Bindings"), ("limitations.html", "Limitations"), ("ai-usage.html", "AI usage"), ("licences.html", "Licences")]),