forked from RobotLocomotion/drake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmathematical_program.cc
1183 lines (1078 loc) · 45.3 KB
/
mathematical_program.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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "drake/solvers/mathematical_program.h"
#include <algorithm>
#include <cstddef>
#include <memory>
#include <ostream>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include "drake/common/eigen_types.h"
#include "drake/common/symbolic.h"
#include "drake/math/matrix_util.h"
#include "drake/solvers/sos_basis_generator.h"
#include "drake/solvers/symbolic_extraction.h"
namespace drake {
namespace solvers {
using std::enable_if;
using std::endl;
using std::find;
using std::is_same;
using std::make_pair;
using std::make_shared;
using std::map;
using std::numeric_limits;
using std::ostringstream;
using std::pair;
using std::runtime_error;
using std::set;
using std::shared_ptr;
using std::string;
using std::to_string;
using std::unordered_map;
using std::vector;
using symbolic::Expression;
using symbolic::Formula;
using symbolic::Variable;
using symbolic::Variables;
using internal::CreateBinding;
using internal::DecomposeLinearExpression;
using internal::SymbolicError;
MathematicalProgram::MathematicalProgram()
: x_initial_guess_(0),
optimal_cost_(numeric_limits<double>::quiet_NaN()),
lower_bound_cost_(-numeric_limits<double>::infinity()),
required_capabilities_{} {}
MathematicalProgram::~MathematicalProgram() = default;
std::unique_ptr<MathematicalProgram> MathematicalProgram::Clone() const {
// The constructor of MathematicalProgram will construct each solver. It
// also sets x_values_ and x_initial_guess_ to default values.
auto new_prog = std::make_unique<MathematicalProgram>();
// Add variables and indeterminates
// AddDecisionVariables and AddIndeterminates also set
// decision_variable_index_ and indeterminate_index_ properly.
new_prog->AddDecisionVariables(decision_variables_);
new_prog->AddIndeterminates(indeterminates_);
// Add costs
new_prog->generic_costs_ = generic_costs_;
new_prog->quadratic_costs_ = quadratic_costs_;
new_prog->linear_costs_ = linear_costs_;
// Add constraints
new_prog->generic_constraints_ = generic_constraints_;
new_prog->linear_constraints_ = linear_constraints_;
new_prog->linear_equality_constraints_ = linear_equality_constraints_;
new_prog->bbox_constraints_ = bbox_constraints_;
new_prog->lorentz_cone_constraint_ = lorentz_cone_constraint_;
new_prog->rotated_lorentz_cone_constraint_ =
rotated_lorentz_cone_constraint_;
new_prog->positive_semidefinite_constraint_ =
positive_semidefinite_constraint_;
new_prog->linear_matrix_inequality_constraint_ =
linear_matrix_inequality_constraint_;
new_prog->exponential_cone_constraints_ = exponential_cone_constraints_;
new_prog->linear_complementarity_constraints_ =
linear_complementarity_constraints_;
new_prog->x_initial_guess_ = x_initial_guess_;
new_prog->solver_id_ = solver_id_;
new_prog->solver_options_ = solver_options_;
new_prog->required_capabilities_ = required_capabilities_;
return new_prog;
}
MatrixXDecisionVariable MathematicalProgram::NewVariables(
VarType type, int rows, int cols, bool is_symmetric,
const vector<string>& names) {
MatrixXDecisionVariable decision_variable_matrix(rows, cols);
NewVariables_impl(type, names, is_symmetric, decision_variable_matrix);
return decision_variable_matrix;
}
MatrixXDecisionVariable MathematicalProgram::NewSymmetricContinuousVariables(
int rows, const string& name) {
vector<string> names(rows * (rows + 1) / 2);
int count = 0;
for (int j = 0; j < static_cast<int>(rows); ++j) {
for (int i = j; i < static_cast<int>(rows); ++i) {
names[count] = name + "(" + to_string(i) + "," + to_string(j) + ")";
++count;
}
}
return NewVariables(VarType::CONTINUOUS, rows, rows, true, names);
}
void MathematicalProgram::AddDecisionVariables(
const Eigen::Ref<const VectorXDecisionVariable>& decision_variables) {
const int num_existing_decision_vars = num_vars();
for (int i = 0; i < decision_variables.rows(); ++i) {
if (decision_variables(i).is_dummy()) {
throw std::runtime_error(fmt::format(
"decision_variables({}) should not be a dummy variable", i));
}
if (decision_variable_index_.find(decision_variables(i).get_id()) !=
decision_variable_index_.end()) {
throw std::runtime_error(fmt::format("{} is already a decision variable.",
decision_variables(i)));
}
if (indeterminates_index_.find(decision_variables(i).get_id()) !=
indeterminates_index_.end()) {
throw std::runtime_error(fmt::format("{} is already an indeterminate.",
decision_variables(i)));
}
decision_variable_index_.insert(std::make_pair(
decision_variables(i).get_id(), num_existing_decision_vars + i));
}
decision_variables_.conservativeResize(num_existing_decision_vars +
decision_variables.rows());
decision_variables_.tail(decision_variables.rows()) = decision_variables;
AppendNanToEnd(decision_variables.rows(), &x_values_);
AppendNanToEnd(decision_variables.rows(), &x_initial_guess_);
}
symbolic::Polynomial MathematicalProgram::NewFreePolynomial(
const Variables& indeterminates, const int degree,
const string& coeff_name) {
const drake::VectorX<symbolic::Monomial> m{
MonomialBasis(indeterminates, degree)};
const VectorXDecisionVariable coeffs{
NewContinuousVariables(m.size(), coeff_name)};
symbolic::Polynomial p;
for (int i = 0; i < m.size(); ++i) {
p.AddProduct(coeffs(i), m(i)); // p += coeffs(i) * m(i);
}
return p;
}
// This is the utility function for creating new nonnegative polynomials
// (sos-polynomial, sdsos-polynomial, dsos-polynomial). It creates a
// symmetric matrix Q as decision variables, and return m' * Q * m as the new
// polynomial, where m is the monomial basis.
pair<symbolic::Polynomial, MatrixXDecisionVariable>
MathematicalProgram::NewNonnegativePolynomial(
const Eigen::Ref<const VectorX<symbolic::Monomial>>& monomial_basis,
NonnegativePolynomial type) {
const MatrixXDecisionVariable Q =
NewSymmetricContinuousVariables(monomial_basis.size());
const symbolic::Polynomial p =
NewNonnegativePolynomial(Q, monomial_basis, type);
return std::make_pair(p, Q);
}
symbolic::Polynomial MathematicalProgram::NewNonnegativePolynomial(
const Eigen::Ref<const MatrixX<symbolic::Variable>>& grammian,
const Eigen::Ref<const VectorX<symbolic::Monomial>>& monomial_basis,
NonnegativePolynomial type) {
DRAKE_ASSERT(grammian.rows() == grammian.cols());
DRAKE_ASSERT(grammian.rows() == monomial_basis.rows());
// TODO(hongkai.dai & soonho.kong): ideally we should compute p in one line as
// monomial_basis.dot(grammian * monomial_basis). But as explained in #10200,
// this one line version is too slow, so we use this double for loop to
// compute the matrix product by hand. I will revert to the one line version
// when it is fast.
symbolic::Polynomial p{};
for (int i = 0; i < grammian.rows(); ++i) {
p.AddProduct(grammian(i, i), pow(monomial_basis(i), 2));
for (int j = i + 1; j < grammian.cols(); ++j) {
p.AddProduct(2 * grammian(i, j), monomial_basis(i) * monomial_basis(j));
}
}
switch (type) {
case MathematicalProgram::NonnegativePolynomial::kSos: {
AddPositiveSemidefiniteConstraint(grammian);
break;
}
case MathematicalProgram::NonnegativePolynomial::kSdsos: {
AddScaledDiagonallyDominantMatrixConstraint(grammian);
break;
}
case MathematicalProgram::NonnegativePolynomial::kDsos: {
AddPositiveDiagonallyDominantMatrixConstraint(
grammian.cast<symbolic::Expression>());
break;
}
}
return p;
}
pair<symbolic::Polynomial, MatrixXDecisionVariable>
MathematicalProgram::NewNonnegativePolynomial(
const symbolic::Variables& indeterminates, int degree,
NonnegativePolynomial type) {
DRAKE_DEMAND(degree > 0 && degree % 2 == 0);
const drake::VectorX<symbolic::Monomial> x{
MonomialBasis(indeterminates, degree / 2)};
return NewNonnegativePolynomial(x, type);
}
std::pair<symbolic::Polynomial, MatrixXDecisionVariable>
MathematicalProgram::NewSosPolynomial(
const Eigen::Ref<const VectorX<symbolic::Monomial>>& monomial_basis) {
return NewNonnegativePolynomial(
monomial_basis, MathematicalProgram::NonnegativePolynomial::kSos);
}
pair<symbolic::Polynomial, MatrixXDecisionVariable>
MathematicalProgram::NewSosPolynomial(const Variables& indeterminates,
const int degree) {
return NewNonnegativePolynomial(
indeterminates, degree, MathematicalProgram::NonnegativePolynomial::kSos);
}
MatrixXIndeterminate MathematicalProgram::NewIndeterminates(
int rows, int cols, const vector<string>& names) {
MatrixXIndeterminate indeterminates_matrix(rows, cols);
NewIndeterminates_impl(names, indeterminates_matrix);
return indeterminates_matrix;
}
VectorXIndeterminate MathematicalProgram::NewIndeterminates(
int rows, const std::vector<std::string>& names) {
return NewIndeterminates(rows, 1, names);
}
VectorXIndeterminate MathematicalProgram::NewIndeterminates(
int rows, const string& name) {
vector<string> names(rows);
for (int i = 0; i < static_cast<int>(rows); ++i) {
names[i] = name + "(" + to_string(i) + ")";
}
return NewIndeterminates(rows, names);
}
MatrixXIndeterminate MathematicalProgram::NewIndeterminates(
int rows, int cols, const string& name) {
vector<string> names(rows * cols);
int count = 0;
for (int j = 0; j < static_cast<int>(cols); ++j) {
for (int i = 0; i < static_cast<int>(rows); ++i) {
names[count] = name + "(" + to_string(i) + "," + to_string(j) + ")";
++count;
}
}
return NewIndeterminates(rows, cols, names);
}
void MathematicalProgram::AddIndeterminates(
const Eigen::Ref<const VectorXDecisionVariable>& new_indeterminates) {
const int num_old_indeterminates = num_indeterminates();
for (int i = 0; i < new_indeterminates.rows(); ++i) {
if (new_indeterminates(i).is_dummy()) {
throw std::runtime_error(fmt::format(
"new_indeterminates({}) should not be a dummy variable.", i));
}
if (indeterminates_index_.find(new_indeterminates(i).get_id()) !=
indeterminates_index_.end() ||
decision_variable_index_.find(new_indeterminates(i).get_id()) !=
decision_variable_index_.end()) {
throw std::runtime_error(
fmt::format("{} already exists in the optimization program.",
new_indeterminates(i)));
}
if (new_indeterminates(i).get_type() !=
symbolic::Variable::Type::CONTINUOUS) {
throw std::runtime_error("indeterminate should of type CONTINUOUS.\n");
}
indeterminates_index_.insert(std::make_pair(new_indeterminates(i).get_id(),
num_old_indeterminates + i));
}
indeterminates_.conservativeResize(num_old_indeterminates +
new_indeterminates.rows());
indeterminates_.tail(new_indeterminates.rows()) = new_indeterminates;
}
Binding<VisualizationCallback> MathematicalProgram::AddVisualizationCallback(
const VisualizationCallback::CallbackFunction &callback,
const Eigen::Ref<const VectorXDecisionVariable> &vars) {
visualization_callbacks_.push_back(
internal::CreateBinding<VisualizationCallback>(
make_shared<VisualizationCallback>(vars.size(), callback), vars));
required_capabilities_.insert(ProgramAttribute::kCallback);
return visualization_callbacks_.back();
}
Binding<Cost> MathematicalProgram::AddCost(const Binding<Cost>& binding) {
// See AddCost(const Binding<Constraint>&) for explanation
Cost* cost = binding.evaluator().get();
if (dynamic_cast<QuadraticCost*>(cost)) {
return AddCost(internal::BindingDynamicCast<QuadraticCost>(binding));
} else if (dynamic_cast<LinearCost*>(cost)) {
return AddCost(internal::BindingDynamicCast<LinearCost>(binding));
} else {
CheckBinding(binding);
required_capabilities_.insert(ProgramAttribute::kGenericCost);
generic_costs_.push_back(binding);
return generic_costs_.back();
}
}
Binding<LinearCost> MathematicalProgram::AddCost(
const Binding<LinearCost>& binding) {
CheckBinding(binding);
required_capabilities_.insert(ProgramAttribute::kLinearCost);
linear_costs_.push_back(binding);
return linear_costs_.back();
}
Binding<LinearCost> MathematicalProgram::AddLinearCost(const Expression& e) {
return AddCost(internal::ParseLinearCost(e));
}
Binding<LinearCost> MathematicalProgram::AddLinearCost(
const Eigen::Ref<const Eigen::VectorXd>& a, double b,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
return AddCost(make_shared<LinearCost>(a, b), vars);
}
Binding<QuadraticCost> MathematicalProgram::AddCost(
const Binding<QuadraticCost>& binding) {
CheckBinding(binding);
required_capabilities_.insert(ProgramAttribute::kQuadraticCost);
DRAKE_ASSERT(binding.evaluator()->Q().rows() ==
static_cast<int>(binding.GetNumElements()) &&
binding.evaluator()->b().rows() ==
static_cast<int>(binding.GetNumElements()));
quadratic_costs_.push_back(binding);
return quadratic_costs_.back();
}
Binding<QuadraticCost> MathematicalProgram::AddQuadraticCost(
const Expression& e) {
return AddCost(internal::ParseQuadraticCost(e));
}
Binding<QuadraticCost> MathematicalProgram::AddQuadraticErrorCost(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& x_desired,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
return AddCost(MakeQuadraticErrorCost(Q, x_desired), vars);
}
Binding<QuadraticCost> MathematicalProgram::AddQuadraticCost(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& b, double c,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
return AddCost(make_shared<QuadraticCost>(Q, b, c), vars);
}
Binding<QuadraticCost> MathematicalProgram::AddQuadraticCost(
const Eigen::Ref<const Eigen::MatrixXd>& Q,
const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
return AddQuadraticCost(Q, b, 0., vars);
}
Binding<PolynomialCost> MathematicalProgram::AddPolynomialCost(
const Expression& e) {
auto binding = AddCost(internal::ParsePolynomialCost(e));
return internal::BindingDynamicCast<PolynomialCost>(binding);
}
Binding<Cost> MathematicalProgram::AddCost(const Expression& e) {
return AddCost(internal::ParseCost(e));
}
void MathematicalProgram::AddMaximizeLogDeterminantSymmetricMatrixCost(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X) {
DRAKE_DEMAND(X.rows() == X.cols());
const int X_rows = X.rows();
auto Z_lower = NewContinuousVariables(X_rows * (X_rows + 1) / 2);
MatrixX<symbolic::Expression> Z(X_rows, X_rows);
Z.setZero();
// diag_Z is the diagonal matrix that only contains the diagonal entries of Z.
MatrixX<symbolic::Expression> diag_Z(X_rows, X_rows);
diag_Z.setZero();
int Z_lower_index = 0;
for (int j = 0; j < X_rows; ++j) {
for (int i = j; i < X_rows; ++i) {
Z(i, j) = Z_lower(Z_lower_index++);
}
diag_Z(j, j) = Z(j, j);
}
MatrixX<symbolic::Expression> psd_mat(2 * X_rows, 2 * X_rows);
// clang-format off
psd_mat << X, Z,
Z.transpose(), diag_Z;
// clang-format on
AddPositiveSemidefiniteConstraint(psd_mat);
// Now introduce the slack variable t.
auto t = NewContinuousVariables(X_rows);
// Introduce the constraint log(Z(i, i)) >= t(i).
for (int i = 0; i < X_rows; ++i) {
AddExponentialConeConstraint(
Vector3<symbolic::Expression>(Z(i, i), 1, t(i)));
}
AddLinearCost(-t.cast<symbolic::Expression>().sum());
}
void MathematicalProgram::AddMaximizeGeometricMeanCost(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorX<symbolic::Variable>>& x) {
if (A.rows() != b.rows() || A.cols() != x.rows()) {
throw std::invalid_argument(
"MathematicalProgram::AddMaximizeGeometricMeanCost: the argument A, b "
"and x don't have consistent size.");
}
if (A.rows() <= 1) {
throw std::runtime_error(
"MathematicalProgram::AddMaximizeGeometricMeanCost: the size of A*x+b "
"should be at least 2.");
}
// We will impose the constraint w(i)² ≤ (A.row(2i) * x + b(2i)) *
// (A.row(2i+1) * x + b(2i+1)). This could be reformulated as the vector
// C * [x;w(i)] + d is in the rotated Lorentz cone, where
// C = [A.row(2i) 0]
// [A.row(2i+1) 0]
// [0, 0, ...,0 1]
// d = [b(2i) ]
// [b(2i+1)]
// [0 ]
// The special case is that if A.rows() is an odd number, then for the last
// entry of w, we will impose (w((A.rows() - 1)/2)² ≤ A.row(A.rows() - 1) * x
// + b(b.rows() - 1)
auto w = NewContinuousVariables((A.rows() + 1) / 2);
DRAKE_ASSERT(w.rows() >= 1);
VectorX<symbolic::Variable> xw(x.rows() + 1);
xw.head(x.rows()) = x;
Eigen::Matrix3Xd C(3, x.rows() + 1);
for (int i = 0; i < w.size(); ++i) {
C.setZero();
C.row(0) << A.row(2 * i), 0;
Eigen::Vector3d d;
d(0) = b(2 * i);
if (2 * i + 1 == A.rows()) {
// The special case, C.row(1) * x + d(1) = 1.
C.row(1).setZero();
d(1) = 1;
} else {
// The normal case, C.row(1) * x + d(1) = A.row(2i+1) * x + b(2i+1)
C.row(1) << A.row(2 * i + 1), 0;
d(1) = b(2 * i + 1);
}
C.row(2).setZero();
C(2, C.cols() - 1) = 1;
d(2) = 0;
xw(x.rows()) = w(i);
AddRotatedLorentzConeConstraint(C, d, xw);
}
if (w.rows() == 1) {
AddLinearCost(-w(0));
return;
}
AddMaximizeGeometricMeanCost(w, 1);
}
void MathematicalProgram::AddMaximizeGeometricMeanCost(
const Eigen::Ref<const VectorX<symbolic::Variable>>& x, double c) {
if (c <= 0) {
throw std::invalid_argument(
"MathematicalProgram::AddMaximizeGeometricMeanCost(): c should be "
"positive.");
}
// We maximize the geometric mean through a recursive procedure. If we assume
// that the size of x is 2ᵏ, then in each iteration, we introduce new slack
// variables w of size 2ᵏ⁻¹, with the constraint
// w(i)² ≤ x(2i) * x(2i+1)
// we then call AddMaximizeGeometricMeanCost(w). This recusion ends until
// w.size() == 2. We then add the constraint z(0)² ≤ w(0) * w(1), and maximize
// the cost z(0).
if (x.rows() <= 1) {
throw std::invalid_argument(
"MathematicalProgram::AddMaximizeGeometricMeanCost(): x should have "
"more than one entry.");
}
// We will impose the constraint w(i)² ≤ x(2i) * x(2i+1). Namely the vector
// [x(2i); x(2i+1); w(i)] is in the rotated Lorentz cone.
// The special case is when x.rows() = 2n+1, then for the last
// entry of w, we impose the constraint w(n)² ≤ x(2n), namely the vector
// [x(2n); 1; w(n)] is in the rotated Lorentz cone.
auto w = NewContinuousVariables((x.rows() + 1) / 2);
DRAKE_ASSERT(w.rows() >= 1);
for (int i = 0; i < w.rows() - 1; ++i) {
AddRotatedLorentzConeConstraint(
Vector3<symbolic::Variable>(x(2 * i), x(2 * i + 1), w(i)));
}
if (2 * w.rows() == x.rows()) {
// x has even number of rows.
AddRotatedLorentzConeConstraint(Vector3<symbolic::Variable>(
x(x.rows() - 2), x(x.rows() - 1), w(w.rows() - 1)));
} else {
// x has odd number of rows.
// C * xw + d = [x(2n); 1; w(n)], where xw = [x(2n); w(n)].
Eigen::Matrix<double, 3, 2> C;
C << 1, 0, 0, 0, 0, 1;
const Eigen::Vector3d d(0, 1, 0);
AddRotatedLorentzConeConstraint(
C, d, Vector2<symbolic::Variable>(x(x.rows() - 1), w(w.rows() - 1)));
}
if (x.rows() == 2) {
AddLinearCost(-c * w(0));
return;
}
AddMaximizeGeometricMeanCost(w);
}
Binding<Constraint> MathematicalProgram::AddConstraint(
const Binding<Constraint>& binding) {
// TODO(eric.cousineau): Use alternative to RTTI.
// Move kGenericConstraint, etc. to Constraint. Dispatch based on this
// information. As it is, this causes extra work when we explicitly want a
// generic constraint.
// If we get here, then this was possibly a dynamically-simplified
// constraint. Determine correct container. As last resort, add to generic
// constraints.
Constraint* constraint = binding.evaluator().get();
// Check constraints types in reverse order, such that classes that inherit
// from other classes will not be prematurely added to less specific (or
// incorrect) container.
if (dynamic_cast<LinearMatrixInequalityConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<LinearMatrixInequalityConstraint>(
binding));
} else if (dynamic_cast<PositiveSemidefiniteConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<PositiveSemidefiniteConstraint>(binding));
} else if (dynamic_cast<RotatedLorentzConeConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<RotatedLorentzConeConstraint>(binding));
} else if (dynamic_cast<LorentzConeConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<LorentzConeConstraint>(binding));
} else if (dynamic_cast<LinearConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<LinearConstraint>(binding));
} else {
CheckBinding(binding);
required_capabilities_.insert(ProgramAttribute::kGenericConstraint);
generic_constraints_.push_back(binding);
return generic_constraints_.back();
}
}
Binding<Constraint> MathematicalProgram::AddConstraint(const Expression& e,
const double lb,
const double ub) {
return AddConstraint(internal::ParseConstraint(e, lb, ub));
}
Binding<Constraint> MathematicalProgram::AddConstraint(
const Eigen::Ref<const VectorX<Expression>>& v,
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub) {
return AddConstraint(internal::ParseConstraint(v, lb, ub));
}
Binding<Constraint> MathematicalProgram::AddConstraint(
const set<Formula>& formulas) {
return AddConstraint(internal::ParseConstraint(formulas));
}
Binding<Constraint> MathematicalProgram::AddConstraint(const Formula& f) {
return AddConstraint(internal::ParseConstraint(f));
}
Binding<LinearConstraint> MathematicalProgram::AddLinearConstraint(
const Expression& e, const double lb, const double ub) {
Binding<Constraint> binding = internal::ParseConstraint(e, lb, ub);
Constraint* constraint = binding.evaluator().get();
if (dynamic_cast<LinearConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<LinearConstraint>(binding));
} else {
std::stringstream oss;
oss << "Expression " << e << " is non-linear.";
throw std::runtime_error(oss.str());
}
}
Binding<LinearConstraint> MathematicalProgram::AddLinearConstraint(
const Eigen::Ref<const VectorX<Expression>>& v,
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub) {
Binding<Constraint> binding = internal::ParseConstraint(v, lb, ub);
Constraint* constraint = binding.evaluator().get();
if (dynamic_cast<LinearConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<LinearConstraint>(binding));
} else {
std::stringstream oss;
oss << "Expression " << v << " is non-linear.";
throw std::runtime_error(oss.str());
}
}
Binding<LinearConstraint> MathematicalProgram::AddLinearConstraint(
const Formula& f) {
Binding<Constraint> binding = internal::ParseConstraint(f);
Constraint* constraint = binding.evaluator().get();
if (dynamic_cast<LinearConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<LinearConstraint>(binding));
} else {
std::stringstream oss;
oss << "Formula " << f << " is non-linear.";
throw std::runtime_error(oss.str());
}
}
Binding<LinearConstraint> MathematicalProgram::AddConstraint(
const Binding<LinearConstraint>& binding) {
// Because the ParseConstraint methods can return instances of
// LinearEqualityConstraint or BoundingBoxConstraint, do a dynamic check
// here.
LinearConstraint* constraint = binding.evaluator().get();
if (dynamic_cast<BoundingBoxConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<BoundingBoxConstraint>(binding));
} else if (dynamic_cast<LinearEqualityConstraint*>(constraint)) {
return AddConstraint(
internal::BindingDynamicCast<LinearEqualityConstraint>(binding));
} else {
// TODO(eric.cousineau): This is a good assertion... But seems out of place,
// possibly redundant w.r.t. the binding infrastructure.
DRAKE_ASSERT(binding.evaluator()->A().cols() ==
static_cast<int>(binding.GetNumElements()));
CheckBinding(binding);
required_capabilities_.insert(ProgramAttribute::kLinearConstraint);
linear_constraints_.push_back(binding);
return linear_constraints_.back();
}
}
Binding<LinearConstraint> MathematicalProgram::AddLinearConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
return AddConstraint(make_shared<LinearConstraint>(A, lb, ub), vars);
}
Binding<LinearEqualityConstraint> MathematicalProgram::AddConstraint(
const Binding<LinearEqualityConstraint>& binding) {
DRAKE_ASSERT(binding.evaluator()->A().cols() ==
static_cast<int>(binding.GetNumElements()));
CheckBinding(binding);
required_capabilities_.insert(ProgramAttribute::kLinearEqualityConstraint);
linear_equality_constraints_.push_back(binding);
return linear_equality_constraints_.back();
}
Binding<LinearEqualityConstraint>
MathematicalProgram::AddLinearEqualityConstraint(const Expression& e,
double b) {
return AddConstraint(internal::ParseLinearEqualityConstraint(e, b));
}
Binding<LinearEqualityConstraint>
MathematicalProgram::AddLinearEqualityConstraint(const set<Formula>& formulas) {
return AddConstraint(internal::ParseLinearEqualityConstraint(formulas));
}
Binding<LinearEqualityConstraint>
MathematicalProgram::AddLinearEqualityConstraint(const Formula& f) {
return AddConstraint(internal::ParseLinearEqualityConstraint(f));
}
Binding<LinearEqualityConstraint>
MathematicalProgram::AddLinearEqualityConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& Aeq,
const Eigen::Ref<const Eigen::VectorXd>& beq,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
return AddConstraint(make_shared<LinearEqualityConstraint>(Aeq, beq), vars);
}
Binding<BoundingBoxConstraint> MathematicalProgram::AddConstraint(
const Binding<BoundingBoxConstraint>& binding) {
CheckBinding(binding);
DRAKE_ASSERT(binding.evaluator()->num_outputs() ==
static_cast<int>(binding.GetNumElements()));
required_capabilities_.insert(ProgramAttribute::kLinearConstraint);
bbox_constraints_.push_back(binding);
return bbox_constraints_.back();
}
Binding<LorentzConeConstraint> MathematicalProgram::AddConstraint(
const Binding<LorentzConeConstraint>& binding) {
CheckBinding(binding);
required_capabilities_.insert(ProgramAttribute::kLorentzConeConstraint);
lorentz_cone_constraint_.push_back(binding);
return lorentz_cone_constraint_.back();
}
Binding<LorentzConeConstraint> MathematicalProgram::AddLorentzConeConstraint(
const Eigen::Ref<const VectorX<Expression>>& v) {
return AddConstraint(internal::ParseLorentzConeConstraint(v));
}
Binding<LorentzConeConstraint> MathematicalProgram::AddLorentzConeConstraint(
const Expression& linear_expression, const Expression& quadratic_expression,
double tol) {
return AddConstraint(internal::ParseLorentzConeConstraint(
linear_expression, quadratic_expression, tol));
}
Binding<LorentzConeConstraint> MathematicalProgram::AddLorentzConeConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
shared_ptr<LorentzConeConstraint> constraint =
make_shared<LorentzConeConstraint>(A, b);
return AddConstraint(Binding<LorentzConeConstraint>(constraint, vars));
}
Binding<RotatedLorentzConeConstraint> MathematicalProgram::AddConstraint(
const Binding<RotatedLorentzConeConstraint>& binding) {
CheckBinding(binding);
required_capabilities_.insert(
ProgramAttribute::kRotatedLorentzConeConstraint);
rotated_lorentz_cone_constraint_.push_back(binding);
return rotated_lorentz_cone_constraint_.back();
}
Binding<RotatedLorentzConeConstraint>
MathematicalProgram::AddRotatedLorentzConeConstraint(
const symbolic::Expression& linear_expression1,
const symbolic::Expression& linear_expression2,
const symbolic::Expression& quadratic_expression, double tol) {
auto binding = internal::ParseRotatedLorentzConeConstraint(
linear_expression1, linear_expression2, quadratic_expression, tol);
AddConstraint(binding);
return binding;
}
Binding<RotatedLorentzConeConstraint>
MathematicalProgram::AddRotatedLorentzConeConstraint(
const Eigen::Ref<const VectorX<Expression>>& v) {
auto binding = internal::ParseRotatedLorentzConeConstraint(v);
AddConstraint(binding);
return binding;
}
Binding<RotatedLorentzConeConstraint>
MathematicalProgram::AddRotatedLorentzConeConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
shared_ptr<RotatedLorentzConeConstraint> constraint =
make_shared<RotatedLorentzConeConstraint>(A, b);
return AddConstraint(constraint, vars);
}
Binding<BoundingBoxConstraint> MathematicalProgram::AddBoundingBoxConstraint(
const Eigen::Ref<const Eigen::VectorXd>& lb,
const Eigen::Ref<const Eigen::VectorXd>& ub,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
shared_ptr<BoundingBoxConstraint> constraint =
make_shared<BoundingBoxConstraint>(lb, ub);
return AddConstraint(Binding<BoundingBoxConstraint>(constraint, vars));
}
Binding<LinearComplementarityConstraint> MathematicalProgram::AddConstraint(
const Binding<LinearComplementarityConstraint>& binding) {
CheckBinding(binding);
required_capabilities_.insert(
ProgramAttribute::kLinearComplementarityConstraint);
linear_complementarity_constraints_.push_back(binding);
return linear_complementarity_constraints_.back();
}
Binding<LinearComplementarityConstraint>
MathematicalProgram::AddLinearComplementarityConstraint(
const Eigen::Ref<const Eigen::MatrixXd>& M,
const Eigen::Ref<const Eigen::VectorXd>& q,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
shared_ptr<LinearComplementarityConstraint> constraint =
make_shared<LinearComplementarityConstraint>(M, q);
return AddConstraint(constraint, vars);
}
Binding<Constraint> MathematicalProgram::AddPolynomialConstraint(
const VectorXPoly& polynomials,
const vector<Polynomiald::VarType>& poly_vars, const Eigen::VectorXd& lb,
const Eigen::VectorXd& ub,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
auto constraint =
internal::MakePolynomialConstraint(polynomials, poly_vars, lb, ub);
return AddConstraint(constraint, vars);
}
Binding<PositiveSemidefiniteConstraint> MathematicalProgram::AddConstraint(
const Binding<PositiveSemidefiniteConstraint>& binding) {
CheckBinding(binding);
DRAKE_ASSERT(math::IsSymmetric(Eigen::Map<const MatrixXDecisionVariable>(
binding.variables().data(), binding.evaluator()->matrix_rows(),
binding.evaluator()->matrix_rows())));
required_capabilities_.insert(
ProgramAttribute::kPositiveSemidefiniteConstraint);
positive_semidefinite_constraint_.push_back(binding);
return positive_semidefinite_constraint_.back();
}
Binding<PositiveSemidefiniteConstraint> MathematicalProgram::AddConstraint(
shared_ptr<PositiveSemidefiniteConstraint> con,
const Eigen::Ref<const MatrixXDecisionVariable>& symmetric_matrix_var) {
DRAKE_ASSERT(math::IsSymmetric(symmetric_matrix_var));
int num_rows = symmetric_matrix_var.rows();
// TODO(hongkai.dai): this dynamic memory allocation/copying is ugly.
// TODO(eric.cousineau): See if Eigen::Map<> can be used (column-major)
VectorXDecisionVariable flat_symmetric_matrix_var(num_rows * num_rows);
for (int i = 0; i < num_rows; ++i) {
flat_symmetric_matrix_var.segment(i * num_rows, num_rows) =
symmetric_matrix_var.col(i);
}
return AddConstraint(CreateBinding(con, flat_symmetric_matrix_var));
}
Binding<PositiveSemidefiniteConstraint>
MathematicalProgram::AddPositiveSemidefiniteConstraint(
const Eigen::Ref<const MatrixXDecisionVariable>& symmetric_matrix_var) {
auto constraint =
make_shared<PositiveSemidefiniteConstraint>(symmetric_matrix_var.rows());
return AddConstraint(constraint, symmetric_matrix_var);
}
Binding<LinearMatrixInequalityConstraint> MathematicalProgram::AddConstraint(
const Binding<LinearMatrixInequalityConstraint>& binding) {
CheckBinding(binding);
DRAKE_ASSERT(static_cast<int>(binding.evaluator()->F().size()) ==
static_cast<int>(binding.GetNumElements()) + 1);
required_capabilities_.insert(
ProgramAttribute::kPositiveSemidefiniteConstraint);
linear_matrix_inequality_constraint_.push_back(binding);
return linear_matrix_inequality_constraint_.back();
}
Binding<LinearMatrixInequalityConstraint>
MathematicalProgram::AddLinearMatrixInequalityConstraint(
const vector<Eigen::Ref<const Eigen::MatrixXd>>& F,
const Eigen::Ref<const VectorXDecisionVariable>& vars) {
auto constraint = make_shared<LinearMatrixInequalityConstraint>(F);
return AddConstraint(constraint, vars);
}
MatrixX<symbolic::Expression>
MathematicalProgram::AddPositiveDiagonallyDominantMatrixConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X) {
// First create the slack variables Y with the same size as X, Y being the
// symmetric matrix representing the absolute value of X.
const int num_X_rows = X.rows();
DRAKE_DEMAND(X.cols() == num_X_rows);
auto Y_upper = NewContinuousVariables((num_X_rows - 1) * num_X_rows / 2,
"diagonally_dominant_slack");
MatrixX<symbolic::Expression> Y(num_X_rows, num_X_rows);
int Y_upper_count = 0;
// Fill in the upper triangle of Y.
for (int j = 0; j < num_X_rows; ++j) {
for (int i = 0; i < j; ++i) {
Y(i, j) = Y_upper(Y_upper_count);
Y(j, i) = Y(i, j);
++Y_upper_count;
}
// The diagonal entries of Y.
Y(j, j) = X(j, j);
}
// Add the constraint that Y(i, j) >= |X(i, j) + X(j, i) / 2|
for (int i = 0; i < num_X_rows; ++i) {
for (int j = i + 1; j < num_X_rows; ++j) {
AddLinearConstraint(Y(i, j) >= (X(i, j) + X(j, i)) / 2);
AddLinearConstraint(Y(i, j) >= -(X(i, j) + X(j, i)) / 2);
}
}
// Add the constraint X(i, i) >= sum_j Y(i, j), j ≠ i
for (int i = 0; i < num_X_rows; ++i) {
symbolic::Expression y_sum = 0;
for (int j = 0; j < num_X_rows; ++j) {
if (j == i) {
continue;
}
y_sum += Y(i, j);
}
AddLinearConstraint(X(i, i) >= y_sum);
}
return Y;
}
namespace {
// Add the slack variable for scaled diagonally dominant matrix constraint. In
// AddScaledDiagonallyDominantMatrixConstraint, we should add the constraint
// that the diagonal terms in the sdd matrix should match the summation of
// the diagonally terms in the slack variable, and the upper diagonal corner
// in M[i][j] should satisfy the rotated Lorentz cone constraint.
template <typename T>
void AddSlackVariableForScaledDiagonallyDominantMatrixConstraint(
const Eigen::Ref<const MatrixX<T>>& X, MathematicalProgram* prog,
Eigen::Matrix<symbolic::Variable, 2, Eigen::Dynamic>* M_ij_diagonal,
std::vector<std::vector<Matrix2<T>>>* M) {
const int n = X.rows();
DRAKE_DEMAND(X.cols() == n);
// The diagonal terms of M[i][j] are new variables.
// M[i][j](0, 0) = M_ij_diagonal(0, k)
// M[i][j](1, 1) = M_ij_diagonal(1, k)
// where k = (2n - 1) * i / 2 + j - i - 1, namely k is the index of X(i, j)
// in the vector X_upper_diagonal, where X_upper_diagonal is obtained by
// stacking each row of the upper diagonal part (not including the diagonal
// entries) in X to a row vector.
*M_ij_diagonal = prog->NewContinuousVariables<2, Eigen::Dynamic>(
2, (n - 1) * n / 2, "sdd_slack_M");
int k = 0;
M->resize(n);
for (int i = 0; i < n; ++i) {
(*M)[i].resize(n);
for (int j = i + 1; j < n; ++j) {
(*M)[i][j](0, 0) = (*M_ij_diagonal)(0, k);
(*M)[i][j](1, 1) = (*M_ij_diagonal)(1, k);
(*M)[i][j](0, 1) = X(i, j);
(*M)[i][j](1, 0) = X(j, i);
++k;
}
}
}
} // namespace
std::vector<std::vector<Matrix2<symbolic::Expression>>>
MathematicalProgram::AddScaledDiagonallyDominantMatrixConstraint(
const Eigen::Ref<const MatrixX<symbolic::Expression>>& X) {
const int n = X.rows();
std::vector<std::vector<Matrix2<symbolic::Expression>>> M(n);
Matrix2X<symbolic::Variable> M_ij_diagonal;
AddSlackVariableForScaledDiagonallyDominantMatrixConstraint<
symbolic::Expression>(X, this, &M_ij_diagonal, &M);
for (int i = 0; i < n; ++i) {
symbolic::Expression diagonal_sum = 0;
for (int j = 0; j < i; ++j) {
diagonal_sum += M[j][i](1, 1);
}
for (int j = i + 1; j < n; ++j) {
diagonal_sum += M[i][j](0, 0);
AddRotatedLorentzConeConstraint(Vector3<symbolic::Expression>(
M[i][j](0, 0), M[i][j](1, 1), M[i][j](0, 1)));
}
AddLinearEqualityConstraint(X(i, i) - diagonal_sum, 0);
}
return M;
}
std::vector<std::vector<Matrix2<symbolic::Variable>>>
MathematicalProgram::AddScaledDiagonallyDominantMatrixConstraint(
const Eigen::Ref<const MatrixX<symbolic::Variable>>& X) {
const int n = X.rows();
std::vector<std::vector<Matrix2<symbolic::Variable>>> M(n);
Matrix2X<symbolic::Variable> M_ij_diagonal;
AddSlackVariableForScaledDiagonallyDominantMatrixConstraint<
symbolic::Variable>(X, this, &M_ij_diagonal, &M);
// k is the index of X(i, j) in the vector X_upper_diagonal, where
// X_upper_diagonal is obtained by stacking each row of the upper diagonal
// part in X to a row vector.
auto ij_to_k = [&n](int i, int j) {
return (2 * n - 1 - i) * i / 2 + j - i - 1;
};
// diagonal_sum_var = [M_ij_diagonal(:); X(0, 0); X(1, 1); ...; X(n-1, n-1)]
const int n_square = n * n;
VectorXDecisionVariable diagonal_sum_var(n_square);
for (int i = 0; i < (n_square - n) / 2; ++i) {
diagonal_sum_var.segment<2>(2 * i) = M_ij_diagonal.col(i);
}