forked from RobotLocomotion/drake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipopt_solver.cc
678 lines (599 loc) · 24.6 KB
/
ipopt_solver.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
#include "drake/solvers/ipopt_solver.h"
#include <algorithm>
#include <cstring>
#include <limits>
#include <memory>
#include <unordered_map>
#include <vector>
#include <IpIpoptApplication.hpp>
#include <IpTNLP.hpp>
#include "drake/common/drake_assert.h"
#include "drake/common/never_destroyed.h"
#include "drake/common/text_logging.h"
#include "drake/common/unused.h"
#include "drake/math/autodiff.h"
#include "drake/solvers/mathematical_program.h"
using Ipopt::Index;
using Ipopt::IpoptCalculatedQuantities;
using Ipopt::IpoptData;
using Ipopt::Number;
using Ipopt::SolverReturn;
namespace drake {
namespace solvers {
namespace {
/// @param[out] lb Array of constraint lower bounds, parallel to @p ub
/// @param[out] ub Array of constraint upper bounds, parallel to @p lb
int GetConstraintBounds(const Constraint& c, Number* lb, Number* ub) {
const Eigen::VectorXd& lower_bound = c.lower_bound();
const Eigen::VectorXd& upper_bound = c.upper_bound();
for (int i = 0; i < c.num_constraints(); i++) {
lb[i] = lower_bound(i);
ub[i] = upper_bound(i);
}
return c.num_constraints();
}
/// @param[out] num_grad number of gradients
/// @return number of constraints
int GetNumGradients(const Constraint& c, int var_count, Index* num_grad) {
const int num_constraints = c.num_constraints();
*num_grad = num_constraints * var_count;
return num_constraints;
}
/// @param constraint_idx The starting row number for the constraint
/// being described.
///
/// Parameters @p iRow and @p jCol are used in the same manner as
/// described in
/// http://www.coin-or.org/Ipopt/documentation/node23.html for the
/// eval_jac_g() function (in the mode where it's requesting the
/// sparsity structure of the Jacobian). The triplet format is also
/// described in
/// http://www.coin-or.org/Ipopt/documentation/node38.html#app.triplet
///
/// @return the number of row/column pairs filled in.
size_t GetGradientMatrix(
const MathematicalProgram& prog, const Constraint& c,
const Eigen::Ref<const VectorXDecisionVariable>& variables,
Index constraint_idx, Index* iRow, Index* jCol) {
const int m = c.num_constraints();
size_t grad_index = 0;
for (int i = 0; i < static_cast<int>(m); ++i) {
for (int j = 0; j < variables.rows(); ++j) {
iRow[grad_index] = constraint_idx + i;
jCol[grad_index] = prog.FindDecisionVariableIndex(variables(j));
grad_index++;
}
}
return grad_index;
}
Eigen::VectorXd MakeEigenVector(Index n, const Number* x) {
Eigen::VectorXd xvec(n);
for (Index i = 0; i < n; i++) {
xvec[i] = x[i];
}
return xvec;
}
/// Evaluate a constraint, storing the result of the evaluation into
/// @p result and gradients into @p grad. @p grad is the sparse
/// matrix data for which the structure was defined in
/// GetGradientMatrix.
///
/// @return number of gradient entries populated.
size_t EvaluateConstraint(const MathematicalProgram& prog,
const Eigen::VectorXd& xvec, const Constraint& c,
const VectorXDecisionVariable& variables,
Number* result, Number* grad) {
// For constraints which don't use all of the variables in the X
// input, extract a subset into the AutoDiffVecXd this_x to evaluate
// the constraint (we actually do this for all constraints. One
// potential optimization might be to detect if the initial "tx" has
// the correct geometry (e.g. the constraint uses all decision
// variables in the same order they appear in xvec), but this is not
// currently done).
int num_v_variables = variables.rows();
Eigen::VectorXd this_x(num_v_variables);
for (int i = 0; i < num_v_variables; ++i) {
this_x(i) = xvec(prog.FindDecisionVariableIndex(variables(i)));
}
AutoDiffVecXd ty(c.num_constraints());
c.Eval(math::initializeAutoDiff(this_x), &ty);
// Store the results. Since IPOPT directly knows the bounds of the
// constraint, we don't need to apply any bounding information here.
for (int i = 0; i < c.num_constraints(); i++) {
result[i] = ty(i).value();
}
// Extract the appropriate derivatives from our result into the
// gradient array.
size_t grad_idx = 0;
DRAKE_ASSERT(ty.rows() == c.num_constraints());
for (int i = 0; i < ty.rows(); i++) {
if (ty(i).derivatives().size() > 0) {
for (int j = 0; j < variables.rows(); j++) {
grad[grad_idx++] = ty(i).derivatives()(j);
}
} else {
for (int j = 0; j < variables.rows(); j++) {
grad[grad_idx++] = 0;
}
}
}
return grad_idx;
}
// IPOPT uses separate callbacks to get the result and the gradients.
// Since Drake's eval() functions emit both of these at once, cache
// the result for IPOPT.
struct ResultCache {
ResultCache(size_t x_size, size_t result_size, size_t grad_size) {
// The choice of infinity as the default value below is arbitrary.
x.resize(x_size, std::numeric_limits<double>::infinity());
result.resize(result_size, std::numeric_limits<double>::infinity());
grad.resize(grad_size, std::numeric_limits<double>::infinity());
}
/// @param n The size of the array located at @p x_in.
bool is_x_equal(Index n, const Number* x_in) {
DRAKE_ASSERT(n == static_cast<Index>(x.size()));
return !std::memcmp(x.data(), x_in, x.size() * sizeof(Number));
}
std::vector<Number> x;
std::vector<Number> result;
std::vector<Number> grad;
};
// The C++ interface for IPOPT is described here:
// http://www.coin-or.org/Ipopt/documentation/node23.html
//
// IPOPT provides a pure(-ish) virtual base class which you have to
// implement a concrete version of as the solver interface.
// IpoptSolver creates an instance of IpoptSolver_NLP which lives for
// the duration of the Solve() call.
class IpoptSolver_NLP : public Ipopt::TNLP {
public:
explicit IpoptSolver_NLP(const MathematicalProgram& problem,
const Eigen::VectorXd& x_init,
MathematicalProgramResult* result)
: problem_(&problem), x_init_{x_init}, result_(result) {}
virtual ~IpoptSolver_NLP() {}
virtual bool get_nlp_info(
// NOLINTNEXTLINE(runtime/references); this is built into ipopt's API.
Index& n, Index& m, Index& nnz_jac_g,
// NOLINTNEXTLINE(runtime/references); this is built into ipopt's API.
Index& nnz_h_lag, IndexStyleEnum& index_style) {
n = problem_->num_vars();
// The IPOPT interface defines eval_f() and eval_grad_f() as
// outputting a single number for the result, and the size of the
// output gradient array at the same order as the x variables.
// Initialize the cost cache with those dimensions.
cost_cache_.reset(new ResultCache(n, 1, n));
m = 0;
nnz_jac_g = 0;
Index num_grad = 0;
for (const auto& c : problem_->generic_constraints()) {
m += GetNumGradients(*(c.evaluator()), c.variables().rows(), &num_grad);
nnz_jac_g += num_grad;
}
for (const auto& c : problem_->lorentz_cone_constraints()) {
m += GetNumGradients(*(c.evaluator()), c.variables().rows(), &num_grad);
nnz_jac_g += num_grad;
}
for (const auto& c : problem_->rotated_lorentz_cone_constraints()) {
m += GetNumGradients(*(c.evaluator()), c.variables().rows(), &num_grad);
nnz_jac_g += num_grad;
}
for (const auto& c : problem_->linear_constraints()) {
m += GetNumGradients(*(c.evaluator()), c.variables().rows(), &num_grad);
nnz_jac_g += num_grad;
}
for (const auto& c : problem_->linear_equality_constraints()) {
m += GetNumGradients(*(c.evaluator()), c.variables().rows(), &num_grad);
nnz_jac_g += num_grad;
}
constraint_cache_.reset(new ResultCache(n, m, nnz_jac_g));
nnz_h_lag = 0;
index_style = C_STYLE;
return true;
}
virtual bool get_bounds_info(Index n, Number* x_l, Number* x_u, Index m,
Number* g_l, Number* g_u) {
unused(m);
DRAKE_ASSERT(n == static_cast<Index>(problem_->num_vars()));
for (Index i = 0; i < n; i++) {
x_l[i] = -std::numeric_limits<double>::infinity();
x_u[i] = std::numeric_limits<double>::infinity();
}
for (auto const& binding : problem_->bounding_box_constraints()) {
const auto& c = binding.evaluator();
const auto& lower_bound = c->lower_bound();
const auto& upper_bound = c->upper_bound();
for (int k = 0; k < static_cast<int>(binding.GetNumElements()); ++k) {
const int idx =
problem_->FindDecisionVariableIndex(binding.variables()(k));
x_l[idx] = std::max(lower_bound(k), x_l[idx]);
x_u[idx] = std::min(upper_bound(k), x_u[idx]);
}
}
size_t constraint_idx = 0; // offset into g_l and g_u output arrays
for (const auto& c : problem_->generic_constraints()) {
constraint_idx += GetConstraintBounds(
*(c.evaluator()), g_l + constraint_idx, g_u + constraint_idx);
}
for (const auto& c : problem_->lorentz_cone_constraints()) {
constraint_idx += GetConstraintBounds(
*(c.evaluator()), g_l + constraint_idx, g_u + constraint_idx);
}
for (const auto& c : problem_->rotated_lorentz_cone_constraints()) {
constraint_idx += GetConstraintBounds(
*(c.evaluator()), g_l + constraint_idx, g_u + constraint_idx);
}
for (const auto& c : problem_->linear_constraints()) {
constraint_idx += GetConstraintBounds(
*(c.evaluator()), g_l + constraint_idx, g_u + constraint_idx);
}
for (const auto& c : problem_->linear_equality_constraints()) {
constraint_idx += GetConstraintBounds(
*(c.evaluator()), g_l + constraint_idx, g_u + constraint_idx);
}
return true;
}
virtual bool get_starting_point(Index n, bool init_x, Number* x, bool init_z,
Number* z_L, Number* z_U, Index m,
bool init_lambda, Number* lambda) {
unused(z_L, z_U, m, lambda);
if (init_x) {
DRAKE_ASSERT(x_init_.size() == n);
for (Index i = 0; i < n; i++) {
if (!std::isnan(x_init_[i])) {
x[i] = x_init_[i];
} else {
x[i] = 0.0;
}
}
}
// We don't currently use any solver options which require
// populating z_L, z_U or lambda. Assert that IPOPT doesn't
// expect us to in case any such options get turned on.
DRAKE_ASSERT(!init_z);
DRAKE_ASSERT(!init_lambda);
return true;
}
// NOLINTNEXTLINE(runtime/references); this is built into ipopt's API.
virtual bool eval_f(Index n, const Number* x, bool new_x, Number& obj_value) {
if (new_x || !cost_cache_->is_x_equal(n, x)) {
EvaluateCosts(n, x);
}
DRAKE_ASSERT(cost_cache_->result.size() == 1);
obj_value = cost_cache_->result[0];
return true;
}
virtual bool eval_grad_f(Index n, const Number* x, bool new_x,
Number* grad_f) {
if (new_x || !cost_cache_->is_x_equal(n, x)) {
EvaluateCosts(n, x);
}
DRAKE_ASSERT(static_cast<Index>(cost_cache_->grad.size()) == n);
std::memcpy(grad_f, cost_cache_->grad.data(), n * sizeof(Number));
return true;
}
virtual bool eval_g(Index n, const Number* x, bool new_x, Index m,
Number* g) {
if (new_x || !constraint_cache_->is_x_equal(n, x)) {
EvaluateConstraints(n, x);
}
DRAKE_ASSERT(static_cast<Index>(constraint_cache_->result.size()) == m);
std::memcpy(g, constraint_cache_->result.data(), m * sizeof(Number));
return true;
}
virtual bool eval_jac_g(Index n, const Number* x, bool new_x, Index m,
Index nele_jac, Index* iRow, Index* jCol,
Number* values) {
unused(m);
if (values == nullptr) {
DRAKE_ASSERT(iRow != nullptr);
DRAKE_ASSERT(jCol != nullptr);
int constraint_idx = 0; // Passed into GetGradientMatrix as
// the starting row number for the
// constraint being described.
int grad_idx = 0; // Offset into iRow, jCol output variables.
// Incremented by the number of triplets
// populated by each call to
// GetGradientMatrix.
for (const auto& c : problem_->generic_constraints()) {
grad_idx +=
GetGradientMatrix(*problem_, *(c.evaluator()), c.variables(),
constraint_idx, iRow + grad_idx, jCol + grad_idx);
constraint_idx += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->lorentz_cone_constraints()) {
grad_idx +=
GetGradientMatrix(*problem_, *(c.evaluator()), c.variables(),
constraint_idx, iRow + grad_idx, jCol + grad_idx);
constraint_idx += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->rotated_lorentz_cone_constraints()) {
grad_idx +=
GetGradientMatrix(*problem_, *(c.evaluator()), c.variables(),
constraint_idx, iRow + grad_idx, jCol + grad_idx);
constraint_idx += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->linear_constraints()) {
grad_idx +=
GetGradientMatrix(*problem_, *(c.evaluator()), c.variables(),
constraint_idx, iRow + grad_idx, jCol + grad_idx);
constraint_idx += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->linear_equality_constraints()) {
grad_idx +=
GetGradientMatrix(*problem_, *(c.evaluator()), c.variables(),
constraint_idx, iRow + grad_idx, jCol + grad_idx);
constraint_idx += c.evaluator()->num_constraints();
}
DRAKE_ASSERT(static_cast<Index>(grad_idx) == nele_jac);
return true;
}
DRAKE_ASSERT(iRow == nullptr);
DRAKE_ASSERT(jCol == nullptr);
// We're being asked for the actual values.
if (new_x || !constraint_cache_->is_x_equal(n, x)) {
EvaluateConstraints(n, x);
}
DRAKE_ASSERT(static_cast<Index>(constraint_cache_->grad.size()) ==
nele_jac);
std::memcpy(values, constraint_cache_->grad.data(),
nele_jac * sizeof(Number));
return true;
}
virtual void finalize_solution(SolverReturn status, Index n, const Number* x,
const Number* z_L, const Number* z_U, Index m,
const Number* g, const Number* lambda,
Number obj_value, const IpoptData* ip_data,
IpoptCalculatedQuantities* ip_cq) {
unused(ip_data, ip_cq);
IpoptSolverDetails& solver_details =
result_->SetSolverDetailsType<IpoptSolverDetails>();
solver_details.status = status;
solver_details.z_L = Eigen::Map<const Eigen::VectorXd>(z_L, n);
solver_details.z_U = Eigen::Map<const Eigen::VectorXd>(z_U, n);
solver_details.g = Eigen::Map<const Eigen::VectorXd>(g, m);
solver_details.lambda = Eigen::Map<const Eigen::VectorXd>(lambda, m);
result_->set_solution_result(SolutionResult::kUnknownError);
switch (status) {
case Ipopt::SUCCESS: {
result_->set_solution_result(SolutionResult::kSolutionFound);
break;
}
case Ipopt::STOP_AT_ACCEPTABLE_POINT: {
// This case happens because the user requested more lenient solution
// acceptability criteria so it is counted as solved.
result_->set_solution_result(SolutionResult::kSolutionFound);
break;
}
case Ipopt::LOCAL_INFEASIBILITY: {
result_->set_solution_result(SolutionResult::kInfeasibleConstraints);
break;
}
case Ipopt::DIVERGING_ITERATES: {
result_->set_solution_result(SolutionResult::kUnbounded);
result_->set_optimal_cost(MathematicalProgram::kUnboundedCost);
break;
}
case Ipopt::MAXITER_EXCEEDED: {
result_->set_solution_result(SolutionResult::kIterationLimit);
drake::log()->warn(
"IPOPT terminated after exceeding the maximum iteration limit. "
"Hint: Remember that IPOPT is an interior-point method "
"and performs badly if any variables are unbounded.");
break;
}
default: {
result_->set_solution_result(SolutionResult::kUnknownError);
break;
}
}
Eigen::VectorXd solution(n);
for (Index i = 0; i < n; i++) {
solution(i) = x[i];
}
result_->set_x_val(solution.cast<double>());
if (result_->get_solution_result() != SolutionResult::kUnbounded) {
result_->set_optimal_cost(obj_value);
}
}
private:
void EvaluateCosts(Index n, const Number* x) {
const Eigen::VectorXd xvec = MakeEigenVector(n, x);
problem_->EvalVisualizationCallbacks(xvec);
AutoDiffVecXd ty(1);
Eigen::VectorXd this_x;
memcpy(cost_cache_->x.data(), x, n * sizeof(Number));
cost_cache_->result[0] = 0;
cost_cache_->grad.assign(n, 0);
for (auto const& binding : problem_->GetAllCosts()) {
int num_v_variables = binding.GetNumElements();
this_x.resize(num_v_variables);
for (int i = 0; i < num_v_variables; ++i) {
this_x(i) =
xvec(problem_->FindDecisionVariableIndex(binding.variables()(i)));
}
binding.evaluator()->Eval(math::initializeAutoDiff(this_x), &ty);
cost_cache_->result[0] += ty(0).value();
if (ty(0).derivatives().size() > 0) {
for (int j = 0; j < num_v_variables; ++j) {
const size_t vj_index =
problem_->FindDecisionVariableIndex(binding.variables()(j));
cost_cache_->grad[vj_index] += ty(0).derivatives()(j);
}
}
// We do not need to add code for ty(0).derivatives().size() == 0, since
// cost_cache_->grad would be unchanged if the derivative has zero size.
}
}
void EvaluateConstraints(Index n, const Number* x) {
const Eigen::VectorXd xvec = MakeEigenVector(n, x);
memcpy(constraint_cache_->x.data(), x, n * sizeof(Number));
Number* result = constraint_cache_->result.data();
Number* grad = constraint_cache_->grad.data();
for (const auto& c : problem_->generic_constraints()) {
grad += EvaluateConstraint(*problem_, xvec, (*c.evaluator()),
c.variables(), result, grad);
result += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->lorentz_cone_constraints()) {
grad += EvaluateConstraint(*problem_, xvec, (*c.evaluator()),
c.variables(), result, grad);
result += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->rotated_lorentz_cone_constraints()) {
grad += EvaluateConstraint(*problem_, xvec, (*c.evaluator()),
c.variables(), result, grad);
result += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->linear_constraints()) {
grad += EvaluateConstraint(*problem_, xvec, (*c.evaluator()),
c.variables(), result, grad);
result += c.evaluator()->num_constraints();
}
for (const auto& c : problem_->linear_equality_constraints()) {
grad += EvaluateConstraint(*problem_, xvec, (*c.evaluator()),
c.variables(), result, grad);
result += c.evaluator()->num_constraints();
}
}
const MathematicalProgram* const problem_;
std::unique_ptr<ResultCache> cost_cache_;
std::unique_ptr<ResultCache> constraint_cache_;
Eigen::VectorXd x_init_;
MathematicalProgramResult* const result_;
};
template <typename T>
bool HasOptionWithKey(const SolverOptions& solver_options,
const std::string& key) {
return solver_options.GetOptions<T>(IpoptSolver::id()).count(key) > 0;
}
/**
* If the key has been set in ipopt_options, then this function is an no-op.
* Otherwise set this key with default_val.
*/
template <typename T>
void SetIpoptOptionsHelper(const std::string& key, const T& default_val,
SolverOptions* ipopt_options) {
if (!HasOptionWithKey<T>(*ipopt_options, key)) {
ipopt_options->SetOption(IpoptSolver::id(), key, default_val);
}
}
void SetIpoptOptions(const MathematicalProgram& prog,
const std::optional<SolverOptions>& user_solver_options,
Ipopt::IpoptApplication* app) {
SolverOptions merged_solver_options = user_solver_options.has_value()
? user_solver_options.value()
: SolverOptions();
merged_solver_options.Merge(prog.solver_options());
// The default tolerance.
const double tol = 1.05e-10; // Note: SNOPT is only 1e-6, but in #3712 we
// diagnosed that the CompareMatrices tolerance needed to be the sqrt of the
// constr_viol_tol
SetIpoptOptionsHelper<double>("tol", tol, &merged_solver_options);
SetIpoptOptionsHelper<double>("constr_viol_tol", tol, &merged_solver_options);
SetIpoptOptionsHelper<double>("acceptable_tol", tol, &merged_solver_options);
SetIpoptOptionsHelper<double>("acceptable_constr_viol_tol", tol,
&merged_solver_options);
SetIpoptOptionsHelper<std::string>("hessian_approximation", "limited-memory",
&merged_solver_options);
// Note: 0<= print_level <= 12, with higher numbers more verbose. 4 is very
// useful for debugging.
SetIpoptOptionsHelper<int>("print_level", 2, &merged_solver_options);
const auto& ipopt_options_double =
merged_solver_options.GetOptionsDouble(IpoptSolver::id());
const auto& ipopt_options_str =
merged_solver_options.GetOptionsStr(IpoptSolver::id());
const auto& ipopt_options_int =
merged_solver_options.GetOptionsInt(IpoptSolver::id());
for (const auto& it : ipopt_options_double) {
app->Options()->SetNumericValue(it.first, it.second);
}
for (const auto& it : ipopt_options_int) {
app->Options()->SetIntegerValue(it.first, it.second);
}
app->Options()->SetStringValue("sb", "yes"); // Turn off the banner.
for (const auto& it : ipopt_options_str) {
app->Options()->SetStringValue(it.first, it.second);
}
}
} // namespace
const char* IpoptSolverDetails::ConvertStatusToString() const {
switch (status) {
case Ipopt::SolverReturn::SUCCESS: {
return "Success";
}
case Ipopt::SolverReturn::MAXITER_EXCEEDED: {
return "Max iteration exceeded";
}
case Ipopt::SolverReturn::CPUTIME_EXCEEDED: {
return "CPU time exceeded";
}
case Ipopt::SolverReturn::STOP_AT_TINY_STEP: {
return "Stop at tiny step";
}
case Ipopt::SolverReturn::STOP_AT_ACCEPTABLE_POINT: {
return "Stop at acceptable point";
}
case Ipopt::SolverReturn::LOCAL_INFEASIBILITY: {
return "Local infeasibility";
}
case Ipopt::SolverReturn::USER_REQUESTED_STOP: {
return "User requested stop";
}
case Ipopt::SolverReturn::FEASIBLE_POINT_FOUND: {
return "Feasible point found";
}
case Ipopt::SolverReturn::DIVERGING_ITERATES: {
return "Divergent iterates";
}
case Ipopt::SolverReturn::RESTORATION_FAILURE: {
return "Restoration failure";
}
case Ipopt::SolverReturn::ERROR_IN_STEP_COMPUTATION: {
return "Error in step computation";
}
case Ipopt::SolverReturn::INVALID_NUMBER_DETECTED: {
return "Invalid number detected";
}
case Ipopt::SolverReturn::TOO_FEW_DEGREES_OF_FREEDOM: {
return "Too few degrees of freedom";
}
case Ipopt::SolverReturn::INVALID_OPTION: {
return "Invalid option";
}
case Ipopt::SolverReturn::OUT_OF_MEMORY: {
return "Out of memory";
}
case Ipopt::SolverReturn::INTERNAL_ERROR: {
return "Internal error";
}
case Ipopt::SolverReturn::UNASSIGNED: {
return "Unassigned";
}
}
return "Unknown enumerated SolverReturn value.";
}
bool IpoptSolver::is_available() { return true; }
void IpoptSolver::DoSolve(
const MathematicalProgram& prog,
const Eigen::VectorXd& initial_guess,
const SolverOptions& merged_options,
MathematicalProgramResult* result) const {
if (!prog.GetVariableScaling().empty()) {
static const logging::Warn log_once(
"IpoptSolver doesn't support the feature of variable scaling.");
}
Ipopt::SmartPtr<Ipopt::IpoptApplication> app = IpoptApplicationFactory();
app->RethrowNonIpoptException(true);
SetIpoptOptions(prog, merged_options, &(*app));
Ipopt::ApplicationReturnStatus status = app->Initialize();
if (status != Ipopt::Solve_Succeeded) {
result->set_solution_result(SolutionResult::kInvalidInput);
return;
}
Ipopt::SmartPtr<IpoptSolver_NLP> nlp =
new IpoptSolver_NLP(prog, initial_guess, result);
status = app->OptimizeTNLP(nlp);
}
} // namespace solvers
} // namespace drake