def greedy_initialization(tasks, num_solutions=5):
solutions = []
rules = [
lambda x: x.time_window_start, # EST
lambda x: -x.time_window_end, # DD
lambda x: x.duration, # ST
]
for rule in rules:
sorted_tasks = sorted(tasks, key=rule)
schedule = list(range(len(tasks)))
for i, task in enumerate(sorted_tasks):
schedule[i] = tasks.index(task)
solutions.append(schedule)
# 如果需要更多解,可以随机打乱顺序生成
while len(solutions) < num_solutions:
np.random.shuffle(tasks)
schedule = list(range(len(tasks)))
for i, task in enumerate(tasks):
schedule[i] = tasks.index(task)
solutions.append(schedule)
return solutions
# 使用启发式规则初始化种群
initial_population = greedy_initialization(tasks, num_solutions=SIZE_POP)
ga = GA(
func=objective_function,
n_dim=n_tasks,
size_pop=SIZE_POP,
max_iter=MAX_ITER,
prob_mut=PROB_MUT,
lb=[0] * n_tasks,
ub=[n_tasks] * n_tasks,
precision=1e-7,
initial_population=initial_population # 传入启发式初始种群
)
2. 定制交叉和变异操作
标准的交叉和变异操作可能破坏良好的部分解,可以定制操作以保留优良基因。
部分映射交叉(PMX)
适用于排序问题,保留父代的部分顺序结构。
python
from sko.operators import crossover_pmx
# 在 GA 实例化时指定交叉操作
ga = GA(
...,
crossover_func=crossover_pmx
)
插入变异(Insertion Mutation)
随机选择一个基因并插入到其他位置,保持解的可行性。
python
def insertion_mutation(individual, prob):
mutated = individual.copy()
for i in range(len(mutated)):
if np.random.rand() < prob:
pos1 = i
pos2 = np.random.randint(0, len(mutated))
gene = mutated.pop(pos1)
mutated.insert(pos2, gene)
return mutated
# 在 GA 实例化时指定变异操作
ga = GA(
...,
mutate_func=insertion_mutation
)
3. 局部搜索增强
在GA迭代过程中,结合局部搜索(如2-opt, 3-opt)进一步优化个体。
python
def local_search(schedule):
improved = True
while improved:
improved = False
for i in range(len(schedule)):
for j in range(i + 1, len(schedule)):
new_schedule = schedule[:i] + schedule[i:j+1][::-1] + schedule[j+1:] # 2-opt交换
if objective_function(new_schedule) < objective_function(schedule):
schedule = new_schedule
improved = True
break
if improved:
break
return schedule
# 在GA迭代过程中应用局部搜索
for gen in range(MAX_ITER):
# GA 正常迭代
ga.next()
# 应用局部搜索
for i in range(ga.size_pop):
ga.population[i] = local_search(ga.population[i])