Carlos
Carlos

Reputation: 23

Linear inequality constraint not working in Drake

I am learning how to use Drake to solving optimization problems. This problem was to find the optimal length and width of a fence, the fence must have a perimeter less than or equal to 40. The code below only works when the perimeter constraint is an equality constraint. It should work as an inequality constraint, but my optimal solution results in x=[nan nan]. Does anyone know why this is the case?

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)}")

Upvotes: 1

Views: 374

Answers (1)

Hongkai Dai
Hongkai Dai

Reputation: 2766

I get [nan, nan] for both inequality constraint and equality constraint.

As Russ mentioned, the problem is the cost being non-convex, and Drake incurred the wrong solver. For the moment, I would suggest to explicitly designate a solver. You could do

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)}")

I will work on a fix on the Drake side, to make sure it incur the right solver when you have non-convex quadratic cost.

Upvotes: 1

Related Questions