数学建模导论:基于Python语言(2022年秋季学期)
1.4案例一遗传代码,小白供参考

import numpy as np
from sko.GA import GA
import math
# x[0] x[1] 存A点坐标 2-7 存运送量 x[8] x[9] 存B点坐标 10-15 存运送量
def object_fun(x): # 目标函数
return math.sqrt((x[0] - 1.25)**2 + (x[1] - 1.25)**2) * x[2] \
+ math.sqrt((x[0] - 8.75)**2 + (x[1] - 0.75)**2) * x[3] \
+ math.sqrt((x[0] - 0.5)**2 + (x[1] - 4.75)**2) * x[4] \
+ math.sqrt((x[0] - 5.75)**2 + (x[1] - 5)**2) * x[5] \
+ math.sqrt((x[0] - 3)**2 + (x[1] - 6.5)**2) * x[6] \
+ math.sqrt((x[0] - 7.25)**2 + (x[1] - 7.25)**2) * x[7] \
+ math.sqrt((x[8] - 1.25)**2 + (x[9] - 1.25)**2) * x[10] \
+ math.sqrt((x[8] - 8.75)**2 + (x[9] - 0.75)**2) * x[11] \
+ math.sqrt((x[8] - 0.5)**2 + (x[9] - 4.75)**2) * x[12] \
+ math.sqrt((x[8] - 5.75)**2 + (x[9] - 5)**2) * x[13] \
+ math.sqrt((x[8] - 3)**2 + (x[9] - 6.5)**2) * x[14] \
+ math.sqrt((x[8] - 7.25)**2 + (x[9] - 7.25)**2) * x[15]
if __name__ == "__main__" :
# 等式约束条件-----每个工地从两个料场获得的量
cons_eq = [lambda x: x[2] + x[10] - 3, lambda x: x[3] + x[11] - 5, lambda x: x[4] + x[12] - 4,
lambda x: x[5] + x[13] - 7, lambda x: x[6] + x[14] - 6, lambda x: x[7] + x[15] - 11]
# 不等式约束条件---每个料场总送出量小于等于20 A != B
cons_uq = [lambda x: -(x[2] + x[3] + x[4] + x[5] + x[6] + x[7] - 20),
lambda x: -(x[10] + x[11] + x[12] + x[13] + x[14] + x[15] - 20),
lambda x: x[0] != x[8], lambda x: x[1] != x[9]]
m_lb = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
m_ub = [10, 10, 3, 5, 4, 7, 6, 11, 10, 10, 3, 5, 4, 7, 6, 11]
ga = GA(func=object_fun, n_dim=16, size_pop=50, max_iter=500, lb=m_lb, ub=m_ub, constraint_eq=cons_eq, constraint_ueq=cons_uq)
best_x, best_y = ga.run()
print('best_x:', best_x)
print('best_y:', best_y)

