Skip to content

feat: add weighted Brovey pansharpening - #247

Merged
giswqs merged 8 commits into
mainfrom
feat/pansharpen
Oct 24, 2026
Merged

giswqs merged 8 commits into
mainfrom
feat/pansharpen

Conversation

@giswqs

@giswqs giswqs commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Add pure Rust weighted Brovey pansharpening with spectral weights, output band selection, six resampling methods, nodata, explicit bit depth, integer clipping and union/intersection/pan footprint handling. Port GDAL 3.12's separable masked convolution and native working-type arithmetic, with attribution.
  • Expose materialized output through Rust, CLI/MCP, Python and JavaScript/WebAssembly. Document the supported subset, including common nodata, masks, north-up grids, native type rounding and explicit bit depth. Virtual pansharpened VRT output remains the follow-up after the VRT extensions in Tracking: practical GDAL feature parity #238.
  • Add 29 real Landsat 8 B8/B4/B3/B2 GDAL comparisons to the conformance workflow. All 28 integer cases agree exactly; Float32 agrees within one ULP at the scene's scale. Include nodata borders/interior holes, disabled nodata, internal masks, unequal extents, fractional origins and clipping.

The materialized API buffers complete inputs and working/output planes. On Linux, a real 1024×1024 UInt16 pan with three 512×512 spectral bands used 125,544 KiB peak RSS with two runtime threads. Memory grows with image area and band count; the bounded virtual/block-I/O follow-up is required before item 8 is complete.

Validation

  • Full workspace tests and pre-commit suite.
  • Rust unequal-resolution/weight/band, working-type rounding, nodata, bit-depth and input-validation regressions.
  • MCP discovery and multiband output verified end to end.
  • Isolated Python wheel built and runtime/persistence regression passed.
  • WebAssembly core build and JavaScript runtime regression passed.
  • All 29 real-image GDAL comparisons pass their documented pixel/CRS/grid/type/nodata checks.

Refs #238 (item 8, materialized output).

Sharpen real panchromatic and spectral images in pure Rust with native-type interpolation, weights, selected output bands, nodata, bit depth and footprint adjustment. Expose the materialized operation through CLI/MCP, Python and WebAssembly and compare real Landsat pairs with GDAL.
@coderabbitai

coderabbitai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 41 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 2 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 63a2741f-9951-46bc-a246-4b060e55b922
Commits

Reviewing files that changed from the base of the PR and between 95c0f5b and 60d3630.

Files selected for processing: 24
  • NOTICE
  • crates/terrio-cli/src/cmd/mod.rs
  • crates/terrio-cli/src/cmd/pansharpen.rs
  • crates/terrio-cli/src/lib.rs
  • crates/terrio-cli/tests/mcp.rs
  • crates/terrio/NOTICE
  • crates/terrio/src/ops/mod.rs
  • crates/terrio/src/ops/pansharpen.rs
  • crates/terrio/src/ops/vrt.rs
  • docs/cli.md
  • docs/javascript.md
  • docs/python.md
  • docs/rust.md
  • docs/testing.md
  • js/src/ops.rs
  • js/tests/node.test.mjs
  • python/python/terrio/__init__.py
  • python/python/terrio/_terrio.pyi
  • python/src/ops.rs
  • python/src/terrain.rs
  • python/tests/test_pansharpen.py
  • scripts/compare_pansharpen_with_gdal.py
  • scripts/conformance.py
  • scripts/fetch_test_data.sh

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 636a4774-7709-4609-8c9d-bbbb4886e944
Commits

Reviewing files that changed from the base of the PR and between 94ac66d and 95c0f5b.

Files selected for processing: 24
  • NOTICE
  • crates/terrio-cli/src/cmd/mod.rs
  • crates/terrio-cli/src/cmd/pansharpen.rs
  • crates/terrio-cli/src/lib.rs
  • crates/terrio-cli/tests/mcp.rs
  • crates/terrio/NOTICE
  • crates/terrio/src/ops/mod.rs
  • crates/terrio/src/ops/pansharpen.rs
  • crates/terrio/src/ops/vrt.rs
  • docs/cli.md
  • docs/javascript.md
  • docs/python.md
  • docs/rust.md
  • docs/testing.md
  • js/src/ops.rs
  • js/tests/node.test.mjs
  • python/python/terrio/__init__.py
  • python/python/terrio/_terrio.pyi
  • python/src/ops.rs
  • python/src/terrain.rs
  • python/tests/test_pansharpen.py
  • scripts/compare_pansharpen_with_gdal.py
  • scripts/conformance.py
  • scripts/fetch_test_data.sh

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 0 remain after this review.

Walkthrough

