`cell.neighborhood` includes the cell itself when it is connected to itself, and `remove_cell` then fails
Describe the bug
If a cell is connected to itself, Cell.get_neighborhood(radius=1, include_center=False) (and so cell.neighborhood) returns the cell itself as one of its own neighbors. With radius=2 or more the cell is correctly left out, so the two paths disagree.
This happens in two normal setups:
- a
Networkbuilt from a graph with a self-loop (e.g.nx.Graph([(0, 1), (1, 1)])) - an orthogonal grid with
torus=Trueand a dimension of size 1 (e.g. a(N, 1)ring), where wrapping connects each cell to itself
A side effect is that DiscreteSpace.remove_cell on such a cell raises ConnectionMissingException. It pops the cell from _cells before failing, so the space is left half-updated (for Network, the node is also still in G).
Expected behavior
With include_center=False, the cell is never in its own neighborhood, whatever the radius. remove_cell works on self-connected cells.
To Reproduce
import random
import networkx as nx
from mesa.discrete_space import Network, OrthogonalVonNeumannGrid
grid = OrthogonalVonNeumannGrid((5, 1), torus=True, random=random.Random(42))
cell = grid._cells[(2, 0)]
print(sorted(c.coordinate for c in cell.neighborhood))
# [(1, 0), (2, 0), (3, 0)] <- (2, 0) is the cell itself
print(sorted(c.coordinate for c in cell.get_neighborhood(radius=2)))
# [(0, 0), (1, 0), (3, 0), (4, 0)] <- radius 2 correctly excludes it
grid.remove_cell(cell)
# mesa.exceptions.ConnectionMissingException: Connection between (2, 0) and (2, 0) does not exist.
net = Network(nx.Graph([(0, 1), (1, 1), (1, 2)]), random=random.Random(42))
print(sorted(c.coordinate for c in net._cells[1].neighborhood)) # [0, 1, 2]
net.remove_cell(net._cells[1]) # ConnectionMissingException
Additional context
The cause is the radius == 1 fast path in Cell._neighborhood. It builds the dict from self.connections and only handles include_center=True. The BFS path for larger radii does neighborhood.pop(self, None) when include_center=False, but the fast path doesn't. remove_cell then calls neighbor.disconnect(cell) and cell.disconnect(neighbor) with neighbor is cell, so the second call fails.
Mesa main (4.0.0a0, commit f85955b), Python 3.13, networkx 3.6.1, Linux.
Opened PR #3885 to fix the fast path logic for self-connected cells and added a test case for it.
Can this happen when you have more than 1 cell?