Skip to content

Commit

Permalink
solaraviz kwargs related bugfix (projectmesa#2463)
Browse files Browse the repository at this point in the history
  • Loading branch information
quaquel authored Nov 6, 2024
1 parent ef383c4 commit 0c1ccd6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
9 changes: 6 additions & 3 deletions mesa/visualization/solara_viz.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,8 @@ def ModelController(
playing = solara.use_reactive(False)
running = solara.use_reactive(True)
if model_parameters is None:
model_parameters = solara.use_reactive({})
model_parameters = {}
model_parameters = solara.use_reactive(model_parameters)

async def step():
while playing.value and running.value:
Expand Down Expand Up @@ -307,7 +308,8 @@ def ModelCreator(
"""
if model_parameters is None:
model_parameters = solara.use_reactive({})
model_parameters = {}
model_parameters = solara.use_reactive(model_parameters)

solara.use_effect(
lambda: _check_model_params(model.value.__class__.__init__, fixed_params),
Expand Down Expand Up @@ -345,10 +347,11 @@ def _check_model_params(init_func, model_params):
model_parameters[name].default == inspect.Parameter.empty
and name not in model_params
and name != "self"
and name != "kwargs"
):
raise ValueError(f"Missing required model parameter: {name}")
for name in model_params:
if name not in model_parameters:
if name not in model_parameters and "kwargs" not in model_parameters:
raise ValueError(f"Invalid model parameter: {name}")


Expand Down
10 changes: 10 additions & 0 deletions tests/test_solara_viz.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,10 @@ class ModelWithOnlyRequired:
def __init__(self, param1, param2):
pass

class ModelWithKwargs:
def __init__(self, **kwargs):
pass

# Test that optional params can be omitted
_check_model_params(ModelWithOptionalParams.__init__, {"required_param": 1})

Expand All @@ -184,6 +188,12 @@ def __init__(self, param1, param2):
ModelWithOptionalParams.__init__, {"required_param": 1, "optional_param": 5}
)

# Test that model_params are accepted if model uses **kwargs
_check_model_params(ModelWithKwargs.__init__, {"another_kwarg": 6})

# test hat kwargs are accepted even if no model_params are specified
_check_model_params(ModelWithKwargs.__init__, {})

# Test invalid parameter name raises ValueError
with pytest.raises(ValueError, match="Invalid model parameter: invalid_param"):
_check_model_params(
Expand Down

0 comments on commit 0c1ccd6

Please sign in to comment.