44"""
55
66import mesa
7-
7+ import mesa . spaces as spaces
88
99def compute_gini (model ):
1010 """Calculate gini for wealth in model.
@@ -42,18 +42,18 @@ def __init__(self, seed=None, n=100, width=10, height=10):
4242 """
4343 super ().__init__ (seed )
4444 self .num_agents = n
45- self .grid = mesa . space . MultiGrid ( width , height , True )
45+ self .grid = spaces . OrthogonalMooreGrid (( width , height ) )
4646 self .schedule = mesa .time .RandomActivation (self )
4747 self .datacollector = mesa .DataCollector (
4848 model_reporters = {"Gini" : compute_gini }, agent_reporters = {"Wealth" : "wealth" }
4949 )
5050 # Create agents
5151 for _ in range (self .num_agents ):
52- a = MoneyAgent (self )
52+ agent = MoneyAgent (self )
5353 # Add the agent to a random grid cell
54- x = self .random .randrange (self . grid . width )
55- y = self .random .randrange (self . grid . height )
56- self .grid . place_agent ( a , ( x , y ))
54+ x = self .random .randrange (width )
55+ y = self .random .randrange (height )
56+ agent . move_to ( self .grid [( x , y )] )
5757
5858 self .running = True
5959 self .datacollector .collect (self )
@@ -75,7 +75,7 @@ def run_model(self, n):
7575 self .step ()
7676
7777
78- class MoneyAgent (mesa .Agent ):
78+ class MoneyAgent (mesa .spaces . CellAgent ):
7979 """An agent with fixed initial wealth."""
8080
8181 def __init__ (self , model ):
@@ -87,27 +87,21 @@ def __init__(self, model):
8787 super ().__init__ (model )
8888 self .wealth = 1
8989
90- def move (self ):
91- """Move the agent to a random neighboring cell."""
92- possible_steps = self .model .grid .get_neighborhood (
93- self .pos , moore = True , include_center = False
94- )
95- new_position = self .random .choice (possible_steps )
96- self .model .grid .move_agent (self , new_position )
97-
9890 def give_money (self ):
99- """Give money to a random cell mate."""
100- cellmates = self .model .grid .get_cell_list_contents ([self .pos ])
101- cellmates .pop (
102- cellmates .index (self )
103- ) # Ensure agent is not giving money to itself
91+ cellmates = [agent for agent in self .cell .agents if not agent is self ]
10492 if len (cellmates ) > 0 :
10593 other = self .random .choice (cellmates )
10694 other .wealth += 1
10795 self .wealth -= 1
10896
10997 def step (self ):
11098 """Run the agent for 1 step."""
111- self .move ( )
99+ self .move_to ( self . cell . neighborhood (). select_random_cell () )
112100 if self .wealth > 0 :
113101 self .give_money ()
102+
103+
104+ if __name__ == '__main__' :
105+ model = BoltzmannWealth ()
106+ for _ in range (10 ):
107+ model .step ()
0 commit comments