Repository navigation
fix: wrap torus query points before distance calculations - #3932
Conversation
ContinuousSpace.calculate_distances and calculate_difference_vector applied the minimum-image convention without first wrapping the query point into the space bounds. That convention only holds when the per-axis separation is at most the space size, so an out-of-bounds query point produced a negative intermediate which then surfaced as an incorrect positive distance once squared. On a unit torus with an agent at [0.1, 0.1], a query at [2.9, 0.1] returned 1.8 and [1.9, 0.1] returned 0.8, although both are congruent to [0.9, 0.1] modulo the space size and should return 0.2. Agent positions are already wrapped on assignment, so only the query side could violate the invariant. Both methods now apply the existing torus_correct before computing deltas. This also fixes get_agents_in_radius and get_k_nearest_agents, which delegate to calculate_distances.
|
Performance benchmarks:
|
|
Thanks for implementing this and for the credit. The tests with equivalent torus coordinates cover the behavior I saw in the issue. I noticed the benchmark bot reports a BoidFlockers runtime increase of 11.8% for the small case and 9.4% for the large case. It may be worth checking whether this change causes that increase before merging. |
The benchmark bot reported BoidFlockers run time up 11.8% (small) and 9.4% (large). BoidFlockers is the only continuous-space model in the suite and the only one flagged, so the cost came from calling torus_correct on the query point in every calculate_distances call. Agents query with their own position, which the position setter has already wrapped, so for that case the wrap was pure overhead. The separation is now computed first and only folded when some axis actually exceeds the space size, which is the only situation where the minimum image convention breaks. The check is per axis rather than against the largest axis. A global maximum is wrong for a space such as [[0, 0.5], [0, 50]], where a separation of 1.0 on the first axis exceeds that axis but not the global maximum of 50.
Replaces the numpy per-axis guard from the previous commit, which was slower than the wrap it was meant to avoid because it scanned the whole separation array. Agents query with their own position, which the setter has already wrapped, so the correction is almost never needed. The bounds are cached as plain Python floats in __init__ and compared without touching numpy, which is what makes the check cheaper than the work it skips. Measured on BoidFlockers small, 20 steps, minimum of 15 replications: main 290.7 ms, torus_correct on every call 329.4 ms, numpy per-axis guard 333.6 ms, this version 324.9 ms. So this is the cheapest correct option I found, but it does not remove the cost: roughly 12% remains, since any per-query check costs microseconds and the benchmark makes about 8000 queries.
|
Hi, so yeah, BoidFlockers is the only continuous space model in the benchmark suite and the only one flagged, so that increase is from my change. The cost was calling Measured locally on BoidFlockers small, 20 steps, min of 15 runs: main 290.7 ms, the version you saw 329.4 ms, this one 324.9 ms. So it helps but it does not remove the cost, about 12% is still there. I also tried a numpy per axis guard and that came out slower at 333.6 ms, and my first attempt guarded on the largest axis only, which was just wrong on a space like If the remaining 12% is not acceptable, the other option is to let the agent facing methods skip the check, since they always pass a position that is already in bounds, and have only the public |
|
Follow up with numbers on that last option, since they change whether it is worth doing. BoidFlockers small, 20 steps, min of 15 runs on my machine: main 290.7 ms, with the bounds check 324.9 ms, and with the check removed entirely (incorrect, purely to measure the floor) 302.4 ms. So the check is about 22 ms of the 34 ms gap. Letting the agent facing methods skip it, since they always pass a position the setter has already wrapped, should recover most of that and leave roughly 4%. My machine swings by about 10 ms run to run though, so the small differences are loose and the bot is the authority. I can put that together in this PR if you want it, or leave it as a follow up. |
ContinuousSpaceAgent.get_neighbors_in_radius and get_nearest_neighbors query with the agent's own position, which the position setter keeps inside the bounds. Those calls can therefore skip the bounds check in calculate_distances, which is what the benchmark regression was paying for. calculate_distances, get_agents_in_radius and get_k_nearest_agents take a private keyword-only _in_bounds flag, and only the two agent methods set it. Model code calling any of these directly is unaffected and still gets the check, so an out-of-bounds query point is handled exactly as before. BoidFlockers small, 20 steps, minimum of 15 replications: main 290.7 ms, this branch 287.0 ms. The earlier commits measured 329.4 ms with the wrap on every call and 324.9 ms with the Python bounds check.
|
Update: the agent path option worked better than I expected, so I have pushed it.
Same session, back to back, BoidFlockers small, 20 steps, min of 15 runs: main 275.3 ms, the version you first saw 312.6 ms, now 290.5 ms. So roughly +13% down to roughly +5%. My machine drifts between sessions, main has measured anywhere from 275 to 290 ms tonight, so these are only useful relative to each other and the bot is the real answer. 836 tests pass, and the property sweep I used over asymmetric, offset origin and 3D spaces still finds no violations on the out of bounds path. |
|
Performance benchmarks:
|
The benchmark re-run on the previous commit still showed BoidFlockers run time up 6.1% (small) and 5.4% (large). calculate_distances had been optimised, but calculate_difference_vector still called torus_correct unconditionally, and the boids example calls it once per agent per step with the agent's own position, which is already inside the bounds. It now uses the same plain Python bounds check as calculate_distances and only wraps when some coordinate is outside, so an out-of-bounds query point behaves exactly as before. BoidFlockers small, 20 steps, minimum of 15 replications, three interleaved rounds on one machine: main 289.9 ms on average, previous commit 308.7 ms (+6.5%, in line with the bot's +6.1%), this commit 295.9 ms (+2.1%).
| # Only wrap when the point is actually outside the bounds. Agents | ||
| # typically pass their own position, which is already inside, and | ||
| # the plain Python comparisons keep numpy calls off that path. | ||
| for value, lower, upper in zip(point, self._lower, self._upper): |
There was a problem hiding this comment.
why do you use zip here? I just like to understand the reasoning.
Why not
lower = self._lower # do the attribute look up only once to save minute overhead.
upper = self.._upper
for value in point:
...There was a problem hiding this comment.
Sooo, I added the check to skip numpy on the in-bounds path, but I never benchmarked it, so I can't justify the extra code. I've simplified it: both methods now call torus_correct(point) unconditionally on a torus. That removes the zip loop, the _lower/_upper attributes and the _in_bounds flag, so the agents file is back to its original form. The continuous-space tests pass. Happy to benchmark if you think the extra call matters.
There was a problem hiding this comment.
Some benchmarking, perhaps just on the specific lines of code would be a good idea.
quaquel
left a comment
There was a problem hiding this comment.
I have one question, but otherwise this looks fine to me. Once the question has been answered. I'll merge it.
Call torus_correct(point) unconditionally on a torus instead of checking the bounds first. This removes the per-axis bounds tuples and the private _in_bounds flag, and restores continuous_space_agents.py to its original form.
Benchmarks showed that calling torus_correct on every query adds about 1.5 us per call, which is 20 to 40 percent of a query in small spaces. A small helper that wraps only out-of-bounds points keeps the overhead near 0.5 us, without the _in_bounds flag or changes to continuous_space_agents.py.
|
Benchmarked on the actual code (N agents, toroidal 2D, seeded random positions, median of 7 runs, per query call). Always calling |
|
Performance benchmarks:
|
|
Quick update on the bot numbers for the current head. BoidFlockers run time is +11.0% (small) and +8.6% (large), everything else is within noise. For comparison, the version that skipped the check on the agent query paths (a161570, the private flag) measured about +6.1% and +5.4% on the same bot. So the simple version is easier to read but costs roughly 5 points more on the one continuous space benchmark. I can bring the skip back if you think that is worth the extra code, or leave it as it is. Your call. |
Sure,happy to answer any more queries. |
|
I am inclined to favor the flag option. Performance on this matters and is worth the slightly more complicated code. Can you update the PR accordingly? |
Agents query with their own position, which the setter keeps inside the space, so they pass a private flag to skip the check. Other queries are still checked and wrapped.
|
Done, I went with the flag. Agents now pass a private On BoidFlockers (small, 20 steps, minimum of 15 runs, same machine, back to back) I get about 270 ms on main and 276 ms with this, so around 2 to 3 percent, down from the 11 percent in the last bot run. |
|
Performance benchmarks:
|
* fix: wrap torus query points before distance calculations ContinuousSpace.calculate_distances and calculate_difference_vector applied the minimum-image convention without first wrapping the query point into the space bounds. That convention only holds when the per-axis separation is at most the space size, so an out-of-bounds query point produced a negative intermediate which then surfaced as an incorrect positive distance once squared. On a unit torus with an agent at [0.1, 0.1], a query at [2.9, 0.1] returned 1.8 and [1.9, 0.1] returned 0.8, although both are congruent to [0.9, 0.1] modulo the space size and should return 0.2. Agent positions are already wrapped on assignment, so only the query side could violate the invariant. Both methods now apply the existing torus_correct before computing deltas. This also fixes get_agents_in_radius and get_k_nearest_agents, which delegate to calculate_distances. * Correct the torus separation lazily to avoid a hot-path cost The benchmark bot reported BoidFlockers run time up 11.8% (small) and 9.4% (large). BoidFlockers is the only continuous-space model in the suite and the only one flagged, so the cost came from calling torus_correct on the query point in every calculate_distances call. Agents query with their own position, which the position setter has already wrapped, so for that case the wrap was pure overhead. The separation is now computed first and only folded when some axis actually exceeds the space size, which is the only situation where the minimum image convention breaks. The check is per axis rather than against the largest axis. A global maximum is wrong for a space such as [[0, 0.5], [0, 50]], where a separation of 1.0 on the first axis exceeds that axis but not the global maximum of 50. * Use a Python-level bounds check to cut the hot-path cost Replaces the numpy per-axis guard from the previous commit, which was slower than the wrap it was meant to avoid because it scanned the whole separation array. Agents query with their own position, which the setter has already wrapped, so the correction is almost never needed. The bounds are cached as plain Python floats in __init__ and compared without touching numpy, which is what makes the check cheaper than the work it skips. Measured on BoidFlockers small, 20 steps, minimum of 15 replications: main 290.7 ms, torus_correct on every call 329.4 ms, numpy per-axis guard 333.6 ms, this version 324.9 ms. So this is the cheapest correct option I found, but it does not remove the cost: roughly 12% remains, since any per-query check costs microseconds and the benchmark makes about 8000 queries. * Skip the bounds check on the agent query paths ContinuousSpaceAgent.get_neighbors_in_radius and get_nearest_neighbors query with the agent's own position, which the position setter keeps inside the bounds. Those calls can therefore skip the bounds check in calculate_distances, which is what the benchmark regression was paying for. calculate_distances, get_agents_in_radius and get_k_nearest_agents take a private keyword-only _in_bounds flag, and only the two agent methods set it. Model code calling any of these directly is unaffected and still gets the check, so an out-of-bounds query point is handled exactly as before. BoidFlockers small, 20 steps, minimum of 15 replications: main 290.7 ms, this branch 287.0 ms. The earlier commits measured 329.4 ms with the wrap on every call and 324.9 ms with the Python bounds check. * Only wrap the query point in calculate_difference_vector when needed The benchmark re-run on the previous commit still showed BoidFlockers run time up 6.1% (small) and 5.4% (large). calculate_distances had been optimised, but calculate_difference_vector still called torus_correct unconditionally, and the boids example calls it once per agent per step with the agent's own position, which is already inside the bounds. It now uses the same plain Python bounds check as calculate_distances and only wraps when some coordinate is outside, so an out-of-bounds query point behaves exactly as before. BoidFlockers small, 20 steps, minimum of 15 replications, three interleaved rounds on one machine: main 289.9 ms on average, previous commit 308.7 ms (+6.5%, in line with the bot's +6.1%), this commit 295.9 ms (+2.1%). * Simplify torus query-point wrapping Call torus_correct(point) unconditionally on a torus instead of checking the bounds first. This removes the per-axis bounds tuples and the private _in_bounds flag, and restores continuous_space_agents.py to its original form. * Wrap torus query points only when they are outside the bounds Benchmarks showed that calling torus_correct on every query adds about 1.5 us per call, which is 20 to 40 percent of a query in small spaces. A small helper that wraps only out-of-bounds points keeps the overhead near 0.5 us, without the _in_bounds flag or changes to continuous_space_agents.py. * Skip the torus bounds check for agent queries Agents query with their own position, which the setter keeps inside the space, so they pass a private flag to skip the check. Other queries are still checked and wrapped. --------- Co-authored-by: AryamannSrivastava <[email protected]> Co-authored-by: Jan Kwakkel <[email protected]> (cherry picked from commit 9251a9f)
Pre-PR Checklist
Summary
On a toroidal
ContinuousSpace,calculate_distancesandcalculate_difference_vectorapply the minimum image convention to the raw query point. That convention only holds while the per axis separation is at most the space size, so a query point far enough outside the bounds produces a negative intermediate which then surfaces as an incorrect positive distance once squared.get_agents_in_radiusandget_k_nearest_agentsinherit the error, since both delegate tocalculate_distances.Bug / Issue
Fixes #3931.
Credit to @SahilKumar75, who diagnosed this first in the issue thread and proposed the
torus_correct()approach used here.Agent positions are wrapped on assignment by the position setter, so
positionsis always inside the bounds. Query points are not wrapped, which is why only the query side can push the separation pastsize.An out of bounds query point is not sufficient to trigger it. Once
delta > size, the reported value becomesdelta - size, the single wrap image, and that coincides with the true minimum image whenever it is at mostsize / 2. So the distance is only wrong oncedelta > 1.5 * size. With size 1 and an agent at[0.1, 0.1], a sweep of 100001 points puts the first failure at1.60001, while1.2,1.4and1.6are all outside the bounds and still return correct answers.That matters for choosing test points: a test written against
1.2passes on the unfixed code and proves nothing.Implementation
Both methods now call the existing
self.torus_correct(point)before computing deltas, and only whenself.torusis set. Non toroidal behaviour is unchanged, since an out of bounds point there is a genuine Euclidean distance and still goes throughcdist.torus_correctis already the wrapping contract for this class, asserted intest_continuous_space, and it is what the position setter uses. Applying it here makes the query side consistent with the position side instead of introducing a second convention.Notessections were added to both docstrings stating the wrapping behaviour, since the issue also carries thedocslabel.Testing
Added
test_continuous_space_torus_out_of_bounds_queryintests/experimental/test_continuous_space.py. It takes five x axis query points that are congruent modulo the space size (0.9,1.9,2.9,-0.1,-1.1) and asserts:0.2np.linalg.norm(space.size / 2)size / 2on any axisThe last two are properties rather than hardcoded expectations, and the vector bound is what catches the
calculate_difference_vectorhalf of the bug.Verified locally on Python 3.13.15:
tests/experimental/test_continuous_space.py: 13 passed-Werror -Wdefault::PendingDeprecationWarning): 836 passedruff checkandruff format --check: cleanThe tests under
tests/exampleswere not run locally because no Playwright browsers are installed. They do not touch this code.Additional Notes
One question from the issue thread is still open and no maintainer has answered it yet: whether periodic equivalence is the intended contract for these query methods, or whether callers are expected to pass in bounds points and the docstrings should simply say so.
This PR implements the first reading. If the second is preferred, the code change can be dropped and the docstring
Noteskept, and I am happy to rework it either way.