Skip to content

[6.40] [mathcore] Fix TKDTreeBinning::FindBin returning out-of-range bins #22668

Merged
guitargeek merged 4 commits into
root-project:v6-40-00-patchesfrom
root-project-bot:BP_6.40_pull_22649
Jun 19, 2026
Merged

[6.40] [mathcore] Fix TKDTreeBinning::FindBin returning out-of-range bins #22668
guitargeek merged 4 commits into
root-project:v6-40-00-patchesfrom
root-project-bot:BP_6.40_pull_22649

Conversation

@root-project-bot

Copy link
Copy Markdown

Backport of #22649, requested by @guitargeek.

The test had no failure return code, so errors would go undetected.

(cherry picked from commit 408adeb)
TKDTreeBinning computed fNBins independently from the kd-tree it builds.
SetNBins picks a bucket size of fDataSize / nBins (integer division), but
the underlying TKDTree creates ceil(fNPoints / bucketSize) terminal nodes.
When the requested number of bins does not divide the data size evenly, the
bucket size is rounded down and the tree ends up with more terminal nodes
than fNBins. Since FindBin returns a terminal-node index, it could return a
value >= GetNBins(), pointing at a bin with no edges and no content:

```c++
binning.GetNBins()                         # 1001
binning.FindBin([1.2, 0.5, 0.5, 0.5, 0.5]) # 1004
binning.GetBinContent(1004)                # RuntimeWarning: No such bin
```

Set fNBins to the actual number of terminal nodes (GetNNodes() + 1) after
building the tree, so FindBin always returns an index within
[0, GetNBins()) and every bin has valid edges and content. This also
self-corrects existing objects on read-back, as the Streamer rebuilds the
tree via SetNBins.

Also fix SetBinsContent to read the per-node point counts directly from the
tree (GetNPointsNode) instead of an incorrect last-bin heuristic, so bin
contents are exact and sum to the data size.

Add a regression test covering the non-evenly-dividing case.

Closes root-project#10786.

🤖 Done with the help of AI.

(cherry picked from commit 753b71b)
Add a regression test covering the non-evenly-dividing TKDTreeBinning
case.

This covers the bug reported in GitHub issue root-project#10786.

🤖 Done with the help of AI.

(cherry picked from commit f873308)
@guitargeek guitargeek merged commit c132d08 into root-project:v6-40-00-patches Jun 19, 2026
28 of 30 checks passed
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.

2 participants