Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

aoc_tsp: Replace scheduler with AgentSet functionality #191

Merged
merged 1 commit into from
Sep 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
Loading