mesa icon indicating copy to clipboard operation
mesa copied to clipboard

`ContinuousSpace` loses agent positions after pickle or deepcopy

Open 0xnithinmys opened this issue 1 month ago • 0 comments

ContinuousSpace stores positions in _agent_positions and exposes the active rows through agent_positions, which is a view of that array (mesa/experimental/continuous_space/continuous_space.py:94-100). Pickle and copy.deepcopy do not keep views, so after a round trip they become two separate arrays. The class has no __getstate__/__setstate__ to rebuild the view.

After a restore, position writes go to one array while some reads use the other. The next time an agent is added or removed, the view is rebuilt from the stale array, and every agent jumps back to its checkpoint position.

Expected behavior

A restored space behaves like the original: distances use current positions, and adding or removing an agent does not move other agents.

To Reproduce

import pickle
from mesa import Model
from mesa.experimental.continuous_space import ContinuousSpace, ContinuousSpaceAgent

model = Model(rng=42)
space = ContinuousSpace([[0, 10], [0, 10]], random=model.random)
a = ContinuousSpaceAgent(space, model)
a.position = [1.0, 1.0]

model, space, a = pickle.loads(pickle.dumps((model, space, a)))  # same with copy.deepcopy

a.position = [9.0, 9.0]
print(space.calculate_distances([9.0, 9.0], agents=[a])[0])  # a sits on this point
ContinuousSpaceAgent(space, model)                           # add any agent
print(a.position)

Output:

[11.3137085]
[1. 1.]

Expected [0.] and [9. 9.].

Additional context

  • No test pickles or deepcopies a ContinuousSpace. Grid and EventList both have pickle support and tests.

  • Proposed fix (tested locally): leave the view out of the pickled state and rebuild it on restore.

    def __getstate__(self):
        state = self.__dict__.copy()
        state.pop("agent_positions", None)
        return state
    
    def __setstate__(self, state):
        self.__dict__.update(state)
        self.agent_positions = self._agent_positions[: self._n_agents]
    

0xnithinmys avatar Oct 22 '26 16:10 0xnithinmys