數(shù)學(xué)建模導(dǎo)論:基于Python語言(2022年秋季學(xué)期)

1.4案例一遺傳代碼,小白供參考

import numpy as np from sko.GA import GA import math # x[0] x[1] 存A點(diǎn)坐標(biāo) 2-7 存運(yùn)送量 x[8] x[9] 存B點(diǎn)坐標(biāo) 10-15 存運(yùn)送量 def object_fun(x): # 目標(biāo)函數(shù) 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__" : # 等式約束條件-----每個(gè)工地從兩個(gè)料場獲得的量 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] # 不等式約束條件---每個(gè)料場總送出量小于等于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)
標(biāo)簽: