internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: projectmesa/mesa

Issue:
batch_run should default to running on 1 CPU
Currently, it uses up all the CPUs available in a system. This causes complication with the tutorial for Windows, where a nasty workaround is needed for `multiprocessing` (i.e. the `freeze_support`).

Then, if `number_processes` is > 1 and on Windows, we show a warning that tells user to add `freeze_support()` (we pre-emptively tell the user of this issue instead of waiting for it to happen). This warning can be disabled via a flag to the function:
```python
batch_run(
    ...
   hide_windows_freeze_support_warning=True,
   ...
)
```

Originally posted in https://github.com/projectmesa/mesa/discussions/1202.


Discussion:

Resolving patch:
diff --git a/mesa/batchrunner.py b/mesa/batchrunner.py
--- a/mesa/batchrunner.py
+++ b/mesa/batchrunner.py
@@ -35,7 +35,8 @@
 def batch_run(
     model_cls: Type[Model],
     parameters: Mapping[str, Union[Any, Iterable[Any]]],
-    number_processes: Optional[int] = None,
+    # We still retain the Optional[int] because users may set it to None (i.e. use all CPUs)
+    number_processes: Optional[int] = 1,
     iterations: int = 1,
     data_collection_period: int = -1,
     max_steps: int = 1000,
@@ -50,7 +51,7 @@ def batch_run(
     parameters : Mapping[str, Union[Any, Iterable[Any]]],
         Dictionary with model parameters over which to run the model. You can either pass single values or iterables.
     number_processes : int, optional
-        Number of processes used. Set to None (default) to use all available processors
+        Number of processes used, by default 1. Set this to None if you want to use all CPUs.
     iterations : int, optional
         Number of iterations for each parameter combination, by default 1
     data_collection_period : int, optional


Test patch:
diff --git a/tests/test_batch_run.py b/tests/test_batch_run.py
--- a/tests/test_batch_run.py
+++ b/tests/test_batch_run.py
@@ -86,7 +86,7 @@ def step(self):
 
 
 def test_batch_run():
-    result = batch_run(MockModel, {})
+    result = batch_run(MockModel, {}, number_processes=2)
     assert result == [
         {
             "RunId": 0,
@@ -125,11 +125,12 @@ def test_batch_run_with_params():
             "variable_model_params": range(5),
             "variable_agent_params": ["H", "E", "L", "L", "O"],
         },
+        number_processes=2,
     )
 
 
 def test_batch_run_no_agent_reporters():
-    result = batch_run(MockModel, {"enable_agent_reporters": False})
+    result = batch_run(MockModel, {"enable_agent_reporters": False}, number_processes=2)
     print(result)
     assert result == [
         {
Repository: projectmesa/mesa

Issue:
random.sample with a set is removed in Python 3.11
Using [`random.sample`](https://docs.python.org/3/library/random.html#random.sample) with a set has been depreciated in Python 3.9 and was removed in Python 3.11.

> Changed in version 3.11: The population must be a sequence. Automatic conversion of sets to lists is no longer supported.

Two cases of this function being used with a set have been detected by the CI in Mesa, both in example models:

1. https://github.com/projectmesa/mesa/blob/5135be8759d9fdac551c5c6ed13e9ae5205bce3e/examples/boltzmann_wealth_model_network/boltzmann_wealth_model_network/model.py#L28
2. https://github.com/projectmesa/mesa/blob/5135be8759d9fdac551c5c6ed13e9ae5205bce3e/examples/virus_on_network/virus_on_network/model.py#L84

What would be the most efficient way to get `self.G.nodes()` in a sequence form (so probably list or tuple)? I feel like just putting it inside a `list()` isn't the proper way to do it.


Discussion:
Using `list(self.G.nodes)` is recommended by https://networkx.org/documentation/stable/reference/classes/generated/networkx.Graph.nodes.html.

> If your node data is not needed, it is simpler and equivalent to use the expression for n in G, or list(G).

In both cases, the node data is not needed.

Resolving patch:
diff --git a/examples/boltzmann_wealth_model_network/boltzmann_wealth_model_network/model.py b/examples/boltzmann_wealth_model_network/boltzmann_wealth_model_network/model.py
--- a/examples/boltzmann_wealth_model_network/boltzmann_wealth_model_network/model.py
+++ b/examples/boltzmann_wealth_model_network/boltzmann_wealth_model_network/model.py
@@ -25,7 +25,7 @@ def __init__(self, num_agents=7, num_nodes=10):
             agent_reporters={"Wealth": lambda _: _.wealth},
         )
 
-        list_of_random_nodes = self.random.sample(self.G.nodes(), self.num_agents)
+        list_of_random_nodes = self.random.sample(list(self.G), self.num_agents)
 
         # Create agents
         for i in range(self.num_agents):
diff --git a/examples/virus_on_network/virus_on_network/model.py b/examples/virus_on_network/virus_on_network/model.py
--- a/examples/virus_on_network/virus_on_network/model.py
+++ b/examples/virus_on_network/virus_on_network/model.py
@@ -81,7 +81,7 @@ def __init__(
             self.grid.place_agent(a, node)
 
         # Infect some nodes
-        infected_nodes = self.random.sample(self.G.nodes(), self.initial_outbreak_size)
+        infected_nodes = self.random.sample(list(self.G), self.initial_outbreak_size)
         for a in self.grid.get_cell_list_contents(infected_nodes):
             a.state = State.INFECTED
 


Test patch:
Repository: projectmesa/mesa

Issue:
refactor: Remove dependency on jQuery
We should replace the `$(...)` with vanilla JS.


Discussion:
See #1319.
Whats the motivation behind this? 

If it is just to remove the dependency then it wont work, because Bootstrap requires jquery. 
Bootstrap 5 actually has removed jQuery from its dependency. And hence why I made #1325 soon.
See https://www.infoq.com/news/2020/08/bootsrap-5-drops-jquery/.

> Whats the motivation behind this?

jQuery is an old tech.
Oh, didn't see #1325, great work! 

Old tech doesn't mean bad, but I think we definitely don't have good use cases for keeping it in and removing it should be straight forward 

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -51,7 +51,7 @@ def ensure_JS_dep(dirname, url):
 
 
 def ensure_JS_dep_single(url, out_name=None):
-    # Used for downloading e.g. jQuery single file
+    # Used for downloading e.g. D3.js single file
     if out_name is None:
         out_name = url.split("/")[-1]
     dst_path = os.path.join(external_dir_single, out_name)
@@ -79,10 +79,6 @@ def ensure_JS_dep_single(url, out_name=None):
     f"https://github.com/seiyria/bootstrap-slider/archive/refs/tags/v{bootstrap_slider_version}.zip",
 )
 
-jquery_version = "2.2.4"
-ensure_JS_dep_single(
-    f"https://code.jquery.com/jquery-{jquery_version}.min.js",
-)
 # Important: when updating the D3 version, make sure to update the constant
 # D3_JS_FILE in mesa/visualization/ModularVisualization.py.
 d3_version = "7.4.3"


Test patch:
Repository: projectmesa/mesa

Issue:
`OSError: Int or String expected` when running boid_flockers example
**Describe the bug**

Running the `boid_flockers` example results in `OSError: Int or String expected`.

**Expected behavior**

Examples should be able to run without errors.

**Additional context**

This is likely due to a breaking change introduced through https://github.com/projectmesa/mesa/pull/1403: a new parameter `port` is added before `model_params` in `ModularServer.__init__()`, i.e.,

```diff
    def __init__(
-         self, model_cls, visualization_elements, name="Mesa Model", model_params=None
+         self,
+         model_cls,
+         visualization_elements,
+         name="Mesa Model",
+         port=None,
+         model_params=None,
    ):
```

As a result, in the `boid_flockers` example, `model_params` gets passed into `__init__()` as `port`:

```python
server = mesa.visualization.ModularServer(
    BoidFlockers, [boid_canvas], "Boids", model_params
)
```

Examples such as `bank_reserves` are not affected:

```python
server = mesa.visualization.ModularServer(
    BankReserves,
    [canvas_element, chart_element],
    "Bank Reserves Model",
    model_params=model_params,
)
```


Discussion:
Is it only boid_flockers? How come this is not caught by the test?
I think the fix is to put `port=None` last, so that it is not breaking other people's code.

Resolving patch:
diff --git a/mesa/visualization/ModularVisualization.py b/mesa/visualization/ModularVisualization.py
--- a/mesa/visualization/ModularVisualization.py
+++ b/mesa/visualization/ModularVisualization.py
@@ -257,8 +257,8 @@ def __init__(
         model_cls,
         visualization_elements,
         name="Mesa Model",
-        port=None,
         model_params=None,
+        port=None,
     ):
         """
         Args:


Test patch:
Repository: projectmesa/mesa

Issue:
v1.1.0 Safford Release
Milestone: https://github.com/projectmesa/mesa/milestone/31

Highlighted changes:
- #1376 > 6x perf speedup for add/remove agent in `ContinuousSpace`
- #1391 correctness fix for `SimultaneousActivation` and `StagedActivation`
- #1399 make `self.running = True` optional. We need to tell existing users that initializing this is no longer necessary, and so, reducing the boilerplate code
- #1435 Allow user-specified local dir to be served by Tornado. Needed by Mesa-Geo
- #1413 Allow batch_run to take arbitrary parameters


Discussion:

Resolving patch:
diff --git a/mesa/__init__.py b/mesa/__init__.py
--- a/mesa/__init__.py
+++ b/mesa/__init__.py
@@ -26,6 +26,6 @@
 ]
 
 __title__ = "mesa"
-__version__ = "1.0.0"
+__version__ = "1.1.0"
 __license__ = "Apache 2.0"
 __copyright__ = f"Copyright {datetime.date.today().year} Project Mesa Team"


Test patch:
Repository: projectmesa/mesa

Issue:
Seed and random should not be class attributes
**Describe the bug**
<!-- A clear and concise description the bug -->

Every time a model instance is created, it updates the seed and random attribute of every other instance of the same class.

**Expected behavior**
<!-- A clear and concise description of what you expected to happen -->

I would expect each instance to have their own attribute. This way, the behavior of each instance is independent and predictable.

**To Reproduce**
<!-- Steps to reproduce the bug, or a link to a project where the bug is visible -->

```pycon
>>> from mesa import Model
>>> class Ex(Model):
...   def __init__(self, seed=2):
...     pass
...
>>> a = Ex(seed=1)
>>> print(a._seed, a.random)
1 <random.Random object at 0x282a8d0>
>>> b = Ex(seed=2)
>>> print(a._seed, a.random)
2 <random.Random object at 0x282b2d0>
```


Discussion:

Resolving patch:
diff --git a/mesa/model.py b/mesa/model.py
--- a/mesa/model.py
+++ b/mesa/model.py
@@ -21,9 +21,10 @@ class Model:
 
     def __new__(cls, *args: Any, **kwargs: Any) -> Any:
         """Create a new model object and instantiate its RNG automatically."""
-        cls._seed = kwargs.get("seed", None)
-        cls.random = random.Random(cls._seed)
-        return object.__new__(cls)
+        obj = object.__new__(cls)
+        obj._seed = kwargs.get("seed", None)
+        obj.random = random.Random(obj._seed)
+        return obj
 
     def __init__(self, *args: Any, **kwargs: Any) -> None:
         """Create a new model. Overload this method with the actual code to


Test patch:
diff --git a/tests/test_model.py b/tests/test_model.py
--- a/tests/test_model.py
+++ b/tests/test_model.py
@@ -28,6 +28,9 @@ def step(self):
 def test_seed(seed=23):
     model = Model(seed=seed)
     assert model._seed == seed
+    model2 = Model(seed=seed + 1)
+    assert model2._seed == seed + 1
+    assert model._seed == seed
 
 
 def test_reset_randomizer(newseed=42):
Repository: projectmesa/mesa

Issue:
[1.1.0 regression] Image files from examples don't load (on Windows)
**Describe the bug**
On Windows using Mesa 1.1.0, agent portrayal images don't load when running an example.

**Expected behavior**
Agent images load without errors in the example model.

**To Reproduce**

1. Checkout Mesa 1.1.0 (or the current main branch)
2. Run the `run.py` file of one of the examples (_sugarscape_cg_ or _wolf_sheep_) (on Windows?)

**Additional context**

### 1.0.0

<img width="300" alt="Screenshot_797" src="https://user-images.githubusercontent.com/15776622/196971492-45090e68-bae1-4150-a168-a5a3c1b98465.png"><img width="300" alt="Screenshot_798" src="https://user-images.githubusercontent.com/15776622/196971495-6870ce27-6635-4bc6-a9d6-78213b05cf10.png">

### 1.1.0

<img width="300" alt="Screenshot_799" src="https://user-images.githubusercontent.com/15776622/196971800-b04e2668-1fc2-46ec-bc86-7156662cc54c.png"><img width="400" alt="Screenshot_796" src="https://user-images.githubusercontent.com/15776622/196971554-23d7eb80-e4e9-4aed-b3e3-1f19c4e21db5.png">



Discussion:
After bisecting the commits, I found this commit to be the cause: https://github.com/projectmesa/mesa/commit/3def79dd18b5f9978c7ccda0930a818082af127f. cc @wang-boyu 

Resolving patch:
diff --git a/mesa/__init__.py b/mesa/__init__.py
--- a/mesa/__init__.py
+++ b/mesa/__init__.py
@@ -26,6 +26,6 @@
 ]
 
 __title__ = "mesa"
-__version__ = "1.1.0"
+__version__ = "1.1.1"
 __license__ = "Apache 2.0"
 __copyright__ = f"Copyright {datetime.date.today().year} Project Mesa Team"
diff --git a/mesa/visualization/ModularVisualization.py b/mesa/visualization/ModularVisualization.py
--- a/mesa/visualization/ModularVisualization.py
+++ b/mesa/visualization/ModularVisualization.py
@@ -297,7 +297,12 @@ def __init__(
             tornado.web.StaticFileHandler,
             {"path": os.path.dirname(__file__) + "/templates"},
         )
-        self.handlers = [page_handler, socket_handler, static_handler]
+        custom_handler = (
+            r"/local/custom/(.*)",
+            tornado.web.StaticFileHandler,
+            {"path": ""},
+        )
+        self.handlers = [page_handler, socket_handler, static_handler, custom_handler]
 
         self.settings = {
             "debug": True,


Test patch:
Repository: projectmesa/mesa

Issue:
Fix codespell build for tutorial docs
Not sure if this is possible, but codespell will pick up image text and try to suggest text edits and says the build is broken. 
Hoping there is a setting somewhere that we can add to ignore the image text. 

Here is an example: https://github.com/projectmesa/mesa/pull/1656/files#diff-732a7eb31fbbd25075ee965837dc0092fb53c2cb64c068e60392d9bf69d9f9bbR877

<img width="1052" alt="Screenshot 2023-04-25 at 12 17 29 PM" src="https://user-images.githubusercontent.com/166734/234368855-d62da5a6-aff8-46f1-bae5-bcf8aa05607f.png">

<img width="708" alt="Screenshot 2023-04-25 at 12 26 06 PM" src="https://user-images.githubusercontent.com/166734/234369720-91c22dbb-f7b9-4b9c-8764-832eb6e63cad.png">




Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -21,7 +21,10 @@
     ],
     # Constrain sphinx version until https://github.com/readthedocs/readthedocs.org/issues/10279
     # is fixed.
-    "docs": ["sphinx<7", "ipython", "nbsphinx"],
+    # Explicitly install ipykernel for Python 3.8.
+    # See https://stackoverflow.com/questions/28831854/how-do-i-add-python3-kernel-to-jupyter-ipython
+    # Could be removed in the future
+    "docs": ["sphinx<7", "ipython", "nbsphinx", "ipykernel"],
 }
 
 version = ""


Test patch:
Repository: projectmesa/mesa

Issue:
JupyterViz: Changing simulation parameters shouldn't automatically start the simulation
**Describe the bug**
Currently, changing the parameters auto-play the simulation.

**Expected behavior**
It shouldn't.

**To Reproduce**
Run any `JupyterViz` simulation.


Discussion:

Resolving patch:
diff --git a/mesa/experimental/jupyter_viz.py b/mesa/experimental/jupyter_viz.py
--- a/mesa/experimental/jupyter_viz.py
+++ b/mesa/experimental/jupyter_viz.py
@@ -89,15 +89,25 @@ def ModelController(
 ):
     playing = solara.use_reactive(False)
     thread = solara.use_reactive(None)
+    # We track the previous step to detect if user resets the model via
+    # clicking the reset button or changing the parameters. If previous_step >
+    # current_step, it means a model reset happens while the simulation is
+    # still playing.
+    previous_step = solara.use_reactive(0)
 
     def on_value_play(change):
-        if model.running:
+        if previous_step.value > current_step and current_step == 0:
+            # We add extra checks for current_step == 0, just to be sure.
+            # We automatically stop the playing if a model is reset.
+            playing.value = False
+        elif model.running:
             do_step()
         else:
             playing.value = False
 
     def do_step():
         model.step()
+        previous_step.value = current_step
         set_current_step(model.schedule.steps)
 
     def do_play():


Test patch:
Repository: projectmesa/mesa

Issue:
jupyterviz checkbox input change is not propagated



Discussion:

Resolving patch:
diff --git a/mesa/experimental/jupyter_viz.py b/mesa/experimental/jupyter_viz.py
--- a/mesa/experimental/jupyter_viz.py
+++ b/mesa/experimental/jupyter_viz.py
@@ -228,6 +228,7 @@ def change_handler(value, name=name):
         elif input_type == "Checkbox":
             solara.Checkbox(
                 label=label,
+                on_value=change_handler,
                 value=options.get("value"),
             )
         else:


Test patch:
Repository: projectmesa/mesa

Issue:
mesa.visualization.chartmodule doesn't work
As shown in the picture, I run the boltzmann_wealth_model in the mesa example, but the line chart is not displayed normally. Can anyone help me?
<img width="788" alt="屏幕截图 2023-11-04 183542" src="https://github.com/projectmesa/mesa/assets/75169342/89ba1b20-4011-471b-909e-5fea97da6b73">



Discussion:
I have tried it many times, ,all other charts can be displayed normally，except for chartmodule
That's https://github.com/projectmesa/mesa-viz-tornado/issues/26. A fix has been pushed to https://github.com/projectmesa/mesa-viz-tornado (this is one of Mesa's dependencies). It just hasn't been released on PyPI yet. If you install from the Git repo, it should solve your problem. cc: @tpike3 

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -8,7 +8,7 @@
     "click",
     "cookiecutter",
     "matplotlib",
-    "mesa_viz_tornado",
+    "mesa_viz_tornado~=0.1.0,>=0.1.2",
     "networkx",
     "numpy",
     "pandas",


Test patch:
Repository: projectmesa/mesa

Issue:
jupyterviz agent space and measures flash on mesa 2.1.4
**Describe the bug**
When I run my simulations on the latest release (v2.1.4), my agent space and charts flicker. 

**Expected behavior**
In mesa 2.1.2 these render smoothly and update without any flickering.

**To Reproduce**
My code base is here if you want to try running solara apps yourself: https://github.com/Princeton-CDH/simulating-risk
If you check it out and install dependencies, you can run one of the models like this:
```sh
solara run --host localhost simulatingrisk/hawkdovevar/app.py
```
I'm going to pin mesa to version 2.1.2 for now, but I like the new layout and would like to update once this is resolved.

**Additional context**
I looked at the release notes and some of the PRs; I tried changing the `play_interval` in my code when I initialize `JupyterViz` for my model, but it didn't have any effect.

I'm using altair instead of matplotlib, in case that's relevant.

I made a couple of screen recordings so you can see what I'm describing.

Nice smooth updating on mesa 2.1.2:
https://github.com/projectmesa/mesa/assets/691231/22b676b9-d83c-4658-a93f-46ab343a8f9d

Jerky, flashing updating on mesa 2.1.4:
https://github.com/projectmesa/mesa/assets/691231/06adccee-8823-44c1-b029-ce3660256034




Discussion:
Upon investigating, it is due to the fact that the plot objects seem to be recreated from scratch for each step. This affects both the Matplotlib render as well. Removing https://github.com/projectmesa/mesa/blob/8e901d3510c46e1d1dba945d29cf014e899ba804/mesa/experimental/jupyter_viz.py#L63 fixes the issue. A proper solution would be to ensure the `ColorCard` and subcomponent of `ColorCard` are rerendered only when necessary.

Resolving patch:
diff --git a/mesa/experimental/jupyter_viz.py b/mesa/experimental/jupyter_viz.py
--- a/mesa/experimental/jupyter_viz.py
+++ b/mesa/experimental/jupyter_viz.py
@@ -60,8 +60,10 @@ def make_model():
     def handle_change_model_params(name: str, value: any):
         set_model_parameters({**model_parameters, name: value})
 
-    @solara.component
     def ColorCard(color, layout_type):
+        # TODO: turn this into a Solara component, but must pass in current
+        # step as a dependency for the plots, so that there is no flickering
+        # due to rerender.
         with rv.Card(
             style_=f"background-color: {color}; width: 100%; height: 100%"
         ) as main:


Test patch:
Repository: projectmesa/mesa

Issue:
JupyterViz: Easy way to plot multiple measures in 1 figure
**What's the problem this feature will solve?**
Currently, each agent variable can only be plotted in separate figures. The virus on a network example is one such use case where we want to plot everything in one figure. See https://github.com/projectmesa/mesa-examples/pull/56#discussion_r1297048939.

**Describe the solution you'd like**
<!-- A clear and concise description of what you want to happen. -->

Supporting this could be as simple as detecting if `measure` in https://github.com/projectmesa/mesa/blob/734496c641d0dcc5d05832d5c530b4badad08e4a/mesa/experimental/jupyter_viz.py#L287 is a list. If so, plot all of them in 1 figure.


Discussion:
If there is no objection to my proposed design, this would be quick for @ankitk50 to implement.
Can you also give an example model where this can be tested?
This example already implements the feature: https://github.com/projectmesa/mesa-examples/tree/main/examples/virus_on_network. It just needs to be ported to core Mesa.
@ankitk50 this is very likely to be a quick merge, since the other 2 PRs are still in draft.
What's the current status of this effort?

Resolving patch:
diff --git a/mesa/experimental/jupyter_viz.py b/mesa/experimental/jupyter_viz.py
--- a/mesa/experimental/jupyter_viz.py
+++ b/mesa/experimental/jupyter_viz.py
@@ -406,8 +406,17 @@ def make_plot(model, measure):
     fig = Figure()
     ax = fig.subplots()
     df = model.datacollector.get_model_vars_dataframe()
-    ax.plot(df.loc[:, measure])
-    ax.set_ylabel(measure)
+    if isinstance(measure, str):
+        ax.plot(df.loc[:, measure])
+        ax.set_ylabel(measure)
+    elif isinstance(measure, dict):
+        for m, color in measure.items():
+            ax.plot(df.loc[:, m], label=m, color=color)
+        fig.legend()
+    elif isinstance(measure, (list, tuple)):
+        for m in measure:
+            ax.plot(df.loc[:, m], label=m)
+        fig.legend()
     # Set integer x axis
     ax.xaxis.set_major_locator(MaxNLocator(integer=True))
     solara.FigureMatplotlib(fig)


Test patch: