Repository navigation
Backport fixes for Mesa 3.5.3 - #4129
Merged
Merged
Conversation
Co-authored-by: Jan Kwakkel <[email protected]> (cherry picked from commit f3ec718)
When no agent data has been recorded (e.g. before collect() is called or when collect() runs on a model with zero agents), all_records is an empty generator. Passing an empty generator to pd.DataFrame.from_records with an index parameter causes pandas to misparse the index labels as row entries, producing a non-empty DataFrame of length 2 containing spurious all-NaN rows instead of an empty DataFrame of length 0. Materialize all_records to a list before constructing the DataFrame, matching the behavior and fix established in get_agenttype_vars_dataframe (mesa#3797). Co-authored-by: Gracy769 <[email protected]> (cherry picked from commit c45fbb7)
) Adapted for 3.5.x: uses the HasPropertyLayers API (_mesa_properties, _mesa_property_layers) instead of 4.0's property_layers and read-only layers; tests adapted the same way. (cherry picked from commit b3bedf7) Assisted-by: Claude Opus 5.5
(cherry picked from commit b0c4ffd)
Co-authored-by: Jan Kwakkel <[email protected]> (cherry picked from commit e49bedc)
clear() with no arguments removed the per-dataset storage instead of emptying it, so the next model step raised KeyError. Empty each dataset's list instead, and raise KeyError for an unknown dataset name, which is what DataRecorder, ParquetDataRecorder and SQLDataRecorder already do. The existing test asserted the KeyError after clear(), so it now checks for an empty dataset instead. Fixes mesa#4014 (cherry picked from commit d420962)
* fix: wrap torus query points before distance calculations ContinuousSpace.calculate_distances and calculate_difference_vector applied the minimum-image convention without first wrapping the query point into the space bounds. That convention only holds when the per-axis separation is at most the space size, so an out-of-bounds query point produced a negative intermediate which then surfaced as an incorrect positive distance once squared. On a unit torus with an agent at [0.1, 0.1], a query at [2.9, 0.1] returned 1.8 and [1.9, 0.1] returned 0.8, although both are congruent to [0.9, 0.1] modulo the space size and should return 0.2. Agent positions are already wrapped on assignment, so only the query side could violate the invariant. Both methods now apply the existing torus_correct before computing deltas. This also fixes get_agents_in_radius and get_k_nearest_agents, which delegate to calculate_distances. * Correct the torus separation lazily to avoid a hot-path cost The benchmark bot reported BoidFlockers run time up 11.8% (small) and 9.4% (large). BoidFlockers is the only continuous-space model in the suite and the only one flagged, so the cost came from calling torus_correct on the query point in every calculate_distances call. Agents query with their own position, which the position setter has already wrapped, so for that case the wrap was pure overhead. The separation is now computed first and only folded when some axis actually exceeds the space size, which is the only situation where the minimum image convention breaks. The check is per axis rather than against the largest axis. A global maximum is wrong for a space such as [[0, 0.5], [0, 50]], where a separation of 1.0 on the first axis exceeds that axis but not the global maximum of 50. * Use a Python-level bounds check to cut the hot-path cost Replaces the numpy per-axis guard from the previous commit, which was slower than the wrap it was meant to avoid because it scanned the whole separation array. Agents query with their own position, which the setter has already wrapped, so the correction is almost never needed. The bounds are cached as plain Python floats in __init__ and compared without touching numpy, which is what makes the check cheaper than the work it skips. Measured on BoidFlockers small, 20 steps, minimum of 15 replications: main 290.7 ms, torus_correct on every call 329.4 ms, numpy per-axis guard 333.6 ms, this version 324.9 ms. So this is the cheapest correct option I found, but it does not remove the cost: roughly 12% remains, since any per-query check costs microseconds and the benchmark makes about 8000 queries. * Skip the bounds check on the agent query paths ContinuousSpaceAgent.get_neighbors_in_radius and get_nearest_neighbors query with the agent's own position, which the position setter keeps inside the bounds. Those calls can therefore skip the bounds check in calculate_distances, which is what the benchmark regression was paying for. calculate_distances, get_agents_in_radius and get_k_nearest_agents take a private keyword-only _in_bounds flag, and only the two agent methods set it. Model code calling any of these directly is unaffected and still gets the check, so an out-of-bounds query point is handled exactly as before. BoidFlockers small, 20 steps, minimum of 15 replications: main 290.7 ms, this branch 287.0 ms. The earlier commits measured 329.4 ms with the wrap on every call and 324.9 ms with the Python bounds check. * Only wrap the query point in calculate_difference_vector when needed The benchmark re-run on the previous commit still showed BoidFlockers run time up 6.1% (small) and 5.4% (large). calculate_distances had been optimised, but calculate_difference_vector still called torus_correct unconditionally, and the boids example calls it once per agent per step with the agent's own position, which is already inside the bounds. It now uses the same plain Python bounds check as calculate_distances and only wraps when some coordinate is outside, so an out-of-bounds query point behaves exactly as before. BoidFlockers small, 20 steps, minimum of 15 replications, three interleaved rounds on one machine: main 289.9 ms on average, previous commit 308.7 ms (+6.5%, in line with the bot's +6.1%), this commit 295.9 ms (+2.1%). * Simplify torus query-point wrapping Call torus_correct(point) unconditionally on a torus instead of checking the bounds first. This removes the per-axis bounds tuples and the private _in_bounds flag, and restores continuous_space_agents.py to its original form. * Wrap torus query points only when they are outside the bounds Benchmarks showed that calling torus_correct on every query adds about 1.5 us per call, which is 20 to 40 percent of a query in small spaces. A small helper that wraps only out-of-bounds points keeps the overhead near 0.5 us, without the _in_bounds flag or changes to continuous_space_agents.py. * Skip the torus bounds check for agent queries Agents query with their own position, which the setter keeps inside the space, so they pass a private flag to skip the check. Other queries are still checked and wrapped. --------- Co-authored-by: AryamannSrivastava <[email protected]> Co-authored-by: Jan Kwakkel <[email protected]> (cherry picked from commit 9251a9f)
(cherry picked from commit fe24c24)
_scatter popped s and alpha out of the arguments, which the image marker branch needs, but ordinary markers then never got them, so every agent was drawn at the default size and fully opaque. Read them without popping, as MatplotlibBackend already does. (cherry picked from commit 7728f16)
copy_renderer still copied space_kwargs and agent_kwargs, but SpaceRenderer stores them as draw_space_kwargs and draw_agent_kwargs. The old names don't exist anymore, so pressing Reset silently dropped everything passed to setup_structure() and setup_agents(). Copy the right attributes, and copy the dicts so the old and new renderer don't share them. Add a regression test. Fixes mesa#3948 (cherry picked from commit b687223)
* Remove the dead inner cache on Cell._neighborhood
Cell.get_neighborhood() and Cell._neighborhood() are both decorated with
functools.cache and take the same arguments, and _neighborhood() is only
ever called from get_neighborhood(). That means the inner cache can never
serve a hit: on an outer hit _neighborhood() is not called at all, and on
an outer miss it is called exactly once for that key. Its cache only ever
accumulates entries.
Measured on a 100x100 Moore grid warmed at radius 1 and 2, the inner cache
reports hits=0, misses=20000, currsize=20000, and dropping it gives:
retained memory 32.420 MiB -> 30.026 MiB (-7.4%)
cold first pass 76.7 ms -> 68.3 ms (-11%, median of 5 runs)
warm 20x pass 48.5 ms -> 47.4 ms (unchanged, as expected)
Both arms ran against the same source, interleaved, with the decorator
stripped at runtime in the second arm.
Because functools.cache keys on self, the removed cache also held a second
strong reference to every Cell on top of the one the get_neighborhood cache
already holds, so it doubled the number of cells pinned alive by the
class-level caches.
Adds two tests covering what the deleted cache_clear() call could otherwise
have been protecting: that connect() and disconnect() invalidate the cached
neighborhood, at radius 1 and at radius 2.
* Assert radius-2 invalidation instead of clearing the cache by hand
The second test called cells[0]._clear_cache() by hand after connecting
cells[1] to cells[2], and my review note claimed the assertion failed
without it. That was wrong, and I had not actually tried removing it.
functools.cache on a method is one cache shared by the whole class, so the
cache_clear() that cells[1].connect() triggers already drops cells[0]'s
cached radius-2 entry. Verified on this branch:
cells[0].connect(cells[1], key=(1,))
cells[0].get_neighborhood(radius=2) # {cells[1]}
cells[1].connect(cells[2], key=(1,)) # no manual clear
cells[0].get_neighborhood(radius=2) # {cells[1], cells[2]}
Dropping the manual clear makes the test assert the case worth asserting:
that a connect() one hop away invalidates a radius-2 neighborhood that spans
it. That is also the case that would regress if invalidation is later scoped
per cell for mesa#3445.
Thanks to @AshNicolus for catching this in review.
---------
Co-authored-by: Jan Kwakkel <[email protected]>
(cherry picked from commit 6cfb252)
Co-authored-by: Jan Kwakkel <[email protected]> (cherry picked from commit f3dc333)
* fix: process events due at the current time in run_until * fix: align time advancement warnings with the guards --------- Co-authored-by: Jan Kwakkel <[email protected]> (cherry picked from commit c9600b8)
_advance_time assigned the end time and each event's time as given, so run_until(5) or schedule_event(at=2) left model.time as an int, while run_for always gave a float. That showed up as mixed 3.0 / 3 times in JSONDataRecorder output and t=5 vs t=5.0 in labels. Convert both assignments to float. (cherry picked from commit 1d3b61e)
Adapted for 3.5.x: tests use 3.5's setup_propertylayer/draw_propertylayer names and the _mesa_property_layers API; the fix itself applied unchanged. (cherry picked from commit aa4ca48) Assisted-by: Claude Opus 5.5
…ger (mesa#4082) * fix(logging): resolve qualified method name dynamically in method_logger - Replace static inspect.getouterframes() lookup at decorator definition time with dynamic func.__qualname__ evaluation inside the wrapper. - Prevent '<module>' or outer frame names from being logged when decorating class methods. - Add unit test in tests/test_mesa_logging.py verifying qualified class and method name logging. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * style(tests) : move method_logger import to top of file. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> (cherry picked from commit 86a34d8)
mesa#3995) * fix(continuous_space): return at most k agents from get_nearest_neighbors get_nearest_neighbors requests the k + 1 nearest agents and filters out self. When more than k other agents share the querying agent's position, self may not be among the k + 1, so k + 1 agents were returned. Keep at most k. Also correct the get_k_nearest_agents docstring: ties at the k-th distance are resolved deterministically by np.argpartition, which is not stable, so they do not follow insertion order. Fixes mesa#3898 * fix(continuous_space): collect nearest neighbors in a single loop Stop at k neighbors in one pass instead of filtering and slicing three times, and drop the docstring change since argpartition is no longer used. --------- Co-authored-by: Jan Kwakkel <[email protected]> (cherry picked from commit 89dd9ca)
) Adapted for 3.5.x: 3.5 has no mesa.exceptions, so removing a missing cell from a directed Network raises KeyError, like DiscreteSpace.remove_cell on 3.5. (cherry picked from commit f36fcfd) Assisted-by: Claude Opus 5.5
mesa#4086) PlotMatplotlib called post_process(ax) before it set the x label to "Step" and the x tick locator to MaxNLocator(integer=True). Any x label or x tick change made in post_process was therefore overwritten, for example ax.set_xlabel("Time Step") in tutorials 8 and 9. Call post_process last, after the defaults, as SpaceMatplotlib and PlotAltair already do. Plots without post_process look the same. (cherry picked from commit 257aebf)
(cherry picked from commit fb15030)
HexGrid connects cells using even-r offsets (even rows shifted right), as its docstring says, and the hex mesh in mpl_space_drawing uses the same layout. cell.position was computed with odd rows shifted instead, so on every cell some connected neighbours were not touching hexagons when drawn at cell.position. Shift even rows in _init_hex_geometry so positions agree with the connections. Connectivity itself is unchanged. Co-authored-by: Jan Kwakkel <[email protected]> (cherry picked from commit e1ca9ea)
…a#4084) When schedule.start is None, EventGenerator.start() schedules the first event at model.time + interval without checking it against schedule.end. If that time is already past end, the generator fires once outside its window. Check _should_stop() before scheduling the first event, matching what resume() already does. (cherry picked from commit 6319f9b)
Unpickling a ContinuousSpace turned agent_positions into an independent array instead of a view on the backing array. Positions written through agents then went only to the copy, and were lost as soon as an agent was added or removed and the view was taken again. Take the view again in __setstate__. (cherry picked from commit 28e4136)
Fixes the flaky Playwright viz tests by taking the two initial screenshots from the newest image, like the later screenshots already do. (cherry picked from commit 667c62b)
…#4046) Fixes property layer visualization on HexGrid where colors are drawn on the wrong hexagons due to mismatched array ordering. Partly backported for 3.5.x: only the legacy draw_property_layers fix. On 3.5 the SpaceRenderer hexagon mesh is still row-major, so the matplotlib backend already uses data.T.ravel() correctly and is left unchanged. The SpaceRenderer test checks the row-major order instead. (cherry picked from commit ac849e1) Assisted-by: Claude Opus 5.5
Adapted for 3.5.x: the Agent.remove() and Event/EventGenerator parts only. 3.5 has no experimental states (Threshold) or locations, so those hunks and their tests are dropped. (cherry picked from commit eac7447) Assisted-by: Claude Opus 5.5
… agent (mesa#3970) Adapted for 3.5.x: 3.5 has the pre-rewrite meta-agents API, so the same one-line fix is applied to its extract_class and a regression test is written for create_meta_agent (remove the last instance, then create the class again by name), which raised StopIteration before. (cherry picked from commit f6f7e53) Assisted-by: Claude Opus 5.5
(cherry picked from commit 53a7766)
Python has released it final 3.15 release candidate, 3.15.0rc2. This seems to be a good moment to see what breaks and what not. Most likely we will have some upstream dependencies who are not ready yet. https://www.python.org/downloads/release/python-3150rc2/ (cherry picked from commit b5c3b20)
Assisted-by: Claude Opus 5.5
|
Thanks @EwoutH for documenting the adapted backports and changes that can affect results. The diff also reformats existing examples throughout Please drop those formatting-only hunks so reviewers can focus on the backports and release notes. Automated note by an AI model; it can be wrong, and maintainers make the decisions. About this bot. |
1 task done
Backport the Starlette cap removal from cbba490 (mesa#4007). Require Solara 1.57.4 or newer for its Starlette lifespan fix (widgetti/solara#1151). Assisted-by: GPT-6
DatasetConfig.window_size is documented as the maximum number of snapshots to keep. DataRecorder applies it, but JSONDataRecorder kept every snapshot, so memory grew without bound and save_to_json wrote the full history. Adapted for 3.5.x: 3.5 recorders do not record when a run ends (mesa#4041 is 4.0-only), so after run_for(4) the window holds times 2.0 and 3.0; DataRecorder gives the same. The test's expected values are changed accordingly. (cherry picked from commit 668c892) Assisted-by: Claude Opus 5.5
…strong ref leaks in set operations (mesa#4105) * fix(agentset): implement _from_iterable to preserve random and avoid strong ref leaks in set operations * fix(agentset): preserve subclass type in _from_iterable and test leak prevention Adapted for 3.5.x: the conflict is only in tests/test_agentset.py, where main's tests follow 4.0-only weighted select_random tests. Only the tests added by mesa#4105 are taken, with their gc, warnings and weakref imports. (cherry picked from commit 71f239a) Assisted-by: Claude Opus 5.5
(cherry picked from commit b70fbfe)
…esa#4061) * Keep agent ids and field names when JSONDataRecorder stores a numpy dataset A NumpyAgentDataSet hands the recorder a bare array of values. The JSON recorder stored it with tolist() and nothing else, so neither the saved file nor get_table_dataframe() said which agent a row belonged to or which field a value was. The dataset removes agents by swapping in the last row, so row order does not identify an agent either. The dataframe came back as one row per snapshot with the whole nested list in a "value" column, where the other three recorders return agent_id, the fields and time. Store such a snapshot as one dict per agent, with agent_id and the field names, which is the shape the recorder already uses for an AgentDataSet. An array from a dataset without agent ids is stored as before. Co-Authored-By: Claude <[email protected]> * Test that agent ids stay with their values after a removal Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --------- Co-authored-by: Claude <[email protected]> (cherry picked from commit feb8845)
…mesa#4157) JSONDataRecorder.data now holds a bounded deque per dataset (mesa#4072), while the test added in mesa#4061 compares it to a list, so main fails test_json_recorder_stores_a_plain_array_as_a_list. Convert to a list before comparing. (cherry picked from commit e89f241)
* Fix partial model data collection after reporter failures Signed-off-by: Sahil Kumar Singh <[email protected]> * test(datacollector): cover model reporter evaluation and copy failures Signed-off-by: Sahil Kumar Singh <[email protected]> --------- Signed-off-by: Sahil Kumar Singh <[email protected]> Co-authored-by: Jan Kwakkel <[email protected]> Adapted for 3.5.x: 3.5 records the collection step even without model reporters (mesa#3579), so the step is appended after the model reporter block, once all model reporters have succeeded, instead of inside it. (cherry picked from commit 7379e9e) Assisted-by: Claude Opus 5.5
(cherry picked from commit 3513647)
Fresh installs now pull in ipyvue and ipyvuetify 3 (Vue 3), as Solara doesn't cap them. Solara 1.65.2 fixes the blank GridDraggable that this caused in SolaraViz, so require at least that version. In Jupyter notebooks, the Solara sidebar and fullscreen mode still don't work with ipyvuetify 3 (widgetti/solara#1292, mesa#1294; fix in mesa#1293). Solara supports both Vue versions and declines to cap them, so document installing ipyvue<3 and ipyvuetify<3 instead of capping them in Mesa. Refs mesa#4133. Backport of mesa#4170, which is still open on main. Adapted for 3.5.x: raised the existing solara>=1.57.4 floor; 3.5 has no websockets<14 pin, so that part of the context was left out. Assisted-by: Claude Opus 5.5
Assisted-by: Claude Opus 5.5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Backports 42 PRs from
main, plus the Starlette 1.x support from #4007 and the Solara floor from #4170 (still open onmain), to3.5.x-maintenanceand bumps the version to 3.5.3, with release notes inHISTORY.md. The notes also cover #4064, which went straight into the maintenance branch after 3.5.2.All 75 PRs merged to
mainfrom the 3.5.2 cut-off (#4012) up to #4161 (merged 2026-11-21) were triaged, including the four labelledbackport-candidate(#3913, #3916, #3951, #4028). The second round (#3913, #4061, #4072, #4105, #4126, #4136, #4141, #4157, #4161 and the Starlette change) was added on 2026-11-22. Picks aregit cherry-pick -x, oldest first. Adapted commits keep the original author and explain what changed in the commit message.Changes that can alter results
#3932, #3946, #3959, #3995, #4048, #4052 and #4119 can change simulation results, but only where the 3.5.2 behaviour was wrong or contradicted the docs. #4061 and #4072 change what the experimental
JSONDataRecorderstores (agent ids and field names for numpy datasets;window_sizeis now honoured). The release notes call this out.Adapted for 3.5.x
GridCellclass after unpickling: ported to 3.5's property-layer system (_mesa_properties,grid.<layer>.data). Bug reproduced on 3.5.2 first.space_kwargs); resolved keeping 3.5's attribute names.propertylayer_*names. Bug reproduced on 3.5.2 first.extract_class, plus a regression test viacreate_meta_agent. TheStopIterationwas reproduced on 3.5.2 first.flatnonzerofallback: uses 3.5'sself.empty.data. Same RNG draw, so results are unchanged.JSONDataRecorderwindow_size: fix unchanged. 3.5 recorders don't record when a run ends (fix: respect DataRecorder start_time when a run ends #4041), so the test expects times[2.0, 3.0]instead of[3.0, 4.0];DataRecordergives the same.Networkremoval: 3.5 has nomesa.exceptions, so removing a missing cell raisesKeyError, likeDiscreteSpace.remove_cellon 3.5.select_randomtests; only fix(agentset): implement _from_iterable to preserve random and avoid strong ref leaks in set operations #4105's tests are taken.main. It raises 3.5'ssolara>=1.57.4floor, since 3.5 has nowebsockets<14pin. We don't cap ipyvue/ipyvuetify: Solara supports both Vue versions and declined to cap them, and the notebook fix is pending in fix: restore notebook layouts with ipyvuetify 3 widgetti/solara#1293.draw_property_layersfix. 3.5's SpaceRenderer hex mesh is still row-major, so itsdata.T.ravel()is already correct.Agent.remove()andEvent/EventGeneratorparts only; 3.5 has no experimental states or locations. Bug reproduced on 3.5.2 first.Not backported
cell_size/origin(Place grids in shared coordinates with cell_size and origin #4114), Remove the legacy space drawing API #4130 (removes the legacy drawing API, which 3.5.3 deprecates), fix: accept numpy arrays and pandas Series as select_random weights #3989 and Fix underflow in weighted sampling without replacement #3990 (weightedselect_random), typing: type hint meta-agent instance creation #4034 and Fix meta-agent class lookup typing #4128 (typing of the rewritten meta-agents), docs: document DiskStore executor limitations #4067 (DiskStore), docs: render math in the discrete event simulation tutorials #4058 (tutorials 11 and 12), docs: update example docstrings for scenario arguments #4009 (scenario-based example arguments).cell.coordinate, so the double conversion doesn't happen), fix: respect DataRecorder start_time when a run ends #4041 (3.5 recorders have no run-ended hook).CellCollection.cellsa tuple, which would break code that shuffles or appends to it; the bug it fixes was found by reading the code, not in a model.maindocs and tooling: Add developer guide and AGENTS.md; slim down CONTRIBUTING.md #3975, docs: document patch releases and the backport policy #4018 (developer guide), update tutorials; strip out cell diffs #4007's tutorial changes and theenvironment.ymlpin (tutorials onmain), docs: remove unused file mesa.md #4065, Fix the docstring examples that cannot run under doctest #4010, Run docstring doctests in CI as their own job #4011, fix(ci): install pyarrow in the benchmarks workflow #4006, Fix benchmark comments not posting on fork PRs #4033, [pre-commit.ci] pre-commit autoupdate #4029.Testing
pytest tests/ -Werror -Wdefault::PendingDeprecationWarning: 831 passed, 1 skipped, on both Python 3.13 and 3.15.2 for the first round. With the second round: 839 passed, 1 skipped on Python 3.14; the 5 tests that needpytest-mockweren't run locally (not installed), so CI covers those. The 9 Playwright browser tests intests/examples/test_examples_viz.pywere not run locally (no browser installed).tests/visualizationpasses (148 tests) with Solara 1.66.3 and ipyvue/ipyvuetify 3.1.1.ruff check: the two remaining warnings are in files this branch doesn't touch.After merging (fast-forward), publish the v3.5.3 draft release and set
__version__to3.5.4.dev.AI use: the backport triage, cherry-picks, adaptations, tests and release notes were prepared with Claude Code.