Skip to content

Instantly share code, notes, and snippets.

@zcliang97
Last active September 1, 2022 08:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zcliang97/7da3a7261c555a5467f636d04c15e23b to your computer and use it in GitHub Desktop.
Save zcliang97/7da3a7261c555a5467f636d04c15e23b to your computer and use it in GitHub Desktop.
An implementation of Tabu Search
"""
Tabu Search Class
"""
class TabuSearch:
def __init__(self, initialSolution, solutionEvaluator, neighborOperator, aspirationCriteria, acceptableScoreThreshold, tabuTenure):
self.currSolution = initialSolution
self.bestSolution = initialSolution
self.evaluate = solutionEvaluator
self.aspirationCriteria = aspirationCriteria
self.neighborOperator = neighborOperator
self.acceptableScoreThreshold = acceptableScoreThreshold
self.tabuTenure = tabuTenure
def isTerminationCriteriaMet(self):
# can add more termination criteria
return self.evaluate(self.bestSolution) < self.acceptableScoreThreshold \
or self.neighborOperator(self.currSolution) == 0
def run(self):
tabuList = {}
while not self.isTerminationCriteriaMet():
# get all of the neighbors
neighbors = self.neighborOperator(self.currSolution)
# find all tabuSolutions other than those
# that fit the aspiration criteria
tabuSolutions = tabuList.keys()
# find all neighbors that are not part of the Tabu list
neighbors = filter(lambda n: self.aspirationCriteria(n), neighbors)
# pick the best neighbor solution
newSolution = sorted(neighbors, key=lambda n: self.evaluate(n))[0]
# get the cost between the two solutions
cost = self.evaluate(self.solution) - self.evaluate(newSolution)
# if the new solution is better,
# update the best solution with the new solution
if cost >= 0:
self.bestSolution = newSolution
# update the current solution with the new solution
self.currSolution = newSolution
# decrement the Tabu Tenure of all tabu list solutions
for sol in tabuList:
tabuList[sol] -= 1
if tabuList[sol] == 0:
del tabuList[sol]
# add new solution to the Tabu list
tabuList[newSolution] = self.tabuTenure
# return best solution found
return self.bestSolution
@Qianhui98
Copy link

Hi, may I know that Tabu search suitable for small sample size? Like 10-20 cities. Or it is more suitable to be used for large sample size which is more than 50 cities?

@ychen306
Copy link

ychen306 commented Jul 3, 2021

I don't see you use tabuSolutions (https://gist.github.com/zcliang97/7da3a7261c555a5467f636d04c15e23b#file-tabu_search-py-L27) after it's computed. Is it a bug?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment