[Algorithm] Taboo algorithm + TSP problem python code

1. The concept of taboo algorithm

Tabu search is an optimization algorithm that simulates human intelligence.Mimics the function of human memory, in the process of solving the problem, the taboo technique is used,Mark the local optimal solution that has been searched, and try to iterateAvoid repeating the same search(but not completely eliminated), so as to obtain a wider search interval, which is conducive to finding the global optimal solution.
insert image description here

2. Explanation of related terms

1. Taboo Object (Tabu Object, TO)

Refers to those variable elements that are prohibited in the taboo list.
For example, in the traveling salesman problem (TSP), the exchanged city pairs can be used as taboo objects, and the total path length can also be used as taboo objects.

2. Taboo List (Tabu List, TL)

A table used to store (remember) taboo objects. It is the basic premise for tabu search to be carried out. The tabu table itself is limited in capacity , and its size affects the number of stored tabu objects and affects the performance of the algorithm.

3. Tabu Tenure (TT)

Also called taboo length, it refers to the period during which taboo objects cannot be selected.
If the taboo period is too short, it is easy to have a cycle, and it is impossible to jump out of the local optimum.
Excessively long urgency deadlines can result in excessively long calculation times.

4. Aspiration Criteria (AC)

Also known as the amnesty rule. When all objects are tabooed, the best performing forbidden object can be unbanned , or the amnesty rule can also be used when unbanning an object will lead to a large improvement in the target value.

insert image description here

5. Termination criteria

three methods:

  1. Given the maximum number of iteration steps.

  2. Sets the maximum taboo frequency for an object.

  3. Set the deviation range of the fit value.

insert image description here

3. Basic flow of the algorithm

Created with Raphaël 2.3.0 开始 初始化,随机生成一个解i,设置代数k=0,禁忌表H为空,最优解s = i 满足终止条件? 退出 构造解i的邻域 A = N(i, H) 从邻域A中找出适应值最好的解j,令i=j,并且更新H f(i)<f(s)? s=i k=k+1 yes no yes no

4. TSP problem

It is known that a traveling salesman problem is a four-city (a, b, c, d) problem, and the distance between cities is shown in the matrix D. For convenience, it is assumed that the neighborhood map is defined as the exchange of two cities, and the starting point and The end cities are all a. Please analyze the process and main steps of the previous three generations of solving this problem using the tabu search algorithm.

insert image description here

The main steps:

insert image description here

python code

1. Import the package.

import time
import numpy as np
import random

2. Set the parameter value of the taboo algorithm.
The taboo length is 2.

# m城市个数  best全局最优  tl初始禁忌长度
# time 迭代次数, spe特赦值
# tabu禁忌表
# best_way 最优解 now_way当前解
# dis两点距离
global m, best, tl
global time, spe
best = 4.0
m= 4
tl = 2
spe= 2
time = 100
tabu = [[0] * (m) for i in range(m)]
best_way =[0] * m
now_way = [0] * m
dis = [[0] * (m) for i in range(m)]

3. Generate an initial solution.

def rand(g):
    vis = [0]*m
    for i in range(m):
        vis[i] = 0;
    g[0] = 0  # 必定要从第一个城市a出发
    vis[0] = 1
    on = 1
    while on < m:
        te = random.randint(1, m - 1) # 随机选择一个城市
        if(vis[te] == 0):
            vis[te] = 1
            g[on] = te
            on += 1

4. Calculate the route length of solution t.

def get_value(t):
    ans = 0.0
    for i in range(1, m):
        ans += dis[t[i-1]][t[i]]
    ans += dis[t[i-1]][t[i]]
    return ans

5. Copy the current solution to the optimal solution array.

def cop(a,b):
    for i in range(m):
        a[i] = b[i]

6. Initialize the taboo table and calculate the path value of the initial solution.

def init():
    global best
    for i in range(m):
        for j in range(m):
            tabu[i][j] = 0  #初始化禁忌表
    rand(now_way)           #生成初始解作为当前解
    now = get_value(now_way)
    cop(best_way, now_way)
    best = now

7. Taboo algorithm.

def slove():
    global best, now
    temp = [0] * m       # 中间变量记录交换结果
    a = 0                # 记录交换城市下标
    b = 0
    ob_way = [0] * m
    cop(ob_way, now_way)
    ob_value = get_value(now_way)    # 暂存邻域最优解
    for i in range(1, m):            # 搜索所有邻域
        for j in range(1, m):
            if(i + j >= m): break;
            if(i == j): continue;
            cop(temp, now_way)
            temp[i], temp[i + j] = temp[i + j], temp[i]
            value = get_value(temp)
            if(value <= best and tabu[i][i + j] < spe): # 如果优于全局最优且禁忌长度小于特赦值
                cop(best_way, temp)
                best = value
                a = i
                b = i + j         #更新全局最优且接受新解

                cop(ob_way, temp)
                ob_value = value
            elif(tabu[i][i + j] == 0 and value < ob_value): # 如果优于邻域中的最优解则接受新解
                cop(ob_way, temp)
                ob_value = value
                a = i
                b = i + j
    cop(now_way, ob_way)  # 更新当前解
    for i in range(m):    # 更新禁忌表
        for j in range(m):
            if(tabu[i][j] > 0):
                tabu[i][j] -= 1
    tabu[a][b] = tl  #重置a,b两个交换城市的禁忌值

8. Main function:

if __name__ == '__main__':
    dis = np.array([[0, 1, 0.5, 1],
                    [1, 0, 1, 1],
                    [1.5, 5, 0, 1],
                    [1, 1, 1, 0]])
    init()                                # 数据初始化
    for i in range(time):                 # 控制迭代次数
        slove()
    print("路线总长度: ", round(best,3))   # 打印最优解距离保留三位小数
    print("具体路线: ", best_way)

9. Running result:
insert image description here

END

insert image description here

Guess you like

Origin blog.csdn.net/qq_51669241/article/details/129529728