Skip to content

Commit

Permalink
PropertyLayer: Fix handling of 'condition' callable in set_cells
Browse files Browse the repository at this point in the history
Resolved an inconsistency in the set_cells method of our grid class. The method's documentation stated that the 'condition' argument should be a callable (such as a lambda function or a NumPy ufunc), but the implementation incorrectly treated 'condition' as a NumPy array.

This update rectifies the implementation to align with the documented behavior. Now, the 'condition' argument is correctly called with the grid data as input, and its output (expected to be a boolean array) is used for conditional in-place updates of the grid. This change ensures that the function operates correctly when provided with callable conditions, fulfilling the intended functionality.

Includes:
- Calling 'condition' with self.data and using its output for conditional updates.
- Adjusted error handling to check the output of the callable, ensuring it's a NumPy array with the correct shape.
- Updated comments within the method for clarity.
  • Loading branch information
EwoutH committed Dec 4, 2023
1 parent 65b7749 commit 5f34480
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions mesa/space.py
Original file line number Diff line number Diff line change
Expand Up @@ -571,20 +571,23 @@ def set_cells(self, value, condition=None):
Args:
value: The value to be used for the update.
condition: (Optional) A callable that returns a boolean array when applied to the data.
condition: (Optional) A callable (like a lambda function or a NumPy ufunc)
that returns a boolean array when applied to the data.
"""
if condition is None:
np.copyto(self.data, value) # In-place update
else:
# Ensure condition is a boolean array of the same shape as self.data
# Call the condition and check if the result is a boolean array
condition_result = condition(self.data)
if (
not isinstance(condition, np.ndarray)
or condition.shape != self.data.shape
not isinstance(condition_result, np.ndarray)
or condition_result.shape != self.data.shape
):
raise ValueError(
"Condition must be a NumPy array with the same shape as the grid."
"Result of condition must be a NumPy array with the same shape as the grid."
)
np.copyto(self.data, value, where=condition) # Conditional in-place update
# Conditional in-place update
np.copyto(self.data, value, where=condition_result)

def modify_cell(self, position: Coordinate, operation, value=None):
"""
Expand Down

0 comments on commit 5f34480

Please sign in to comment.