/
graph_of_convex_sets.cc
1618 lines (1482 loc) · 61.2 KB
/
graph_of_convex_sets.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
// TODO(jwnimmer-tri) Port GetGraphvizString to fmt, once we have sufficient
// options there to control precision and scientific formatting.
#undef EIGEN_NO_IO
#include "drake/geometry/optimization/graph_of_convex_sets.h"
#include <limits>
#include <memory>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include <fmt/format.h>
#include "drake/math/quadratic_form.h"
#include "drake/solvers/choose_best_solver.h"
#include "drake/solvers/create_constraint.h"
#include "drake/solvers/create_cost.h"
#include "drake/solvers/get_program_type.h"
#include "drake/solvers/mosek_solver.h"
namespace drake {
namespace geometry {
namespace optimization {
using Edge = GraphOfConvexSets::Edge;
using EdgeId = GraphOfConvexSets::EdgeId;
using Transcription = GraphOfConvexSets::Transcription;
using Vertex = GraphOfConvexSets::Vertex;
using VertexId = GraphOfConvexSets::VertexId;
using Eigen::MatrixXd;
using Eigen::Ref;
using Eigen::RowVector2d;
using Eigen::RowVectorXd;
using Eigen::SparseMatrix;
using Eigen::VectorXd;
using solvers::Binding;
using solvers::Constraint;
using solvers::Cost;
using solvers::L1NormCost;
using solvers::L2NormCost;
using solvers::LinearConstraint;
using solvers::LinearCost;
using solvers::LinearEqualityConstraint;
using solvers::LInfNormCost;
using solvers::LorentzConeConstraint;
using solvers::MathematicalProgram;
using solvers::MathematicalProgramResult;
using solvers::MatrixXDecisionVariable;
using solvers::PerspectiveQuadraticCost;
using solvers::PositiveSemidefiniteConstraint;
using solvers::ProgramType;
using solvers::QuadraticCost;
using solvers::RotatedLorentzConeConstraint;
using solvers::SolutionResult;
using solvers::VariableRefList;
using solvers::VectorXDecisionVariable;
using solvers::internal::CreateBinding;
using symbolic::Expression;
using symbolic::Variable;
using symbolic::Variables;
namespace {
MathematicalProgramResult Solve(const MathematicalProgram& prog,
const GraphOfConvexSetsOptions& options) {
MathematicalProgramResult result;
if (options.solver) {
options.solver->Solve(prog, {}, options.solver_options, &result);
// TODO(wrangelvid): Call the MixedIntegerBranchAndBound solver when
// asking to solve the MIP without a solver that supports it.
} else {
std::unique_ptr<solvers::SolverInterface> solver{};
try {
solvers::SolverId solver_id = solvers::ChooseBestSolver(prog);
solver = solvers::MakeSolver(solver_id);
} catch (const std::exception&) {
// We should only get here if the user is trying to solve the MIP.
DRAKE_DEMAND(options.convex_relaxation == false);
// TODO(russt): Consider calling MixedIntegerBranchAndBound automatically
// here. The small trick is that we need to pass the SolverId into that
// constructor manually, and ChooseBestSolver doesn't make it easy to
// figure out what the best solver would be if we removed the integer
// variables.
throw std::runtime_error(
"GraphOfConvexSets: There is no solver available that can solve the "
"mixed-integer version of this problem. Please check "
"https://drake.mit.edu/doxygen_cxx/group__solvers.html for more "
"details about supported solvers and how to enable them.\n\n "
"Alternatively, you can try to solve the problem without integer "
"variables by setting options.convex_relaxation=true (and likely "
"setting options.max_rounded_paths > 0 if you want an "
"integer-feasible solution). See the documentation for "
"GraphOfConvexSetsOptions for more details.");
}
DRAKE_DEMAND(solver != nullptr);
solver->Solve(prog, {}, options.solver_options, &result);
}
return result;
}
struct VertexIdComparator {
bool operator()(const Vertex* lhs, const Vertex* rhs) const {
return lhs->id() < rhs->id();
}
};
struct EdgeIdComparator {
bool operator()(const Edge* lhs, const Edge* rhs) const {
return lhs->id() < rhs->id();
}
};
} // namespace
GraphOfConvexSets::~GraphOfConvexSets() = default;
Vertex::Vertex(VertexId id, const ConvexSet& set, std::string name)
: id_(id),
set_(set.Clone()),
name_(std::move(name)),
placeholder_x_(symbolic::MakeVectorContinuousVariable(
set_->ambient_dimension(), name_)) {}
Vertex::~Vertex() = default;
std::pair<Variable, Binding<Cost>> Vertex::AddCost(
const symbolic::Expression& e) {
return AddCost(solvers::internal::ParseCost(e));
}
std::pair<Variable, Binding<Cost>> Vertex::AddCost(
const Binding<Cost>& binding) {
DRAKE_THROW_UNLESS(
Variables(binding.variables()).IsSubsetOf(Variables(placeholder_x_)));
const int n = ell_.size();
ell_.conservativeResize(n + 1);
ell_[n] = Variable(fmt::format("v_ell{}", n), Variable::Type::CONTINUOUS);
costs_.emplace_back(binding);
return std::pair<Variable, Binding<Cost>>(ell_[n], costs_.back());
}
Binding<Constraint> Vertex::AddConstraint(
const symbolic::Formula& f,
const std::unordered_set<GraphOfConvexSets::Transcription>&
use_in_transcription) {
return AddConstraint(solvers::internal::ParseConstraint(f),
use_in_transcription);
}
Binding<Constraint> Vertex::AddConstraint(
const Binding<Constraint>& binding,
const std::unordered_set<GraphOfConvexSets::Transcription>&
use_in_transcription) {
DRAKE_THROW_UNLESS(ambient_dimension() > 0);
DRAKE_THROW_UNLESS(
Variables(binding.variables()).IsSubsetOf(Variables(placeholder_x_)));
DRAKE_THROW_UNLESS(use_in_transcription.size() > 0);
constraints_.push_back({binding, use_in_transcription});
return binding;
}
std::vector<solvers::Binding<solvers::Constraint>> Vertex::GetConstraints(
const std::unordered_set<GraphOfConvexSets::Transcription>&
used_in_transcription) const {
DRAKE_THROW_UNLESS(used_in_transcription.size() > 0);
std::vector<solvers::Binding<solvers::Constraint>> constraints;
// Add all constraints that are used in the transcription.
for (const auto& [binding, transcriptions] : constraints_) {
if (std::any_of(transcriptions.begin(), transcriptions.end(),
[&used_in_transcription](const auto& elem) {
return used_in_transcription.contains(elem);
})) {
constraints.push_back(binding);
}
}
return constraints;
}
double Vertex::GetSolutionCost(const MathematicalProgramResult& result) const {
return result.GetSolution(ell_).sum();
}
VectorXd Vertex::GetSolution(const MathematicalProgramResult& result) const {
return result.GetSolution(placeholder_x_);
}
void Vertex::AddIncomingEdge(Edge* e) {
incoming_edges_.push_back(e);
}
void Vertex::AddOutgoingEdge(Edge* e) {
outgoing_edges_.push_back(e);
}
void Vertex::RemoveIncomingEdge(Edge* e) {
incoming_edges_.erase(
std::remove(incoming_edges_.begin(), incoming_edges_.end(), e),
incoming_edges_.end());
}
void Vertex::RemoveOutgoingEdge(Edge* e) {
outgoing_edges_.erase(
std::remove(outgoing_edges_.begin(), outgoing_edges_.end(), e),
outgoing_edges_.end());
}
Edge::Edge(const EdgeId& id, Vertex* u, Vertex* v, std::string name)
: id_{id},
u_{u},
v_{v},
allowed_vars_{u_->x()},
phi_{name + "phi", symbolic::Variable::Type::BINARY},
name_(std::move(name)),
y_{symbolic::MakeVectorContinuousVariable(u_->ambient_dimension(),
name_ + "y")},
z_{symbolic::MakeVectorContinuousVariable(v_->ambient_dimension(),
name_ + "z")},
x_to_yz_{static_cast<size_t>(y_.size() + z_.size())} {
DRAKE_DEMAND(u_ != nullptr);
DRAKE_DEMAND(v_ != nullptr);
allowed_vars_.insert(Variables(v_->x()));
for (int i = 0; i < u_->ambient_dimension(); ++i) {
x_to_yz_.emplace(u_->x()[i], y_[i]);
}
for (int i = 0; i < v_->ambient_dimension(); ++i) {
x_to_yz_.emplace(v_->x()[i], z_[i]);
}
}
Edge::~Edge() = default;
std::pair<Variable, Binding<Cost>> Edge::AddCost(
const symbolic::Expression& e) {
return AddCost(solvers::internal::ParseCost(e));
}
std::pair<Variable, Binding<Cost>> Edge::AddCost(const Binding<Cost>& binding) {
DRAKE_THROW_UNLESS(Variables(binding.variables()).IsSubsetOf(allowed_vars_));
const int n = ell_.size();
ell_.conservativeResize(n + 1);
ell_[n] =
Variable(fmt::format("{}ell{}", name_, n), Variable::Type::CONTINUOUS);
costs_.emplace_back(binding);
return std::pair<Variable, Binding<Cost>>(ell_[n], costs_.back());
}
Binding<Constraint> Edge::AddConstraint(
const symbolic::Formula& f,
const std::unordered_set<GraphOfConvexSets::Transcription>&
use_in_transcription) {
return AddConstraint(solvers::internal::ParseConstraint(f),
use_in_transcription);
}
Binding<Constraint> Edge::AddConstraint(
const Binding<Constraint>& binding,
const std::unordered_set<GraphOfConvexSets::Transcription>&
use_in_transcription) {
const int total_ambient_dimension = allowed_vars_.size();
DRAKE_THROW_UNLESS(total_ambient_dimension > 0);
DRAKE_THROW_UNLESS(Variables(binding.variables()).IsSubsetOf(allowed_vars_));
DRAKE_THROW_UNLESS(use_in_transcription.size() > 0);
constraints_.push_back({binding, use_in_transcription});
return binding;
}
std::vector<solvers::Binding<solvers::Constraint>> Edge::GetConstraints(
const std::unordered_set<GraphOfConvexSets::Transcription>&
used_in_transcription) const {
DRAKE_THROW_UNLESS(used_in_transcription.size() > 0);
std::vector<solvers::Binding<solvers::Constraint>> constraints;
// Add all constraints that are used in the transcription.
for (const auto& [binding, transcriptions] : constraints_) {
if (std::any_of(transcriptions.begin(), transcriptions.end(),
[&used_in_transcription](const auto& elem) {
return used_in_transcription.contains(elem);
})) {
constraints.push_back(binding);
}
}
return constraints;
}
void Edge::AddPhiConstraint(bool phi_value) {
phi_value_ = phi_value;
}
void Edge::ClearPhiConstraints() {
phi_value_ = std::nullopt;
}
double Edge::GetSolutionCost(const MathematicalProgramResult& result) const {
return result.GetSolution(ell_).sum();
}
Eigen::VectorXd Edge::GetSolutionPhiXu(
const solvers::MathematicalProgramResult& result) const {
return result.GetSolution(y_);
}
Eigen::VectorXd Edge::GetSolutionPhiXv(
const solvers::MathematicalProgramResult& result) const {
return result.GetSolution(z_);
}
Vertex* GraphOfConvexSets::AddVertex(const ConvexSet& set, std::string name) {
if (name.empty()) {
name = fmt::format("v{}", vertices_.size());
}
VertexId id = VertexId::get_new_id();
auto [iter, success] = vertices_.try_emplace(id, new Vertex(id, set, name));
DRAKE_DEMAND(success);
return iter->second.get();
}
Edge* GraphOfConvexSets::AddEdge(Vertex* u, Vertex* v, std::string name) {
DRAKE_DEMAND(u != nullptr);
DRAKE_DEMAND(v != nullptr);
if (name.empty()) {
name = fmt::format("e{}", edges_.size());
}
EdgeId id = EdgeId::get_new_id();
auto [iter, success] = edges_.try_emplace(id, new Edge(id, u, v, name));
DRAKE_DEMAND(success);
Edge* e = iter->second.get();
u->AddOutgoingEdge(e);
v->AddIncomingEdge(e);
return e;
}
void GraphOfConvexSets::RemoveVertex(Vertex* vertex) {
DRAKE_THROW_UNLESS(vertex != nullptr);
VertexId vertex_id = vertex->id();
DRAKE_THROW_UNLESS(vertices_.contains(vertex_id));
for (auto it = edges_.begin(); it != edges_.end();) {
if (it->second->u().id() == vertex_id) {
it->second->v().RemoveIncomingEdge(it->second.get());
it = edges_.erase(it);
} else if (it->second->v().id() == vertex_id) {
it->second->u().RemoveOutgoingEdge(it->second.get());
it = edges_.erase(it);
} else {
++it;
}
}
vertices_.erase(vertex_id);
}
void GraphOfConvexSets::RemoveEdge(Edge* edge) {
DRAKE_THROW_UNLESS(edge != nullptr);
DRAKE_THROW_UNLESS(edges_.contains(edge->id()));
edge->u().RemoveOutgoingEdge(edge);
edge->v().RemoveIncomingEdge(edge);
edges_.erase(edge->id());
}
std::vector<Vertex*> GraphOfConvexSets::Vertices() {
std::vector<Vertex*> vertices;
vertices.reserve(vertices_.size());
for (const auto& v : vertices_) {
vertices.push_back(v.second.get());
}
return vertices;
}
std::vector<const Vertex*> GraphOfConvexSets::Vertices() const {
std::vector<const Vertex*> vertices;
vertices.reserve(vertices_.size());
for (const auto& v : vertices_) {
vertices.push_back(v.second.get());
}
return vertices;
}
std::vector<Edge*> GraphOfConvexSets::Edges() {
std::vector<Edge*> edges;
edges.reserve(edges_.size());
for (const auto& e : edges_) {
edges.push_back(e.second.get());
}
return edges;
}
std::vector<const Edge*> GraphOfConvexSets::Edges() const {
std::vector<const Edge*> edges;
edges.reserve(edges_.size());
for (const auto& e : edges_) {
edges.push_back(e.second.get());
}
return edges;
}
void GraphOfConvexSets::ClearAllPhiConstraints() {
for (const auto& e : edges_) {
e.second->ClearPhiConstraints();
}
}
// TODO(russt): We could get fancy and dim the color of the nodes/edges
// according to phi, using e.g. https://graphviz.org/docs/attr-types/color/ .
std::string GraphOfConvexSets::GetGraphvizString(
const std::optional<solvers::MathematicalProgramResult>& result,
bool show_slacks, int precision, bool scientific) const {
// Note: We use stringstream instead of fmt in order to control the
// formatting of the Eigen output and double output in a consistent way.
std::stringstream graphviz;
graphviz.precision(precision);
if (!scientific) graphviz << std::fixed;
graphviz << "digraph GraphOfConvexSets {\n";
graphviz << "labelloc=t;\n";
for (const auto& [v_id, v] : vertices_) {
graphviz << "v" << v_id << " [label=\"" << v->name();
if (result) {
graphviz << "\n x = [" << result->GetSolution(v->x()).transpose() << "]";
}
graphviz << "\"]\n";
}
for (const auto& [e_id, e] : edges_) {
unused(e_id);
graphviz << "v" << e->u().id() << " -> v" << e->v().id();
graphviz << " [label=\"" << e->name();
if (result) {
graphviz << "\n";
if (e->ell_.size() > 0) {
// SolveConvexRestriction does not yet return the rewritten costs.
if (result->get_decision_variable_index()->contains(
e->ell_[0].get_id())) {
graphviz << "cost = " << e->GetSolutionCost(*result);
}
} else {
graphviz << "cost = 0";
}
if (show_slacks) {
graphviz << ",\n";
graphviz << "ϕ = " << result->GetSolution(e->phi()) << ",\n";
if (result->get_decision_variable_index()->contains(
e->y_[0].get_id())) {
graphviz << "ϕ xᵤ = [" << e->GetSolutionPhiXu(*result).transpose()
<< "],\n";
graphviz << "ϕ xᵥ = [" << e->GetSolutionPhiXv(*result).transpose()
<< "]";
}
}
}
graphviz << "\"];\n";
}
graphviz << "}\n";
return graphviz.str();
}
// Implements the preprocessing scheme put forth in Appendix A.2 of
// "Motion Planning around Obstacles with Convex Optimization":
// https://arxiv.org/abs/2205.04422
std::set<EdgeId> GraphOfConvexSets::PreprocessShortestPath(
VertexId source_id, VertexId target_id,
const GraphOfConvexSetsOptions& options) const {
if (vertices_.find(source_id) == vertices_.end()) {
throw std::runtime_error(fmt::format(
"Source vertex {} is not a vertex in this GraphOfConvexSets.",
source_id));
}
if (vertices_.find(target_id) == vertices_.end()) {
throw std::runtime_error(fmt::format(
"Target vertex {} is not a vertex in this GraphOfConvexSets.",
target_id));
}
std::map<VertexId, std::vector<int>> incoming_edges;
std::map<VertexId, std::vector<int>> outgoing_edges;
std::set<EdgeId> unusable_edges;
int edge_count = 0;
for (const auto& [edge_id, e] : edges_) {
// Turn off edges into source or out of target
if (e->v().id() == source_id || e->u().id() == target_id) {
unusable_edges.insert(edge_id);
} else {
outgoing_edges[e->u().id()].push_back(edge_count);
incoming_edges[e->v().id()].push_back(edge_count);
}
edge_count++;
}
int nE = edges_.size();
// Given an edge (u,v) check if a path from source to u and another from v to
// target exist without sharing edges.
MathematicalProgram prog;
// Flow for each edge is between 0 and 1 for both paths.
VectorXDecisionVariable f = prog.NewContinuousVariables(nE, "flow_su");
Binding<solvers::BoundingBoxConstraint> f_limits =
prog.AddBoundingBoxConstraint(0, 1, f);
VectorXDecisionVariable g = prog.NewContinuousVariables(nE, "flow_vt");
Binding<solvers::BoundingBoxConstraint> g_limits =
prog.AddBoundingBoxConstraint(0, 1, g);
std::map<VertexId, Binding<LinearEqualityConstraint>> conservation_f;
std::map<VertexId, Binding<LinearEqualityConstraint>> conservation_g;
std::map<VertexId, Binding<LinearConstraint>> degree;
for (const auto& [vertex_id, v] : vertices_) {
std::vector<int> Ev_in = incoming_edges[vertex_id];
std::vector<int> Ev_out = outgoing_edges[vertex_id];
std::vector<int> Ev = Ev_in;
Ev.insert(Ev.end(), Ev_out.begin(), Ev_out.end());
if (Ev.size() > 0) {
RowVectorXd A_flow(Ev.size());
A_flow << RowVectorXd::Ones(Ev_in.size()),
-1 * RowVectorXd::Ones(Ev_out.size());
VectorXDecisionVariable fv(Ev.size());
VectorXDecisionVariable gv(Ev.size());
for (size_t ii = 0; ii < Ev.size(); ++ii) {
fv(ii) = f(Ev[ii]);
gv(ii) = g(Ev[ii]);
}
// Conservation of flow for f: ∑ f_in - ∑ f_out = -δ(is_source).
if (vertex_id == source_id) {
conservation_f.insert(
{vertex_id, prog.AddLinearEqualityConstraint(A_flow, -1, fv)});
} else {
conservation_f.insert(
{vertex_id, prog.AddLinearEqualityConstraint(A_flow, 0, fv)});
}
// Conservation of flow for g: ∑ g_in - ∑ g_out = δ(is_target).
if (vertex_id == target_id) {
conservation_g.insert(
{vertex_id, prog.AddLinearEqualityConstraint(A_flow, 1, gv)});
} else {
conservation_g.insert(
{vertex_id, prog.AddLinearEqualityConstraint(A_flow, 0, gv)});
}
}
// Degree constraints (redundant if indegree of w is 0):
// 0 <= ∑ f_in + ∑ g_in <= 1
if (Ev_in.size() > 0) {
RowVectorXd A_degree = RowVectorXd::Ones(2 * Ev_in.size());
VectorXDecisionVariable fgin(2 * Ev_in.size());
for (size_t ii = 0; ii < Ev_in.size(); ++ii) {
fgin(ii) = f(Ev_in[ii]);
fgin(Ev_in.size() + ii) = g(Ev_in[ii]);
}
degree.insert(
{vertex_id, prog.AddLinearConstraint(A_degree, 0, 1, fgin)});
}
}
for (const auto& [edge_id, e] : edges_) {
if (unusable_edges.contains(edge_id)) {
continue;
}
// Update bounds of conservation of flow:
// ∑ f_in,u - ∑ f_out,u = 1 - δ(is_source).
if (e->u().id() == source_id) {
f_limits.evaluator()->set_bounds(VectorXd::Zero(nE), VectorXd::Zero(nE));
conservation_f.at(e->u().id())
.evaluator()
->set_bounds(Vector1d(0), Vector1d(0));
} else {
conservation_f.at(e->u().id())
.evaluator()
->set_bounds(Vector1d(1), Vector1d(1));
}
// ∑ g_in,v - ∑ f_out,v = δ(is_target) - 1.
if (e->v().id() == target_id) {
g_limits.evaluator()->set_bounds(VectorXd::Zero(nE), VectorXd::Zero(nE));
conservation_g.at(e->v().id())
.evaluator()
->set_bounds(Vector1d(0), Vector1d(0));
} else {
conservation_g.at(e->v().id())
.evaluator()
->set_bounds(Vector1d(-1), Vector1d(-1));
}
// Update bounds of degree constraints:
// ∑ f_in,v + ∑ g_in,v = 0.
degree.at(e->v().id()).evaluator()->set_bounds(Vector1d(0), Vector1d(0));
// Check if edge e = (u,v) could be on a path from start to goal.
auto result = Solve(prog, options);
if (!result.is_success()) {
unusable_edges.insert(edge_id);
}
// Reset constraint bounds.
if (e->u().id() == source_id) {
f_limits.evaluator()->set_bounds(VectorXd::Zero(nE), VectorXd::Ones(nE));
conservation_f.at(e->u().id())
.evaluator()
->set_bounds(Vector1d(-1), Vector1d(-1));
} else {
conservation_f.at(e->u().id())
.evaluator()
->set_bounds(Vector1d(0), Vector1d(0));
}
if (e->v().id() == target_id) {
g_limits.evaluator()->set_bounds(VectorXd::Zero(nE), VectorXd::Ones(nE));
conservation_g.at(e->v().id())
.evaluator()
->set_bounds(Vector1d(1), Vector1d(1));
} else {
conservation_g.at(e->v().id())
.evaluator()
->set_bounds(Vector1d(0), Vector1d(0));
}
degree.at(e->v().id()).evaluator()->set_bounds(Vector1d(0), Vector1d(1));
}
return unusable_edges;
}
void GraphOfConvexSets::AddPerspectiveCost(
MathematicalProgram* prog, const Binding<Cost>& binding,
const VectorXDecisionVariable& vars) const {
const double inf = std::numeric_limits<double>::infinity();
// TODO(russt): Avoid this use of RTTI, which mirrors the current
// pattern in MathematicalProgram::AddCost.
Cost* cost = binding.evaluator().get();
if (LinearCost* lc = dynamic_cast<LinearCost*>(cost)) {
// TODO(russt): Consider setting a precision here (and exposing it to
// the user) instead of using Eigen's dummy_precision.
if (lc->a().isZero() && lc->b() < 0.0) {
throw std::runtime_error(fmt::format(
"Constant costs must be non-negative: {}", binding.to_string()));
}
// a*x + phi*b <= ell or [b, -1.0, a][phi; ell; x] <= 0
RowVectorXd a(lc->a().size() + 2);
a(0) = lc->b();
a(1) = -1.0;
a.tail(lc->a().size()) = lc->a();
prog->AddLinearConstraint(a, -inf, 0.0, vars);
} else if (QuadraticCost* qc = dynamic_cast<QuadraticCost*>(cost)) {
// .5 x'Qx + b'x + c is restated as a rotated Lorentz cone constraint
// enforcing that ℓ should be lower-bounded by the perspective, with
// coefficient ϕ, of the quadratic form:
// slack ≥ 0, and slack ϕ ≥ .5x'Qx, with slack := ℓ - b'x - ϕ c.
// TODO(russt): Allow users to set this tolerance. (Probably in
// solvers::QuadraticCost instead of here).
const double tol = 1e-10;
Eigen::MatrixXd R =
math::DecomposePSDmatrixIntoXtransposeTimesX(.5 * qc->Q(), tol);
// Note: QuadraticCost guarantees that Q() is symmetric.
const VectorXd xmin = -qc->Q().ldlt().solve(qc->b());
VectorXd minimum(1);
qc->Eval(xmin, &minimum);
if (minimum[0] < -tol) {
throw std::runtime_error(fmt::format(
"In order to prevent negative edge lengths, quadratic "
"costs must be strictly non-negative: {} obtains a minimum of "
"{}.",
binding.to_string(), minimum[0]));
}
MatrixXd A_cone = MatrixXd::Zero(R.rows() + 2, vars.size());
A_cone(0, 0) = 1.0; // z₀ = ϕ.
// z₁ = ℓ - b'x - ϕ c.
A_cone(1, 1) = 1.0;
A_cone.block(1, 2, 1, qc->b().rows()) = -qc->b().transpose();
A_cone(1, 0) = -qc->c();
// z₂ ... z_{n+1} = R x.
A_cone.block(2, 2, R.rows(), R.cols()) = R;
prog->AddRotatedLorentzConeConstraint(A_cone, VectorXd::Zero(A_cone.rows()),
vars);
} else if (L1NormCost* l1c = dynamic_cast<L1NormCost*>(cost)) {
// |Ax + b|₁ becomes ℓ ≥ Σᵢ δᵢ and δᵢ ≥ |Aᵢx+bᵢϕ|.
int A_rows = l1c->A().rows();
int A_cols = l1c->A().cols();
auto l1c_slack = prog->NewContinuousVariables(A_rows, "l1c_slack");
VectorXDecisionVariable cost_vars(vars.size() + l1c_slack.size());
cost_vars << vars, l1c_slack;
MatrixXd A_linear = MatrixXd::Zero(2 * A_rows + 1, cost_vars.size());
// δᵢ ≥ Aᵢx+bᵢϕ
A_linear.block(0, 0, A_rows, 1) = l1c->b(); // bϕ.
A_linear.block(0, 2, A_rows, A_cols) = l1c->A(); // Ax.
A_linear.block(0, A_cols + 2, A_rows, l1c_slack.size()) =
-MatrixXd::Identity(A_rows, A_rows); // -δ.
// -δᵢ ≤ Aᵢx+bᵢϕ
A_linear.block(A_rows, 0, A_rows, 1) = -l1c->b(); // -bϕ.
A_linear.block(A_rows, 2, A_rows, A_cols) = -l1c->A(); // -Ax.
A_linear.block(A_rows, A_cols + 2, A_rows, l1c_slack.size()) =
-MatrixXd::Identity(A_rows, A_rows); // -δ.
// ℓ ≥ Σᵢ δᵢ
A_linear(2 * A_rows, 1) = -1;
A_linear.block(2 * A_rows, A_cols + 2, 1, l1c_slack.size()) =
RowVectorXd::Ones(l1c_slack.size());
prog->AddLinearConstraint(A_linear,
VectorXd::Constant(A_linear.rows(), -inf),
VectorXd::Zero(A_linear.rows()), cost_vars);
} else if (L2NormCost* l2c = dynamic_cast<L2NormCost*>(cost)) {
// |Ax + b|₂ becomes ℓ ≥ |Ax+bϕ|₂.
MatrixXd A_cone =
MatrixXd::Zero(l2c->get_sparse_A().rows() + 1, vars.size());
A_cone(0, 1) = 1.0; // z₀ = ℓ.
A_cone.block(1, 0, l2c->get_sparse_A().rows(), 1) = l2c->b(); // bϕ.
A_cone.block(1, 2, l2c->get_sparse_A().rows(), l2c->get_sparse_A().cols()) =
l2c->get_sparse_A(); // Ax.
prog->AddLorentzConeConstraint(A_cone, VectorXd::Zero(A_cone.rows()), vars);
} else if (LInfNormCost* linfc = dynamic_cast<LInfNormCost*>(cost)) {
// |Ax + b|∞ becomes ℓ ≥ |Aᵢx+bᵢϕ| ∀ i.
int A_rows = linfc->A().rows();
MatrixXd A_linear(2 * A_rows, vars.size());
A_linear.block(0, 0, A_rows, 1) = linfc->b(); // bϕ.
A_linear.block(0, 1, A_rows, 1) = -VectorXd::Ones(A_rows); // -ℓ.
A_linear.block(0, 2, A_rows, linfc->A().cols()) = linfc->A(); // Ax.
A_linear.block(A_rows, 0, A_rows, 1) = -linfc->b(); // -bϕ.
A_linear.block(A_rows, 1, A_rows, 1) = -VectorXd::Ones(A_rows); // -ℓ.
A_linear.block(A_rows, 2, A_rows, linfc->A().cols()) = -linfc->A(); // -Ax.
prog->AddLinearConstraint(A_linear,
VectorXd::Constant(A_linear.rows(), -inf),
VectorXd::Zero(A_linear.rows()), vars);
} else if (PerspectiveQuadraticCost* pqc =
dynamic_cast<PerspectiveQuadraticCost*>(cost)) {
// (z_1^2 + ... + z_{n-1}^2) / z_0 for z = Ax + b becomes
// ℓ z_0 ≥ z_1^2 + ... + z_{n-1}^2 for z = Ax + bϕ
MatrixXd A_cone = MatrixXd::Zero(pqc->A().rows() + 1, vars.size());
A_cone(0, 1) = 1.0;
A_cone.block(1, 0, pqc->A().rows(), 1) = pqc->b();
A_cone.block(1, 2, pqc->A().rows(), pqc->A().cols()) = pqc->A();
prog->AddRotatedLorentzConeConstraint(
A_cone, VectorXd::Zero(pqc->A().rows() + 1), vars);
} else {
throw std::runtime_error(fmt::format(
"GraphOfConvexSets::Edge does not support this binding type: {}",
binding.to_string()));
}
}
void GraphOfConvexSets::AddPerspectiveConstraint(
MathematicalProgram* prog, const Binding<Constraint>& binding,
const VectorXDecisionVariable& vars) const {
const double inf = std::numeric_limits<double>::infinity();
Constraint* constraint = binding.evaluator().get();
if (LinearEqualityConstraint* lec =
dynamic_cast<LinearEqualityConstraint*>(constraint)) {
// A*x = b becomes A*x = phi*b.
const SparseMatrix<double>& A = lec->get_sparse_A();
SparseMatrix<double> Aeq(A.rows(), A.cols() + 1);
Aeq.col(0) = -lec->lower_bound().sparseView();
Aeq.rightCols(A.cols()) = A;
prog->AddConstraint(
CreateBinding(std::make_shared<LinearEqualityConstraint>(
Aeq, VectorXd::Zero(A.rows())),
vars));
// Note that LinearEqualityConstraint must come before LinearConstraint,
// because LinearEqualityConstraint isa LinearConstraint.
} else if (LinearConstraint* lc =
dynamic_cast<LinearConstraint*>(constraint)) {
// lb <= A*x <= ub becomes
// A*x <= phi*ub and phi*lb <= A*x, which can be spelled
// [-ub, A][phi; x] <= 0, and 0 <= [-lb, A][phi; x].
if (lc->upper_bound().array().isFinite().all()) {
const SparseMatrix<double>& A = lc->get_sparse_A();
SparseMatrix<double> Ac(A.rows(), A.cols() + 1);
Ac.col(0) = -lc->upper_bound().sparseView();
Ac.rightCols(A.cols()) = A;
prog->AddConstraint(
CreateBinding(std::make_shared<LinearConstraint>(
Ac, VectorXd::Constant(Ac.rows(), -inf),
VectorXd::Zero(Ac.rows())),
vars));
} else if (lc->upper_bound().array().isInf().all()) {
// Then do nothing.
} else {
// Need to go constraint by constraint.
// TODO(Alexandre.Amice) make this only access the sparse matrix.
const Eigen::MatrixXd& A = lc->GetDenseA();
RowVectorXd a(vars.size());
for (int i = 0; i < A.rows(); ++i) {
if (std::isfinite(lc->upper_bound()[i])) {
a[0] = -lc->upper_bound()[i];
a.tail(A.cols()) = A.row(i);
prog->AddLinearConstraint(a, -inf, 0, vars);
}
}
}
if (lc->lower_bound().array().isFinite().all()) {
const SparseMatrix<double>& A = lc->get_sparse_A();
SparseMatrix<double> Ac(A.rows(), A.cols() + 1);
Ac.col(0) = -lc->lower_bound().sparseView();
Ac.rightCols(A.cols()) = A;
prog->AddConstraint(CreateBinding(std::make_shared<LinearConstraint>(
Ac, VectorXd::Zero(Ac.rows()),
VectorXd::Constant(Ac.rows(), inf)),
vars));
} else if (lc->lower_bound().array().isInf().all()) {
// Then do nothing.
} else {
// Need to go constraint by constraint.
const Eigen::MatrixXd& A = lc->GetDenseA();
RowVectorXd a(vars.size());
for (int i = 0; i < A.rows(); ++i) {
if (std::isfinite(lc->lower_bound()[i])) {
a[0] = -lc->lower_bound()[i];
a.tail(A.cols()) = A.row(i);
prog->AddLinearConstraint(a, 0, inf, vars);
}
}
}
} else if (LorentzConeConstraint* lcc =
dynamic_cast<LorentzConeConstraint*>(constraint)) {
// z ∈ K for z = Ax + b becomes
// z ∈ K for z = Ax + bϕ = [b A] [ϕ; x]
// (Notice that this is the same as for a RotatedLorentzConeConstraint,
// as it does not depend on whether the cone is rotated or not).
MatrixXd A_cone = MatrixXd::Zero(lcc->A().rows(), vars.size());
A_cone.block(0, 0, lcc->A().rows(), 1) = lcc->b();
A_cone.block(0, 1, lcc->A().rows(), lcc->A().cols()) = lcc->A_dense();
prog->AddLorentzConeConstraint(A_cone, VectorXd::Zero(lcc->A().rows()),
vars);
} else if (RotatedLorentzConeConstraint* rc =
dynamic_cast<RotatedLorentzConeConstraint*>(constraint)) {
// z ∈ K for z = Ax + b becomes
// z ∈ K for z = Ax + bϕ = [b A] [ϕ; x]
// (Notice that this is the same as for a LorentzConeConstraint,
// as it does not depend on whether the cone is rotated or not).
MatrixXd A_cone = MatrixXd::Zero(rc->A().rows(), vars.size());
A_cone.block(0, 0, rc->A().rows(), 1) = rc->b();
A_cone.block(0, 1, rc->A().rows(), rc->A().cols()) = rc->A_dense();
prog->AddRotatedLorentzConeConstraint(A_cone,
VectorXd::Zero(rc->A().rows()), vars);
} else if (dynamic_cast<PositiveSemidefiniteConstraint*>(constraint) !=
nullptr) {
// Since we have ϕ ≥ 0, we have S ≽ 0 ⇔ ϕS ≽ 0.
// It is sufficient to add the original constraint to the program (with the
// new variables).
prog->AddConstraint(binding.evaluator(), vars.tail(vars.size() - 1));
} else {
throw std::runtime_error(
fmt::format("ShortestPathProblem::Edge does not support this "
"binding type: {}",
binding.to_string()));
}
}
MathematicalProgramResult GraphOfConvexSets::SolveShortestPath(
const Vertex& source, const Vertex& target,
const GraphOfConvexSetsOptions& specified_options) const {
VertexId source_id = source.id();
VertexId target_id = target.id();
if (vertices_.find(source_id) == vertices_.end()) {
throw std::runtime_error(fmt::format(
"Source vertex {} is not a vertex in this GraphOfConvexSets.",
source_id));
}
if (vertices_.find(target_id) == vertices_.end()) {
throw std::runtime_error(fmt::format(
"Target vertex {} is not a vertex in this GraphOfConvexSets.",
target_id));
}
// Fill in default options. Note: if these options change, they must also be
// updated in the method documentation.
GraphOfConvexSetsOptions options = specified_options;
if (!options.convex_relaxation) {
options.convex_relaxation = false;
}
if (!options.preprocessing) {
options.preprocessing = false;
}
if (!options.max_rounded_paths) {
options.max_rounded_paths = 0;
}
std::set<EdgeId> unusable_edges;
if (*options.preprocessing) {
unusable_edges = PreprocessShortestPath(source_id, target_id, options);
}
MathematicalProgram prog;
std::map<VertexId, std::vector<Edge*>> incoming_edges;
std::map<VertexId, std::vector<Edge*>> outgoing_edges;
std::map<VertexId, MatrixXDecisionVariable> vertex_edge_ell;
std::vector<Edge*> excluded_edges;
std::map<EdgeId, Variable> relaxed_phi;
std::vector<Variable> excluded_phi;
// The flow constraints below assume that we have some edge out of the source
// and into the target, so we handle that case explicitly.
bool has_edges_out_of_source = false;
bool has_edges_into_target = false;
for (const auto& [edge_id, e] : edges_) {
// If an edge is turned off (ϕ = 0) or excluded by preprocessing, don't
// include it in the optimization.
if (!e->phi_value_.value_or(true) || unusable_edges.contains(edge_id)) {
// Track excluded edges (ϕ = 0 and preprocessed) so that their variables
// can be set in the optimization result.
excluded_edges.emplace_back(e.get());
if (*options.convex_relaxation) {
Variable phi("phi_excluded");
excluded_phi.push_back(phi);
}
continue;
}
if (e->u().id() == source_id) {
has_edges_out_of_source = true;
}
if (e->v().id() == target_id) {
has_edges_into_target = true;
}
outgoing_edges[e->u().id()].emplace_back(e.get());
incoming_edges[e->v().id()].emplace_back(e.get());
Variable phi;
if (*options.convex_relaxation) {
phi = prog.NewContinuousVariables<1>(e->name() + "phi")[0];
prog.AddBoundingBoxConstraint(0, 1, phi);
relaxed_phi.emplace(edge_id, phi);
} else {
phi = e->phi_;
prog.AddDecisionVariables(Vector1<Variable>(phi));
}
if (e->phi_value_.has_value()) {
DRAKE_DEMAND(*e->phi_value_);
double phi_value = *e->phi_value_ ? 1.0 : 0.0;
prog.AddLinearEqualityConstraint(Vector1d(1.0), phi_value,
Vector1<Variable>(phi));
}
prog.AddDecisionVariables(e->y_);
prog.AddDecisionVariables(e->z_);
prog.AddDecisionVariables(e->ell_);
prog.AddLinearCost(VectorXd::Ones(e->ell_.size()), e->ell_);
// Spatial non-negativity: y ∈ ϕX, z ∈ ϕX.
if (e->u().ambient_dimension() > 0) {
e->u().set().AddPointInNonnegativeScalingConstraints(&prog, e->y_, phi);
}
if (e->v().ambient_dimension() > 0) {
e->v().set().AddPointInNonnegativeScalingConstraints(&prog, e->z_, phi);
}
// Edge costs.
for (int i = 0; i < e->ell_.size(); ++i) {
const Binding<Cost>& b = e->costs_[i];
const VectorXDecisionVariable& old_vars = b.variables();
VectorXDecisionVariable vars(old_vars.size() + 2);
// vars = [phi; ell; yz_vars]
vars[0] = phi;
vars[1] = e->ell_[i];
for (int j = 0; j < old_vars.size(); ++j) {
vars[j + 2] = e->x_to_yz_.at(old_vars[j]);
}
AddPerspectiveCost(&prog, b, vars);
}
// Edge constraints.
for (const auto& [b, transcriptions] : e->constraints_) {
if ((*options.convex_relaxation &&
transcriptions.contains(Transcription::kRelaxation)) ||
(!*options.convex_relaxation &&
transcriptions.contains(Transcription::kMIP))) {
const VectorXDecisionVariable& old_vars = b.variables();
VectorXDecisionVariable vars(old_vars.size() + 1);
// vars = [phi; yz_vars]
vars[0] = phi;
for (int j = 0; j < old_vars.size(); ++j) {
vars[j + 1] = e->x_to_yz_.at(old_vars[j]);
}
// Note: The use of perspective functions here does not check (nor
// assume) that the constraints describe a bounded set. The boundedness
// is ensured by the intersection of these constraints with the convex
// sets (on the vertices).
AddPerspectiveConstraint(&prog, b, vars);
}
}
}
if (!has_edges_out_of_source) {
MathematicalProgramResult result;
log()->info("Source vertex {} ({}) has no outgoing edges.", source.name(),
source_id);
result.set_solution_result(SolutionResult::kInfeasibleConstraints);
return result;
}
if (!has_edges_into_target) {
MathematicalProgramResult result;
log()->info("Target vertex {} ({}) has no incoming edges.", target.name(),
target_id);
result.set_solution_result(SolutionResult::kInfeasibleConstraints);
return result;
}