Mesa 3.1.0__py3-none-any.whl → 3.1.0.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of Mesa might be problematic. Click here for more details.
- mesa/__init__.py +3 -3
- mesa/agent.py +0 -48
- mesa/batchrunner.py +1 -14
- mesa/datacollection.py +6 -1
- mesa/examples/__init__.py +2 -2
- mesa/examples/advanced/epstein_civil_violence/app.py +0 -5
- mesa/examples/advanced/pd_grid/app.py +0 -5
- mesa/examples/advanced/sugarscape_g1mt/app.py +2 -7
- mesa/examples/basic/boid_flockers/app.py +0 -5
- mesa/examples/basic/boltzmann_wealth_model/app.py +5 -8
- mesa/examples/basic/boltzmann_wealth_model/st_app.py +1 -1
- mesa/examples/basic/conways_game_of_life/app.py +0 -5
- mesa/examples/basic/conways_game_of_life/st_app.py +2 -2
- mesa/examples/basic/schelling/app.py +0 -5
- mesa/examples/basic/virus_on_network/app.py +0 -5
- mesa/experimental/UserParam.py +67 -0
- mesa/experimental/__init__.py +10 -17
- mesa/experimental/cell_space/__init__.py +7 -19
- mesa/experimental/cell_space/cell.py +37 -22
- mesa/experimental/cell_space/cell_agent.py +1 -12
- mesa/experimental/cell_space/cell_collection.py +3 -18
- mesa/experimental/cell_space/discrete_space.py +64 -15
- mesa/experimental/cell_space/grid.py +4 -74
- mesa/experimental/cell_space/network.py +1 -13
- mesa/experimental/cell_space/voronoi.py +1 -13
- mesa/experimental/components/altair.py +81 -0
- mesa/experimental/components/matplotlib.py +242 -0
- mesa/experimental/devs/__init__.py +2 -20
- mesa/experimental/devs/eventlist.py +1 -19
- mesa/experimental/devs/examples/epstein_civil_violence.py +305 -0
- mesa/experimental/devs/examples/wolf_sheep.py +250 -0
- mesa/experimental/devs/simulator.py +8 -24
- mesa/experimental/solara_viz.py +453 -0
- mesa/model.py +23 -17
- mesa/visualization/__init__.py +2 -2
- mesa/visualization/mpl_space_drawing.py +2 -2
- mesa/visualization/solara_viz.py +5 -23
- {mesa-3.1.0.dist-info → mesa-3.1.0.dev0.dist-info}/METADATA +1 -1
- {mesa-3.1.0.dist-info → mesa-3.1.0.dev0.dist-info}/RECORD +43 -43
- {mesa-3.1.0.dist-info → mesa-3.1.0.dev0.dist-info}/WHEEL +1 -1
- mesa/experimental/cell_space/property_layer.py +0 -444
- mesa/experimental/mesa_signals/__init__.py +0 -23
- mesa/experimental/mesa_signals/mesa_signal.py +0 -485
- mesa/experimental/mesa_signals/observable_collections.py +0 -133
- mesa/experimental/mesa_signals/signals_util.py +0 -52
- mesa/mesa_logging.py +0 -190
- {mesa-3.1.0.dist-info → mesa-3.1.0.dev0.dist-info}/entry_points.txt +0 -0
- {mesa-3.1.0.dist-info → mesa-3.1.0.dev0.dist-info}/licenses/LICENSE +0 -0
- {mesa-3.1.0.dist-info → mesa-3.1.0.dev0.dist-info}/licenses/NOTICE +0 -0
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
"""Mesa visualization module for creating interactive model visualizations.
|
|
2
|
+
|
|
3
|
+
This module provides components to create browser- and Jupyter notebook-based visualizations of
|
|
4
|
+
Mesa models, allowing users to watch models run step-by-step and interact with model parameters.
|
|
5
|
+
|
|
6
|
+
Key features:
|
|
7
|
+
- SolaraViz: Main component for creating visualizations, supporting grid displays and plots
|
|
8
|
+
- ModelController: Handles model execution controls (step, play, pause, reset)
|
|
9
|
+
- UserInputs: Generates UI elements for adjusting model parameters
|
|
10
|
+
- Card: Renders individual visualization elements (space, measures)
|
|
11
|
+
|
|
12
|
+
The module uses Solara for rendering in Jupyter notebooks or as standalone web applications.
|
|
13
|
+
It supports various types of visualizations including matplotlib plots, agent grids, and
|
|
14
|
+
custom visualization components.
|
|
15
|
+
|
|
16
|
+
Usage:
|
|
17
|
+
1. Define an agent_portrayal function to specify how agents should be displayed
|
|
18
|
+
2. Set up model_params to define adjustable parameters
|
|
19
|
+
3. Create a SolaraViz instance with your model, parameters, and desired measures
|
|
20
|
+
4. Display the visualization in a Jupyter notebook or run as a Solara app
|
|
21
|
+
|
|
22
|
+
See the Visualization Tutorial and example models for more details.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
import threading
|
|
26
|
+
|
|
27
|
+
import reacton.ipywidgets as widgets
|
|
28
|
+
import solara
|
|
29
|
+
from solara.alias import rv
|
|
30
|
+
|
|
31
|
+
import mesa.experimental.components.altair as components_altair
|
|
32
|
+
import mesa.experimental.components.matplotlib as components_matplotlib
|
|
33
|
+
from mesa.experimental.UserParam import Slider
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# TODO: Turn this function into a Solara component once the current_step.value
|
|
37
|
+
# dependency is passed to measure()
|
|
38
|
+
def Card(
|
|
39
|
+
model, measures, agent_portrayal, space_drawer, dependencies, color, layout_type
|
|
40
|
+
):
|
|
41
|
+
"""Create a card component for visualizing model space or measures.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
model: The Mesa model instance
|
|
45
|
+
measures: List of measures to be plotted
|
|
46
|
+
agent_portrayal: Function to define agent appearance
|
|
47
|
+
space_drawer: Method to render agent space
|
|
48
|
+
dependencies: List of dependencies for updating the visualization
|
|
49
|
+
color: Background color of the card
|
|
50
|
+
layout_type: Type of layout (Space or Measure)
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
rv.Card: A card component containing the visualization
|
|
54
|
+
"""
|
|
55
|
+
with rv.Card(
|
|
56
|
+
style_=f"background-color: {color}; width: 100%; height: 100%"
|
|
57
|
+
) as main:
|
|
58
|
+
if "Space" in layout_type:
|
|
59
|
+
rv.CardTitle(children=["Space"])
|
|
60
|
+
if space_drawer == "default":
|
|
61
|
+
# draw with the default implementation
|
|
62
|
+
components_matplotlib.SpaceMatplotlib(
|
|
63
|
+
model, agent_portrayal, dependencies=dependencies
|
|
64
|
+
)
|
|
65
|
+
elif space_drawer == "altair":
|
|
66
|
+
components_altair.SpaceAltair(
|
|
67
|
+
model, agent_portrayal, dependencies=dependencies
|
|
68
|
+
)
|
|
69
|
+
elif space_drawer:
|
|
70
|
+
# if specified, draw agent space with an alternate renderer
|
|
71
|
+
space_drawer(model, agent_portrayal, dependencies=dependencies)
|
|
72
|
+
elif "Measure" in layout_type:
|
|
73
|
+
rv.CardTitle(children=["Measure"])
|
|
74
|
+
measure = measures[layout_type["Measure"]]
|
|
75
|
+
if callable(measure):
|
|
76
|
+
# Is a custom object
|
|
77
|
+
measure(model)
|
|
78
|
+
else:
|
|
79
|
+
components_matplotlib.PlotMatplotlib(
|
|
80
|
+
model, measure, dependencies=dependencies
|
|
81
|
+
)
|
|
82
|
+
return main
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@solara.component
|
|
86
|
+
def SolaraViz(
|
|
87
|
+
model_class,
|
|
88
|
+
model_params,
|
|
89
|
+
measures=None,
|
|
90
|
+
name=None,
|
|
91
|
+
agent_portrayal=None,
|
|
92
|
+
space_drawer="default",
|
|
93
|
+
play_interval=150,
|
|
94
|
+
seed=None,
|
|
95
|
+
):
|
|
96
|
+
"""Initialize a component to visualize a model.
|
|
97
|
+
|
|
98
|
+
Args:
|
|
99
|
+
model_class: Class of the model to instantiate
|
|
100
|
+
model_params: Parameters for initializing the model
|
|
101
|
+
measures: List of callables or data attributes to plot
|
|
102
|
+
name: Name for display
|
|
103
|
+
agent_portrayal: Options for rendering agents (dictionary);
|
|
104
|
+
Default drawer supports custom `"size"`, `"color"`, and `"shape"`.
|
|
105
|
+
space_drawer: Method to render the agent space for
|
|
106
|
+
the model; default implementation is the `SpaceMatplotlib` component;
|
|
107
|
+
simulations with no space to visualize should
|
|
108
|
+
specify `space_drawer=False`
|
|
109
|
+
play_interval: Play interval (default: 150)
|
|
110
|
+
seed: The random seed used to initialize the model
|
|
111
|
+
"""
|
|
112
|
+
if name is None:
|
|
113
|
+
name = model_class.__name__
|
|
114
|
+
|
|
115
|
+
current_step = solara.use_reactive(0)
|
|
116
|
+
|
|
117
|
+
# 1. Set up model parameters
|
|
118
|
+
reactive_seed = solara.use_reactive(0)
|
|
119
|
+
user_params, fixed_params = split_model_params(model_params)
|
|
120
|
+
model_parameters, set_model_parameters = solara.use_state(
|
|
121
|
+
{**fixed_params, **{k: v.get("value") for k, v in user_params.items()}}
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
# 2. Set up Model
|
|
125
|
+
def make_model():
|
|
126
|
+
"""Create a new model instance with current parameters and seed."""
|
|
127
|
+
model = model_class.__new__(
|
|
128
|
+
model_class, **model_parameters, seed=reactive_seed.value
|
|
129
|
+
)
|
|
130
|
+
model.__init__(**model_parameters)
|
|
131
|
+
current_step.value = 0
|
|
132
|
+
return model
|
|
133
|
+
|
|
134
|
+
reset_counter = solara.use_reactive(0)
|
|
135
|
+
model = solara.use_memo(
|
|
136
|
+
make_model,
|
|
137
|
+
dependencies=[
|
|
138
|
+
*list(model_parameters.values()),
|
|
139
|
+
reset_counter.value,
|
|
140
|
+
reactive_seed.value,
|
|
141
|
+
],
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
def handle_change_model_params(name: str, value: any):
|
|
145
|
+
"""Update model parameters when user input changes."""
|
|
146
|
+
set_model_parameters({**model_parameters, name: value})
|
|
147
|
+
|
|
148
|
+
# 3. Set up UI
|
|
149
|
+
|
|
150
|
+
with solara.AppBar():
|
|
151
|
+
solara.AppBarTitle(name)
|
|
152
|
+
|
|
153
|
+
# render layout and plot
|
|
154
|
+
def do_reseed():
|
|
155
|
+
"""Update the random seed for the model."""
|
|
156
|
+
reactive_seed.value = model.random.random()
|
|
157
|
+
|
|
158
|
+
dependencies = [
|
|
159
|
+
*list(model_parameters.values()),
|
|
160
|
+
current_step.value,
|
|
161
|
+
reactive_seed.value,
|
|
162
|
+
]
|
|
163
|
+
|
|
164
|
+
# if space drawer is disabled, do not include it
|
|
165
|
+
layout_types = [{"Space": "default"}] if space_drawer else []
|
|
166
|
+
|
|
167
|
+
if measures:
|
|
168
|
+
layout_types += [{"Measure": elem} for elem in range(len(measures))]
|
|
169
|
+
|
|
170
|
+
grid_layout_initial = make_initial_grid_layout(layout_types=layout_types)
|
|
171
|
+
grid_layout, set_grid_layout = solara.use_state(grid_layout_initial)
|
|
172
|
+
|
|
173
|
+
with solara.Sidebar():
|
|
174
|
+
with solara.Card("Controls", margin=1, elevation=2):
|
|
175
|
+
solara.InputText(
|
|
176
|
+
label="Seed",
|
|
177
|
+
value=reactive_seed,
|
|
178
|
+
continuous_update=True,
|
|
179
|
+
)
|
|
180
|
+
UserInputs(user_params, on_change=handle_change_model_params)
|
|
181
|
+
ModelController(model, play_interval, current_step, reset_counter)
|
|
182
|
+
solara.Button(label="Reseed", color="primary", on_click=do_reseed)
|
|
183
|
+
with solara.Card("Information", margin=1, elevation=2):
|
|
184
|
+
solara.Markdown(md_text=f"Step - {current_step}")
|
|
185
|
+
|
|
186
|
+
items = [
|
|
187
|
+
Card(
|
|
188
|
+
model,
|
|
189
|
+
measures,
|
|
190
|
+
agent_portrayal,
|
|
191
|
+
space_drawer,
|
|
192
|
+
dependencies,
|
|
193
|
+
color="white",
|
|
194
|
+
layout_type=layout_types[i],
|
|
195
|
+
)
|
|
196
|
+
for i in range(len(layout_types))
|
|
197
|
+
]
|
|
198
|
+
solara.GridDraggable(
|
|
199
|
+
items=items,
|
|
200
|
+
grid_layout=grid_layout,
|
|
201
|
+
resizable=True,
|
|
202
|
+
draggable=True,
|
|
203
|
+
on_grid_layout=set_grid_layout,
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
JupyterViz = SolaraViz
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
@solara.component
|
|
211
|
+
def ModelController(model, play_interval, current_step, reset_counter):
|
|
212
|
+
"""Create controls for model execution (step, play, pause, reset).
|
|
213
|
+
|
|
214
|
+
Args:
|
|
215
|
+
model: The model being visualized
|
|
216
|
+
play_interval: Interval between steps during play
|
|
217
|
+
current_step: Reactive value for the current step
|
|
218
|
+
reset_counter: Counter to trigger model reset
|
|
219
|
+
"""
|
|
220
|
+
playing = solara.use_reactive(False)
|
|
221
|
+
thread = solara.use_reactive(None)
|
|
222
|
+
# We track the previous step to detect if user resets the model via
|
|
223
|
+
# clicking the reset button or changing the parameters. If previous_step >
|
|
224
|
+
# current_step, it means a model reset happens while the simulation is
|
|
225
|
+
# still playing.
|
|
226
|
+
previous_step = solara.use_reactive(0)
|
|
227
|
+
|
|
228
|
+
def on_value_play(change):
|
|
229
|
+
"""Handle play/pause state changes."""
|
|
230
|
+
if previous_step.value > current_step.value and current_step.value == 0:
|
|
231
|
+
# We add extra checks for current_step.value == 0, just to be sure.
|
|
232
|
+
# We automatically stop the playing if a model is reset.
|
|
233
|
+
playing.value = False
|
|
234
|
+
elif model.running:
|
|
235
|
+
do_step()
|
|
236
|
+
else:
|
|
237
|
+
playing.value = False
|
|
238
|
+
|
|
239
|
+
def do_step():
|
|
240
|
+
"""Advance the model by one step."""
|
|
241
|
+
model.step()
|
|
242
|
+
previous_step.value = current_step.value
|
|
243
|
+
current_step.value = model.steps
|
|
244
|
+
|
|
245
|
+
def do_play():
|
|
246
|
+
"""Run the model continuously."""
|
|
247
|
+
model.running = True
|
|
248
|
+
while model.running:
|
|
249
|
+
do_step()
|
|
250
|
+
|
|
251
|
+
def threaded_do_play():
|
|
252
|
+
"""Start a new thread for continuous model execution."""
|
|
253
|
+
if thread is not None and thread.is_alive():
|
|
254
|
+
return
|
|
255
|
+
thread.value = threading.Thread(target=do_play)
|
|
256
|
+
thread.start()
|
|
257
|
+
|
|
258
|
+
def do_pause():
|
|
259
|
+
"""Pause the model execution."""
|
|
260
|
+
if (thread is None) or (not thread.is_alive()):
|
|
261
|
+
return
|
|
262
|
+
model.running = False
|
|
263
|
+
thread.join()
|
|
264
|
+
|
|
265
|
+
def do_reset():
|
|
266
|
+
"""Reset the model."""
|
|
267
|
+
reset_counter.value += 1
|
|
268
|
+
|
|
269
|
+
def do_set_playing(value):
|
|
270
|
+
"""Set the playing state."""
|
|
271
|
+
if current_step.value == 0:
|
|
272
|
+
# This means the model has been recreated, and the step resets to
|
|
273
|
+
# 0. We want to avoid triggering the playing.value = False in the
|
|
274
|
+
# on_value_play function.
|
|
275
|
+
previous_step.value = current_step.value
|
|
276
|
+
playing.set(value)
|
|
277
|
+
|
|
278
|
+
with solara.Row():
|
|
279
|
+
solara.Button(label="Step", color="primary", on_click=do_step)
|
|
280
|
+
# This style is necessary so that the play widget has almost the same
|
|
281
|
+
# height as typical Solara buttons.
|
|
282
|
+
solara.Style(
|
|
283
|
+
"""
|
|
284
|
+
.widget-play {
|
|
285
|
+
height: 35px;
|
|
286
|
+
}
|
|
287
|
+
.widget-play button {
|
|
288
|
+
color: white;
|
|
289
|
+
background-color: #1976D2; // Solara blue color
|
|
290
|
+
}
|
|
291
|
+
"""
|
|
292
|
+
)
|
|
293
|
+
widgets.Play(
|
|
294
|
+
value=0,
|
|
295
|
+
interval=play_interval,
|
|
296
|
+
repeat=True,
|
|
297
|
+
show_repeat=False,
|
|
298
|
+
on_value=on_value_play,
|
|
299
|
+
playing=playing.value,
|
|
300
|
+
on_playing=do_set_playing,
|
|
301
|
+
)
|
|
302
|
+
solara.Button(label="Reset", color="primary", on_click=do_reset)
|
|
303
|
+
# threaded_do_play is not used for now because it
|
|
304
|
+
# doesn't work in Google colab. We use
|
|
305
|
+
# ipywidgets.Play until it is fixed. The threading
|
|
306
|
+
# version is definite a much better implementation,
|
|
307
|
+
# if it works.
|
|
308
|
+
# solara.Button(label="▶", color="primary", on_click=viz.threaded_do_play)
|
|
309
|
+
# solara.Button(label="⏸︎", color="primary", on_click=viz.do_pause)
|
|
310
|
+
# solara.Button(label="Reset", color="primary", on_click=do_reset)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def split_model_params(model_params):
|
|
314
|
+
"""Split model parameters into user-adjustable and fixed parameters.
|
|
315
|
+
|
|
316
|
+
Args:
|
|
317
|
+
model_params: Dictionary of all model parameters
|
|
318
|
+
|
|
319
|
+
Returns:
|
|
320
|
+
tuple: (user_adjustable_params, fixed_params)
|
|
321
|
+
"""
|
|
322
|
+
model_params_input = {}
|
|
323
|
+
model_params_fixed = {}
|
|
324
|
+
for k, v in model_params.items():
|
|
325
|
+
if check_param_is_fixed(v):
|
|
326
|
+
model_params_fixed[k] = v
|
|
327
|
+
else:
|
|
328
|
+
model_params_input[k] = v
|
|
329
|
+
return model_params_input, model_params_fixed
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def check_param_is_fixed(param):
|
|
333
|
+
"""Check if a parameter is fixed (not user-adjustable).
|
|
334
|
+
|
|
335
|
+
Args:
|
|
336
|
+
param: Parameter to check
|
|
337
|
+
|
|
338
|
+
Returns:
|
|
339
|
+
bool: True if parameter is fixed, False otherwise
|
|
340
|
+
"""
|
|
341
|
+
if isinstance(param, Slider):
|
|
342
|
+
return False
|
|
343
|
+
if not isinstance(param, dict):
|
|
344
|
+
return True
|
|
345
|
+
if "type" not in param:
|
|
346
|
+
return True
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
@solara.component
|
|
350
|
+
def UserInputs(user_params, on_change=None):
|
|
351
|
+
"""Initialize user inputs for configurable model parameters.
|
|
352
|
+
|
|
353
|
+
Currently supports :class:`solara.SliderInt`, :class:`solara.SliderFloat`,
|
|
354
|
+
:class:`solara.Select`, and :class:`solara.Checkbox`.
|
|
355
|
+
|
|
356
|
+
Args:
|
|
357
|
+
user_params: Dictionary with options for the input, including label,
|
|
358
|
+
min and max values, and other fields specific to the input type.
|
|
359
|
+
on_change: Function to be called with (name, value) when the value of an input changes.
|
|
360
|
+
"""
|
|
361
|
+
for name, options in user_params.items():
|
|
362
|
+
|
|
363
|
+
def change_handler(value, name=name):
|
|
364
|
+
on_change(name, value)
|
|
365
|
+
|
|
366
|
+
if isinstance(options, Slider):
|
|
367
|
+
slider_class = (
|
|
368
|
+
solara.SliderFloat if options.is_float_slider else solara.SliderInt
|
|
369
|
+
)
|
|
370
|
+
slider_class(
|
|
371
|
+
options.label,
|
|
372
|
+
value=options.value,
|
|
373
|
+
on_value=change_handler,
|
|
374
|
+
min=options.min,
|
|
375
|
+
max=options.max,
|
|
376
|
+
step=options.step,
|
|
377
|
+
)
|
|
378
|
+
continue
|
|
379
|
+
|
|
380
|
+
# label for the input is "label" from options or name
|
|
381
|
+
label = options.get("label", name)
|
|
382
|
+
input_type = options.get("type")
|
|
383
|
+
if input_type == "SliderInt":
|
|
384
|
+
solara.SliderInt(
|
|
385
|
+
label,
|
|
386
|
+
value=options.get("value"),
|
|
387
|
+
on_value=change_handler,
|
|
388
|
+
min=options.get("min"),
|
|
389
|
+
max=options.get("max"),
|
|
390
|
+
step=options.get("step"),
|
|
391
|
+
)
|
|
392
|
+
elif input_type == "SliderFloat":
|
|
393
|
+
solara.SliderFloat(
|
|
394
|
+
label,
|
|
395
|
+
value=options.get("value"),
|
|
396
|
+
on_value=change_handler,
|
|
397
|
+
min=options.get("min"),
|
|
398
|
+
max=options.get("max"),
|
|
399
|
+
step=options.get("step"),
|
|
400
|
+
)
|
|
401
|
+
elif input_type == "Select":
|
|
402
|
+
solara.Select(
|
|
403
|
+
label,
|
|
404
|
+
value=options.get("value"),
|
|
405
|
+
on_value=change_handler,
|
|
406
|
+
values=options.get("values"),
|
|
407
|
+
)
|
|
408
|
+
elif input_type == "Checkbox":
|
|
409
|
+
solara.Checkbox(
|
|
410
|
+
label=label,
|
|
411
|
+
on_value=change_handler,
|
|
412
|
+
value=options.get("value"),
|
|
413
|
+
)
|
|
414
|
+
else:
|
|
415
|
+
raise ValueError(f"{input_type} is not a supported input type")
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def make_text(renderer):
|
|
419
|
+
"""Create a function that renders text using Markdown.
|
|
420
|
+
|
|
421
|
+
Args:
|
|
422
|
+
renderer: Function that takes a model and returns a string
|
|
423
|
+
|
|
424
|
+
Returns:
|
|
425
|
+
function: A function that renders the text as Markdown
|
|
426
|
+
"""
|
|
427
|
+
|
|
428
|
+
def function(model):
|
|
429
|
+
solara.Markdown(renderer(model))
|
|
430
|
+
|
|
431
|
+
return function
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def make_initial_grid_layout(layout_types):
|
|
435
|
+
"""Create an initial grid layout for visualization components.
|
|
436
|
+
|
|
437
|
+
Args:
|
|
438
|
+
layout_types: List of layout types (Space or Measure)
|
|
439
|
+
|
|
440
|
+
Returns:
|
|
441
|
+
list: Initial grid layout configuration
|
|
442
|
+
"""
|
|
443
|
+
return [
|
|
444
|
+
{
|
|
445
|
+
"i": i,
|
|
446
|
+
"w": 6,
|
|
447
|
+
"h": 10,
|
|
448
|
+
"moved": False,
|
|
449
|
+
"x": 6 * (i % 2),
|
|
450
|
+
"y": 16 * (i - i % 2),
|
|
451
|
+
}
|
|
452
|
+
for i in range(len(layout_types))
|
|
453
|
+
]
|
mesa/model.py
CHANGED
|
@@ -9,6 +9,7 @@ from __future__ import annotations
|
|
|
9
9
|
|
|
10
10
|
import random
|
|
11
11
|
import sys
|
|
12
|
+
import warnings
|
|
12
13
|
from collections.abc import Sequence
|
|
13
14
|
|
|
14
15
|
# mypy
|
|
@@ -17,15 +18,11 @@ from typing import Any
|
|
|
17
18
|
import numpy as np
|
|
18
19
|
|
|
19
20
|
from mesa.agent import Agent, AgentSet
|
|
20
|
-
from mesa.mesa_logging import create_module_logger, method_logger
|
|
21
21
|
|
|
22
22
|
SeedLike = int | np.integer | Sequence[int] | np.random.SeedSequence
|
|
23
23
|
RNGLike = np.random.Generator | np.random.BitGenerator
|
|
24
24
|
|
|
25
25
|
|
|
26
|
-
_mesa_logger = create_module_logger()
|
|
27
|
-
|
|
28
|
-
|
|
29
26
|
class Model:
|
|
30
27
|
"""Base class for models in the Mesa ABM library.
|
|
31
28
|
|
|
@@ -35,6 +32,7 @@ class Model:
|
|
|
35
32
|
|
|
36
33
|
Attributes:
|
|
37
34
|
running: A boolean indicating if the model should continue running.
|
|
35
|
+
schedule: An object to manage the order and execution of agent steps.
|
|
38
36
|
steps: the number of times `model.step()` has been called.
|
|
39
37
|
random: a seeded python.random number generator.
|
|
40
38
|
rng : a seeded numpy.random.Generator
|
|
@@ -46,7 +44,6 @@ class Model:
|
|
|
46
44
|
|
|
47
45
|
"""
|
|
48
46
|
|
|
49
|
-
@method_logger(__name__)
|
|
50
47
|
def __init__(
|
|
51
48
|
self,
|
|
52
49
|
*args: Any,
|
|
@@ -105,19 +102,12 @@ class Model:
|
|
|
105
102
|
self.step = self._wrapped_step
|
|
106
103
|
|
|
107
104
|
# setup agent registration data structures
|
|
108
|
-
self.
|
|
109
|
-
self._agents_by_type: dict[
|
|
110
|
-
type[Agent], AgentSet
|
|
111
|
-
] = {} # a dict with an agentset for each class of agents
|
|
112
|
-
self._all_agents = AgentSet(
|
|
113
|
-
[], random=self.random
|
|
114
|
-
) # an agenset with all agents
|
|
105
|
+
self._setup_agent_registration()
|
|
115
106
|
|
|
116
107
|
def _wrapped_step(self, *args: Any, **kwargs: Any) -> None:
|
|
117
108
|
"""Automatically increments time and steps after calling the user's step method."""
|
|
118
109
|
# Automatically increment time and step counters
|
|
119
110
|
self.steps += 1
|
|
120
|
-
_mesa_logger.info(f"calling model.step for timestep {self.steps} ")
|
|
121
111
|
# Call the original user-defined step method
|
|
122
112
|
self._user_step(*args, **kwargs)
|
|
123
113
|
|
|
@@ -144,6 +134,16 @@ class Model:
|
|
|
144
134
|
"""A dictionary where the keys are agent types and the values are the corresponding AgentSets."""
|
|
145
135
|
return self._agents_by_type
|
|
146
136
|
|
|
137
|
+
def _setup_agent_registration(self):
|
|
138
|
+
"""Helper method to initialize the agent registration datastructures."""
|
|
139
|
+
self._agents = {} # the hard references to all agents in the model
|
|
140
|
+
self._agents_by_type: dict[
|
|
141
|
+
type[Agent], AgentSet
|
|
142
|
+
] = {} # a dict with an agentset for each class of agents
|
|
143
|
+
self._all_agents = AgentSet(
|
|
144
|
+
[], random=self.random
|
|
145
|
+
) # an agenset with all agents
|
|
146
|
+
|
|
147
147
|
def register_agent(self, agent):
|
|
148
148
|
"""Register the agent with the model.
|
|
149
149
|
|
|
@@ -155,6 +155,16 @@ class Model:
|
|
|
155
155
|
if you are subclassing Agent and calling its super in the ``__init__`` method.
|
|
156
156
|
|
|
157
157
|
"""
|
|
158
|
+
if not hasattr(self, "_agents"):
|
|
159
|
+
self._setup_agent_registration()
|
|
160
|
+
|
|
161
|
+
warnings.warn(
|
|
162
|
+
"The Mesa Model class was not initialized. In the future, you need to explicitly initialize "
|
|
163
|
+
"the Model by calling super().__init__() on initialization.",
|
|
164
|
+
FutureWarning,
|
|
165
|
+
stacklevel=2,
|
|
166
|
+
)
|
|
167
|
+
|
|
158
168
|
self._agents[agent] = None
|
|
159
169
|
|
|
160
170
|
# because AgentSet requires model, we cannot use defaultdict
|
|
@@ -170,9 +180,6 @@ class Model:
|
|
|
170
180
|
)
|
|
171
181
|
|
|
172
182
|
self._all_agents.add(agent)
|
|
173
|
-
_mesa_logger.debug(
|
|
174
|
-
f"registered {agent.__class__.__name__} with agent_id {agent.unique_id}"
|
|
175
|
-
)
|
|
176
183
|
|
|
177
184
|
def deregister_agent(self, agent):
|
|
178
185
|
"""Deregister the agent with the model.
|
|
@@ -187,7 +194,6 @@ class Model:
|
|
|
187
194
|
del self._agents[agent]
|
|
188
195
|
self._agents_by_type[type(agent)].remove(agent)
|
|
189
196
|
self._all_agents.remove(agent)
|
|
190
|
-
_mesa_logger.debug(f"deregistered agent with agent_id {agent.unique_id}")
|
|
191
197
|
|
|
192
198
|
def run_model(self) -> None:
|
|
193
199
|
"""Run the model until the end condition is reached.
|
mesa/visualization/__init__.py
CHANGED
|
@@ -178,7 +178,7 @@ def draw_property_layers(
|
|
|
178
178
|
property_layers = space.properties
|
|
179
179
|
except AttributeError:
|
|
180
180
|
# new style spaces
|
|
181
|
-
property_layers = space.
|
|
181
|
+
property_layers = space.property_layers
|
|
182
182
|
|
|
183
183
|
for layer_name, portrayal in propertylayer_portrayal.items():
|
|
184
184
|
layer = property_layers.get(layer_name, None)
|
|
@@ -186,7 +186,7 @@ def draw_property_layers(
|
|
|
186
186
|
continue
|
|
187
187
|
|
|
188
188
|
data = layer.data.astype(float) if layer.data.dtype == bool else layer.data
|
|
189
|
-
width, height = data.shape
|
|
189
|
+
width, height = data.shape if space is None else (space.width, space.height)
|
|
190
190
|
|
|
191
191
|
if space and data.shape != (width, height):
|
|
192
192
|
warnings.warn(
|
mesa/visualization/solara_viz.py
CHANGED
|
@@ -33,18 +33,14 @@ import solara
|
|
|
33
33
|
|
|
34
34
|
import mesa.visualization.components.altair_components as components_altair
|
|
35
35
|
from mesa.experimental.devs.simulator import Simulator
|
|
36
|
-
from mesa.mesa_logging import create_module_logger, function_logger
|
|
37
36
|
from mesa.visualization.user_param import Slider
|
|
38
37
|
from mesa.visualization.utils import force_update, update_counter
|
|
39
38
|
|
|
40
39
|
if TYPE_CHECKING:
|
|
41
40
|
from mesa.model import Model
|
|
42
41
|
|
|
43
|
-
_mesa_logger = create_module_logger()
|
|
44
|
-
|
|
45
42
|
|
|
46
43
|
@solara.component
|
|
47
|
-
@function_logger(__name__)
|
|
48
44
|
def SolaraViz(
|
|
49
45
|
model: Model | solara.Reactive[Model],
|
|
50
46
|
components: list[reacton.core.Component]
|
|
@@ -204,25 +200,18 @@ def ModelController(
|
|
|
204
200
|
step, dependencies=[playing.value, running.value], prefer_threaded=False
|
|
205
201
|
)
|
|
206
202
|
|
|
207
|
-
@function_logger(__name__)
|
|
208
203
|
def do_step():
|
|
209
204
|
"""Advance the model by one step."""
|
|
210
205
|
model.value.step()
|
|
211
206
|
running.value = model.value.running
|
|
212
207
|
force_update()
|
|
213
208
|
|
|
214
|
-
@function_logger(__name__)
|
|
215
209
|
def do_reset():
|
|
216
210
|
"""Reset the model to its initial state."""
|
|
217
211
|
playing.value = False
|
|
218
212
|
running.value = True
|
|
219
|
-
_mesa_logger.log(
|
|
220
|
-
10,
|
|
221
|
-
f"creating new {model.value.__class__} instance with {model_parameters.value}",
|
|
222
|
-
)
|
|
223
213
|
model.value = model.value = model.value.__class__(**model_parameters.value)
|
|
224
214
|
|
|
225
|
-
@function_logger(__name__)
|
|
226
215
|
def do_play_pause():
|
|
227
216
|
"""Toggle play/pause."""
|
|
228
217
|
playing.value = not playing.value
|
|
@@ -393,19 +382,12 @@ def ModelCreator(
|
|
|
393
382
|
)
|
|
394
383
|
user_params, fixed_params = split_model_params(user_params)
|
|
395
384
|
|
|
396
|
-
#
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
**fixed_params,
|
|
402
|
-
**{k: v.get("value") for k, v in user_params.items()},
|
|
403
|
-
}
|
|
404
|
-
),
|
|
405
|
-
[],
|
|
406
|
-
)
|
|
385
|
+
# set model_parameters to the default values for all parameters
|
|
386
|
+
model_parameters.value = {
|
|
387
|
+
**fixed_params,
|
|
388
|
+
**{k: v.get("value") for k, v in user_params.items()},
|
|
389
|
+
}
|
|
407
390
|
|
|
408
|
-
@function_logger(__name__)
|
|
409
391
|
def on_change(name, value):
|
|
410
392
|
model_parameters.value = {**model_parameters.value, name: value}
|
|
411
393
|
|