Skip to content

Network initialization crashes when layout dictionary is missing node positions #3385

@falloficarus22

Description

@falloficarus22

Describe the bug
Network space initialization incorrectly handles nodes that are missing from the layout mapping. When a node ID is not found in the layout, node_positions.get(node_id) returns None. However, the code immediately wraps this in a NumPy array: pos = np.array(None).

Because a NumPy array (even one wrapping None) is not the Python None singleton, the subsequent guard if pos is not None: evaluates to True. This causes the invalid position to be passed to scipy.spatial.KDTree, which crashes the initialization with a ValueError.

Expected behavior
The Network space should identify nodes without specified positions and skip them when building the spatial KDTree. If the resulting list of positions is empty, it should gracefully set self._kdtree = None, allowing the space to function in a purely topological mode (as intended and documented).

To Reproduce

import networkx as nx
from mesa.discrete_space import Network

# 1. Create a graph with nodes
G = nx.Graph()
G.add_nodes_from([1, 2, 3])

# 2. Attempt to initialize Network with an empty layout dictionary
# This raises: ValueError: data must be of shape (n, m) (from SciPy KDTree)
net = Network(G, layout={})

Additional context
Suggested Fix: Check for None before wrapping the position in a NumPy array

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