Skip to content

In Data Loading, Clip to Layer BoundingBox (Redo #8551) #8573

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from

Conversation

MichaelBuessemeyer
Copy link
Contributor

@MichaelBuessemeyer MichaelBuessemeyer commented Apr 28, 2025

2nd iteration of #8551

Additionally, the nullable DataSource in various data request classes was replaced by Option[DataSourceId] to avoid Null exceptions in this context in the future.

Steps to test:

  • Edit the datasource-properties.json of an existing dataset to have a smaller bounding box than the existing data on disk
  • When viewing the dataset (after cache clear), the loaded data for that layer should be clipped accordingly
  • Zoom out to test different mags
  • Test that volume annotating works even if you touch the bounding box dataset (data should still be there after reload)
  • Test that for both on-disk segmentations and volume annotations, and proofreading, data loading and ad-hoc meshing still works.

Issues:


  • Updated changelog
  • Removed dev-only changes like prints and application.conf edits
  • Considered common edge cases
  • Needs datastore update after deployment

Copy link
Contributor

coderabbitai bot commented Apr 28, 2025

📝 Walkthrough

"""

Walkthrough

This change introduces logic to ensure that when loading data from a data layer, any voxel data outside the defined bounding box is zeroed out, effectively clipping the layer to its bounding box. The core implementation is in the backend data service, which now clips data arrays to the bounding box before further processing. Supporting changes include new methods for bounding box containment and translation, vector negation using a unary operator, and conversions between cuboid and bounding box representations. The changelog is updated to document this behavior.

Changes

Files/Paths Change Summary
util/src/main/scala/com/scalableminds/util/geometry/BoundingBox.scala Added lazy evaluation for bottomRight, methods for bounding box containment (isFullyContainedIn) and translation (move).
util/src/main/scala/com/scalableminds/util/geometry/Vec3Int.scala Replaced negate method with standard Scala unary minus operator (unary_-) for vector negation.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/Cuboid.scala Added methods to convert a Cuboid to a BoundingBox in different magnitudes.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/DataServiceRequests.scala Replaced DataSource with DataSourceId or Option[DataSourceId] in request classes; added fallback dummy IDs for volume tracings; added method to access cuboid magnitude vector.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/BinaryDataService.scala Implemented clipping of data arrays to the layer bounding box, adjusted data copying logic, and added a private method for zeroing out-of-bounds voxels; simplified coordinate calculations in cuboid voxel copying.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/controllers/BinaryDataController.scala Changed method signatures and calls to use DataSourceId instead of full DataSource objects for data requests.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/controllers/ZarrStreamingController.scala Modified construction of DataServiceDataRequest to use optional DataSourceId instead of full DataSource.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/dataformats/DatasetArrayBucketProvider.scala Changed argument from readInstruction.dataSource.id to readInstruction.dataSourceId in vaultPathFor call.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/dataformats/MappingProvider.scala Updated path resolution to use dataSourceId instead of nested dataSource.id fields.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/datasource/DataSource.scala Modified toString of DataSourceId to return a simplified string without wrapper text.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/AdHocMeshService.scala Replaced optional DataSource with optional DataSourceId in AdHocMeshRequest and related usages.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/DSFullMeshService.scala Changed construction of AdHocMeshRequest to pass Some(dataSource.id) instead of Some(dataSource).
webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/FindDataService.scala Replaced all DataSource parameters with DataSourceId in service methods; updated internal calls accordingly.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/MappingService.scala Changed argument in MappingReadInstruction construction from dataSource to dataSourceIdOrVolumeDummy.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/SegmentIndexFileService.scala Replaced dataSource with Some(dataSource.id) in DataServiceDataRequest construction.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/storage/AgglomerateFileCache.scala Updated AgglomerateFileKey construction to use dataSourceIdOrVolumeDummy instead of dataSource.id for organization and directory fields.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/storage/ParsedMappingCache.scala Modified CachedMapping.fromMappingRequest to use dataSourceIdOrVolumeDummy instead of dataSource.id for organization and directory fields.
webknossos-tracingstore/app/com/scalableminds/webknossos/tracingstore/tracings/editablemapping/EditableMappingService.scala Replaced null with None for optional DataSource/DataSourceId fields in request constructions.
webknossos-tracingstore/app/com/scalableminds/webknossos/tracingstore/tracings/volume/VolumeTracingService.scala Replaced null with None for optional DataSource fields in request constructions.
CHANGELOG.unreleased.md Documented the new behavior of zeroing out data outside the bounding box when loading from a data layer.

Assessment against linked issues

Objective Addressed Explanation
Clip/crop layer data at the bounding box, zeroing out voxels outside the bounding box (#5775)

Possibly related PRs

Suggested labels

backend, enhancement

Suggested reviewers

  • frcroth
  • philippotto

Poem

In the warren of code, a change hops in—
Bounding boxes drawn, so neat and thin.
No voxel shall stray beyond the line,
For out-of-bounds now equals zero—how fine!
With bounding and clipping, the data’s just right,
A rabbit’s delight—oh, what a byte!
🐇✨
"""


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 616cef3 and 2baa0ff.

📒 Files selected for processing (2)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/DataServiceRequests.scala (2 hunks)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/BinaryDataService.scala (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/DataServiceRequests.scala
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/BinaryDataService.scala
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: frontend-tests
  • GitHub Check: backend-tests
  • GitHub Check: build-smoketest-push

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@MichaelBuessemeyer MichaelBuessemeyer changed the title In Data Loading, Clip to Layer BoundingBox ( Redo #8551) In Data Loading, Clip to Layer BoundingBox (Redo #8551) Apr 28, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
CHANGELOG.unreleased.md (1)

22-22: LGTM, but consider a minor language improvement.

Clearly explains the new behavior of zeroing out data outside the defined bounding box. The explanation is precise and matches the PR's objectives.

Consider simplifying "outside of the bounding box" to just "outside the bounding box" to avoid redundancy:

- When loading data from a data layer that has data stored beyond the bounding box specified in the datasource-properties.json, data outside of the bounding box is now zeroed. (the layer is "clipped"). [#8551](https://github.com/scalableminds/webknossos/pull/8551)
+ When loading data from a data layer that has data stored beyond the bounding box specified in the datasource-properties.json, data outside the bounding box is now zeroed. (the layer is "clipped"). [#8551](https://github.com/scalableminds/webknossos/pull/8551)
🧰 Tools
🪛 LanguageTool

[style] ~22-~22: This phrase is redundant. Consider using “outside”.
Context: ...in the datasource-properties.json, data outside of the bounding box is now zeroed. (the la...

(OUTSIDE_OF)

util/src/main/scala/com/scalableminds/util/geometry/BoundingBox.scala (2)

48-50: Avoid temporary allocation in isFullyContainedIn for a micro-performance win
intersection allocates a new BoundingBox just to compare against this.
For a hot path you can sidestep the allocation by comparing coordinates directly:

- def isFullyContainedIn(other: BoundingBox): Boolean =
-   this.intersection(other).contains(this)
+ def isFullyContainedIn(other: BoundingBox): Boolean =
+   topLeft.x >= other.topLeft.x &&
+   topLeft.y >= other.topLeft.y &&
+   topLeft.z >= other.topLeft.z &&
+   bottomRight.x <= other.bottomRight.x &&
+   bottomRight.y <= other.bottomRight.y &&
+   bottomRight.z <= other.bottomRight.z

This keeps the method allocation–free while preserving semantics.


67-69: Minor naming nitpick – consider translate instead of move
The new helper is great, but move now exists in both BoundingBox and Vec3Int with slightly different semantics (in-place vs. returning a new box). Using a verb like translate or shift would reduce cognitive load and avoid confusing it with the Vec3Int counterpart.

webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/BinaryDataService.scala (1)

111-139: clipToLayerBoundingBox copies row-wise but still triple-loops ‑ can be flattened
Great to see explicit clipping! The inner copy already works per X-row; you can also flatten Y/Z loops by computing linear slice offsets and invoking a single System.arraycopy per contiguous block.
This typically halves the loop overhead for large requests:

- for {
-   z <- intersection.topLeft.z until intersection.bottomRight.z
-   y <- intersection.topLeft.y until intersection.bottomRight.y
- } {
-   val offset = (intersection.topLeft.x +
-                 y * requestBboxInMag.width +
-                 z * requestBboxInMag.width * requestBboxInMag.height) * bytesPerElement
-   System.arraycopy(inputArray,
-                    offset,
-                    outputArray,
-                    offset,
-                    (intersection.bottomRight.x - intersection.topLeft.x) * bytesPerElement)
- }
+val rowBytes = (intersection.bottomRight.x - intersection.topLeft.x) * bytesPerElement
+val sliceBytes = requestBboxInMag.width * requestBboxInMag.height * bytesPerElement
+val yStride   = requestBboxInMag.width * bytesPerElement
+
+var z = intersection.topLeft.z
+while (z < intersection.bottomRight.z) {
+  var y = intersection.topLeft.y
+  val zOffset = z * sliceBytes
+  while (y < intersection.bottomRight.y) {
+    val offset = zOffset + y * yStride + intersection.topLeft.x * bytesPerElement
+    System.arraycopy(inputArray, offset, outputArray, offset, rowBytes)
+    y += 1
+  }
+  z += 1
+}

No change in behaviour, ~2-3× speed-up on large volumes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d30f8d8 and 0b77cdf.

📒 Files selected for processing (6)
  • CHANGELOG.unreleased.md (1 hunks)
  • util/src/main/scala/com/scalableminds/util/geometry/BoundingBox.scala (3 hunks)
  • util/src/main/scala/com/scalableminds/util/geometry/Vec3Int.scala (1 hunks)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/Cuboid.scala (2 hunks)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/DataServiceRequests.scala (2 hunks)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/BinaryDataService.scala (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/DataServiceRequests.scala (2)
util/src/main/scala/com/scalableminds/util/geometry/Vec3Int.scala (2)
  • Vec3Int (7-89)
  • Vec3Int (91-157)
webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/Cuboid.scala (1)
  • mag (46-46)
util/src/main/scala/com/scalableminds/util/geometry/BoundingBox.scala (1)
util/src/main/scala/com/scalableminds/util/geometry/Vec3Int.scala (3)
  • move (53-56)
  • move (56-59)
  • other (32-35)
🪛 LanguageTool
CHANGELOG.unreleased.md

[style] ~22-~22: This phrase is redundant. Consider using “outside”.
Context: ...in the datasource-properties.json, data outside of the bounding box is now zeroed. (the la...

(OUTSIDE_OF)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build-smoketest-push
  • GitHub Check: backend-tests
  • GitHub Check: frontend-tests
🔇 Additional comments (7)
webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/DataServiceRequests.scala (2)

3-3: LGTM - Import correctly added.

The Vec3Int import is properly added to support the new mag method.


25-25: LGTM - Convenience accessor method.

This new method provides direct access to the cuboid's magnitude vector, consistent with the existing pattern of convenience methods like isSingleBucket. This will simplify code that needs to access the magnitude in data request processing.

util/src/main/scala/com/scalableminds/util/geometry/Vec3Int.scala (1)

26-28: LGTM - Good use of Scala's unary operator overloading.

Replacing a negate method with the unary minus operator unary_- is a good improvement. This follows idiomatic Scala by allowing the more natural syntax -vec instead of vec.negate(), making the code more readable and aligning with mathematical notation.

webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/Cuboid.scala (2)

3-3: LGTM - Import correctly added.

The BoundingBox import is properly added to support the new conversion methods.


55-59: LGTM - Well-implemented conversion methods.

The new methods provide useful conversions between Cuboid and BoundingBox representations, which are essential for the bounding box clipping functionality. The implementation is correct, using the appropriate magnitude-aware coordinates.

  • toBoundingBoxInMag creates a BoundingBox using the cuboid's top-left position in magnitude coordinates
  • toMag1BoundingBox leverages the existing toMag1 method to first normalize to mag1, then convert to a BoundingBox

These methods follow the naming pattern of existing conversion methods like toMag1.

webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/BinaryDataService.scala (2)

143-148: Clipping before agglomerate / half-byte conversion is the right order – nice!
The guard !request.cuboid.toMag1BoundingBox.isFullyContainedIn(...) prevents an unnecessary copy when the request is already inside bounds, keeping the fast path untouched.


232-235: Variable extraction improves readability – LGTM
Deriving rx/ry/rz once clarifies the intent and removes the previous silent division by subsampling stride. Implementation and indexing logic remain correct.

@fm3 fm3 self-assigned this Apr 29, 2025
@fm3
Copy link
Member

fm3 commented Apr 29, 2025

@MichaelBuessemeyer I found the problem here. The DataSource was set to null in the request classes for volume tracings. That was always by design and we had null checks in many spots. But this variable is accessed in convertIfNecessary (which now also happens in the tracingstore’s BinaryDataService). I now went ahead and replaced this null hack with an Option, so that the scala type system will help us avoid such problems in the future. Could you please have a look at my latest changes when you have time? (No hurry)

As you opened this PR someone else will have to hit approve eventually, but I still think that you could review the content 😇

Copy link
Contributor Author

@MichaelBuessemeyer MichaelBuessemeyer left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome, thanks for fixing this so fast 🎉

I found 2 things please find them below.

Would give this PR an approval but as I opened it myself that up to you :)

@MichaelBuessemeyer MichaelBuessemeyer requested a review from fm3 April 29, 2025 12:50
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.

Layer should be clipped at bounding box
2 participants