pymoo:
安装:
pip install -U pymoo
例子:
条件约束请全部转化为<=的形式,不要有等式。
代码:
提示:代码编辑的有点乱,但是是最新版本pymoo5.0
"""
Created on Thu Mar 10 17:04:10 2022
@author: 18705
"""
#多目标优化问题
#可能涉及到遗传算法,还是比较激动的
#变量数下x[0]=r1,x[1]=r2,x[2]=h1,x[3]=h2
#约束数7
import autograd.numpy as anp
from pymoo.core.problem import Problem
import numpy as np
b=0.012
a=0.036
c=0.040
d=0.020#参数
class MyProblem(Problem):
def __init__(self):
super().__init__(n_var=4, # 变量数
n_obj=2, # 目标数
n_constr=7, # 约束数
xl=anp.array([0, 0, 0, 0]), # 变量下界
xu=anp.array([3, 4,10,1]), # 变量上界
)
def _evaluate(self, x, out, *args, **kwargs):
# 定义目标函数
f1 = a*np.pi*x[:, 0]**2 +c*np.pi*x[:, 1]**2+b*2*np.pi*x[:,1]*x[:,2]+d*np.pi*(x[:,0]+\
x[:,1])*(x[:,3]**2+(x[:,1]-x[:,0])**2)**0.5 # x1放在x的第0列,x2放在x的第一列
f2 = x[:,2]+2*np.pi*(x[:,0]+2*x[:,1])+(x[:,3]**2+(x[:,1]-x[:,0])**2)**0.5
# 定义约束条件
g1 = 355-np.pi*x[:,1]**2*x[:,2]-1/3*(np.pi*x[:,0]**2+np.pi*x[:,1]**2+\
np.pi*x[:,0]*x[:,1])*x[:,3]
g2 = np.pi*x[:,1]-18.56
g3 = 8.71-x[:,2]-x[:,3]
g4= 0.602-2*x[:,1]/(x[:,2]+x[:,3])
g5=0.618-0.05*0.618-(x[:,0]+x[:,1])/(x[:,2]+x[:,3])
g6=(x[:,0]+x[:,1])/(x[:,2]+x[:,3])-0.618+0.618*0.05
g7=x[:,1]-x[:,0]
# todo
out["F"] = anp.column_stack([f1, f2])
out["G"] = anp.column_stack([g1, g2,g3,g4,g5,g6,g7])
from pymoo.algorithms.moo.nsga2 import NSGA2#最新版已经发生改变
from pymoo.factory import get_sampling, get_crossover, get_mutation
from pymoo.optimize import minimize
# 定义遗传算法
algorithm = NSGA2(
pop_size=40,
n_offsprings=10,
sampling=get_sampling("real_random"),
crossover=get_crossover("real_sbx", prob=0.9, eta=15),
mutation=get_mutation("real_pm", eta=20),
eliminate_duplicates=True
)
#求解方程
res = minimize(MyProblem(),
algorithm,
('n_gen', 40),
seed=1,
return_least_infeasible=True,#在固定的迭代次数没有完成之前,算出最小值
)
#取消警告
from pymoo.config import Config
Config.show_compile_hint = False
print(res.X)
print(res.F)#显示结果
结果:
其他命令:
提示:需要具体的命令
可视化举例:
import numpy as np
A = np.random.random((20,2))
B = np.random.random((20,2))
from pymoo.factory import get_visualization
plot = get_visualization("scatter")
plot.add(A, color="green", marker="x")
plot.add(B, color="red", marker="*")
plot.show()
注:文章的代码来自pymoo官网,在写数学建模作业时,学习到相关算法,希望能帮到大家。https://pymoo.org/news.html