Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added empty iterable checks and updated tests #2523

Merged
merged 2 commits into from
Dec 1, 2024
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
15 changes: 14 additions & 1 deletion mesa/batchrunner.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,14 @@ def _make_model_kwargs(
Parameters
----------
parameters : Mapping[str, Union[Any, Iterable[Any]]]
Single or multiple values for each model parameter name
Single or multiple values for each model parameter name.

Allowed values for each parameter:
- A single value (e.g., `32`, `"relu"`).
- A non-empty iterable (e.g., `[0.01, 0.1]`, `["relu", "sigmoid"]`).

Not allowed:
- Empty lists or empty iterables (e.g., `[]`, `()`, etc.). These should be removed manually.

Returns:
-------
Expand All @@ -118,6 +125,12 @@ def _make_model_kwargs(
if isinstance(values, str):
# The values is a single string, so we shouldn't iterate over it.
all_values = [(param, values)]
elif isinstance(values, list | tuple | set) and len(values) == 0:
# If it's an empty iterable, raise an error
raise ValueError(
f"Parameter '{param}' contains an empty iterable, which is not allowed."
)

else:
try:
all_values = [(param, value) for value in values]
Expand Down
31 changes: 31 additions & 0 deletions tests/test_batch_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,37 @@ def test_make_model_kwargs(): # noqa: D103
assert _make_model_kwargs({"a": "value"}) == [{"a": "value"}]


def test_batch_run_with_params_with_empty_content():
"""Test handling of empty iterables in model kwargs."""
# If "a" is a single value and "b" is an empty list (should raise error for the empty list)
parameters_with_empty_list = {
"a": 3,
"b": [],
}

try:
_make_model_kwargs(parameters_with_empty_list)
raise AssertionError(
"Expected ValueError for empty iterable but no error was raised."
)
except ValueError as e:
assert "contains an empty iterable" in str(e)

# If "a" is a iterable and "b" is an empty list (should still raise error)
parameters_with_empty_b = {
"a": [1, 2],
"b": [],
}

try:
_make_model_kwargs(parameters_with_empty_b)
raise AssertionError(
"Expected ValueError for empty iterable but no error was raised."
)
except ValueError as e:
assert "contains an empty iterable" in str(e)


class MockAgent(Agent):
"""Minimalistic agent implementation for testing purposes."""

Expand Down
Loading