forked from RobotLocomotion/drake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconstraint.cc
696 lines (608 loc) · 23.8 KB
/
constraint.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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
#include "drake/solvers/constraint.h"
#include <cmath>
#include <limits>
#include <set>
#include <stdexcept>
#include <unordered_map>
#include <fmt/format.h>
#include "drake/common/symbolic/decompose.h"
#include "drake/math/autodiff_gradient.h"
#include "drake/math/matrix_util.h"
using std::abs;
namespace drake {
namespace solvers {
const double kInf = std::numeric_limits<double>::infinity();
namespace {
// Returns `True` if lb is -∞. Otherwise returns a symbolic formula `lb <= e`.
symbolic::Formula MakeLowerBound(const double lb,
const symbolic::Expression& e) {
if (lb == -std::numeric_limits<double>::infinity()) {
return symbolic::Formula::True();
} else {
return lb <= e;
}
}
// Returns `True` if ub is ∞. Otherwise returns a symbolic formula `e <= ub`.
symbolic::Formula MakeUpperBound(const symbolic::Expression& e,
const double ub) {
if (ub == std::numeric_limits<double>::infinity()) {
return symbolic::Formula::True();
} else {
return e <= ub;
}
}
std::ostream& DisplayConstraint(const Constraint& constraint, std::ostream& os,
const std::string& name,
const VectorX<symbolic::Variable>& vars,
bool equality) {
os << name;
VectorX<symbolic::Expression> e(constraint.num_constraints());
constraint.Eval(vars, &e);
// Append the description (when provided).
const std::string& description = constraint.get_description();
if (!description.empty()) {
os << " described as '" << description << "'";
}
os << "\n";
for (int i = 0; i < constraint.num_constraints(); ++i) {
if (equality) {
os << e(i) << " == " << constraint.upper_bound()(i) << "\n";
} else {
os << constraint.lower_bound()(i) << " <= " << e(i)
<< " <= " << constraint.upper_bound()(i) << "\n";
}
}
return os;
}
} // namespace
void Constraint::check(int num_constraints) const {
if (lower_bound_.size() != num_constraints ||
upper_bound_.size() != num_constraints) {
throw std::invalid_argument(
fmt::format("Constraint {} expects lower and upper bounds of size {}, "
"got lower bound of size {} and upper bound of size {}.",
this->get_description(), num_constraints,
lower_bound_.size(), upper_bound_.size()));
}
}
symbolic::Formula Constraint::DoCheckSatisfied(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x) const {
VectorX<symbolic::Expression> y(num_constraints());
DoEval(x, &y);
symbolic::Formula f{symbolic::Formula::True()};
for (int i = 0; i < num_constraints(); ++i) {
if (lower_bound_[i] == upper_bound_[i]) {
// Add 'lbᵢ = yᵢ' to f.
f = f && lower_bound_[i] == y[i];
} else {
// Add 'lbᵢ ≤ yᵢ ≤ ubᵢ' to f.
f = f && MakeLowerBound(lower_bound_[i], y[i]) &&
MakeUpperBound(y[i], upper_bound_[i]);
}
}
return f;
}
template <typename DerivedX, typename ScalarY>
void QuadraticConstraint::DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x,
VectorX<ScalarY>* y) const {
y->resize(num_constraints());
*y = .5 * x.transpose() * Q_ * x + b_.transpose() * x;
}
void QuadraticConstraint::DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
DoEvalGeneric(x, y);
}
void QuadraticConstraint::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
DoEvalGeneric(x, y);
}
void QuadraticConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DoEvalGeneric(x, y);
}
std::ostream& QuadraticConstraint::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayConstraint(*this, os, "QuadraticConstraint", vars, false);
}
namespace {
int get_lorentz_cone_constraint_size(
LorentzConeConstraint::EvalType eval_type) {
return eval_type == LorentzConeConstraint::EvalType::kNonconvex ? 2 : 1;
}
} // namespace
LorentzConeConstraint::LorentzConeConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b, EvalType eval_type)
: Constraint(
get_lorentz_cone_constraint_size(eval_type), A.cols(),
Eigen::VectorXd::Zero(get_lorentz_cone_constraint_size(eval_type)),
Eigen::VectorXd::Constant(get_lorentz_cone_constraint_size(eval_type),
kInf)),
A_(A.sparseView()),
A_dense_(A),
b_(b),
eval_type_{eval_type} {
DRAKE_DEMAND(A_.rows() >= 2);
DRAKE_ASSERT(A_.rows() == b_.rows());
}
void LorentzConeConstraint::UpdateCoefficients(
const Eigen::Ref<const Eigen::MatrixXd>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_b) {
if (new_A.cols() != num_vars()) {
throw std::invalid_argument(
fmt::format("LorentzConeConstraint::UpdateCoefficients uses new_A with "
"{} columns to update a constraint with {} variables.",
new_A.cols(), num_vars()));
}
A_ = new_A.sparseView();
A_dense_ = new_A;
b_ = new_b;
DRAKE_DEMAND(A_.rows() >= 2);
DRAKE_DEMAND(A_.rows() == b_.rows());
// Note that we don't need to update the lower and upper bounds as the
// constraints lower/upper bounds are fixed (independent of A and b). The
// bounds only depend on EvalType. When EvalType=kNonconvex, the lower/upper
// bound is [0, 0]/[inf, inf] respectively; otherwise, the lower/upper bound
// is 0/inf respectively.
}
namespace {
template <typename DerivedX>
void LorentzConeConstraintEvalConvex2Autodiff(
const Eigen::MatrixXd& A_dense, const Eigen::VectorXd& b,
const Eigen::MatrixBase<DerivedX>& x, VectorX<AutoDiffXd>* y) {
const Eigen::VectorXd x_val = math::ExtractValue(x);
const Eigen::VectorXd z_val = A_dense * x_val + b;
const double z_tail_squared_norm = z_val.tail(z_val.rows() - 1).squaredNorm();
Vector1d y_val(z_val(0) - std::sqrt(z_tail_squared_norm));
Eigen::RowVectorXd dy_dz(z_val.rows());
dy_dz(0) = 1;
// We use a small value epsilon to approximate the gradient of sqrt(z) as
// ∂sqrt(zᵀz) / ∂z ≈ z(i) / sqrt(zᵀz + eps)
const double eps = 1E-12;
dy_dz.tail(z_val.rows() - 1) =
-z_val.tail(z_val.rows() - 1) / std::sqrt(z_tail_squared_norm + eps);
Eigen::RowVectorXd dy = dy_dz * A_dense * math::ExtractGradient(x);
(*y) = math::InitializeAutoDiff(y_val, dy);
}
} // namespace
template <typename DerivedX, typename ScalarY>
void LorentzConeConstraint::DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x,
VectorX<ScalarY>* y) const {
using std::pow;
const VectorX<ScalarY> z = A_dense_ * x.template cast<ScalarY>() + b_;
y->resize(num_constraints());
switch (eval_type_) {
case EvalType::kConvex: {
(*y)(0) = z(0) - z.tail(z.rows() - 1).norm();
break;
}
case EvalType::kConvexSmooth: {
if constexpr (std::is_same_v<ScalarY, AutoDiffXd>) {
LorentzConeConstraintEvalConvex2Autodiff(A_dense_, b_, x, y);
} else {
(*y)(0) = z(0) - z.tail(z.rows() - 1).norm();
}
break;
}
case EvalType::kNonconvex: {
(*y)(0) = z(0);
(*y)(1) = pow(z(0), 2) - z.tail(z.size() - 1).squaredNorm();
break;
}
}
}
void LorentzConeConstraint::DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
DoEvalGeneric(x, y);
}
void LorentzConeConstraint::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
DoEvalGeneric(x, y);
}
void LorentzConeConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DoEvalGeneric(x, y);
}
std::ostream& LorentzConeConstraint::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayConstraint(*this, os, "LorentzConeConstraint", vars, false);
}
void RotatedLorentzConeConstraint::UpdateCoefficients(
const Eigen::Ref<const Eigen::MatrixXd>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_b) {
if (new_A.cols() != num_vars()) {
throw std::invalid_argument(fmt::format(
"RotatedLorentzConeConstraint::UpdateCoefficients uses new_A with "
"{} columns to update a constraint with {} variables.",
new_A.cols(), num_vars()));
}
A_ = new_A.sparseView();
A_dense_ = new_A;
b_ = new_b;
DRAKE_DEMAND(A_.rows() >= 3);
DRAKE_DEMAND(A_.rows() == b_.rows());
// Note that we don't need to update the lower and upper bounds as the
// constraints lower/upper bounds are fixed (independent of A and b).
}
template <typename DerivedX, typename ScalarY>
void RotatedLorentzConeConstraint::DoEvalGeneric(
const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const {
const VectorX<ScalarY> z = A_dense_ * x.template cast<ScalarY>() + b_;
y->resize(num_constraints());
(*y)(0) = z(0);
(*y)(1) = z(1);
(*y)(2) = z(0) * z(1) - z.tail(z.size() - 2).squaredNorm();
}
void RotatedLorentzConeConstraint::DoEval(
const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const {
DoEvalGeneric(x, y);
}
void RotatedLorentzConeConstraint::DoEval(
const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const {
DoEvalGeneric(x, y);
}
void RotatedLorentzConeConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DoEvalGeneric(x, y);
}
std::ostream& RotatedLorentzConeConstraint::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayConstraint(*this, os, "RotatedLorentzConeConstraint", vars,
false);
}
LinearConstraint::LinearConstraint(const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub)
: Constraint(A.rows(), A.cols(), lb, ub), A_(A) {
DRAKE_DEMAND(A.rows() == lb.rows());
DRAKE_DEMAND(A.array().isFinite().all());
}
LinearConstraint::LinearConstraint(const Eigen::SparseMatrix<double>& A,
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub)
: Constraint(A.rows(), A.cols(), lb, ub), A_(A) {
DRAKE_DEMAND(A.rows() == lb.rows());
DRAKE_DEMAND(A_.IsFinite());
}
const Eigen::MatrixXd& LinearConstraint::GetDenseA() const {
return A_.GetAsDense();
}
void LinearConstraint::UpdateCoefficients(
const Eigen::Ref<const Eigen::MatrixXd>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_lb,
const Eigen::Ref<const Eigen::VectorXd>& new_ub) {
if (new_A.rows() != new_lb.rows() || new_lb.rows() != new_ub.rows()) {
throw std::runtime_error("New constraints have invalid dimensions");
}
if (new_A.cols() != A_.get_as_sparse().cols()) {
throw std::runtime_error("Can't change the number of decision variables");
}
A_ = new_A;
DRAKE_DEMAND(A_.IsFinite());
set_num_outputs(A_.get_as_sparse().rows());
set_bounds(new_lb, new_ub);
}
void LinearConstraint::UpdateCoefficients(
const Eigen::SparseMatrix<double>& new_A,
const Eigen::Ref<const Eigen::VectorXd>& new_lb,
const Eigen::Ref<const Eigen::VectorXd>& new_ub) {
if (new_A.rows() != new_lb.rows() || new_lb.rows() != new_ub.rows()) {
throw std::runtime_error("New constraints have invalid dimensions");
}
if (new_A.cols() != A_.get_as_sparse().cols()) {
throw std::runtime_error("Can't change the number of decision variables");
}
A_ = new_A;
DRAKE_DEMAND(A_.IsFinite());
set_num_outputs(A_.get_as_sparse().rows());
set_bounds(new_lb, new_ub);
}
void LinearConstraint::RemoveTinyCoefficient(double tol) {
if (tol < 0) {
throw std::invalid_argument(
"RemoveTinyCoefficient: tol should be non-negative");
}
std::vector<Eigen::Triplet<double>> new_A_triplets;
const auto& A_sparse = A_.get_as_sparse();
new_A_triplets.reserve(A_sparse.nonZeros());
for (int i = 0; i < A_sparse.outerSize(); ++i) {
for (Eigen::SparseMatrix<double>::InnerIterator it(A_sparse, i); it; ++it) {
if (std::abs(it.value()) > tol) {
new_A_triplets.emplace_back(it.row(), it.col(), it.value());
}
}
}
Eigen::SparseMatrix<double> new_A(A_sparse.rows(), A_sparse.cols());
new_A.setFromTriplets(new_A_triplets.begin(), new_A_triplets.end());
UpdateCoefficients(new_A, lower_bound(), upper_bound());
}
template <typename DerivedX, typename ScalarY>
void LinearConstraint::DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x,
VectorX<ScalarY>* y) const {
y->resize(num_constraints());
(*y) = A_.get_as_sparse() * x.template cast<ScalarY>();
}
void LinearConstraint::DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
DoEvalGeneric(x, y);
}
void LinearConstraint::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
DoEvalGeneric(x, y);
}
void LinearConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DoEvalGeneric(x, y);
}
std::ostream& LinearConstraint::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayConstraint(*this, os, "LinearConstraint", vars, false);
}
std::ostream& LinearEqualityConstraint::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayConstraint(*this, os, "LinearEqualityConstraint", vars, true);
}
namespace internal {
Eigen::SparseMatrix<double> ConstructSparseIdentity(int rows) {
Eigen::SparseMatrix<double> mat(rows, rows);
mat.setIdentity();
return mat;
}
} // namespace internal
BoundingBoxConstraint::BoundingBoxConstraint(
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub)
: LinearConstraint(internal::ConstructSparseIdentity(lb.rows()), lb, ub) {}
template <typename DerivedX, typename ScalarY>
void BoundingBoxConstraint::DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x,
VectorX<ScalarY>* y) const {
y->resize(num_constraints());
(*y) = x.template cast<ScalarY>();
}
void BoundingBoxConstraint::DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
DoEvalGeneric(x, y);
}
void BoundingBoxConstraint::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
DoEvalGeneric(x, y);
}
void BoundingBoxConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DoEvalGeneric(x, y);
}
std::ostream& BoundingBoxConstraint::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayConstraint(*this, os, "BoundingBoxConstraint", vars, false);
}
template <typename DerivedX, typename ScalarY>
void LinearComplementarityConstraint::DoEvalGeneric(
const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const {
y->resize(num_constraints());
(*y) = (M_ * x.template cast<ScalarY>()) + q_;
}
void LinearComplementarityConstraint::DoEval(
const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const {
DoEvalGeneric(x, y);
}
void LinearComplementarityConstraint::DoEval(
const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const {
DoEvalGeneric(x, y);
}
void LinearComplementarityConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DoEvalGeneric(x, y);
}
bool LinearComplementarityConstraint::DoCheckSatisfied(
const Eigen::Ref<const Eigen::VectorXd>& x, const double tol) const {
// Check: x >= 0 && Mx + q >= 0 && x'(Mx + q) == 0
Eigen::VectorXd y(num_constraints());
DoEval(x, &y);
return (x.array() > -tol).all() && (y.array() > -tol).all() &&
(abs(x.dot(y)) < tol);
}
bool LinearComplementarityConstraint::DoCheckSatisfied(
const Eigen::Ref<const AutoDiffVecXd>& x, const double tol) const {
AutoDiffVecXd y(num_constraints());
DoEval(x, &y);
return (x.array() > -tol).all() && (y.array() > -tol).all() &&
(abs(x.dot(y)) < tol);
}
symbolic::Formula LinearComplementarityConstraint::DoCheckSatisfied(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x) const {
VectorX<symbolic::Expression> y(num_constraints());
DoEval(x, &y);
symbolic::Formula f{symbolic::Formula::True()};
// 1. Mx + q >= 0
for (VectorX<symbolic::Expression>::Index i = 0; i < y.size(); ++i) {
f = f && (y(i) >= 0);
}
// 2. x >= 0
for (VectorX<symbolic::Expression>::Index i = 0; i < x.size(); ++i) {
f = f && (x(i) >= 0);
}
// 3. x'(Mx + q) == 0
f = f && (x.dot(y) == 0);
return f;
}
void PositiveSemidefiniteConstraint::DoEval(
const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const {
DRAKE_ASSERT(x.rows() == num_constraints() * num_constraints());
Eigen::MatrixXd S(num_constraints(), num_constraints());
for (int i = 0; i < num_constraints(); ++i) {
S.col(i) = x.segment(i * num_constraints(), num_constraints());
}
DRAKE_ASSERT(S.rows() == num_constraints());
// This uses the lower diagonal part of S to compute the eigen values.
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigen_solver(S);
*y = eigen_solver.eigenvalues();
}
void PositiveSemidefiniteConstraint::DoEval(
const Eigen::Ref<const AutoDiffVecXd>&, AutoDiffVecXd*) const {
throw std::logic_error(
"The Eval function for positive semidefinite constraint is not defined, "
"since the eigen solver does not work for AutoDiffXd.");
}
void PositiveSemidefiniteConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>&,
VectorX<symbolic::Expression>*) const {
throw std::logic_error(
"The Eval function for positive semidefinite constraint is not defined, "
"since the eigen solver does not work for symbolic::Expression.");
}
void LinearMatrixInequalityConstraint::DoEval(
const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const {
DRAKE_ASSERT(x.rows() == static_cast<int>(F_.size()) - 1);
Eigen::MatrixXd S = F_[0];
for (int i = 1; i < static_cast<int>(F_.size()); ++i) {
S += x(i - 1) * F_[i];
}
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigen_solver(S);
*y = eigen_solver.eigenvalues();
}
void LinearMatrixInequalityConstraint::DoEval(
const Eigen::Ref<const AutoDiffVecXd>&, AutoDiffVecXd*) const {
throw std::logic_error(
"The Eval function for positive semidefinite constraint is not defined, "
"since the eigen solver does not work for AutoDiffXd.");
}
void LinearMatrixInequalityConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>&,
VectorX<symbolic::Expression>*) const {
throw std::logic_error(
"The Eval function for positive semidefinite constraint is not defined, "
"since the eigen solver does not work for symbolic::Expression.");
}
LinearMatrixInequalityConstraint::LinearMatrixInequalityConstraint(
const std::vector<Eigen::Ref<const Eigen::MatrixXd>>& F,
double symmetry_tolerance)
: Constraint(F.empty() ? 0 : F.front().rows(),
F.empty() ? 0 : F.size() - 1),
F_(F.begin(), F.end()),
matrix_rows_(F.empty() ? 0 : F.front().rows()) {
DRAKE_DEMAND(!F.empty());
set_bounds(Eigen::VectorXd::Zero(matrix_rows_),
Eigen::VectorXd::Constant(
matrix_rows_, std::numeric_limits<double>::infinity()));
for (const auto& Fi : F) {
DRAKE_ASSERT(Fi.rows() == matrix_rows_);
DRAKE_ASSERT(math::IsSymmetric(Fi, symmetry_tolerance));
}
}
ExpressionConstraint::ExpressionConstraint(
const Eigen::Ref<const VectorX<symbolic::Expression>>& v,
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub)
: Constraint(v.rows(), GetDistinctVariables(v).size(), lb, ub),
expressions_(v) {
// Setup map_var_to_index_ and vars_ so that
// map_var_to_index_[vars_(i).get_id()] = i.
std::tie(vars_, map_var_to_index_) =
symbolic::ExtractVariablesFromExpression(expressions_);
derivatives_ = symbolic::Jacobian(expressions_, vars_);
// Setup the environment.
for (int i = 0; i < vars_.size(); i++) {
environment_.insert(vars_[i], 0.0);
}
}
void ExpressionConstraint::DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const {
DRAKE_DEMAND(x.rows() == vars_.rows());
// Set environment with current x values.
for (int i = 0; i < vars_.size(); i++) {
environment_[vars_[i]] = x(map_var_to_index_.at(vars_[i].get_id()));
}
// Evaluate into the output, y.
y->resize(num_constraints());
for (int i = 0; i < num_constraints(); i++) {
(*y)[i] = expressions_[i].Evaluate(environment_);
}
}
void ExpressionConstraint::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
DRAKE_DEMAND(x.rows() == vars_.rows());
// Set environment with current x values.
for (int i = 0; i < vars_.size(); i++) {
environment_[vars_[i]] = x(map_var_to_index_.at(vars_[i].get_id())).value();
}
// Evaluate value and derivatives into the output, y.
// Using ∂yᵢ/∂zⱼ = ∑ₖ ∂fᵢ/∂xₖ ∂xₖ/∂zⱼ.
y->resize(num_constraints());
Eigen::VectorXd dyidx(x.size());
for (int i = 0; i < num_constraints(); i++) {
(*y)[i].value() = expressions_[i].Evaluate(environment_);
for (int k = 0; k < x.size(); k++) {
dyidx[k] = derivatives_(i, k).Evaluate(environment_);
}
(*y)[i].derivatives().resize(x(0).derivatives().size());
for (int j = 0; j < x(0).derivatives().size(); j++) {
(*y)[i].derivatives()[j] = 0.0;
for (int k = 0; k < x.size(); k++) {
(*y)[i].derivatives()[j] += dyidx[k] * x(k).derivatives()[j];
}
}
}
}
void ExpressionConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DRAKE_DEMAND(x.rows() == vars_.rows());
symbolic::Substitution subst;
for (int i = 0; i < vars_.size(); ++i) {
if (!vars_[i].equal_to(x[i])) {
subst.emplace(vars_[i], x[i]);
}
}
y->resize(num_constraints());
if (subst.empty()) {
*y = expressions_;
} else {
for (int i = 0; i < num_constraints(); ++i) {
(*y)[i] = expressions_[i].Substitute(subst);
}
}
}
std::ostream& ExpressionConstraint::DoDisplay(
std::ostream& os, const VectorX<symbolic::Variable>& vars) const {
return DisplayConstraint(*this, os, "ExpressionConstraint", vars, false);
}
ExponentialConeConstraint::ExponentialConeConstraint(
const Eigen::Ref<const Eigen::SparseMatrix<double>>& A,
const Eigen::Ref<const Eigen::Vector3d>& b)
: Constraint(
2, A.cols(), Eigen::Vector2d::Zero(),
Eigen::Vector2d::Constant(std::numeric_limits<double>::infinity())),
A_{A},
b_{b} {
DRAKE_DEMAND(A.rows() == 3);
}
template <typename DerivedX, typename ScalarY>
void ExponentialConeConstraint::DoEvalGeneric(
const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const {
y->resize(num_constraints());
Vector3<ScalarY> z = A_ * x.template cast<ScalarY>() + b_;
using std::exp;
(*y)(0) = z(0) - z(1) * exp(z(2) / z(1));
(*y)(1) = z(1);
}
void ExponentialConeConstraint::DoEval(
const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const {
DoEvalGeneric(x, y);
}
void ExponentialConeConstraint::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
DoEvalGeneric(x, y);
}
void ExponentialConeConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x,
VectorX<symbolic::Expression>* y) const {
DoEvalGeneric(x, y);
}
} // namespace solvers
} // namespace drake