Incorrect distances for out-of-bounds query points in toroidal ContinuousSpace
Describe the bug When ContinuousSpace is initialized with torus=True, calculate_distances() can return incorrect distances when the query point lies outside the space bounds.
Unlike ContinuousSpaceAgent.position, which automatically wraps out-of-bounds coordinates using torus_correct(), the distance-query methods do not wrap their input points.
Expected behavior In a toroidal space, equivalent coordinates should produce the same distance results. For example, querying with [2.9, 0.1] should produce the same distance as querying with its wrapped equivalent [0.9, 0.1].
For an agent at [0.1, 0.1], both queries should return a distance of [0.2].
To Reproduce
import numpy as np
from mesa import Model
from mesa.experimental.continuous_space import (
ContinuousSpace,
ContinuousSpaceAgent,
)
model = Model(rng=42)
space = ContinuousSpace(
np.asarray([[0, 1], [0, 1]]),
torus=True,
random=model.random,
)
agent = ContinuousSpaceAgent(space, model)
agent.position = [0.1, 0.1]
print(space.calculate_distances([0.9, 0.1])[0])
print(space.calculate_distances([2.9, 0.1])[0])
Expected output:
[0.2] [0.2]
Actual output:
[0.2] [1.8]
Additional context ContinuousSpaceAgent.position explicitly applies torus_correct() when an assigned position is outside the space bounds. However, calculate_distances() and calculate_difference_vector() do not apply this correction to query points. I haven't been able to establish whether this difference is intentional from the current documentation, so I'd like to clarify the expected behavior before proposing a code change.
I ran the reproducer locally. With an agent at [0.1, 0.1], the toroidal distance query returns 0.2 for [0.9, 0.1], but 1.8 for the equivalent point [2.9, 0.1]. calculate_difference_vector() also changes from [0.2, 0] to [-1.8, 0].
The agent position setter wraps out of bounds coordinates, while these two query methods use the point without wrapping it. I propose normalizing query points with torus_correct() in both methods when torus=True, then testing points shifted by one and multiple box widths. Non toroidal behavior would stay unchanged.
Is periodic equivalence the intended behavior for these query methods? If so, I can prepare a focused fix.
Confirmed on main (4.0.0a0). The cause is that the minimum-image convention in calculate_distances is applied without first wrapping the query point:
delta = np.abs(point - positions)
delta = np.minimum(delta, self.size - delta, out=delta)
That is only valid while |delta| <= size. On a unit torus with an agent at [0.1, 0.1] and a query at [2.9, 0.1]: delta = 2.8, size - delta = -1.8, so np.minimum selects -1.8. The sign is lost to the squaring on the next lines and the method reports 1.8.
Two things to add to the report:
[1.9, 0.1]fails the same way and returns0.8.[-1.1, 0.1]returns the correct0.2, but only coincidentally. It also passes through a negative intermediate (-0.2) whose magnitude happens to equal the true distance.
The precise condition is narrower than out-of-bounds. Once delta > size, the reported magnitude becomes delta - size, which is the single-wrap image rather than the minimum image. That coincides with the correct answer whenever it is at most size / 2, so the distance is only wrong once delta > 1.5 * size. With size 1 and an agent at 0.1, the first failure is at p = 1.60001, while 1.2, 1.4 and 1.6 are all outside the bounds and still correct. That is probably why it has gone unnoticed: a query point just past the boundary lands in the accidentally correct range, and reaching the broken region takes a point more than 1.5 space widths away.
Agent positions are wrapped on assignment (asserted in test_continuous_agent), so positions is always within bounds and only the query point can push |delta| past size.
calculate_difference_vector shares the root cause through a different expression:
inverse_delta = delta - np.sign(delta) * self.size
logical = np.abs(delta) < np.abs(inverse_delta)
When |delta| > size neither candidate is the true minimum image, so [1.9, 0.1] gives [-0.8, 0.] and [2.9, 0.1] gives [-1.8, 0.]. Both exceed size / 2, which is not geometrically reachable on a torus.
On intended behaviour: torus_correct is already asserted as the wrapping contract for this class in test_continuous_space (torus_correct([1.5, -0.5]) == [0.5, -0.5]), and the position setter applies it. Applying it to the query point in both methods would make the query side consistent with the position side, and get_agents_in_radius and get_k_nearest_agents would inherit the fix since both delegate to calculate_distances.
Is that the preferred resolution, or is the contract that callers pass in-bounds points, in which case the docstrings should say so?
I am not sure. Intuitively, I would say that only in bound points should be valid and an out of bounds points should raise the associated out of bounds exception. However, for a real verdict, I would need to consider some use cases. Also, if we don't allow out of bounds points when calculating distances, there should be an easy function that one might use to torus correct a point.
So, thoughts and options are welcome.
Both are defensible. My preference is to wrap the query point on a torus: a torus has no "outside", and the agent position setter already wraps with torus_correct(), so [2.9, 0.1] and [0.9, 0.1] are the same place. If you'd rather keep out-of-bounds points as errors, then these two methods should raise a clear error that points to torus_correct. Either way, the real bug is the silent wrong distance. I'm happy to open a PR for whichever you choose, with tests for points shifted by one and several box widths.