-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsynthesis.cpp
More file actions
1975 lines (1873 loc) · 68.5 KB
/
Copy pathsynthesis.cpp
File metadata and controls
1975 lines (1873 loc) · 68.5 KB
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 <optional>
#include <random>
//#include <glpk.h>
#include <Python.h>
#include "abstract.hpp"
#define MAX_SPLITS 1
#define ABSTRACT_DOMAIN AbstractDomain::INTERVAL
//static PyObject* DomainError;
struct Interval {
Eigen::MatrixXd lower;
Eigen::MatrixXd upper;
};
/**
* A Space is just a polytope along with its bounding box.
*/
struct Space {
LinCons space;
Eigen::VectorXd bb_lower;
Eigen::VectorXd bb_upper;
};
/**
* A linear controller.
*/
struct Controller {
/** The controller itself: the action is u = K x */
Eigen::MatrixXd k;
/** A region for which this controller is invariant. */
LinCons invariant;
/** The space this controller is intended to cover. */
Space space;
};
class Environment {
public:
/** True if the environment uses continuous semantics. */
bool continuous;
/** The time step for continuous environments. */
double dt;
/** The safe part of the state space. */
std::vector<LinCons> unsafe_space;
Environment(bool c, double d, const std::vector<LinCons>& unsafe):
continuous(c), dt(d), unsafe_space(unsafe) {}
/**
* Take a concrete step in this environment.
*
* \param state The current state of the system.
* \param controller The controller to use for this step.
* \return The new state of the system.
*/
virtual Eigen::VectorXd step(const Eigen::VectorXd& state,
const Eigen::MatrixXd& controller) const = 0;
/**
* Take a step using an abstract state and a concrete controller.
*
* \param state The (asbstract) state of the system.
* \param controller The (concrete) controller to use.
* \return The new (abstract) state of the system.
*/
virtual std::unique_ptr<AbstractVal> semi_abstract_step(
const AbstractVal& state, const Eigen::MatrixXd& controller) const = 0;
/**
* Take a step using an abstract state and an interval of controllers.
*
* \param state The current system state.
* \param controller The interval of possible controllers.
* \return The new system state.
*/
virtual std::unique_ptr<AbstractVal> abstract_step(
const AbstractVal& state, const Interval& controller) const = 0;
/**
* Find the largest invariant for some controller.
*
* In general a controller may be safe for a region larger than the cover
* for which it was computed. Here we want to find the largest region in which
* the given controller is safe.
*
* \param env The environment under control.
* \param cover The initial space covered by the controller.
* \param bound The bound on the time horizon.
* \param other_covers The regions covered by other controllers.
* \param k The controller.
* \return The region over which the controller is safe.
*/
virtual LinCons compute_invariant(const Space& cover, int bound,
const std::vector<LinCons>& other_covers,
const Eigen::MatrixXd& k) const = 0;
virtual ~Environment() = default;
};
bool controller_is_safe(const Environment& env, const Controller& controller,
const std::vector<LinCons>& covers, int bound);
/**
* A linear environment.
*
* The environment behavior is defined as follows: if `continuous` is true
* then \f$\dot{x} = A x + B u\f$ where \f$x\f$ is the state and \f$u\f$ is an
* action. This continuous environment is discretized with a time step `dt`.
* If `continuous` is false then \f$x' = A x + B u\f$ where \f$x'\f$ is the
* state in the next time step and `dt` is not used. In either case,
* `unsafe_space` defines the unsafe part of the state space.
*/
class LinearEnv: public Environment {
public:
/** An environment transition matrix. */
Eigen::MatrixXd A;
/** An environment transition matrix. */
Eigen::MatrixXd B;
LinearEnv(const Eigen::MatrixXd& a, const Eigen::MatrixXd& b, bool c,
double d, const std::vector<LinCons>& unsafe):
Environment(c, d, unsafe), A(a), B(b) {}
Eigen::VectorXd step(const Eigen::VectorXd& state,
const Eigen::MatrixXd& controller) const override {
if (continuous) {
return state + dt * (A * state + B * controller * state);
} else {
return A * state + B * controller * state;
}
}
std::unique_ptr<AbstractVal> semi_abstract_step(const AbstractVal& state,
const Eigen::MatrixXd& controller) const override {
if (continuous) {
// x' = x + dt (A x + B K x) = x + dt (A + B K) x
// = (I + dt * (A + B K)) x
Eigen::MatrixXd transition =
Eigen::MatrixXd::Identity(A.rows(), A.rows()) +
dt * (A + B * controller);
return state.scalar_affine(transition,
Eigen::VectorXd::Zero(A.rows()));
} else {
return state.scalar_affine(A + B * controller,
Eigen::VectorXd::Zero(A.rows()));
}
}
std::unique_ptr<AbstractVal> abstract_step(const AbstractVal& state,
const Interval& controller) const override {
// Construct upper and lower bounds on the transition matrix. For a
// concrete matrix we have W = A + B K for discrete environments or
// W = I + dt (A + B K) = I + dt A + dt B K for continuous environments.
Eigen::MatrixXd w_lower, w_upper;
if (continuous) {
w_lower = Eigen::MatrixXd::Identity(A.rows(), A.rows()) + dt * A;
w_upper = Eigen::MatrixXd::Identity(A.rows(), A.rows()) + dt * A;
} else {
w_lower = A;
w_upper = A;
}
// At this point w_lower and w_upper are both equal to W - B K.
// Now we compute B K element-wise so that we can get appropriate bounds
for (int i = 0; i < A.rows(); i++) {
for (int j = 0; j < A.rows(); j++) {
// Find a min of (B K)(i,j) for K in controller.
double min_bk = 0.0;
double max_bk = 0.0;
for (int k = 0; k < B.cols(); k++) {
if (B(i,k) < 0) {
min_bk += B(i,k) * controller.upper(k,j);
max_bk += B(i,k) * controller.lower(k,j);
} else {
min_bk += B(i,k) * controller.lower(k,j);
max_bk += B(i,k) * controller.upper(k,j);
}
}
if (continuous) {
w_lower(i,j) += dt * min_bk;
w_upper(i,j) += dt * max_bk;
} else {
w_lower(i,j) += min_bk;
w_upper(i,j) += max_bk;
}
}
}
Eigen::VectorXd bias = Eigen::VectorXd::Zero(A.rows());
return state.interval_affine(w_lower, w_upper, bias, bias);
}
LinCons compute_invariant(const Space& cover,
int bound, const std::vector<LinCons>& other_covers,
const Eigen::MatrixXd& k) const override {
if (bound <= 0) {
//if (true) {
// TODO
return cover.space;
}
// Find an invariant for x' = (A + B K) x or x' = (I + dt * (A + B K)) x
// For the bounded case, find the maximum space such that `bound` iterations
// are safe.
Eigen::MatrixXd transition;
if (continuous) {
transition = Eigen::MatrixXd::Identity(A.rows(), A.rows()) +
dt * (A + B * k);
} else {
transition = A + B * k;
}
Eigen::MatrixXd ws;
Eigen::VectorXd bs;
if (unsafe_space.size() > 0 && unsafe_space[0].weights.rows() <= 1) {
// Find X such that for all x \in X, T * x \in Safe where T is the n-step
// transition matrix and Safe is the safe region. Then if the _unsafe_ region
// is defined by A x < b, we need to have
// A (T x) >= b ==> (A T) x >= b ==> (- A T) x <= - b.
Eigen::MatrixXd n_step = Eigen::MatrixXd::Identity(A.rows(), A.rows());
std::vector<Eigen::VectorXd> constraints;
std::vector<double> coeffs;
for (int i = 0; i < bound; i++) {
for (const LinCons& lc : unsafe_space) {
Eigen::MatrixXd m = -lc.weights * n_step;
for (int i = 0; i < m.rows(); i++) {
constraints.push_back(m.row(i));
coeffs.push_back(-lc.biases(i));
}
}
n_step *= transition;
}
// FUTURE: Remove redundant constraints.
// This procedure produces a lot more constraints than necessary, but I
// think it should be okay since we only use these constraints a few times
// and the extra constraints don't compound.
ws = Eigen::MatrixXd(constraints.size(), constraints[0].size());
bs = Eigen::VectorXd(constraints.size());
for (int i = 0; i < ws.rows(); i++) {
ws.row(i) = constraints[i];
bs(i) = coeffs[i];
}
} else {
// Here we don't have an analytical way to expand the covers, but we
// can just try increasing the elements of b.
ws = cover.space.weights;
bs = cover.space.biases;
for (int i = 0; i < bs.size(); i++) {
double low = bs(i);
bs(i) += 1;
double high = bs(i);
for (int j = 0; j < 10; j++) {
Controller c { .k = k,
.invariant = LinCons(ws, bs),
.space = cover };
if (controller_is_safe(*this, c, other_covers, bound)) {
break;
}
bs(i) = (low + high) / 2.0;
high = bs(i);
}
}
}
return LinCons(ws, bs);
}
};
class NonlinearEnv: public Environment {
public:
std::vector<ArithExpr> update;
std::function<Eigen::VectorXd(const Eigen::VectorXd&,
const Eigen::VectorXd&)> concrete;
NonlinearEnv(std::function<Eigen::VectorXd(const Eigen::VectorXd&,
const Eigen::VectorXd&)> con,
const std::vector<ArithExpr>& up, bool c, double d,
const std::vector<LinCons>& unsafe):
Environment(c, d, unsafe), concrete(con), update(up) {}
Eigen::VectorXd step(const Eigen::VectorXd& state,
const Eigen::MatrixXd& controller) const override {
return concrete(state, controller * state);
}
std::unique_ptr<AbstractVal> semi_abstract_step(const AbstractVal& state,
const Eigen::MatrixXd& controller) const override {
auto action = state.scalar_affine(controller,
Eigen::VectorXd::Zero(controller.rows()));
auto combined = state.append(*action);
//std::cout << "State with action appended" << std::endl;
//combined->print(stdout);
auto new_state = combined->arith_computation(update);
if (continuous) {
int n = update.size();
auto both_states = state.append(*new_state);
Eigen::MatrixXd tr = Eigen::MatrixXd::Identity(n, 2 * n);
tr.block(0, n, n, n) = dt * Eigen::MatrixXd::Identity(n, n);
return both_states->scalar_affine(tr, Eigen::VectorXd::Zero(n));
} else {
return new_state;
}
}
std::unique_ptr<AbstractVal> abstract_step(const AbstractVal& state,
const Interval& controller) const override {
auto action = state.interval_affine(controller.lower, controller.upper,
Eigen::VectorXd::Zero(state.dims()),
Eigen::VectorXd::Zero(state.dims()));
auto combined = state.append(*action);
auto new_state = combined->arith_computation(update);
if (continuous) {
int n = update.size();
auto both_states = state.append(*new_state);
Eigen::MatrixXd tr = Eigen::MatrixXd::Identity(n, 2 * n);
tr.block(0, n, n, n) = dt * Eigen::MatrixXd::Identity(n, n);
return both_states->scalar_affine(tr, Eigen::VectorXd::Zero(n));
} else {
return new_state;
}
}
LinCons compute_invariant(const Space& cover,
int bound, const std::vector<LinCons>& other_covers,
const Eigen::MatrixXd& k) const override {
// `cover` should already be safe because of the properties of the
// synthesis algorithm. In this method we just need to expand out as
// much as possible.
// TODO
return cover.space;
}
};
class ApproxEnv: public Environment {
private:
// Get the right controller index using the breakpoints.
int get_index(const Eigen::VectorXd& state,
const Eigen::VectorXd& action) const {
Eigen::VectorXd sa(state.size() + action.size());
sa << state, action;
for (int i = 0; i < itv_lowers.size(); i++) {
bool inside = true;
for (int j = 0; j < itv_lowers[i].size(); j++) {
if (itv_lowers[i](j) > sa(j) || itv_uppers[i](j) < sa(j)) {
inside = false;
break;
}
}
if (inside) {
return i;
}
}
}
std::unique_ptr<AbstractVal> env_step(const AbstractVal& state,
const AbstractVal& action) const {
auto sa = state.append(action);
//std::cout << "State-Action pair:" << std::endl;
//sa->print(stdout);
auto output = state.bottom();
for (int i = 0; i < lower_As.size(); i++) {
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(2 * sa->dims(), sa->dims());
Eigen::VectorXd b = Eigen::VectorXd::Zero(2 * sa->dims());
//std::cout << "Interval:" << std::endl;
for (int j = 0; j < itv_lowers[i].size(); j++) {
//std::cout << "[" << itv_lowers[i](j) << ", " << itv_uppers[i](j) << "] x ";
A(2*j, j) = 1.0;
A(2*j+1, j) = -1.0;
b(2*j) = itv_uppers[i](j);
b(2*j+1) = -itv_lowers[i](j);
}
auto piece = sa->meet_linear_constraint(A, b);
//std::cout << "Piece:" << std::endl;
//piece->print(stdout);
// x' = A x + B u = (A | B) /x\
// \u/
// x' = x + dt * (A x + B u)
// = x + dt * (A | B) (x | u)^T
// = x + (dt * (A | B)) (x | u)^t
// = ((I | 0) + dt * (A | B)) (x | u)^t
// for I having the state dimension, and 0 being a zero matrix
// with the dimensions of B.
Eigen::MatrixXd lAB = lower_As[i];
lAB.conservativeResize(Eigen::NoChange,
lower_As[i].cols() + lower_Bs[i].cols());
lAB.block(0, lower_As[i].cols(), lower_Bs[i].rows(),
lower_Bs[i].cols()) = lower_Bs[i];
Eigen::MatrixXd uAB = upper_As[i];
uAB.conservativeResize(Eigen::NoChange,
upper_As[i].cols() + upper_Bs[i].cols());
uAB.block(0, upper_As[i].cols(), upper_Bs[i].rows(),
upper_Bs[i].cols()) = upper_Bs[i];
Eigen::VectorXd zero = Eigen::VectorXd::Zero(lAB.rows());
if (continuous) {
Eigen::MatrixXd I = Eigen::MatrixXd::Identity(
lower_As[i].rows(), lower_As[i].cols());
Eigen::MatrixXd Z = Eigen::MatrixXd::Zero(
lower_Bs[i].rows(), lower_Bs[i].cols());
I.conservativeResize(Eigen::NoChange, I.cols() + Z.cols());
I.block(0, lower_As[i].cols(), Z.rows(), Z.cols()) = Z;
lAB = I + dt * lAB;
uAB = I + dt * uAB;
}
//std::cout << "Transformation bounds:" << std::endl;
//std::cout << "Lower:" << std::endl;
//std::cout << lAB << std::endl;
//std::cout << "Upper:" << std::endl;
//std::cout << uAB << std::endl;
auto transformed = piece->interval_affine(lAB, uAB, zero, zero);
//std::cout << "Transformed:" << std::endl;
//transformed->print(stdout);
output = output->join(*transformed);
//std::cout << "Output so far: " << std::endl;
//output->print(stdout);
}
return output;
}
public:
std::vector<Eigen::MatrixXd> lower_As;
std::vector<Eigen::MatrixXd> lower_Bs;
std::vector<Eigen::MatrixXd> upper_As;
std::vector<Eigen::MatrixXd> upper_Bs;
std::vector<Eigen::VectorXd> itv_lowers;
std::vector<Eigen::VectorXd> itv_uppers;
ApproxEnv(const std::vector<double>& bs, const std::vector<int>& bss,
const std::vector<Eigen::MatrixXd>& lAs,
const std::vector<Eigen::MatrixXd>& lBs,
const std::vector<Eigen::MatrixXd>& uAs,
const std::vector<Eigen::MatrixXd>& uBs,
bool c, double d, const std::vector<LinCons>& unsafe):
Environment(c, d, unsafe),
lower_As(lAs), lower_Bs(lBs), upper_As(uAs), upper_Bs(uBs) {
int n = 1;
std::vector<int> sizes;
int last = 0;
std::vector<std::vector<double>> breakpoints(bss.size());
int t = 0;
for (int i : bss) {
n *= i - last + 1;
sizes.push_back(i - last + 1);
breakpoints[t] = std::vector<double>(i - last);
for (int j = last; j < i; j++) {
breakpoints[t][j] = bs[j];
}
last = i;
t++;
}
itv_lowers = std::vector<Eigen::VectorXd>(n);
itv_uppers = std::vector<Eigen::VectorXd>(n);
int inds[bss.size()];
for (int i = 0; i < bss.size(); i++) {
inds[i] = 0;
}
itv_lowers[0] = Eigen::VectorXd::Constant(bss.size(), -1000.0);
itv_uppers[0] = Eigen::VectorXd::Constant(bss.size(), 1000.0);
while (sizes.size() > 0 && inds[0] < sizes[0]) {
int index = 0;
for (int i = 0; i < bss.size(); i++) {
int size = 1;
for (int j = i + 1; j < sizes.size(); j++) {
size *= sizes[j];
}
index += inds[i] * size;
}
itv_lowers[index] = Eigen::VectorXd(bss.size());
itv_uppers[index] = Eigen::VectorXd(bss.size());
for (int i = 0; i < bss.size(); i++) {
if (inds[i] == 0) {
itv_lowers[index](i) = -1000.0;
} else {
itv_lowers[index](i) = breakpoints[i][inds[i]];
}
if (inds[i] + 1 == sizes[i]) {
itv_uppers[index](i) = 1000.0;
} else {
itv_uppers[index](i) = breakpoints[i][inds[i] + 1];
}
}
int axis = bss.size() - 1;
inds[axis]++;
while (axis > 0 && inds[axis] >= sizes[axis]) {
inds[axis] = 0;
axis--;
inds[axis]++;
}
}
}
/**
* Take a concrete step in this environment.
*
* \param state The current state of the system.
* \param controller The controller to use for this step.
* \return The new state of the system.
*/
Eigen::VectorXd step(const Eigen::VectorXd& state,
const Eigen::MatrixXd& controller) const override {
// We can't do this exactly here, so what we'll do is take an upper
// bound step and a lower bound step, then return the average.
Eigen::VectorXd action = controller * state;
int i = get_index(state, action);
Eigen::VectorXd lower = lower_As[i] * state + lower_Bs[i] * action;
Eigen::VectorXd upper = upper_As[i] * state + upper_Bs[i] * action;
Eigen::VectorXd x = (lower + upper) / 2.0;
if (continuous) {
return state + dt * x;
} else {
return x;
}
}
/**
* Take a step using an abstract state and a concrete controller.
*
* \param state The (asbstract) state of the system.
* \param controller The (concrete) controller to use.
* \return The new (abstract) state of the system.
*/
std::unique_ptr<AbstractVal> semi_abstract_step(
const AbstractVal& state,
const Eigen::MatrixXd& controller) const override {
auto action = state.scalar_affine(controller,
Eigen::VectorXd::Zero(controller.rows()));
return env_step(state, *action);
}
/**
* Take a step using an abstract state and an interval of controllers.
*
* \param state The current system state.
* \param controller The interval of possible controllers.
* \return The new system state.
*/
std::unique_ptr<AbstractVal> abstract_step(
const AbstractVal& state,
const Interval& controller) const override {
Eigen::VectorXd bias = Eigen::VectorXd::Zero(controller.lower.rows());
auto action = state.interval_affine(controller.lower,
controller.upper, bias, bias);
return env_step(state, *action);
}
/**
* Find the largest invariant for some controller.
*
* In general a controller may be safe for a region larger than the cover
* for which it was computed. Here we want to find the largest region in which
* the given controller is safe.
*
* \param env The environment under control.
* \param cover The initial space covered by the controller.
* \param bound The bound on the time horizon.
* \param other_covers The regions covered by other controllers.
* \param k The controller.
* \return The region over which the controller is safe.
*/
LinCons compute_invariant(const Space& cover, int bound,
const std::vector<LinCons>& other_covers,
const Eigen::MatrixXd& k) const override {
// TODO: There is probably a smarter way to do this.
Eigen::MatrixXd ws = cover.space.weights;
Eigen::VectorXd bs = cover.space.biases;
for (int i = 0; i < bs.size(); i++) {
double low = bs(i);
bs(i) += 0.4;
double high = bs(i);
for (int j = 0; j < 10; j++) {
Controller c { .k = k,
.invariant = LinCons(ws, bs),
.space = cover };
if (controller_is_safe(*this, c, other_covers, bound)) {
break;
}
bs(i) = (low + high) / 2.0;
high = bs(i);
}
}
return LinCons(ws, bs);
}
};
struct PythonCapsule {
std::vector<ArithExpr> update;
std::function<Eigen::VectorXd(const Eigen::VectorXd&,
const Eigen::VectorXd&)> concrete;
};
/**
* Determine whether an interval of controllers is safe.
*
* Given an interval [Kl, Ku], determines whether K is safe for all
* Kl <= K <= Ku (where the comparisons are element-wise).
*
* \param itv The set of controllers to check.
* \param env The environment under control.
* \param cover The initial space the controller should cover.
* \param other_covers Regions covered by other controllers.
* \param bound The bound on the time horizon.
* \return True if all of the controllers in `itv` are safe.
*/
bool interval_is_safe(const Interval& itv, const Environment& env,
const Space& cover, const std::vector<LinCons>& other_covers,
int bound) {
auto state = std::make_unique<AbstractVal>(ABSTRACT_DOMAIN,
cover.bb_lower, cover.bb_upper);
state = state->meet_linear_constraint(cover.space.weights,
cover.space.biases);
//std::cout << "Verifying interval" << std::endl;
//std::cout << itv.lower.transpose() << std::endl;
//std::cout << itv.upper.transpose() << std::endl;
if (bound > 0) {
for (int i = 0; i < bound; i++) {
//state->print(stdout);
auto next = env.abstract_step(*state, itv);
state = state->join(*next);
}
} else {
while (true) {
auto next = env.abstract_step(*state, itv);
auto old_state = state->clone();
state = state->widen(*state->join(*next));
if (*old_state == *state) {
break;
}
}
}
for (const LinCons& lc : env.unsafe_space) {
if (!state->meet_linear_constraint(lc.weights, lc.biases)->is_bottom()) {
//std::cout << "Unsafe" << std::endl;
//auto t = state->meet_linear_constraint(lc.weights, lc.biases);
//std::cout << lc.weights << std::endl;
//std::cout << lc.biases << std::endl;
//t->print(stdout);
//for (const LinCons& lc : env.unsafe_space) {
// std::cout << lc.weights << std::endl;
// std::cout << lc.biases << std::endl;
//}
//throw std::runtime_error("");
return false;
// FUTURE: Deal with covers
}
}
//std::cout << "Safe" << std::endl;
return true;
}
/**
* Determine whether a controller is safe in its region.
*
* Assuming safe controllers exist which cover each element of `covers`,
* this function determines whether the given controller is safe in its
* declared cover.
*
* \param env The environment under control.
* \param controller The controller to check.
* \param covers The regions covered by other controllers.
* \return True if `controller` is safe for the region it covers.
*/
bool controller_is_safe(const Environment& env, const Controller& controller,
const std::vector<LinCons>& covers, int bound) {
auto state = std::make_unique<AbstractVal>(ABSTRACT_DOMAIN,
controller.invariant);
if (bound > 0) {
for (int i = 0; i < bound; i++) {
state = state->join(*env.semi_abstract_step(*state, controller.k));
}
} else {
while (true) {
auto next = env.semi_abstract_step(*state, controller.k);
auto old_state = state->clone();
state = state->widen(*state->join(*next));
if (*old_state == *state) {
break;
}
}
}
for (const LinCons& lc : env.unsafe_space) {
if (!state->meet_linear_constraint(lc.weights, lc.biases)->is_bottom()) {
return false;
// FUTURE: Deal with covers
}
}
return true;
}
/**
* Measure the safety of a controller in an environment.
*
* We measure safety by sampling initial states, evolving the system for some
* time, then seeing how close the result is to the unsafe states.
*
* \param env The environment under control.
* \param k The controller.
* \param initial The states the controller should be safe in.
* \return A measure of the safety of this controller.
*/
double measure_safety(const Environment& env, const Eigen::MatrixXd& k,
const Space& initial, int bound) {
int iters = 50;
double total = 0.0;
//Eigen::MatrixXd update = env.A + env.B * k;
//Eigen::MatrixXd n_step = Eigen::MatrixXd::Identity(
// update.rows(), update.rows());
//for (int j = 0; j < bound; j++) {
// n_step *= update;
//}
for (int i = 0; i < iters; i++) {
// Sample x from the initial space.
Eigen::VectorXd x;
while (true) {
x = initial.bb_lower + Eigen::VectorXd::Random(
initial.bb_lower.size()).cwiseProduct(
initial.bb_upper - initial.bb_lower);
Eigen::VectorXd ax = initial.space.weights * x;
bool inside = true;
for (int j = 0; j < ax.size(); j++) {
if (ax(j) > initial.space.biases(j)) {
inside = false;
break;
}
}
if (inside) {
break;
}
}
int is = bound > 0 ? bound : 20;
// See how safe x is.
for (int j = 0; j < is; j++) {
x = env.step(x, k);
}
//x.applyOnTheLeft(n_step);
double min = std::numeric_limits<double>::max();
for (const LinCons& lc : env.unsafe_space) {
if (lc.distance_from(x) < min) {
min = lc.distance_from(x);
}
}
total += min;
}
return total / iters;
}
/**
* Find an unsafe controller in a given interval.
*
* We do this with the same approximated gradient descent used for the overall
* shield synthesis.
*
* \param env The environment under control.
* \param cover The initial space in which we need to be safe.
* \param other_covers Spaces where other controllers exist.
* \param itv The interval in which to search.
* \param The bound on the time horizon.
* \return An unsafe controller if one can be found.
*/
std::optional<Eigen::MatrixXd> find_counterexample(const Environment& env,
const Space& cover, const std::vector<LinCons>& other_covers,
const Interval& itv, int bound) {
// Start from the center of the given space.
Eigen::MatrixXd k = (itv.lower + itv.upper) / 2;
Controller contr = {
.k = k,
.invariant = cover.space,
.space = cover
};
double lr = 0.05; // originally 0.005
double v = 0.08; // oroginally 0.04
for (int i = 0; i < 30; i++) { // originally 200
if (!controller_is_safe(env, contr, other_covers, bound)) {
// If the controller is unsafe then we've found a counterexample.
return k;
}
Eigen::MatrixXd delta = Eigen::MatrixXd::Random(k.rows(), k.cols());
double sim_plus = measure_safety(env, k + v * delta, cover, bound);
double sim_minus = measure_safety(env, k - v * delta, cover, bound);
if (sim_plus <= 0.0) {
// k + v * delta has a non-positive safety score, so it is unsafe.
return k + v * delta;
} else if (sim_minus <= 0.0) {
return k - v * delta;
}
Eigen::MatrixXd grad = (sim_plus - sim_minus) / v * delta;
k -= lr * grad;
k = k.cwiseMax(itv.lower).cwiseMin(itv.upper);
}
return {};
}
/**
* Find a safe region in the parameter space around `k`.
*
* Given an environment and a current (safe) controller `k`, find an interval
* of safe parameters. This first tries to verify an interval of size
* `step_size` around the initial controller. If it is unable to do so, then
* it starts shrinking the space until it finds an interval that can be
* verified.
*
* \param env The environment under control.
* \param cover The initial space where we need to be safe.
* \param other_covers Spaces where other controllers exist.
* \param k The controller to use as a starting point.
* \param step_size The maximum step size for gradient descent.
* \param bound The bound on the time horizon.
* \return A region of the controller space which is safe on `cover`.
*/
std::optional<Interval> compute_safe_space(
const Environment& env, const Space& cover,
const std::vector<LinCons>& other_covers, const Eigen::MatrixXd& k,
double step_size, int bound) {
Interval itv = {
.lower = k - Eigen::MatrixXd::Constant(k.rows(), k.cols(), step_size),
.upper = k + Eigen::MatrixXd::Constant(k.rows(), k.cols(), step_size)
};
int iters = 0;
while (!interval_is_safe(itv, env, cover, other_covers, bound)) {
auto ce = find_counterexample(env, cover, other_covers,
itv, bound);
if (!ce) {
// If we couldn't find a counterexample we just shrink the entire space.
for (int i = 0; i < itv.lower.rows(); i++) {
for (int j = 0; j < itv.lower.cols(); j++) {
double c = k(i,j);
itv.lower(i,j) = itv.lower(i,j) + (c - itv.lower(i,j)) / 2;
itv.upper(i,j) = itv.upper(i,j) - (itv.upper(i,j) - c) / 2;
}
}
} else {
// Cut out the counterexample. We do this by pushing the closest face of
// the interval inward until the counterexample is excluded.
Eigen::MatrixXd bad_k = ce.value();
for (int i = 0; i < bad_k.rows(); i++) {
for (int j = 0; j < bad_k.cols(); j++) {
//double c = (itv.lower(i,j) + itv.upper(i,j)) / 2;
double c = k(i,j);
//if (itv.upper(i,j) - bad_k(i,j) < bad_k(i,j) - itv.lower(i,j)) {
if (bad_k(i,j) > c) {
itv.upper(i,j) = (c + bad_k(i,j)) / 2;
} else {
itv.lower(i,j) = (c + bad_k(i,j)) / 2;
}
}
}
}
iters++;
if (iters > 20) {
return {};
}
}
return itv;
}
// Convert a python list of doubles to an Eigen::VectorXd
static Eigen::VectorXd pylist_to_vector(PyObject* list) {
Py_ssize_t size = PyList_Size(list);
Eigen::VectorXd ret(size);
for (Py_ssize_t i = 0; i < size; i++) {
PyObject* elem = PyList_GetItem(list, i);
ret(i) = PyFloat_AsDouble(elem);
}
return ret;
}
static Eigen::MatrixXd pylist_to_matrix(PyObject* list) {
Py_ssize_t rows = PyList_Size(list);
if (rows == 0) {
return Eigen::MatrixXd(0, 0);
}
PyObject* first = PyList_GetItem(list, 0);
Py_ssize_t cols = PyList_Size(first);
Eigen::MatrixXd ret(rows, cols);
for (Py_ssize_t i = 0; i < rows; i++) {
Eigen::VectorXd row = pylist_to_vector(PyList_GetItem(list, i));
ret.row(i) = row;
}
return ret;
}
static std::vector<Eigen::MatrixXd> pylist_to_matrix_list(PyObject* list) {
Py_ssize_t size = PyList_Size(list);
std::vector<Eigen::MatrixXd> ret;
for (int i = 0; i < size; i++) {
ret.push_back(pylist_to_matrix(PyList_GetItem(list, i)));
}
return ret;
}
static std::vector<Space> pylist_to_space(PyObject* list) {
Py_ssize_t len = PyList_Size(list);
if (PyErr_Occurred()) {
PyErr_PrintEx(0);
throw std::runtime_error("pylist_to_space after PyList_Size");
}
std::vector<Space> ret = {};
for (Py_ssize_t i = 0; i < len; i++) {
PyObject* lc = PyList_GetItem(list, i);
Eigen::MatrixXd a = pylist_to_matrix(PyTuple_GetItem(lc, 0));
if (PyErr_Occurred()) {
PyErr_PrintEx(0);
throw std::runtime_error("pylist_to_space after a: " + std::to_string(i));
}
Eigen::VectorXd b = pylist_to_vector(PyTuple_GetItem(lc, 1));
if (PyErr_Occurred()) {
PyErr_PrintEx(0);
throw std::runtime_error("pylist_to_space after b: " + std::to_string(i));
}
Eigen::VectorXd l = pylist_to_vector(PyTuple_GetItem(lc, 2));
if (PyErr_Occurred()) {
PyErr_PrintEx(0);
throw std::runtime_error("pylist_to_space after l: " + std::to_string(i));
}
Eigen::VectorXd u = pylist_to_vector(PyTuple_GetItem(lc, 3));
if (PyErr_Occurred()) {
PyErr_PrintEx(0);
throw std::runtime_error("pylist_to_space after u: " + std::to_string(i));
}
Space tmp = {
.space = LinCons(a, b),
.bb_lower = l,
.bb_upper = u
};
ret.push_back(tmp);
if (PyErr_Occurred()) {
PyErr_PrintEx(0);
throw std::runtime_error("pylist_to_space after iteration " + std::to_string(i));
}
}
return ret;
}
static std::vector<LinCons> pylist_to_lincons(PyObject* list) {
Py_ssize_t len = PyList_Size(list);
std::vector<LinCons> ret = {};
for (Py_ssize_t i = 0; i < len; i++) {
PyObject* lc = PyList_GetItem(list, i);
Eigen::MatrixXd a = pylist_to_matrix(PyTuple_GetItem(lc, 0));
Eigen::VectorXd b = pylist_to_vector(PyTuple_GetItem(lc, 1));
ret.push_back(LinCons(a, b));
}
return ret;
}
// Convert an Eigen::VectorXd to a python list of doubles
static PyObject* vector_to_pylist(const Eigen::VectorXd& b) {
PyObject* ret = PyList_New(b.size());
for (Py_ssize_t i = 0; i < b.size(); i++) {
PyObject* pi = PyFloat_FromDouble(b(i));
PyList_SetItem(ret, i, pi);
}
return ret;
}
static PyObject* matrix_to_pylist(const Eigen::MatrixXd& m) {
PyObject* ret = PyList_New(m.rows());
for (Py_ssize_t i = 0; i < m.rows(); i++) {
PyObject* pyrow = vector_to_pylist(m.row(i));
PyList_SetItem(ret, i, pyrow);
}
return ret;
}
static PyObject* controller_to_pylist(const std::vector<Controller>& contr) {
PyObject* ret = PyList_New(contr.size());
for (Py_ssize_t i = 0; i < contr.size(); i++) {
PyObject* k = matrix_to_pylist(contr[i].k);
PyObject* a = matrix_to_pylist(contr[i].invariant.weights);
PyObject* b = vector_to_pylist(contr[i].invariant.biases);
PyObject* l = vector_to_pylist(contr[i].space.bb_lower);
PyObject* u = vector_to_pylist(contr[i].space.bb_upper);
PyObject* sa = matrix_to_pylist(contr[i].space.space.weights);
PyObject* sb = vector_to_pylist(contr[i].space.space.biases);
PyObject* c = Py_BuildValue("N(NN)(NNNN)", k, a, b, sa, sb, l, u);
PyList_SetItem(ret, i, c);
}
return ret;
}
double measure_similarity(const Eigen::MatrixXd& mat, const Space& cover,
PyObject* measure, PyObject* dataset) {
if (measure == NULL) {
return -mat.norm();
}
PyObject* K = matrix_to_pylist(mat);
PyObject* s = Py_BuildValue("NNNN", matrix_to_pylist(cover.space.weights),
vector_to_pylist(cover.space.biases), vector_to_pylist(cover.bb_lower),
vector_to_pylist(cover.bb_upper));
PyObject* args;
if (dataset == NULL) {
args = Py_BuildValue("NNO", K, s, Py_None);
} else {
args = Py_BuildValue("NNO", K, s, dataset);
}