Py.Cafe

psn_pro/

mesa-wealth-distribution

Wealth Distribution with Mesa Agents

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import mesa
from mesa.visualization import SolaraViz, make_space_component

# 1. Создаем класс агента
class MoneyAgent(mesa.Agent):
    def __init__(self, model):
        # ИСПРАВЛЕНО: Передаем уникальный ID автоматической генерации и модель
        super().__init__(model.next_id(), model)
        self.wealth = 1  

    def step(self):
        if self.wealth == 0:
            return
        
        # Перемещаемся в случайную соседнюю клетку
        possible_steps = self.model.grid.get_neighborhood(
            self.pos, moore=True, include_center=False
        )
        new_position = self.random.choice(possible_steps)
        self.model.grid.move_agent(self, new_position)
        
        # Если на новой клетке есть другие агенты, отдаем одному из них монету
        cell_mates = self.model.grid.get_cell_list_contents([self.pos])
        if len(cell_mates) > 1:
            other_agent = self.random.choice(cell_mates)
            if other_agent != self:
                other_agent.wealth += 1
                self.wealth -= 1

# 2. Создаем класс модели
class MoneyModel(mesa.Model):
    def __init__(self, width=15, height=15, n_agents=40):
        super().__init__()
        self.grid = mesa.space.MultiGrid(width, height, torus=True)
        
        for _ in range(n_agents):
            agent = MoneyAgent(self)
            self.grid.place_agent(agent, self.grid.find_empty())

    def step(self):
        # ИСПРАВЛЕНО: Новый синтаксис запуска шага для всех агентов в Mesa 3.0
        self.agents.do("step")

# 3. Настраиваем внешний вид агентов
def agent_portrayal(agent):
    if agent.wealth == 0:
        color = "tab:red"      
    elif agent.wealth == 1:
        color = "tab:blue"     
    else:
        color = "tab:green"    
    return {"type": "circle", "color": color, "size": 60}

# 4. Параметры для слайдеров в UI
model_params = {
    "n_agents": {
        "type": "SliderInt",
        "value": 40,
        "label": "Число участников",
        "min": 10,
        "max": 100,
    }
}

# 5. Инициализируем интерфейс SolaraViz
page = SolaraViz(
    model_class=MoneyModel,
    model_params=model_params,
    components=[make_space_component(agent_portrayal)]
)