Skip to content

Commit e83c64e

Browse files
catherinedevlinCatherine Devlin
authored andcommitted
Use pre-commit (#27)
* Use Pathlib Code by Phil Robare (versilimidude2) * Use pre-commit * Dropped unused imports * used pre-commit to run pyupgrade, trim whitespace * Remove pathlib changes These belong in a separate PR. * remove redundant black, move comment as per rht's suggestions --------- Co-authored-by: Catherine Devlin <[email protected]>
1 parent 50b422b commit e83c64e

File tree

36 files changed

+127
-85
lines changed

36 files changed

+127
-85
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,5 @@ dmypy.json
7979

8080
# Virtual environment
8181
venv/
82+
83+
examples/caching_and_replay/my_cache_file_path.cache

.pre-commit-config.yaml

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
ci:
2+
autoupdate_schedule: 'monthly'
3+
autofix_prs: false
4+
5+
repos:
6+
- repo: https://github.com/psf/black
7+
rev: 23.3.0
8+
hooks:
9+
- id: black-jupyter
10+
- repo: https://github.com/asottile/pyupgrade
11+
rev: v3.3.1
12+
hooks:
13+
- id: pyupgrade
14+
args: [--py38-plus]
15+
- repo: https://github.com/pre-commit/pre-commit-hooks
16+
rev: v4.4.0 # Use the ref you want to point at
17+
hooks:
18+
- id: trailing-whitespace
19+
- id: check-toml
20+
- id: check-yaml

CONTRIBUTING.rst

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
Contributing
22
=========================
33

4-
As an open source project, Mesa welcomes contributions of many forms, and from beginners to experts.
4+
As an open source project, Mesa welcomes contributions of many forms, and from beginners to experts.
55

6-
Contributions can a full model or it could one of the following to an existing model:
6+
Contributions can a full model or it could one of the following to an existing model:
77

88
- Code patches
99
- Bug reports and patch reviews

README.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# mesa-examples
22

3-
This repository contains examples that work with Mesa and illustrate different features of Mesa.
3+
This repository contains examples that work with Mesa and illustrate different features of Mesa.
44

55
To contribute to this repository, see `CONTRIBUTING.rst`_
66

examples/bank_reserves/bank_reserves/agents.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
The following code was adapted from the Bank Reserves model included in Netlogo
3-
Model information can be found at: http://ccl.northwestern.edu/netlogo/models/BankReserves
3+
Model information can be found at:
4+
http://ccl.northwestern.edu/netlogo/models/BankReserves
45
Accessed on: November 2, 2017
56
Author of NetLogo code:
67
Wilensky, U. (1998). NetLogo Bank Reserves model.
@@ -76,12 +77,14 @@ def do_business(self):
7677
if self.random.randint(0, 1) == 0:
7778
# 50% chance of trading $5
7879
if self.random.randint(0, 1) == 0:
79-
# give customer $5 from my wallet (may result in negative wallet)
80+
# give customer $5 from my wallet
81+
# (may result in negative wallet)
8082
customer.wallet += 5
8183
self.wallet -= 5
8284
# 50% chance of trading $2
8385
else:
84-
# give customer $2 from my wallet (may result in negative wallet)
86+
# give customer $2 from my wallet
87+
# (may result in negative wallet)
8588
customer.wallet += 2
8689
self.wallet -= 2
8790

examples/bank_reserves/bank_reserves/model.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
The following code was adapted from the Bank Reserves model included in Netlogo
3-
Model information can be found at: http://ccl.northwestern.edu/netlogo/models/BankReserves
3+
Model information can be found at:
4+
http://ccl.northwestern.edu/netlogo/models/BankReserves
45
Accessed on: November 2, 2017
56
Author of NetLogo code:
67
Wilensky, U. (1998). NetLogo Bank Reserves model.

examples/bank_reserves/batch_run.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
The following code was adapted from the Bank Reserves model included in Netlogo
3-
Model information can be found at: http://ccl.northwestern.edu/netlogo/models/BankReserves
3+
Model information can be found at:
4+
http://ccl.northwestern.edu/netlogo/models/BankReserves
45
Accessed on: November 2, 2017
56
Author of NetLogo code:
67
Wilensky, U. (1998). NetLogo Bank Reserves model.

examples/boltzmann_wealth_model_network/boltzmann_wealth_model_network/model.py

-2
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ class BoltzmannWealthModelNetwork(mesa.Model):
1414
"""A model with some number of agents."""
1515

1616
def __init__(self, num_agents=7, num_nodes=10):
17-
1817
self.num_agents = num_agents
1918
self.num_nodes = num_nodes if num_nodes >= self.num_agents else self.num_agents
2019
self.G = nx.erdos_renyi_graph(n=self.num_nodes, p=0.5)
@@ -65,7 +64,6 @@ def move(self):
6564
self.model.grid.move_agent(self, new_position)
6665

6766
def give_money(self):
68-
6967
neighbors_nodes = self.model.grid.get_neighbors(self.pos, include_center=False)
7068
neighbors = self.model.grid.get_cell_list_contents(neighbors_nodes)
7169
if len(neighbors) > 0:

examples/caching_and_replay/README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ It uses the [Mesa-Replay](https://github.com/Logende/mesa-replay) library and pu
99
From the user's perspective, the new model behaves the same way as the original Schelling model, but additionally supports caching.
1010

1111
Note that the main purpose of this example is to demonstrate that caching and replaying simulation runs is possible.
12-
The example is designed to be accessible.
12+
The example is designed to be accessible.
1313
In practice, someone who wants to replay their simulation might not necessarily embed a replay button into the web view, but instead have a dedicated script to run a simulation that is being cached, separate from a script to replay a simulation run from a given cache file.
1414
More examples of caching and replay can be found in the [Mesa-Replay Repository](https://github.com/Logende/mesa-replay/tree/main/examples).
1515

@@ -31,7 +31,7 @@ To run the model interactively, run ``mesa runserver`` in this directory. e.g.
3131

3232
Then open your browser to [http://127.0.0.1:8521/](http://127.0.0.1:8521/) and press Reset, then Run.
3333

34-
First, run the **simulation** with the 'Replay' switch disabled.
34+
First, run the **simulation** with the 'Replay' switch disabled.
3535
When the simulation run is finished (e.g. all agents are happy, no more new steps are simulated), the run will automatically be stored in a cache file.
3636

3737
Next, **replay** your latest cached simulation run by enabling the Replay switch and then pressing Reset.

examples/caching_and_replay/cacheablemodel.py

+11-6
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,15 @@
33

44

55
class CacheableSchelling(CacheableModel):
6-
"""A wrapper around the original Schelling model to make the simulation cacheable and replay-able.
7-
Uses CacheableModel from the Mesa-Replay library, which is a wrapper that can be put around any regular mesa model
8-
to make it "cacheable". From outside, a CacheableSchelling instance can be treated like any regular Mesa model.
9-
The only difference is that the model will write the state of every simulation step to a cache file or when in
10-
replay mode use a given cache file to replay that cached simulation run."""
6+
"""A wrapper around the original Schelling model to make the simulation cacheable
7+
and replay-able. Uses CacheableModel from the Mesa-Replay library,
8+
which is a wrapper that can be put around any regular mesa model to make it
9+
"cacheable".
10+
From outside, a CacheableSchelling instance can be treated like any
11+
regular Mesa model.
12+
The only difference is that the model will write the state of every simulation step
13+
to a cache file or when in replay mode use a given cache file to replay that cached
14+
simulation run."""
1115

1216
def __init__(
1317
self,
@@ -16,7 +20,8 @@ def __init__(
1620
density=0.8,
1721
minority_pc=0.2,
1822
homophily=3,
19-
# Note that this is an additional parameter we add to our model, which decides whether to simulate or replay
23+
# Note that this is an additional parameter we add to our model,
24+
# which decides whether to simulate or replay
2025
replay=False,
2126
):
2227
actual_model = Schelling(width, height, density, minority_pc, homophily)

examples/charts/charts/agents.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
The following code was adapted from the Bank Reserves model included in Netlogo
3-
Model information can be found at: http://ccl.northwestern.edu/netlogo/models/BankReserves
3+
Model information can be found at:
4+
http://ccl.northwestern.edu/netlogo/models/BankReserves
45
Accessed on: November 2, 2017
56
Author of NetLogo code:
67
Wilensky, U. (1998). NetLogo Bank Reserves model.
@@ -76,12 +77,14 @@ def do_business(self):
7677
if self.random.randint(0, 1) == 0:
7778
# 50% chance of trading $5
7879
if self.random.randint(0, 1) == 0:
79-
# give customer $5 from my wallet (may result in negative wallet)
80+
# give customer $5 from my wallet
81+
# (may result in negative wallet)
8082
customer.wallet += 5
8183
self.wallet -= 5
8284
# 50% chance of trading $2
8385
else:
84-
# give customer $2 from my wallet (may result in negative wallet)
86+
# give customer $2 from my wallet
87+
# (may result in negative wallet)
8588
customer.wallet += 2
8689
self.wallet -= 2
8790

examples/charts/charts/model.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
The following code was adapted from the Bank Reserves model included in Netlogo
3-
Model information can be found at: http://ccl.northwestern.edu/netlogo/models/BankReserves
3+
Model information can be found at:
4+
http://ccl.northwestern.edu/netlogo/models/BankReserves
45
Accessed on: November 2, 2017
56
Author of NetLogo code:
67
Wilensky, U. (1998). NetLogo Bank Reserves model.
@@ -80,7 +81,6 @@ def get_total_loans(model):
8081

8182

8283
class Charts(mesa.Model):
83-
8484
# grid height
8585
grid_h = 20
8686
# grid width

examples/color_patches/color_patches/model.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def __init__(self, width=20, height=20):
8080
# -->but only col & row
8181
# for (contents, col, row) in self._grid.coord_iter():
8282
# replaced content with _ to appease linter
83-
for (_, row, col) in self._grid.coord_iter():
83+
for _, row, col in self._grid.coord_iter():
8484
cell = ColorCell(
8585
(row, col), self, ColorCell.OPINIONS[self.random.randrange(0, 16)]
8686
)
@@ -115,7 +115,7 @@ def grid(self):
115115
80 cell_objects = model.grid.get_cell_list_contents([(x, y)])
116116
117117
AttributeError: 'ColorPatches' object has no attribute 'grid'
118-
"""
118+
""" # noqa: E501
119119
return self._grid
120120

121121
@property

examples/conways_game_of_life/conways_game_of_life/model.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def __init__(self, width=50, height=50):
2727

2828
# Place a cell at each location, with some initialized to
2929
# ALIVE and some to DEAD.
30-
for (contents, x, y) in self.grid.coord_iter():
30+
for contents, x, y in self.grid.coord_iter():
3131
cell = Cell((x, y), self)
3232
if self.random.random() < 0.1:
3333
cell.state = cell.ALIVE

examples/epstein_civil_violence/epstein_civil_violence/model.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def __init__(
7979
unique_id = 0
8080
if self.cop_density + self.citizen_density > 1:
8181
raise ValueError("Cop density + citizen density must be less than 1")
82-
for (contents, x, y) in self.grid.coord_iter():
82+
for contents, x, y in self.grid.coord_iter():
8383
if self.random.random() < self.cop_density:
8484
cop = Cop(unique_id, self, (x, y), vision=self.cop_vision)
8585
unique_id += 1

examples/forest_fire/forest_fire/model.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def __init__(self, width=100, height=100, density=0.65):
2929
)
3030

3131
# Place a tree in each cell with Prob = density
32-
for (contents, x, y) in self.grid.coord_iter():
32+
for contents, x, y in self.grid.coord_iter():
3333
if self.random.random() < density:
3434
# Create a tree
3535
new_tree = TreeCell((x, y), self)

examples/hex_snowflake/hex_snowflake/cell.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ def step(self):
3636
changed here, but is just computed and stored in self._nextState,
3737
because our current state may still be necessary for our neighbors
3838
to calculate their next state.
39-
When a cell is made alive, its neighbors are able to be considered in the next step. Only cells that are considered check their neighbors for performance reasons.
39+
When a cell is made alive, its neighbors are able to be considered
40+
in the next step. Only cells that are considered check their neighbors
41+
for performance reasons.
4042
"""
4143
# assume no state change
4244
self._nextState = self.state

examples/hex_snowflake/hex_snowflake/model.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55

66
class HexSnowflake(mesa.Model):
77
"""
8-
Represents the hex grid of cells. The grid is represented by a 2-dimensional array of cells with adjacency rules specific to hexagons.
8+
Represents the hex grid of cells. The grid is represented by a 2-dimensional array
9+
of cells with adjacency rules specific to hexagons.
910
"""
1011

1112
def __init__(self, width=50, height=50):
@@ -25,7 +26,7 @@ def __init__(self, width=50, height=50):
2526
self.grid = mesa.space.HexGrid(width, height, torus=True)
2627

2728
# Place a dead cell at each location.
28-
for (contents, x, y) in self.grid.coord_iter():
29+
for contents, x, y in self.grid.coord_iter():
2930
cell = Cell((x, y), self)
3031
self.grid.place_agent(cell, (x, y))
3132
self.schedule.add(cell)

examples/pd_grid/pd_grid/agent.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ def isCooroperating(self):
2828
return self.move == "C"
2929

3030
def step(self):
31-
"""Get the best neighbor's move, and change own move accordingly if better than own score."""
31+
"""Get the best neighbor's move, and change own move accordingly
32+
if better than own score."""
33+
3234
neighbors = self.model.grid.get_neighbors(self.pos, True, include_center=True)
3335
best_neighbor = max(neighbors, key=lambda a: a.score)
3436
self.next_move = best_neighbor.move

examples/shape_example/shape_example/server.py

-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ def agent_draw(agent):
1717
"Layer": 2,
1818
"Color": ["#00FF00", "#99FF99"],
1919
"stroke_color": "#666666",
20-
"Filled": "true",
2120
"heading_x": agent.heading[0],
2221
"heading_y": agent.heading[1],
2322
"text": agent.unique_id,

examples/sugarscape_cg/sugarscape_cg/model.py

-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,6 @@ def step(self):
7575
print([self.schedule.time, self.schedule.get_type_count(SsAgent)])
7676

7777
def run_model(self, step_count=200):
78-
7978
if self.verbose:
8079
print(
8180
"Initial number Sugarscape Agent: ",

examples/sugarscape_g1mt/Readme.md

+12-12
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,19 @@
55
This is Epstein & Axtell's Sugarscape model with Traders, a detailed description is in Chapter four of
66
*Growing Artificial Societies: Social Science from the Bottom Up.* (1996)
77

8-
This code generally matches the code in the Complexity Explorer Tutorial, but in `.py` instead of `.ipynb` format.
8+
This code generally matches the code in the Complexity Explorer Tutorial, but in `.py` instead of `.ipynb` format.
99

10-
### Agents:
10+
### Agents:
1111

1212
- **Sugar**: Sugar agents grow back at one unit per time step and can be harvested and traded by the trader agents. Sugar
1313
is unequally distributed across the landscape with sugar hills in the upper left and lower right of the space.
1414
(green if you do the interactive run)
1515
- **Spice**: Spice agents grow back at one unit per time step and can be harvested and traded by the trader agents. Spice
16-
is unequally distributed across the landscape with spice hills in the upper right and lower left of the space.
16+
is unequally distributed across the landscape with spice hills in the upper right and lower left of the space.
1717
(yellow if you do the interactive run)
1818
- **Traders**: Trader agents have the following attributes: (1) metabolism for sugar, (2) metabolism for spice, (3) vision,
19-
(4) initial sugar endowment and (5) initial spice endowment. The traverse the landscape harvesting sugar and spice and
20-
trading with other agents. If they run out of sugar or spice then they are removed from the model.
19+
(4) initial sugar endowment and (5) initial spice endowment. The traverse the landscape harvesting sugar and spice and
20+
trading with other agents. If they run out of sugar or spice then they are removed from the model.
2121

2222
The trader agents traverse the landscape according to rule **M**:
2323
- Look out as far as vision permits in the four principal lattice directions and identify the unoccupied site(s).
@@ -26,15 +26,15 @@ The trader agents traverse the landscape according to rule **M**:
2626
- Collect all the resources (sugar and spice) at that location
2727
(Epstein and Axtell, 1996, p. 99)
2828

29-
The traders trade according to rule **T**:
29+
The traders trade according to rule **T**:
3030
- Agents and potential trade partner compute their marginal rates of substitution (MRS), if they are equal *end*.
31-
- Exchange resources, with spice flowing from the agent with the higher MRS to the agent with the lower MRS and sugar
31+
- Exchange resources, with spice flowing from the agent with the higher MRS to the agent with the lower MRS and sugar
3232
flowing the opposite direction.
3333
- The price (p) is calculated by taking the geometric mean of the agents' MRS.
3434
- If p > 1 then p units of spice are traded for 1 unit of sugar; if p < 1 then 1/p units of sugar for 1 unit of spice
35-
- The trade occurs if it will (a) make both agent better off (increases MRS) and (b) does not cause the agents' MRS to
35+
- The trade occurs if it will (a) make both agent better off (increases MRS) and (b) does not cause the agents' MRS to
3636
cross over one another otherwise *end*.
37-
- This process then repeats until an *end* condition is met.
37+
- This process then repeats until an *end* condition is met.
3838
(Epstein and Axtell, 1996, p. 105)
3939

4040
The model demonstrates several Mesa concepts and features:
@@ -54,13 +54,13 @@ To install the dependencies use pip and the requirements.txt in this directory.
5454

5555
## How to Run
5656

57-
To run the model a single instance of the model:
57+
To run the model a single instance of the model:
5858

5959
```
6060
$ python run.py -s
6161
```
6262

63-
To run the model with BatchRunner:
63+
To run the model with BatchRunner:
6464

6565
```
6666
$ python run.py -b
@@ -85,5 +85,5 @@ Then open your browser to [http://127.0.0.1:8521/](http://127.0.0.1:8521/) and p
8585

8686
## Additional Resources
8787

88-
- [Growing Artificial Societies](https://mitpress.mit.edu/9780262550253/growing-artificial-societies/)
88+
- [Growing Artificial Societies](https://mitpress.mit.edu/9780262550253/growing-artificial-societies/)
8989
- [Complexity Explorer Sugarscape with Traders Tutorial](https://www.complexityexplorer.org/courses/172-agent-based-models-with-python-an-introduction-to-mesa)

examples/sugarscape_g1mt/run.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,9 @@ def assess_results(results, single_agent):
4444
G.add_edge(row["AgentID"], agent)
4545

4646
# Get Basic Network Statistics
47-
print("Node Connectivity {}".format(nx.node_connectivity(G)))
48-
print("Average Clustering {}".format(nx.average_clustering(G)))
49-
print("Global Efficiency {}".format(nx.global_efficiency(G)))
47+
print(f"Node Connectivity {nx.node_connectivity(G)}")
48+
print(f"Average Clustering {nx.average_clustering(G)}")
49+
print(f"Global Efficiency {nx.global_efficiency(G)}")
5050

5151
# Plot histogram of degree distribution
5252
degree_sequence = sorted((d for n, d in G.degree()), reverse=True)

0 commit comments

Comments
 (0)