from pydrake.solvers import MathematicalProgram, SolverOptions, Solve
from pydrake.solvers import IpoptSolver
import numpy as np
prog = MathematicalProgram()
x = prog.NewContinuousVariables(2)
prog.AddCost(x[0]**2 + x[1] ** 2)
prog.AddConstraint(x[0] + x[1] == 1)

# Set the maximum iteration for IPOPT to be 1.
# max_iter is a parameter of IPOPT solver, explained in
# https://www.coin-or.org/Ipopt/documentation/node42.html
prog.SetSolverOption(IpoptSolver().solver_id(), "max_iter", 1)
solver = IpoptSolver()
result = solver.Solve(prog, np.array([10, 1]), None)
# With fewer maximum iteration, IPOPT hasn't converged to optimality yet (The true optimal is [0.5, 0.5])
print("Success? ", result.is_success())
print(result.get_solution_result())
print("IPOPT x*= ", result.GetSolution(x))prog.SetSolverOption(IpoptSolver().solver_id(), "max_iter", 1)
result = Solve(prog)
print(result.get_solver_id().name())prog = MathematicalProgram()
x = prog.NewContinuousVariables(2)
prog.AddCost(x[0]**2 + x[1] ** 2)
prog.AddConstraint(x[0] + x[1] == 1)

solver_options = SolverOptions()
solver_options.SetOption(IpoptSolver().solver_id(), "max_iter", 1)
solver = IpoptSolver()

# Call Solve with solver_options, IPOPT will use `max_iter` = 1
result = solver.Solve(prog, np.array([10, 1]), solver_options)
print("Success? ", result.is_success())
print(result.get_solution_result())
# Call Solve without solver_options, IPOPT will use the default options.
result = solver.Solve(prog, np.array([10, 1]), None)
print("Success? ", result.is_success())
print(result.get_solution_result())