pymoo by davila7/claude-code-templates
npx skills add https://github.com/davila7/claude-code-templates --skill pymooPymoo 是一个全面的 Python 优化框架,专注于多目标问题。使用最先进的算法(NSGA-II/III、MOEA/D)、基准问题(ZDT、DTLZ)、可定制的遗传算子和多准则决策方法来求解单目标和多目标优化问题。擅长为具有冲突目标的问题寻找折衷解(帕累托前沿)。
此技能应在以下情况下使用:
Pymoo 对所有优化任务使用一致的 minimize() 函数:
from pymoo.optimize import minimize
result = minimize(
problem, # 优化什么
algorithm, # 如何优化
termination, # 何时停止
seed=1,
verbose=True
)
结果对象包含:
result.X:最优解(们)的决策变量result.F:最优解(们)的目标值广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
result.G:约束违反情况(如果有约束)result.algorithm:包含历史的算法对象单目标: 一个要最小化/最大化的目标 多目标: 2-3 个冲突目标 → 帕累托前沿 多目标(高维): 4 个及以上目标 → 高维帕累托前沿 约束: 目标 + 不等式/等式约束 动态: 时变目标或约束
何时使用: 优化一个目标函数
步骤:
示例:
from pymoo.algorithms.soo.nonconvex.ga import GA
from pymoo.problems import get_problem
from pymoo.optimize import minimize
# 内置问题
problem = get_problem("rastrigin", n_var=10)
# 配置遗传算法
algorithm = GA(
pop_size=100,
eliminate_duplicates=True
)
# 优化
result = minimize(
problem,
algorithm,
('n_gen', 200),
seed=1,
verbose=True
)
print(f"Best solution: {result.X}")
print(f"Best objective: {result.F[0]}")
参见: scripts/single_objective_example.py 获取完整示例
何时使用: 优化 2-3 个冲突目标,需要帕累托前沿
算法选择: NSGA-II(双/三目标问题的标准算法)
步骤:
示例:
from pymoo.algorithms.moo.nsga2 import NSGA2
from pymoo.problems import get_problem
from pymoo.optimize import minimize
from pymoo.visualization.scatter import Scatter
# 双目标基准问题
problem = get_problem("zdt1")
# NSGA-II 算法
algorithm = NSGA2(pop_size=100)
# 优化
result = minimize(problem, algorithm, ('n_gen', 200), seed=1)
# 可视化帕累托前沿
plot = Scatter()
plot.add(result.F, label="Obtained Front")
plot.add(problem.pareto_front(), label="True Front", alpha=0.3)
plot.show()
print(f"Found {len(result.F)} Pareto-optimal solutions")
参见: scripts/multi_objective_example.py 获取完整示例
何时使用: 优化 4 个或更多目标
算法选择: NSGA-III(专为多目标设计)
关键区别: 必须提供参考方向以指导种群
步骤:
示例:
from pymoo.algorithms.moo.nsga3 import NSGA3
from pymoo.problems import get_problem
from pymoo.optimize import minimize
from pymoo.util.ref_dirs import get_reference_directions
from pymoo.visualization.pcp import PCP
# 多目标问题(5 个目标)
problem = get_problem("dtlz2", n_obj=5)
# 生成参考方向(NSGA-III 必需)
ref_dirs = get_reference_directions("das-dennis", n_dim=5, n_partitions=12)
# 配置 NSGA-III
algorithm = NSGA3(ref_dirs=ref_dirs)
# 优化
result = minimize(problem, algorithm, ('n_gen', 300), seed=1)
# 使用平行坐标可视化
plot = PCP(labels=[f"f{i+1}" for i in range(5)])
plot.add(result.F, alpha=0.3)
plot.show()
参见: scripts/many_objective_example.py 获取完整示例
何时使用: 解决特定领域的优化问题
步骤:
ElementwiseProblem 类__init__ 中定义问题维度和边界_evaluate 方法无约束示例:
from pymoo.core.problem import ElementwiseProblem
import numpy as np
class MyProblem(ElementwiseProblem):
def __init__(self):
super().__init__(
n_var=2, # 变量数量
n_obj=2, # 目标数量
xl=np.array([0, 0]), # 下界
xu=np.array([5, 5]) # 上界
)
def _evaluate(self, x, out, *args, **kwargs):
# 定义目标
f1 = x[0]**2 + x[1]**2
f2 = (x[0]-1)**2 + (x[1]-1)**2
out["F"] = [f1, f2]
约束示例:
class ConstrainedProblem(ElementwiseProblem):
def __init__(self):
super().__init__(
n_var=2,
n_obj=2,
n_ieq_constr=2, # 不等式约束
n_eq_constr=1, # 等式约束
xl=np.array([0, 0]),
xu=np.array([5, 5])
)
def _evaluate(self, x, out, *args, **kwargs):
# 目标
out["F"] = [f1, f2]
# 不等式约束 (g <= 0)
out["G"] = [g1, g2]
# 等式约束 (h = 0)
out["H"] = [h1]
约束公式规则:
g(x) <= 0(当 ≤ 0 时可行)h(x) = 0(当 = 0 时可行)g(x) >= b 转换为 -(g(x) - b) <= 0参见: scripts/custom_problem_example.py 获取完整示例
何时使用: 问题具有可行性约束
方法选项:
1. 可行性优先(默认 - 推荐)
from pymoo.algorithms.moo.nsga2 import NSGA2
# 自动处理约束问题
algorithm = NSGA2(pop_size=100)
result = minimize(problem, algorithm, termination)
# 检查可行性
feasible = result.CV[:, 0] == 0 # CV = 约束违反
print(f"Feasible solutions: {np.sum(feasible)}")
2. 惩罚方法
from pymoo.constraints.as_penalty import ConstraintsAsPenalty
# 包装问题以将约束转换为惩罚
problem_penalized = ConstraintsAsPenalty(problem, penalty=1e6)
3. 约束作为目标
from pymoo.constraints.as_obj import ConstraintsAsObjective
# 将约束违反视为附加目标
problem_with_cv = ConstraintsAsObjective(problem)
4. 专用算法
from pymoo.algorithms.soo.nonconvex.sres import SRES
# SRES 具有内置的约束处理能力
algorithm = SRES()
参见: references/constraints_mcdm.md 获取全面的约束处理指南
何时使用: 拥有帕累托前沿,需要选择偏好的解
步骤:
使用伪权重的示例:
from pymoo.mcdm.pseudo_weights import PseudoWeights
import numpy as np
# 从多目标优化获得结果后
# 归一化目标
F_norm = (result.F - result.F.min(axis=0)) / (result.F.max(axis=0) - result.F.min(axis=0))
# 定义偏好(必须总和为 1)
weights = np.array([0.3, 0.7]) # 30% f1, 70% f2
# 应用决策
dm = PseudoWeights(weights)
selected_idx = dm.do(F_norm)
# 获取选定的解
best_solution = result.X[selected_idx]
best_objectives = result.F[selected_idx]
print(f"Selected solution: {best_solution}")
print(f"Objective values: {best_objectives}")
其他 MCDM 方法:
参见:
scripts/decision_making_example.py 获取完整示例references/constraints_mcdm.md 获取详细的 MCDM 方法根据目标数量选择可视化方法:
2 个目标:散点图
from pymoo.visualization.scatter import Scatter
plot = Scatter(title="Bi-objective Results")
plot.add(result.F, color="blue", alpha=0.7)
plot.show()
3 个目标:3D 散点图
plot = Scatter(title="Tri-objective Results")
plot.add(result.F) # 自动以 3D 渲染
plot.show()
4 个及以上目标:平行坐标图
from pymoo.visualization.pcp import PCP
plot = PCP(
labels=[f"f{i+1}" for i in range(n_obj)],
normalize_each_axis=True
)
plot.add(result.F, alpha=0.3)
plot.show()
解决方案比较:花瓣图
from pymoo.visualization.petal import Petal
plot = Petal(
bounds=[result.F.min(axis=0), result.F.max(axis=0)],
labels=["Cost", "Weight", "Efficiency"]
)
plot.add(solution_A, label="Design A")
plot.add(solution_B, label="Design B")
plot.show()
参见: references/visualization.md 获取所有可视化类型和用法
| 算法 | 最适合 | 关键特性 |
|---|---|---|
| GA | 通用 | 灵活,可定制的算子 |
| DE | 连续优化 | 良好的全局搜索能力 |
| PSO | 平滑的景观 | 快速收敛 |
| CMA-ES | 困难/有噪声的问题 | 自适应 |
| 算法 | 最适合 | 关键特性 |
|---|---|---|
| NSGA-II | 标准基准 | 快速、可靠、经过充分测试 |
| R-NSGA-II | 偏好区域 | 参考点引导 |
| MOEA/D | 可分解问题 | 标量化方法 |
| 算法 | 最适合 | 关键特性 |
|---|---|---|
| NSGA-III | 4-15 个目标 | 基于参考方向 |
| RVEA | 自适应搜索 | 参考向量进化 |
| AGE-MOEA | 复杂景观 | 自适应几何 |
| 方法 | 算法 | 何时使用 |
|---|---|---|
| 可行性优先 | 任何算法 | 可行域较大 |
| 专用算法 | SRES, ISRES | 约束较多 |
| 惩罚方法 | GA + 惩罚 | 算法兼容性 |
参见: references/algorithms.md 获取全面的算法参考
from pymoo.problems import get_problem
# 单目标
problem = get_problem("rastrigin", n_var=10)
problem = get_problem("rosenbrock", n_var=10)
# 多目标
problem = get_problem("zdt1") # 凸前沿
problem = get_problem("zdt2") # 非凸前沿
problem = get_problem("zdt3") # 不连续前沿
# 多目标(高维)
problem = get_problem("dtlz2", n_obj=5, n_var=12)
problem = get_problem("dtlz7", n_obj=4)
参见: references/problems.md 获取完整的测试问题参考
from pymoo.algorithms.soo.nonconvex.ga import GA
from pymoo.operators.crossover.sbx import SBX
from pymoo.operators.mutation.pm import PM
algorithm = GA(
pop_size=100,
crossover=SBX(prob=0.9, eta=15),
mutation=PM(eta=20),
eliminate_duplicates=True
)
连续变量:
二进制变量:
排列(TSP,调度):
参见: references/operators.md 获取全面的算子参考
问题:算法不收敛
问题:帕累托前沿分布不佳
问题:可行解很少
问题:计算成本高
save_history=True此技能包含全面的参考文档和可执行示例:
详细文档供深入理解:
参考资料的搜索模式:
grep -r "NSGA-II\|NSGA-III\|MOEA/D" references/grep -r "Feasibility First\|Penalty\|Repair" references/grep -r "Scatter\|PCP\|Petal" references/演示常见工作流的可执行示例:
运行示例:
python3 scripts/single_objective_example.py
python3 scripts/multi_objective_example.py
python3 scripts/many_objective_example.py
python3 scripts/custom_problem_example.py
python3 scripts/decision_making_example.py
安装:
uv pip install pymoo
依赖项: NumPy, SciPy, matplotlib, autograd(用于基于梯度的优化,可选)
版本: 此技能基于 pymoo 0.6.x
常见模式:
ElementwiseProblemg(x) <= 0 和 h(x) = 0('n_gen', N) 或 get_termination("f_tol", tol=0.001)每周安装
136
仓库
GitHub 星标
22.6K
首次出现
2026 年 1 月 21 日
安全审计
安装于
claude-code117
opencode111
cursor105
gemini-cli104
antigravity97
codex93
Pymoo is a comprehensive Python framework for optimization with emphasis on multi-objective problems. Solve single and multi-objective optimization using state-of-the-art algorithms (NSGA-II/III, MOEA/D), benchmark problems (ZDT, DTLZ), customizable genetic operators, and multi-criteria decision making methods. Excels at finding trade-off solutions (Pareto fronts) for problems with conflicting objectives.
This skill should be used when:
Pymoo uses a consistent minimize() function for all optimization tasks:
from pymoo.optimize import minimize
result = minimize(
problem, # What to optimize
algorithm, # How to optimize
termination, # When to stop
seed=1,
verbose=True
)
Result object contains:
result.X: Decision variables of optimal solution(s)result.F: Objective values of optimal solution(s)result.G: Constraint violations (if constrained)result.algorithm: Algorithm object with historySingle-objective: One objective to minimize/maximize Multi-objective: 2-3 conflicting objectives → Pareto front Many-objective: 4+ objectives → High-dimensional Pareto front Constrained: Objectives + inequality/equality constraints Dynamic: Time-varying objectives or constraints
When: Optimizing one objective function
Steps:
Example:
from pymoo.algorithms.soo.nonconvex.ga import GA
from pymoo.problems import get_problem
from pymoo.optimize import minimize
# Built-in problem
problem = get_problem("rastrigin", n_var=10)
# Configure Genetic Algorithm
algorithm = GA(
pop_size=100,
eliminate_duplicates=True
)
# Optimize
result = minimize(
problem,
algorithm,
('n_gen', 200),
seed=1,
verbose=True
)
print(f"Best solution: {result.X}")
print(f"Best objective: {result.F[0]}")
See: scripts/single_objective_example.py for complete example
When: Optimizing 2-3 conflicting objectives, need Pareto front
Algorithm choice: NSGA-II (standard for bi/tri-objective)
Steps:
Example:
from pymoo.algorithms.moo.nsga2 import NSGA2
from pymoo.problems import get_problem
from pymoo.optimize import minimize
from pymoo.visualization.scatter import Scatter
# Bi-objective benchmark problem
problem = get_problem("zdt1")
# NSGA-II algorithm
algorithm = NSGA2(pop_size=100)
# Optimize
result = minimize(problem, algorithm, ('n_gen', 200), seed=1)
# Visualize Pareto front
plot = Scatter()
plot.add(result.F, label="Obtained Front")
plot.add(problem.pareto_front(), label="True Front", alpha=0.3)
plot.show()
print(f"Found {len(result.F)} Pareto-optimal solutions")
See: scripts/multi_objective_example.py for complete example
When: Optimizing 4 or more objectives
Algorithm choice: NSGA-III (designed for many objectives)
Key difference: Must provide reference directions for population guidance
Steps:
Example:
from pymoo.algorithms.moo.nsga3 import NSGA3
from pymoo.problems import get_problem
from pymoo.optimize import minimize
from pymoo.util.ref_dirs import get_reference_directions
from pymoo.visualization.pcp import PCP
# Many-objective problem (5 objectives)
problem = get_problem("dtlz2", n_obj=5)
# Generate reference directions (required for NSGA-III)
ref_dirs = get_reference_directions("das-dennis", n_dim=5, n_partitions=12)
# Configure NSGA-III
algorithm = NSGA3(ref_dirs=ref_dirs)
# Optimize
result = minimize(problem, algorithm, ('n_gen', 300), seed=1)
# Visualize with Parallel Coordinates
plot = PCP(labels=[f"f{i+1}" for i in range(5)])
plot.add(result.F, alpha=0.3)
plot.show()
See: scripts/many_objective_example.py for complete example
When: Solving domain-specific optimization problem
Steps:
ElementwiseProblem class__init__ with problem dimensions and bounds_evaluate method for objectives (and constraints)Unconstrained example:
from pymoo.core.problem import ElementwiseProblem
import numpy as np
class MyProblem(ElementwiseProblem):
def __init__(self):
super().__init__(
n_var=2, # Number of variables
n_obj=2, # Number of objectives
xl=np.array([0, 0]), # Lower bounds
xu=np.array([5, 5]) # Upper bounds
)
def _evaluate(self, x, out, *args, **kwargs):
# Define objectives
f1 = x[0]**2 + x[1]**2
f2 = (x[0]-1)**2 + (x[1]-1)**2
out["F"] = [f1, f2]
Constrained example:
class ConstrainedProblem(ElementwiseProblem):
def __init__(self):
super().__init__(
n_var=2,
n_obj=2,
n_ieq_constr=2, # Inequality constraints
n_eq_constr=1, # Equality constraints
xl=np.array([0, 0]),
xu=np.array([5, 5])
)
def _evaluate(self, x, out, *args, **kwargs):
# Objectives
out["F"] = [f1, f2]
# Inequality constraints (g <= 0)
out["G"] = [g1, g2]
# Equality constraints (h = 0)
out["H"] = [h1]
Constraint formulation rules:
g(x) <= 0 (feasible when ≤ 0)h(x) = 0 (feasible when = 0)g(x) >= b to -(g(x) - b) <= 0See: scripts/custom_problem_example.py for complete examples
When: Problem has feasibility constraints
Approach options:
1. Feasibility First (Default - Recommended)
from pymoo.algorithms.moo.nsga2 import NSGA2
# Works automatically with constrained problems
algorithm = NSGA2(pop_size=100)
result = minimize(problem, algorithm, termination)
# Check feasibility
feasible = result.CV[:, 0] == 0 # CV = constraint violation
print(f"Feasible solutions: {np.sum(feasible)}")
2. Penalty Method
from pymoo.constraints.as_penalty import ConstraintsAsPenalty
# Wrap problem to convert constraints to penalties
problem_penalized = ConstraintsAsPenalty(problem, penalty=1e6)
3. Constraint as Objective
from pymoo.constraints.as_obj import ConstraintsAsObjective
# Treat constraint violation as additional objective
problem_with_cv = ConstraintsAsObjective(problem)
4. Specialized Algorithms
from pymoo.algorithms.soo.nonconvex.sres import SRES
# SRES has built-in constraint handling
algorithm = SRES()
See: references/constraints_mcdm.md for comprehensive constraint handling guide
When: Have Pareto front, need to select preferred solution(s)
Steps:
Example using Pseudo-Weights:
from pymoo.mcdm.pseudo_weights import PseudoWeights
import numpy as np
# After obtaining result from multi-objective optimization
# Normalize objectives
F_norm = (result.F - result.F.min(axis=0)) / (result.F.max(axis=0) - result.F.min(axis=0))
# Define preferences (must sum to 1)
weights = np.array([0.3, 0.7]) # 30% f1, 70% f2
# Apply decision making
dm = PseudoWeights(weights)
selected_idx = dm.do(F_norm)
# Get selected solution
best_solution = result.X[selected_idx]
best_objectives = result.F[selected_idx]
print(f"Selected solution: {best_solution}")
print(f"Objective values: {best_objectives}")
Other MCDM methods:
See:
scripts/decision_making_example.py for complete examplereferences/constraints_mcdm.md for detailed MCDM methodsChoose visualization based on number of objectives:
2 objectives: Scatter Plot
from pymoo.visualization.scatter import Scatter
plot = Scatter(title="Bi-objective Results")
plot.add(result.F, color="blue", alpha=0.7)
plot.show()
3 objectives: 3D Scatter
plot = Scatter(title="Tri-objective Results")
plot.add(result.F) # Automatically renders in 3D
plot.show()
4+ objectives: Parallel Coordinate Plot
from pymoo.visualization.pcp import PCP
plot = PCP(
labels=[f"f{i+1}" for i in range(n_obj)],
normalize_each_axis=True
)
plot.add(result.F, alpha=0.3)
plot.show()
Solution comparison: Petal Diagram
from pymoo.visualization.petal import Petal
plot = Petal(
bounds=[result.F.min(axis=0), result.F.max(axis=0)],
labels=["Cost", "Weight", "Efficiency"]
)
plot.add(solution_A, label="Design A")
plot.add(solution_B, label="Design B")
plot.show()
See: references/visualization.md for all visualization types and usage
| Algorithm | Best For | Key Features |
|---|---|---|
| GA | General-purpose | Flexible, customizable operators |
| DE | Continuous optimization | Good global search |
| PSO | Smooth landscapes | Fast convergence |
| CMA-ES | Difficult/noisy problems | Self-adapting |
| Algorithm | Best For | Key Features |
|---|---|---|
| NSGA-II | Standard benchmark | Fast, reliable, well-tested |
| R-NSGA-II | Preference regions | Reference point guidance |
| MOEA/D | Decomposable problems | Scalarization approach |
| Algorithm | Best For | Key Features |
|---|---|---|
| NSGA-III | 4-15 objectives | Reference direction-based |
| RVEA | Adaptive search | Reference vector evolution |
| AGE-MOEA | Complex landscapes | Adaptive geometry |
| Approach | Algorithm | When to Use |
|---|---|---|
| Feasibility-first | Any algorithm | Large feasible region |
| Specialized | SRES, ISRES | Heavy constraints |
| Penalty | GA + penalty | Algorithm compatibility |
See: references/algorithms.md for comprehensive algorithm reference
from pymoo.problems import get_problem
# Single-objective
problem = get_problem("rastrigin", n_var=10)
problem = get_problem("rosenbrock", n_var=10)
# Multi-objective
problem = get_problem("zdt1") # Convex front
problem = get_problem("zdt2") # Non-convex front
problem = get_problem("zdt3") # Disconnected front
# Many-objective
problem = get_problem("dtlz2", n_obj=5, n_var=12)
problem = get_problem("dtlz7", n_obj=4)
See: references/problems.md for complete test problem reference
from pymoo.algorithms.soo.nonconvex.ga import GA
from pymoo.operators.crossover.sbx import SBX
from pymoo.operators.mutation.pm import PM
algorithm = GA(
pop_size=100,
crossover=SBX(prob=0.9, eta=15),
mutation=PM(eta=20),
eliminate_duplicates=True
)
Continuous variables:
Binary variables:
Permutations (TSP, scheduling):
See: references/operators.md for comprehensive operator reference
Problem: Algorithm not converging
Problem: Poor Pareto front distribution
Problem: Few feasible solutions
Problem: High computational cost
save_history=TrueThis skill includes comprehensive reference documentation and executable examples:
Detailed documentation for in-depth understanding:
Search patterns for references:
grep -r "NSGA-II\|NSGA-III\|MOEA/D" references/grep -r "Feasibility First\|Penalty\|Repair" references/grep -r "Scatter\|PCP\|Petal" references/Executable examples demonstrating common workflows:
Run examples:
python3 scripts/single_objective_example.py
python3 scripts/multi_objective_example.py
python3 scripts/many_objective_example.py
python3 scripts/custom_problem_example.py
python3 scripts/decision_making_example.py
Installation:
uv pip install pymoo
Dependencies: NumPy, SciPy, matplotlib, autograd (optional for gradient-based)
Documentation: https://pymoo.org/
Version: This skill is based on pymoo 0.6.x
Common patterns:
ElementwiseProblem for custom problemsg(x) <= 0 and h(x) = 0('n_gen', N) or get_termination("f_tol", tol=0.001)Weekly Installs
136
Repository
GitHub Stars
22.6K
First Seen
Jan 21, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
claude-code117
opencode111
cursor105
gemini-cli104
antigravity97
codex93
AI 代码实施计划编写技能 | 自动化开发任务分解与 TDD 流程规划工具
46,800 周安装