Adds weighted Brovey pansharpening to the Rust API, CLI, Python, and JavaScript interfaces. The operation supports spectral resampling, output-band selection, nodata handling, and extent adjustment. Tests and scripts compare its outputs with GDAL.

Changes: Pansharpening

Layer / File(s) Summary
Core operation and Rust API
crates/terrio/src/ops/pansharpen.rs, crates/terrio/src/ops/vrt.rs, crates/terrio/src/ops/mod.rs, crates/terrio/NOTICE, docs/rust.md
Adds public pansharpening types and an operation with input validation, extent adjustment, spectral resampling, nodata handling, and weighted Brovey output. Adds Rust tests and GDAL attribution.
CLI and MCP integration
crates/terrio-cli/src/cmd/*, crates/terrio-cli/src/lib.rs, crates/terrio-cli/tests/mcp.rs, docs/cli.md
Adds the pansharpen CLI command, parses its inputs and options, runs the operation, and writes the result. Adds MCP integration coverage and CLI documentation.
Python and JavaScript bindings
python/src/terrain.rs, python/src/ops.rs, python/python/terrio/*, python/tests/test_pansharpen.py, js/src/ops.rs, js/tests/node.test.mjs, docs/python.md, docs/javascript.md
Adds Python and JavaScript entry points, flattens spectral raster bands into operation inputs, and exposes the Python function through package exports and type stubs. Adds binding tests and examples.
GDAL comparison and conformance
scripts/compare_pansharpen_with_gdal.py, scripts/conformance.py, scripts/fetch_test_data.sh, docs/testing.md
Adds Landsat fixtures and comparisons covering resampling, weights, output bands, bit depth, nodata, masks, and extent adjustment. Registers a pansharpening conformance suite.

Priority: Normal

Estimated code review effort: 4 (Complex) | ~50 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant PythonCaller
  participant PythonTerrainWrapper
  participant PansharpenOperation
  PythonCaller->>PythonTerrainWrapper: pansharpen inputs and options
  PythonTerrainWrapper->>PansharpenOperation: spectral bands and PansharpenOptions
  PansharpenOperation-->>PythonTerrainWrapper: pansharpened RasterDataset
  PythonTerrainWrapper-->>PythonCaller: Raster result or destination output
Loading
Merge Risk: Minimal · up to 95c0f

This adds weighted Brovey pansharpening across the Rust, CLI/MCP, Python and JavaScript interfaces. The PR reports GDAL parity checks and binding tests. The materialized implementation buffers full images in memory, which the author documents and defers to bounded virtual processing in later work. No concrete merge-blocking risk remains in the reviewed evidence.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 47.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 36 functions across 17 files. (7 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the pull request's primary change: adding weighted Brovey pansharpening.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 47.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 36 functions across 17 files. (7 skipped: 7 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

❤️ Share

A rabbit lays out bands in rows,
Then blends their colors as light flows.
The pan band guides each spectral hue,
While weights and footprints shape the view.
Tests compare each pixel’s place,
And rabbit hops through sharper space.

Comment @coderabbitai help to get the list of available commands.

Comment thread crates/terrio/src/ops/pansharpen.rs Resolved
Comment thread crates/terrio/src/ops/pansharpen.rs Resolved
@github-actions

Copy link
Copy Markdown
Contributor

Code review

I reviewed the pansharpen op, CLI, bindings, docs and tests by reading the diff and source. I did not build the code or run any tests.

Bugs

  • Auto nodata is lost when extents are adjusted (crates/terrio/src/ops/pansharpen.rs:138, medium-high confidence). adjust() builds the padded or cropped raster with nodata = None. PansharpenNodata::Auto and source_nodata read nodata from those adjusted datasets. When footprints differ and the union/intersection path pads or crops, the inferred nodata silently turns off. Pass ds.nodata() through.
  • No tolerance on the window-offset check (pansharpen.rs:322, low-medium confidence). The check x < 0.0 || y < 0.0 can fail on a tiny negative float such as -1e-12. That gives a spurious "outside input" error, including with PansharpenExtent::None. Clamp values within ~1e-6 of zero.

Security

  • Nothing found. Grid dimensions are bounds-checked and the allocation size uses checked_mul.

Performance

  • In convolution, the horizontal pass runs over all s.height source rows, even rows outside the requested rect. Restricting it to the rows the vertical taps need would cut work for small windows. Confidence: low.

Quality

  • A comment in convolution has a typo: "an binary row validity" should read "a binary row validity". Confidence: high, trivial.
  • The CLI's --spat-adjust parse error and the doc comment on PansharpenExtent::parse don't match. The parser also accepts nonewithoutwarning, which the error text doesn't list. Confidence: low.

CLAUDE.md

  • No CLAUDE.md guidelines were checked beyond surrounding-code style. The new files follow the existing conventions.

@giswqs giswqs mentioned this pull request Oct 24, 2026
9 tasks done
Match GDAL fractional RasterIO origins across all resamplers, accept shared affine space without a CRS, and bound convolution to needed rows. Document intentional nodata loss during footprint adjustment and compare both inferred and explicit nodata on real shifted images.
Comment thread crates/terrio/src/ops/pansharpen.rs Resolved
Comment thread python/src/terrain.rs Resolved
@github-actions

Copy link
Copy Markdown
Contributor

Code review

I read the full diff and the surrounding source. The review is from reading only: I could not run the build or the tests. The change adds weighted Brovey pansharpening with a core op, CLI, Python, JS and MCP bindings, docs, tests and a GDAL comparison script. I found no correctness bugs and no security issues.

Bugs

  • None found. I traced the extent adjustment, the separable convolution, the nodata handling and the Brovey loop. They are internally consistent and match the documented GDAL behaviour. I could not check the output against GDAL, so that comparison is untested by me.

Security

  • None found. File paths come from user input as expected for a CLI. The new fetch script pins the rio-pansharpen fixtures to a specific commit SHA.

Performance

  • Full-size f64 buffers (medium confidence). Every spectral band is held as a full-size Vec<f64> at pan resolution, alongside pan_values and result. adjust also copies each input band through translate even when no adjustment is needed. A large pan scene with several bands could need tens of GB. Row-strip processing, or a documented size limit, would help. Inline comment on crates/terrio/src/ops/pansharpen.rs.

Quality

  • Python nodata accepts bools (low confidence). In python/src/terrain.rs, nodata=True is silently read as 1.0 because extract::<f64>() accepts a Python bool. Rejecting bools would avoid that. Inline comment posted.
  • Duplicated bounds code (nit). The footprint-bounds arithmetic in pansharpen() calls pg.bounds() repeatedly. Binding it once would make the code easier to read.

CLAUDE.md

  • No CLAUDE.md violations found. The NOTICE attribution is updated in both copies, and the docs and conformance suite are extended.

Comment thread crates/terrio/src/ops/pansharpen.rs Resolved
@github-actions

Copy link
Copy Markdown
Contributor

Code review

I reviewed the core algorithm in crates/terrio/src/ops/pansharpen.rs in detail. I did not read the CLI, Python, JS or docs changes beyond the file list, so those are unreviewed. I found no correctness bugs in the core algorithm, and nothing that raises a security concern. I did not run any code or tests.

Bugs

  • None found. I traced these paths and they hold up:
    • Extent union and intersection, and the snapping of bounds to the pan grid.
    • Nodata handling, including the nudge applied when a result value collides with the nodata value.
    • The offset checks that reject a spectral window outside the input.
    • Bit-depth clamping.
    • The separable convolution tap and coverage indexing.

Security

  • None found.

Performance

  • Everything is materialized in memory (moderate confidence). adjust copies each full band, the per-band values planes are f64 at pan resolution, and pan_values and result are also full-size. For an 8-band image, peak memory is roughly (2×bands + 1) × width × height × 8 bytes. I left an inline comment at lines 306–321 of pansharpen.rs. The doc comment says virtual VRT output is deferred, but nothing says the inputs are read in full. Row-strip processing, a size guard, or an explicit note in the docs would address it.

Quality

  • Several lines in pansharpen.rs are very long, for example lines 113, 118, 262 and 296. Check them against the repo's rustfmt settings. The pre-commit run should catch this.
  • Line 296 recomputes pg.bounds() four times. Binding it once would be clearer.
  • The comment above convolution has a typo: "an binary row validity".

CLAUDE.md / AGENTS.md

  • The PR adds NOTICE entries, docs, MCP/CLI/Python/JS surfaces, and conformance registration, which matches what the guidelines ask for. The one gap is the lazy-read concern under Performance. The guidelines ask for measured I/O or memory impact when I/O behavior changes, and I saw no such measurement. This is moderate confidence, since I haven't seen the PR description's validation section.

Comment thread crates/terrio/src/ops/pansharpen.rs Resolved
Comment thread crates/terrio/src/ops/pansharpen.rs Resolved
@github-actions

Copy link
Copy Markdown
Contributor

Code review

I read the core algorithm in crates/terrio/src/ops/pansharpen.rs in full. I did not review the CLI, Python, JS bindings, docs or scripts in detail, so those are not covered here. The algorithm follows GDAL's structure closely, and the input validation is thorough. The findings below are two inline comments, both on pansharpen.rs.

Bugs

  • Explicit nodata vs. working type (medium-low confidence). With PansharpenNodata::Value(v), the pixel sentinel is convert_value(v, work), which clamps and rounds into the U8/U16 range. The output raster still declares the raw v. For example, nodata 300 on a U8 pan writes 255 into pixels but declares 300. See inline comment.

Security

  • Unbounded allocation (medium confidence). adjust caps each dimension below i32::MAX, but not the total cell count. Union extents that are far apart can request a huge vec!, and an allocation failure aborts the process instead of returning InvalidArgument. The same applies to the per-band full-size f64 planes in pansharpen. See inline comment.

Performance

  • The PR description already notes that the materialized API buffers whole inputs and f64 working planes. Memory grows with area × bands, and the bounded virtual or block-I/O follow-up is needed. This is not a blocker. Under the lazy-read guidance in AGENTS.md, it should stay tracked as incomplete for item 8.

Quality

  • no.unwrap() at line 404 in the per-pixel loop is safe because of the invalid guard. Restructuring with if let Some(nd) = no.filter(|_| invalid) would be clearer.
  • The nearest, average and convolution branches in pansharpen are long. Splitting them into helper functions would help readability.

CLAUDE.md / AGENTS.md

  • NOTICE attribution is added in both NOTICE files, and a GDAL conformance script and registration are included. I did not check the format/Clippy/test results, so I can't confirm them from this review.
  • The new operation is exposed in Rust, CLI/MCP, Python and JS, which matches the "consistent surfaces" guidance.

Comment thread crates/terrio/src/ops/pansharpen.rs Resolved
Comment thread crates/terrio/src/ops/pansharpen.rs Resolved
@github-actions

Copy link
Copy Markdown
Contributor

Code review

I read the core algorithm (crates/terrio/src/ops/pansharpen.rs) and the CLI wrapper in full. I did not read the Python or JS bindings, the docs, or the conformance scripts, so those are unreviewed. I did not run any code. Overall the core logic looks careful and consistent with its GDAL-port intent. I found no definite bugs.

Bugs

  • Auto nodata silently disabled with unequal footprints (pansharpen.rs:323, ~50% confidence). adjust drops nodata whenever it pads or crops, so PansharpenNodata::Auto ends up with no nodata even when every input declares the same value. The zero-filled padding is then treated as real data. The code comment says this mirrors GDAL. Users get no warning, though, and no test covers this path. Either resolve Auto from the original inputs or document the behavior clearly.

Security

  • Nothing found. Allocations use try_reserve_exact, and grid dimensions and bit depth are validated. The CLI parses the ,band=N suffix defensively.

Performance

  • The materialized path buffers every input, working plane and output plane in f64. The PR description acknowledges this and defers the bounded virtual/block-I/O work. That is a known limitation, not a regression. It means the roadmap item should stay unchecked.

Quality

  • no.unwrap() at pansharpen.rs:413 is correct today, but it depends on the earlier invalid flag. A filter or match would be sturdier (low confidence, nit).
  • output_bands accepts duplicates. That is probably fine, but it is undocumented.

CLAUDE.md / AGENTS.md

  • NOTICE files, docs, MCP tests, the Python and JS surfaces, and conformance registration are all present. That is consistent with the guidance to expose options across surfaces and attribute ports.
  • The PR states that 26 integer cases match GDAL exactly and Float32 matches within one ULP. That is worded in line with the rule about not overstating approximate agreement.

Comment thread crates/terrio/src/ops/pansharpen.rs Resolved
@github-actions

Copy link
Copy Markdown
Contributor

Code review

I read the core algorithm, crates/terrio/src/ops/pansharpen.rs, in full. I did not review the CLI, Python and JS bindings, docs, or conformance scripts in depth. I ran nothing, so none of the PR's GDAL-comparison claims are re-verified here.

Bugs

  • bit_depth is silently ignored when the pan band is not U8 or U16, because the working type is then F64 (pansharpen.rs:328). Validation still accepts any value from 1 to 31. A Float32 or Int16 pan with bit_depth set gets unclamped output and no error. Either reject it or document it as a no-op. Confidence: medium-low.

Security

  • Nothing found. Allocations go through try_reserve_exact and checked multiplication, and the non-finite and oversized-grid checks are covered by tests.

Performance

  • The PR description already notes that inputs and planes are fully buffered. That is a documented limitation, not a new finding.

Quality

  • Nothing blocking.

CLAUDE.md

  • The PR adds NOTICE entries, docs, regression tests, and conformance registration, which is what the repo's instructions ask for.

@giswqs
giswqs merged commit 54ae3ea into main Oct 24, 2026
17 checks passed
@giswqs
giswqs deleted the feat/pansharpen branch October 24, 2026 18:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant