Repository navigation
fix(rgbw): NNLS out-of-hull projection (#2708) + in-test ground truth - #2709
Conversation
…follow-up) Adds two new test cases to fl_gfx_rgbw_colorimetric: 1. FastLED strict subgamut agrees with reference port (in-hull) Ports the math-model gist's strict sub-gamut + §3 NNLS hull projection into the test TU (`reference::strict_with_projection`). For ten in-hull inputs (D65 white, mid grey, red, green, cyan, magenta, yellow, cool blue, orange, dim grey), asserts every channel of FastLED's output stays within ±24 / 255 of the reference. FastLED's solver is mirrored inline (`fastled_mirror::strict_subgamut`) — exact text-copy of the production .cpp.hpp so the test exercises identical logic without depending on FASTLED_RGBW_COLORIMETRIC at library-build time. 2. out-of-hull sRGB blue: FastLED zeroes while reference projects Documents #2708 as an executable contract. sRGB pure blue at xy ≈ (0.15, 0.06) lies outside all three LED sub-gamuts on the default profile; FastLED currently returns (0,0,0,0) while the reference's NNLS projection produces a real RGBW. When #2708 lands, this test fails and the assertion gets flipped to agree with the reference. The reference port lives entirely in this TU — no Python at test time, no new dependencies. NNLS is the same projected-gradient fallback the reference uses on platforms without scipy (500 iters @ step 0.01). Verification trail: while writing the test, a standalone harness drove FastLED's actual solver code byte-for-byte (separate from this test TU) and was compared against compare_rgbw.py (which mirrors the C++ logic in Python). All three matched bit-exactly across strict/boosted/native modes on 14 test inputs before the mirror was trusted as the in-test ground truth. Drive-by: - Add IWYU pragma: private to audio_input_teensy_config.h (PostToolUse stop hook caught the missing pragma on the file I edited in #2707). - Drop redundant `except KeyboardInterrupt: raise` in ci/lint_cpp/rust_bridge.py — KBI checker rule wants either an explicit _thread.interrupt_main() call or no catch at all. Plain `raise` was a no-op anyway since unhandled KI propagates naturally. References: - Math model gist: https://gist.github.com/JChalka/915603d7930b7216d5c5aae834ec2ea9 - Reference implementation gist: https://gist.github.com/JChalka/cebc5a018066cae05d98cf9088c3b3b9 - Comparison harness: compare_rgbw.py (uncommitted scratch file — fetches the gist, mirrors FastLED's algorithm in Python, prints side-by-side delta vs. the reference). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
📝 WalkthroughWalkthroughThis PR adds Python and C++ validation for FastLED's RGBW colorimetric solvers (strict and boosted), implements out-of-hull NNLS projection and an inline 3×3 NNLS helper, adds comparison tooling and tests, and applies small lint/header cleanup. ChangesRGBW Colorimetric Validation Framework
Maintenance Updates
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 Infer (1.2.0)tests/fl/gfx/rgbw_colorimetric.cpptests/fl/gfx/rgbw_colorimetric.cpp:19:10: fatal error: 'test.h' file not found ... [truncated 1070 characters] ... /lib/clang/18/include" Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@compare_rgbw.py`:
- Around line 269-275: Replace ambiguous Unicode glyphs in the diagnostic print
strings by using ASCII equivalents: change "Profile: %d×%d×%d × %d-LED
primaries..." to use "x" (e.g. "%dx%dx%d x %d-LED primaries..."), change the
header separator "FastLED − Ref (∆R,G,B,W)" to use plain hyphen and ASCII
delta/name (e.g. "FastLED - Ref (dR,dG,dB,dW)" or "FastLED - Ref
(ΔR,ΔG,ΔB,ΔW)"), and replace any "ρ" with "rho" in the other print strings;
update the literal strings used in the print(...) calls shown so all occurrences
(including the other grouped print statements at the same blocks) use ASCII-only
glyphs.
- Line 48: Update the function signatures to follow the repo contract: add
explicit type annotations for all parameters and return types and remove any
default parameter values. Specifically modify build_source_matrix(xy_r, xy_g,
xy_b, xy_w)->tuple[np.ndarray, bool] to include typed parameters, annotate
barycentric_xy, ProfileCache.__init__, solve_wx_overdrive, fastled_rgb_to_rgbw,
ref_rgb_to_rgbw, fmt, and main with explicit parameter and return types, and
remove defaults from solve_wx_overdrive, fastled_rgb_to_rgbw, and
ref_rgb_to_rgbw so no parameters have default values; ensure signatures match
the code usage sites after changes.
- Around line 81-106: ProfileCache currently ingests raw dicts and handles
positional tuples from helpers, so change the pipeline to use typed `@dataclass`
carriers and runtime validation: define dataclasses for the input profile (e.g.,
ProfileSpec) and for multi-value returns (e.g., XYZResult, InvertResult,
SourceMatrixResult), annotate functions xyY_to_XYZ, invert3x3, and
build_source_matrix to return those dataclasses instead of tuples, and decorate
dataclasses with `@typechecked` so invalid shapes/keys fail at construction; then
update ProfileCache.__init__ to accept a ProfileSpec (or construct one at its
start) and use field names (e.g., .xy_r, .lum_r, .P_W) and the new return types
(e.g., InvertResult.inv) when building P_RGB/P_RGW/P_RBW/P_BGW and computing
self.P_RGB_inv/self.d_W to ensure schema/shape validation occurs at data
boundaries.
- Around line 263-264: The delta function delta(a, b) currently computes b - a
but tables label the column as "FastLED - Ref"; change the implementation to
return tuple(int(a[i]) - int(b[i]) for i in range(4)) so the sign matches the
"FastLED - Ref" label (or alternatively update the label wherever delta is
used). Locate the delta function and adjust its return expression (or the
labeling logic) so per-case channel diagnostics reflect FastLED minus Reference
correctly.
In `@tests/fl/gfx/rgbw_colorimetric.cpp`:
- Around line 518-544: In build_cache, when build_source_matrix fails you only
flip cache->has_source_space but do not clear cache->M_src; change build_cache
so that after calling build_source_matrix you set cache->has_source_space =
result and if result is false zero out ProfileCache::M_src (e.g., set all
elements to 0) to match the production fallback behavior and keep the mirror
cache identical.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: ff9d5fd2-30ce-4509-8877-7e9e2720111e
📒 Files selected for processing (4)
ci/lint_cpp/rust_bridge.pycompare_rgbw.pysrc/platforms/arm/teensy/audio_input_teensy_config.htests/fl/gfx/rgbw_colorimetric.cpp
💤 Files with no reviewable changes (1)
- ci/lint_cpp/rust_bridge.py
Implements gist §3 hull projection so that source colors mapping outside the LED 4-emitter convex hull (e.g. sRGB pure blue at xy ≈ 0.15, 0.06) no longer collapse to (0,0,0,0). The strict and overdrive solvers now project out-of-hull XYZ targets to the nearest achievable point inside the LED hull before triangle routing. Implementation ============== - `colorimetric_detail::nnls3` (inline in rgbw_colorimetric.h): projected- gradient NNLS for 3x3 systems (500 iters @ step 0.01), matching the reference's scipy-less fallback. Cheap (~50 µs on an MCU at -O2) and alloc-free; only invoked when the target is out-of-hull, never on the in-hull fast path. - `project_to_hull` (static in rgbw_colorimetric.cpp.hpp): for an out-of-hull XYZ target, runs NNLS in each of the three sub-gamuts (RGW/RBW/BGW), caps drive at 1.0 per sub-gamut, and selects the one with smallest residual. Returns the achieved chromaticity at unit Y for the strict triangle solve to route on. - Wired into `solve_strict_subgamut`, `solve_strict_subgamut_xy`, and `solve_wx_overdrive`. The LUT builder's grid points run through `solve_strict_subgamut_xy` so the rebuilt LUT cells contain projected RGBW for boundary samples — no separate dispatch-side projection needed for the LUT lookup path. Tests ===== The "out-of-hull sRGB blue" test added in 762c341 documented #2708 as an executable contract — it asserted FastLED returned zeros while reference projected. Flipped to assert FastLED now matches the reference within ±1/255 (rounding only — both share the same NNLS implementation). The `fastled_mirror::strict_subgamut` test helper gains a verbatim copy of `project_to_hull` so the mirror continues to match production behavior. All 308 unit tests pass clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
♻️ Duplicate comments (1)
tests/fl/gfx/rgbw_colorimetric.cpp (1)
518-544:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winMirror diverges from production: missing M_src zeroing on degenerate source space.
The production
build_profile_cache(lines 76–79 inrgbw_colorimetric.cpp.hpp) explicitly zerosM_srcwhenhas_source_spaceis false, but this mirror only flips the flag. AlthoughM_srcwon't be read whenhas_source_space == false, the mirror should match the production fallback to maintain the "exact text-copy" contract stated in lines 504–506.🔧 Suggested fix
matvec3(cache->P_RGB_inv, cache->P_W, cache->d_W); cache->has_source_space = (p->input_xy_w[1] > 1e-6f) && build_source_matrix(p->input_xy_r, p->input_xy_g, p->input_xy_b, p->input_xy_w, cache->M_src); + if (!cache->has_source_space) { + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) { + cache->M_src[i][j] = 0.0f; + } + } + } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/fl/gfx/rgbw_colorimetric.cpp` around lines 518 - 544, The mirror implementation of build_cache sets cache->has_source_space based on build_source_matrix but does not zero cache->M_src when the source space is degenerate; update build_cache so that after computing cache->has_source_space (using build_source_matrix with p->input_xy_r/g/b/w) you explicitly zero cache->M_src (e.g., set all 9 elements to 0 or memset) when has_source_space is false, keeping the same behavior as the production build_profile_cache and ensuring build_cache, cache->M_src, cache->has_source_space, and build_source_matrix remain consistent.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Duplicate comments:
In `@tests/fl/gfx/rgbw_colorimetric.cpp`:
- Around line 518-544: The mirror implementation of build_cache sets
cache->has_source_space based on build_source_matrix but does not zero
cache->M_src when the source space is degenerate; update build_cache so that
after computing cache->has_source_space (using build_source_matrix with
p->input_xy_r/g/b/w) you explicitly zero cache->M_src (e.g., set all 9 elements
to 0 or memset) when has_source_space is false, keeping the same behavior as the
production build_profile_cache and ensuring build_cache, cache->M_src,
cache->has_source_space, and build_source_matrix remain consistent.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 535f6888-d18e-403d-90de-5fafe37c8497
📒 Files selected for processing (3)
src/fl/gfx/rgbw_colorimetric.cpp.hppsrc/fl/gfx/rgbw_colorimetric.htests/fl/gfx/rgbw_colorimetric.cpp
- Drop compare_rgbw.py. It was a one-off developer harness used during the gist-vs-FastLED verification (now permanently captured by the in-test reference port). CodeRabbit flagged it for type-annotation / dataclass / signature-policy issues that would be valid for production Python but are noise on a scratch file; cleanest fix is to not ship it. - Mirror the production cache builder's M_src zero-init on build_source_matrix failure. Matches the "exact text-copy" contract the comment promises and keeps the mirror byte-faithful to production. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
#2711) * fix(rgbw): default source = native LED gamut + D65; named-gamut opt-in (#2710) Closes #2710. #2705 added the source-RGB → LED-XYZ transform with `kRgbwDefaultProfile` defaulting to Rec709/sRGB primaries + D65. That silently clipped saturated inputs to the sRGB sub-volume of the LED's native gamut — `RGB=(255,0,0)` on a typical SK6812 strip drove the LED red diode to ~70 % of its capability, leaving the rest unreachable through the public API. Flips the default to **native LED gamut + D65 white**: - `kRgbwDefaultProfile.input_xy_r/g/b` now mirror the profile's own LED `xy_r/g/b` (was sRGB), so saturated inputs hit the LED gamut at full saturation. - `input_xy_w` stays at D65 so neutral inputs land on a standard daylight white. - Same applies to `kRgbwwDefaultProfile` (RGBWW warm + cool paths). Adds a small opt-in API for users who explicitly want standard color-space input semantics: enum class InputGamut : u8 { Native, Rec709, Rec2020, DciP3D65, DciP3D60 }; void set_input_gamut(DiodeProfile* profile, InputGamut g) noexcept; void set_input_gamut(DiodeProfile* profile, InputGamut g, const float white_xy[2]) noexcept; Users with sRGB content (ambilight, video bridges) write one line at setup: `fl::set_input_gamut(&my_profile, fl::InputGamut::Rec709);`. The white-override overload covers niche cases like D50 photography workflow or D60 ACES theatrical mastering. Tests ===== - `default profile carries native-LED + D65 source space (#2710)` — asserts input_xy_* mirror xy_* and input_xy_w == D65. - `source matrix matches published sRGB->XYZ matrix (Rec709 opt-in)` — the existing sRGB matrix-derivation check now opts into Rec709 via set_input_gamut() before building M_src. - `set_input_gamut: Native copies LED primaries` — trashes input_xy_* then proves Native restores them from xy_*. - `set_input_gamut: named gamuts populate canonical primaries` — hits Rec709 / Rec2020 / DCI-P3 D65 / DCI-P3 D60 and asserts canonical primary + white-point values. - `set_input_gamut: white override honored` — covers the overload that takes a custom white (D50 in the test). - `set_input_gamut: null profile is a no-op` — defensive guard parity with `set_rgbw_colorimetric_profile(nullptr)`. Drive-by ======== Removes `compare_rgbw.py`, a one-off scratch comparison harness that slipped into master via #2709's squash-merge despite being deleted on the branch. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * chore(ci): apply ruff format drift bash lint reformatted three CI files during PR #2711 review work. No functional change — purely line-break/whitespace adjustments that ruff flagged as drift from the current format profile. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(rgbw): address CodeRabbit review on #2711 Three follow-ups from the CodeRabbit review: 1. **(major) Cache invalidation on in-place gamut mutation** — set_input_gamut() rewrites profile->input_xy_* in place, but the ColorimetricCacheHolder and LutStateHolder are keyed on (profile_ptr, cct). Without invalidation, the cache held stale M_src/LUT entries after a gamut switch on the currently active profile, producing deterministic wrong colors. Now the active per-process caches are evicted whenever set_input_gamut() mutates a profile that matches the cache key. No-op in the FASTLED_RGBW_COLORIMETRIC=0 build (no cache exists to invalidate). 2. **(contract) white_xy doc mismatch** — The header doc said the `white_xy` override "must point to a 2-float array" but the impl already accepted nullptr as "use the gamut's reference white" (equivalent to the 2-arg overload). Doc now matches behavior. Kept the raw-array signature instead of switching to fl::span<const float, 2> — the header sits low in the include graph and pulling fl/stl/span.h here would be a heavier change than the contract bug warrants; the 2-arg overload remains the recommended call site for the default-white path. 3. **(nitpick) RGBWW native-gamut guard** — Added an explicit test asserting kRgbwwDefaultProfile.warm_path / cool_path keep input_xy_* mirroring xy_* and input_xy_w pinned at D65. Symmetric to the existing assertion at rgbw_colorimetric.cpp:252-272; locks the native-LED-gamut contract on both warm and cool paths so future chromaticity retuning can't silently desync source from emitter. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(cpp): wrap fl::set_input_gamut on CFastLED per Public Settings Pattern `fl::set_input_gamut` (#2710) is a library-wide global setter. Under the Public Settings Pattern in agents/docs/cpp-standards.md, every public fl:: global setter must ship with a thin inline `CFastLED` wrapper that becomes the documented user-facing call site. The two-arg and three-arg overloads now have matching `CFastLED::setInputGamut` wrappers. Removes the implicit grandfathered exception this function was relying on in PR #2715 — that PR's follow-up commit explicitly dropped the allowlist, so this wrapper is now required before merge rather than deferred. Co-Authored-By: Claude Opus 4.7 <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Closes #2708.
Single PR that lands both halves of the math-model gist's §3 + §5 contract:
#2708 — out-of-hull NNLS projection
When a source RGB triple mapped to an XYZ target outside the LED 4-emitter convex hull, the strict solver returned (0,0,0,0) because no sub-gamut triangle accepted the chromaticity. sRGB blue at xy ≈ (0.15, 0.06) was the canonical case — outside the LED's RBW and BGW triangles on the default profile.
Implementation:
colorimetric_detail::nnls3(inline inrgbw_colorimetric.h): projected-gradient NNLS for 3×3 systems (500 iters @ step 0.01), matching the reference's scipy-less fallback. Alloc-free; only invoked when the target is out-of-hull.project_to_hull(static inrgbw_colorimetric.cpp.hpp): runs NNLS in each of the three sub-gamuts (RGW / RBW / BGW), caps drive at 1.0 per sub-gamut, selects min-residual. Returns the achieved chromaticity at unit Y.solve_strict_subgamut,solve_strict_subgamut_xy, andsolve_wx_overdrive. The LUT builder reusessolve_strict_subgamut_xyso the rebuilt LUT cells contain projected RGBW for boundary samples.In-test ground truth (no Python at test time)
tests/fl/gfx/rgbw_colorimetric.cppgets two namespaces:reference::— port ofxy_target_rgbw_model.pystrict sub-gamut + §3 NNLS projection. Independent of production code.fastled_mirror::— text-copy of the production solver (kept in sync with.cpp.hppfor tests that can't link the colorimetric path).Test cases
FastLED strict subgamut agrees with reference port (in-hull)— 10 inputs (D65, primaries, secondaries, mixed). Asserts every channel within ±24 / 255 of the reference.out-of-hull sRGB blue: FastLED projects to match reference (#2708)— was the executable contract for bug(rgbw): out-of-hull source colors return (0,0,0,0) — missing NNLS projection (gist §3) #2708; now asserts FastLED produces non-trivial output AND matches the reference within ±1 / 255 (rounding only — both share the same NNLS).Verification trail
Before trusting the C++ port as ground truth, three independent implementations were checked against each other on 14 test inputs across strict / boosted / native-gamut modes:
.cpp.hpp) — driven by a standalone harness compiled directly with clang++.fastled_mirror::strict_subgamut) — text-copy of the production code.compare_rgbw.py— scratch file, fetches the gist, mirrors FastLED's algorithm in Python).All three produced bit-identical RGBW across every case before #2708 was implemented. After #2708, the reference port and FastLED now also agree on out-of-hull cases.
Drive-by fixes
src/platforms/arm/teensy/audio_input_teensy_config.hgains// IWYU pragma: private.ci/lint_cpp/rust_bridge.pydrops a redundantexcept KeyboardInterrupt: raisethat the KBI checker flagged. Plain re-raise was a no-op.Test plan
bash lintclean (Python, C++, JS)bash test --cpp --cleanpasses 308/308 including the new ground-truth cases🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Tests
Chores