Skip to content

Fix seed logic to ensure reproducibility#3192

Merged
quaquel merged 6 commits intomesa:mainfrom
codebreaker32:entropy_issue
Jan 22, 2026
Merged

Fix seed logic to ensure reproducibility#3192
quaquel merged 6 commits intomesa:mainfrom
codebreaker32:entropy_issue

Conversation

@codebreaker32
Copy link
Copy Markdown
Collaborator

Summary

This PR fixes a bug in Model.__init__ where self._seed was incorrectly set to None even when a valid rng (integer) was provided. This ensures that the Scenario instance is initialized with the correct seed and that reset_randomizer() works as intended.

Bug / Issue

Closes #3190

Implementation

I refactored the initialization logic in mesa/model.py to use a try-except-else pattern, strictly separating seed generation from validation.

  • Case A (rng=None): Explicitly generates and stores an integer seed. This ensures post-hoc reproducibility (users can check model.scenario.rng to debug a random run that wasn't explicitly seeded).
  • Case B (rng=42): The else block now correctly captures seed = rng when random.Random(rng) succeeds.
  • Case C (rng=Generator): The except block handles Numpy generators by extracting a valid integer seed.

@github-actions
Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 -0.7% [-1.7%, +0.3%] 🔵 -0.3% [-0.4%, -0.1%]
BoltzmannWealth large 🔵 -2.7% [-11.1%, +7.7%] 🟢 -6.6% [-9.4%, -3.2%]
Schelling small 🔵 -0.0% [-0.7%, +0.7%] 🔵 -0.3% [-0.5%, +0.0%]
Schelling large 🔵 -2.4% [-6.1%, +2.2%] 🔵 -0.0% [-3.8%, +3.9%]
WolfSheep small 🔵 -0.6% [-2.5%, +1.3%] 🔵 +0.5% [+0.1%, +0.8%]
WolfSheep large 🔵 +3.0% [-2.9%, +8.5%] 🔵 +2.7% [+1.7%, +3.9%]
BoidFlockers small 🔵 -2.9% [-3.4%, -2.3%] 🔵 -0.3% [-0.6%, -0.1%]
BoidFlockers large 🔵 -3.4% [-4.2%, -2.6%] 🔵 -1.1% [-1.4%, -0.8%]

@quaquel
Copy link
Copy Markdown
Member

quaquel commented Jan 21, 2026

can you add tests to ensure the original bug is now discovered (and the fixed with this PR)?

@quaquel quaquel merged commit 1d8c4ad into mesa:main Jan 22, 2026
11 of 12 checks passed
@EwoutH EwoutH added the bug Release notes label label Feb 11, 2026
@codebreaker32 codebreaker32 deleted the entropy_issue branch February 17, 2026 16:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Reproducibilty Trap in model.py

3 participants