|
| 1 | +# https://github.com/projectmesa/mesa-examples/blob/main/examples/boltzmann_wealth_model_experimental/model.py |
| 2 | +import mesa |
| 3 | + |
| 4 | + |
| 5 | +def compute_gini(model): |
| 6 | + agent_wealths = [agent.wealth for agent in model.agents] |
| 7 | + x = sorted(agent_wealths) |
| 8 | + n = model.num_agents |
| 9 | + b = sum(xi * (n - i) for i, xi in enumerate(x)) / (n * sum(x)) |
| 10 | + return 1 + (1 / n) - 2 * b |
| 11 | + |
| 12 | + |
| 13 | +class BoltzmannWealth(mesa.Model): |
| 14 | + """A simple model of an economy where agents exchange currency at random. |
| 15 | +
|
| 16 | + All the agents begin with one unit of currency, and each time step can give |
| 17 | + a unit of currency to another agent. Note how, over time, this produces a |
| 18 | + highly skewed distribution of wealth. |
| 19 | + """ |
| 20 | + |
| 21 | + def __init__(self, seed=None, n=100, width=10, height=10): |
| 22 | + super().__init__() |
| 23 | + self.num_agents = n |
| 24 | + self.grid = mesa.space.MultiGrid(width, height, True) |
| 25 | + self.schedule = mesa.time.RandomActivation(self) |
| 26 | + self.datacollector = mesa.DataCollector( |
| 27 | + model_reporters={"Gini": compute_gini}, agent_reporters={"Wealth": "wealth"} |
| 28 | + ) |
| 29 | + # Create agents |
| 30 | + for i in range(self.num_agents): |
| 31 | + a = MoneyAgent(i, self) |
| 32 | + # Add the agent to a random grid cell |
| 33 | + x = self.random.randrange(self.grid.width) |
| 34 | + y = self.random.randrange(self.grid.height) |
| 35 | + self.grid.place_agent(a, (x, y)) |
| 36 | + |
| 37 | + self.running = True |
| 38 | + self.datacollector.collect(self) |
| 39 | + |
| 40 | + def step(self): |
| 41 | + self._advance_time() |
| 42 | + self.agents.shuffle().do("step") |
| 43 | + # collect data |
| 44 | + self.datacollector.collect(self) |
| 45 | + |
| 46 | + def run_model(self, n): |
| 47 | + for _i in range(n): |
| 48 | + self.step() |
| 49 | + |
| 50 | + |
| 51 | +class MoneyAgent(mesa.Agent): |
| 52 | + """An agent with fixed initial wealth.""" |
| 53 | + |
| 54 | + def __init__(self, unique_id, model): |
| 55 | + super().__init__(unique_id, model) |
| 56 | + self.wealth = 1 |
| 57 | + |
| 58 | + def move(self): |
| 59 | + possible_steps = self.model.grid.get_neighborhood( |
| 60 | + self.pos, moore=True, include_center=False |
| 61 | + ) |
| 62 | + new_position = self.random.choice(possible_steps) |
| 63 | + self.model.grid.move_agent(self, new_position) |
| 64 | + |
| 65 | + def give_money(self): |
| 66 | + cellmates = self.model.grid.get_cell_list_contents([self.pos]) |
| 67 | + cellmates.pop( |
| 68 | + cellmates.index(self) |
| 69 | + ) # Ensure agent is not giving money to itself |
| 70 | + if len(cellmates) > 0: |
| 71 | + other = self.random.choice(cellmates) |
| 72 | + other.wealth += 1 |
| 73 | + self.wealth -= 1 |
| 74 | + |
| 75 | + def step(self): |
| 76 | + self.move() |
| 77 | + if self.wealth > 0: |
| 78 | + self.give_money() |
0 commit comments