Skip to content

Grid connectivity changes are lost after pickle / unpickle #3215

@ShreyasN707

Description

@ShreyasN707

I ran into an issue when using pickle to save and restore a model that modifies grid connectivity at runtime (for example, creating walls by disconnecting neighboring cells).

After unpickling, the grid always falls back to its default neighbor structure (Moore / Von Neumann / Hex), even if cells were explicitly disconnected before saving. This means runtime topology changes are silently lost, which makes checkpointing unreliable for models with dynamic grids.

Reproduction:

import pickle
from mesa.discrete_space.grid import OrthogonalMooreGrid

grid = OrthogonalMooreGrid((3, 3))

a = grid[(1, 1)]
b = grid[(1, 2)]

a.disconnect(b)
b.disconnect(a)

restored = pickle.loads(pickle.dumps(grid))

ra = restored[(1, 1)]
rb = restored[(1, 2)]

print(rb in ra.connections.values())  # True (but should be False)

During pickling, cell connections are cleared:

# grid_cell.py
state[1]["connections"] = {}

Then during unpickling, the grid rebuilds the default topology:

# grid.py
self._connect_cells()

So any runtime changes to connectivity are overwritten.

This matters because many models rely on changing spatial connectivity (walls, obstacles, damaged roads, etc.). After unpickling, the model is no longer running on the same world it was saved from, which breaks reproducibility and checkpointing.

Expected behavior

After pickle / unpickle, the grid should preserve whatever connectivity existed at the time it was saved. If this isn’t supported by design, it would at least be good to document it clearly.

If this is indeed a bug, I’d be happy to work on a fix or propose a PR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions