Skip to content

Commit

Permalink
aoc_tsp: Replace scheduler with AgentSet functionality
Browse files Browse the repository at this point in the history
Also use the new, standardized order of count-do-collect.
  • Loading branch information
EwoutH committed Sep 3, 2024
1 parent 679b677 commit db053ad
Showing 1 changed file with 7 additions and 10 deletions.
17 changes: 7 additions & 10 deletions examples/aco_tsp/aco_tsp/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,6 @@ class AcoTspModel(mesa.Model):
There is only one model-level parameter: how many agents the model contains. When a new model
is started, we want it to populate itself with the given number of agents.
The scheduler is a special model component which controls the order in which agents are activated.
"""

def __init__(
Expand All @@ -176,12 +174,10 @@ def __init__(
self.num_cities = tsp_graph.num_cities
self.all_cities = set(range(self.num_cities))
self.max_steps = max_steps
self.schedule = mesa.time.RandomActivation(self)
self.grid = mesa.space.NetworkGrid(tsp_graph.g)

for i in range(self.num_agents):
agent = AntTSP(unique_id=i, model=self, alpha=ant_alpha, beta=ant_beta)
self.schedule.add(agent)

city = tsp_graph.cities[self.random.randrange(self.num_cities)]
self.grid.place_agent(agent, city)
Expand All @@ -206,14 +202,15 @@ def __init__(
"tsp_solution": "tsp_solution",
},
)
self.datacollector.collect(self) # Collect initial state at steps=0

self.running = True

def update_pheromone(self, q: float = 100, ro: float = 0.5):
# tau_ij(t+1) = (1-ro)*tau_ij(t) + delta_tau_ij(t)
# delta_tau_ij(t) = sum_k^M {Q/L^k} * I[i,j \in T^k]
delta_tau_ij = {}
for k, agent in enumerate(self.schedule.agents):
for k, agent in enumerate(self.agents):
delta_tau_ij[k] = agent.calculate_pheromone_delta(q)

for i, j in self.grid.G.edges():
Expand All @@ -227,16 +224,14 @@ def update_pheromone(self, q: float = 100, ro: float = 0.5):

def step(self):
"""
A model step. Used for collecting data and advancing the schedule
A model step. Used for activating the agents and collecting data.
"""
self.datacollector.collect(self)
self.schedule.step()
self.num_steps += 1
self.agents.shuffle().do("step")
self.update_pheromone()

# Check len of cities visited by an agent
best_instance_iter = float("inf")
for agent in self.schedule.agents:
for agent in self.agents:
# Check for best path
if agent.tsp_distance < self.best_distance:
self.best_distance = agent.tsp_distance
Expand All @@ -249,3 +244,5 @@ def step(self):

if self.num_steps >= self.max_steps:
self.running = False

self.datacollector.collect(self)

0 comments on commit db053ad

Please sign in to comment.