python - 线性不等式约束在 Drake 中不起作用
问题描述
我正在学习如何使用 Drake 来解决优化问题。这个问题是找到栅栏的最佳长度和宽度,栅栏的周长必须小于或等于 40。下面的代码仅在周长约束是等式约束时有效。它应该作为一个不等式约束,但我的最佳解决方案导致 x=[nan nan]。有谁知道为什么会这样?
from pydrake.solvers.mathematicalprogram import MathematicalProgram, Solve
import numpy as np
import matplotlib.pyplot as plt
prog = MathematicalProgram()
#add two decision variables
x = prog.NewContinuousVariables(2, "x")
#adds objective function where
#
# min 0.5 xt * Q * x + bt * x
#
# Q = [0,-1
# -1,0]
#
# bt = [0,
# 0]
#
Q = [[0,-1],[-1,0]]
b = [[0],[0]]
prog.AddQuadraticCost(Q , b, vars=[x[0],x[1]])
# Adds the linear constraints.
prog.AddLinearEqualityConstraint(2*x[0] + 2*x[1] == 40)
#prog.AddLinearConstraint(2*x[0] + 2*x[1] <= 40)
prog.AddLinearConstraint(0*x[0] + -1*x[1] <= 0)
prog.AddLinearConstraint(-1*x[0] + 0*x[1] <= 0)
# Solve the program.
result = Solve(prog)
print(f"optimal solution x: {result.GetSolution(x)}")
解决方案
对于不等式约束和等式约束,我得到 [nan, nan]。
正如 Russ 所提到的,问题在于成本是非凸的,并且 Drake 导致了错误的求解器。目前,我建议明确指定求解器。你可以做
from pydrake.solvers.ipopt_solver import IpoptSolver
from pydrake.solvers.mathematicalprogram import MathematicalProgram, Solve
import numpy as np
import matplotlib.pyplot as plt
prog = MathematicalProgram()
#add two decision variables
x = prog.NewContinuousVariables(2, "x")
#adds objective function where
#
# min 0.5 xt * Q * x + bt * x
#
# Q = [0,-1
# -1,0]
#
# bt = [0,
# 0]
#
Q = [[0,-1],[-1,0]]
b = [[0],[0]]
prog.AddQuadraticCost(Q , b, vars=[x[0],x[1]])
# Adds the linear constraints.
prog.AddLinearEqualityConstraint(2*x[0] + 2*x[1] == 40)
#prog.AddLinearConstraint(2*x[0] + 2*x[1] <= 40)
prog.AddLinearConstraint(0*x[0] + -1*x[1] <= 0)
prog.AddLinearConstraint(-1*x[0] + 0*x[1] <= 0)
# Solve the program.
solver = IpoptSolver()
result = solver.Solve(prog)
print(f"optimal solution x: {result.GetSolution(x)}")
我将在 Drake 方面进行修复,以确保当您有非凸二次成本时它会产生正确的求解器。
推荐阅读
- javascript - 如何仅显示字段为真的数据
- python - 在图形中表示非常小的数字和非常大的数字?
- java - 在 Java 中查找大型数据数组中的特定元素?
- python - 加速 Pandas Dataframe groupby 聚合的最佳方法
- unity3d - iOS 横向模式下的插页式 Unity 广告崩溃
- html - 如何在 django html 主页模板的主页上仅显示图像列表/集中的 1 张图像?
- javascript - 使用 TensorFlow JS 使用字符串作为输入来预测特征
- google-cloud-platform - 如何使用 python 获取 GCP vm 实例总内存大小?
- wpf - 作为单个窗口打开一个新的 WPF 视图
- python - 为什么类大多是通过函数实例化的?