[ PROMPT_NODE_27144 ]
constraints_mcdm
[ SKILL_DOCUMENTATION ]
# Pymoo 约束与决策参考
关于 pymoo 中约束处理和多准则决策分析的参考。
## 约束处理
### 定义约束
约束在问题定义中指定:
python
from pymoo.core.problem import ElementwiseProblem
import numpy as np
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):
# 目标函数
f1 = x[0]**2 + x[1]**2
f2 = (x[0]-1)**2 + (x[1]-1)**2
out["F"] = [f1, f2]
# 不等式约束 (形式为 g(x) = 5 → -(x[0] + x[1] - 5) <= 0
g2 = x[0]**2 + x[1]**2 - 25 # x[0]^2 + x[1]^2 <= 25
out["G"] = [g1, g2]
# 等式约束 (形式为 h(x) = 0)
h1 = x[0] - 2*x[1]
out["H"] = [h1]
**约束公式规则:**
- 不等式:`g(x) = 0` 转换为 `-g(x) <= 0`
### 约束处理技术
#### 1. 可行性优先 (默认)
**机制:** 始终优先选择可行解而非不可行解
**比较:**
1. 均为可行解 → 按目标函数值比较
2. 一个可行,一个不可行 → 可行解胜出
3. 均为不可行解 → 按约束违反程度比较
**用法:**
python
from pymoo.algorithms.moo.nsga2 import NSGA2
# 大多数算法默认使用可行性优先
algorithm = NSGA2(pop_size=100)
**优点:**
- 适用于任何基于排序的算法
- 简单有效
- 无需参数调整
**缺点:**
- 在可行域较小时可能表现不佳
- 可能忽略优秀的不可行解
#### 2. 惩罚函数法
**机制:** 根据约束违反程度向目标函数添加惩罚项
**公式:** `F_penalized = F + penalty_factor * violation`
**用法:**
python
from pymoo.algorithms.soo.nonconvex.ga import GA
from pymoo.constraints.as_penalty import ConstraintsAsPenalty
# 使用惩罚项包装问题
problem_with_penalty = ConstraintsAsPenalty(problem, penalty=1e6)
algorithm = GA(pop_size=100)
**参数:**
- `penalty`: 惩罚系数 (根据问题规模进行调整)