Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions src/power_grid_model_ds/_core/model/containers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,11 +212,18 @@ def _update_id_counter(self, array, check_max_id: bool = True):
array = self.attach_ids(array)
elif np.any(array.id == EMPTY_ID):
raise ValueError(f"Cannot append: array contains empty [{EMPTY_ID}] and non-empty ids.")
elif check_max_id and self.id_counter > 0:
# Only check for overlaps when array has prescribed (non-empty) IDs
# Check if any incoming ID might overlap with existing IDs
# This prevents overlaps since counter tracks the highest used ID
new_min_id = np.min(array.id)
if new_min_id <= self._id_counter:
raise ValueError(
f"Cannot append: minimum id {new_min_id} is not greater than "
f"the current id counter {self._id_counter}"
)

new_max_id = np.max(array.id)
if check_max_id and new_max_id < self._id_counter:
raise ValueError(f"Cannot append: id {new_max_id} is lower than the id counter")

# Update _id_counter
self._id_counter = max(self._id_counter, new_max_id)

Expand Down
40 changes: 40 additions & 0 deletions tests/unit/model/test_containers.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,46 @@ def test_id_counter():
assert 42 == container.id_counter


def test_append_with_overlapping_ids():
"""Test that appending arrays with overlapping IDs raises an error."""
grid = Grid.empty()

# Create first array with IDs [1, 2, 3]
nodes_1 = NodeArray.zeros(3)
nodes_1.id = [1, 2, 3]
grid.append(nodes_1)

# Create second array with overlapping IDs [3, 4, 5] (ID 3 overlaps)
nodes_2 = NodeArray.zeros(3)
nodes_2.id = [3, 4, 5]

# This should raise a ValueError due to overlapping ID 3
with pytest.raises(ValueError, match="Cannot append: minimum id 3 is not greater than the current id counter 3"):
grid.append(nodes_2)


def test_append_with_non_overlapping_ids():
"""Test that appending arrays with non-overlapping IDs works correctly."""
grid = Grid.empty()

# Create first array with IDs [1, 2, 3]
nodes_1 = NodeArray.zeros(3)
nodes_1.id = [1, 2, 3]
grid.append(nodes_1)

# Create second array with non-overlapping IDs [4, 5, 6]
nodes_2 = NodeArray.zeros(3)
nodes_2.id = [4, 5, 6]

# This should work without error
grid.append(nodes_2)

# Verify all nodes are in the grid
assert grid.node.size == 6
expected_ids = [1, 2, 3, 4, 5, 6]
assert sorted(grid.node.id.tolist()) == expected_ids


def test_branches(grid: Grid):
nodes = NodeArray.zeros(10)
grid.append(nodes)
Expand Down
Loading