-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidation_code.jl
More file actions
1606 lines (1414 loc) · 47.9 KB
/
validation_code.jl
File metadata and controls
1606 lines (1414 loc) · 47.9 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
"""
This document is an automatically-generated file that contains all typeset code blocks from
Algorithms for Validation by Mykel J. Kochenderfer, Sydney M. Katz, Anthony L. Corso, and Robert J. Moss. A PDF version of the book is available online at algorithmsbook.com/validation.
We share this content in the hopes that it helps you and makes the validation algorithms
more approachable and accessible. Thank you for reading!
If you encounter any issues or have pressing comments, please file an issue at
github.com/algorithmsbooks/validation.
"""
#################### introduction 1
abstract type Agent end
abstract type Environment end
abstract type Sensor end
struct System
agent::Agent
env::Environment
sensor::Sensor
end
####################
#################### introduction 2
function step(sys::System, s)
o = sys.sensor(s)
a = sys.agent(o)
s′ = sys.env(s, a)
return (; o, a, s′)
end
function rollout(sys::System; d)
s = rand(Ps(sys.env))
τ = []
for t in 1:d
o, a, s′ = step(sys, s)
push!(τ, (; s, o, a))
s = s′
end
return τ
end
####################
#################### introduction 3
abstract type Specification end
function evaluate(ψ::Specification, τ) end
isfailure(ψ::Specification, τ) = !evaluate(ψ, τ)
####################
#################### model_building 1
struct MaximumLikelihoodParameterEstimation
likelihood # p(y) = likelihood(x; θ)
optimizer # optimization algorithm: θ = optimizer(f)
end
function fit(alg::MaximumLikelihoodParameterEstimation, data)
f(θ) = sum(-logpdf(alg.likelihood(x, θ), y) for (x,y) in data)
return alg.optimizer(f)
end
####################
#################### model_building 2
struct BayesianParameterEstimation
likelihood # p(y) = likelihood(x, θ)
prior # prior distribution
sampler # Turing.jl sampler
m # number of samples from posterior
end
function fit(alg::BayesianParameterEstimation, data)
x, y = first.(data), last.(data)
@model function posterior(x, y)
θ ~ alg.prior
for i in eachindex(x)
y[i] ~ alg.likelihood(x[i], θ)
end
end
return Turing.sample(posterior(x, y), alg.sampler, alg.m)
end
####################
#################### property_specification 1
struct LTLSpecification <: Specification
formula # formula specified using SignalTemporalLogic.jl
end
evaluate(ψ::LTLSpecification, τ) = ψ.formula([step.s for step in τ])
####################
#################### property_specification 2
struct STLSpecification <: Specification
formula # formula specified using SignalTemporalLogic.jl
I # time interval (e.g. 3:10)
end
evaluate(ψ::STLSpecification, τ) = ψ.formula([step.s for step in τ[ψ.I]])
####################
#################### falsification 1
struct DirectFalsification
d # depth
m # number of samples
end
function falsify(alg::DirectFalsification, sys, ψ)
d, m = alg.d, alg.m
τs = [rollout(sys, d=d) for i in 1:m]
return filter(τ->isfailure(ψ, τ), τs)
end
####################
#################### falsification 2
struct Disturbance
xa # agent disturbance
xs # environment disturbance
xo # sensor disturbance
end
struct DisturbanceDistribution
Da # agent disturbance distribution
Ds # environment disturbance distribution
Do # sensor disturbance distribution
end
function step(sys::System, s, D::DisturbanceDistribution)
xo = rand(D.Do(s))
o = sys.sensor(s, xo)
xa = rand(D.Da(o))
a = sys.agent(o, xa)
xs = rand(D.Ds(s, a))
s′ = sys.env(s, a, xs)
x = Disturbance(xa, xs, xo)
return (; o, a, s′, x)
end
####################
#################### falsification 3
abstract type TrajectoryDistribution end
function initial_state_distribution(p::TrajectoryDistribution) end
function disturbance_distribution(p::TrajectoryDistribution, t) end
function depth(p::TrajectoryDistribution) end
####################
#################### falsification 4
struct NominalTrajectoryDistribution <: TrajectoryDistribution
Ps # initial state distribution
D # disturbance distribution
d # depth
end
function NominalTrajectoryDistribution(sys::System, d)
D = DisturbanceDistribution((o) -> Da(sys.agent, o),
(s, a) -> Ds(sys.env, s, a),
(s) -> Do(sys.sensor, s))
return NominalTrajectoryDistribution(Ps(sys.env), D, d)
end
initial_state_distribution(p::NominalTrajectoryDistribution) = p.Ps
disturbance_distribution(p::NominalTrajectoryDistribution, t) = p.D
depth(p::NominalTrajectoryDistribution) = p.d
####################
#################### falsification 5
function rollout(sys::System, p::TrajectoryDistribution; d=depth(p))
s = rand(initial_state_distribution(p))
τ = []
for t in 1:d
o, a, s′, x = step(sys, s, disturbance_distribution(p, t))
push!(τ, (; s, o, a, x))
s = s′
end
return τ
end
####################
#################### falsification 6
function step(sys::System, s, x)
o = sys.sensor(s, x.xo)
a = sys.agent(o, x.xa)
s′ = sys.env(s, a, x.xs)
return (; o, a, s′)
end
function rollout(sys::System, s, 𝐱; d=length(𝐱))
τ = []
for t in 1:d
x = 𝐱[t]
o, a, s′ = step(sys, s, x)
push!(τ, (; s, o, a, x))
s = s′
end
return τ
end
####################
#################### falsification 7
function robustness_objective(x, sys, ψ; smoothness=0.0)
s, 𝐱 = extract(sys.env, x)
τ = rollout(sys, s, 𝐱)
𝐬 = [step.s for step in τ]
return robustness(𝐬, ψ.formula, w=smoothness)
end
####################
#################### falsification 8
function Distributions.logpdf(D::DisturbanceDistribution, s, o, a, x)
logp_xa = logpdf(D.Da(o), x.xa)
logp_xs = logpdf(D.Ds(s, a), x.xs)
logp_xo = logpdf(D.Do(s), x.xo)
return logp_xa + logp_xs + logp_xo
end
function Distributions.pdf(p::TrajectoryDistribution, τ)
logprob = logpdf(initial_state_distribution(p), τ[1].s)
for (t, step) in enumerate(τ)
s, o, a, x = step
logprob += logpdf(disturbance_distribution(p, t), s, o, a, x)
end
return exp(logprob)
end
####################
#################### falsification 9
function likelihood_objective(x, sys, ψ; smoothness=0.0)
s, 𝐱 = extract(sys.env, x)
τ = rollout(sys, s, 𝐱)
if isfailure(ψ, τ)
p = NominalTrajectoryDistribution(sys, length(𝐱))
return -pdf(p, τ)
else
𝐬 = [step.s for step in τ]
return robustness(𝐬, ψ.formula, w=smoothness)
end
end
####################
#################### falsification 10
function weighted_likelihood_objective(x, sys, ψ; smoothness=0.0, λ=1.0)
s, 𝐱 = extract(sys.env, x)
τ = rollout(sys, s, 𝐱)
𝐬 = [step.s for step in τ]
p = NominalTrajectoryDistribution(sys, length(𝐱))
return robustness(𝐬, ψ.formula, w=smoothness) - λ * log(pdf(p, τ))
end
####################
#################### falsification 11
struct OptimizationBasedFalsification
objective # objective function
optimizer # optimization algorithm
end
function falsify(alg::OptimizationBasedFalsification, sys, ψ)
f(x) = alg.objective(x, sys, ψ)
return alg.optimizer(f, sys, ψ)
end
####################
#################### planning 1
defect(τᵢ, τᵢ₊₁) = norm(τᵢ₊₁[1].s - τᵢ[end].s)
function shooting_robustness(x, sys, ψ; smoothness=0.0, λ=1.0)
segments = extract(sys.env, x)
n = length(segments)
τ_segments = [rollout(sys, seg.s, seg.𝐱) for seg in segments]
τ = vcat(τ_segments...)
𝐬 = [step.s for step in τ]
ρ = smooth_robustness(𝐬, ψ.formula, w=smoothness)
defects = [defect(τ_segments[i], τ_segments[i+1]) for i in 1:n-1]
return ρ + λ*sum(defects)
end
####################
#################### planning 2
abstract type TreeSearch end
function falsify(alg::TreeSearch, sys, ψ)
tree = initialize_tree(alg, sys)
for i in 1:alg.k_max
node = select(alg, sys, ψ, tree)
extend!(alg, sys, ψ, tree, node)
end
return failures(tree, sys, ψ)
end
####################
#################### planning 3
function trajectory(node)
τ = []
while !isnothing(node.parent)
pushfirst!(τ, (s=node.parent.state, node.edge...))
node = node.parent
end
return τ
end
function failures(tree, sys, ψ)
leaves = filter(node -> isempty(node.children), tree)
τs = [trajectory(node) for node in leaves]
return filter(τ -> isfailure(ψ, τ), τs)
end
####################
#################### planning 4
struct RRT <: TreeSearch
sample_goal # sgoal = sample_goal(tree)
compute_objectives # objectives = compute_objectives(tree, sgoal)
select_disturbance # x = select_disturbance(sys, node)
k_max # number of iterations
end
mutable struct RRTNode
state # node state
parent # parent node
edge # (o, a, x)
children # vector of child nodes
goal_state # current goal state
end
function initialize_tree(alg::RRT, sys)
return [RRTNode(rand(Ps(sys.env)), nothing, nothing, [], nothing)]
end
function select(alg::RRT, sys, ψ, tree)
sgoal = alg.sample_goal(tree)
objectives = alg.compute_objectives(tree, sgoal)
node = tree[argmin(objectives)]
node.goal_state = sgoal
return node
end
function extend!(alg::RRT, sys, ψ, tree, node)
x = alg.select_disturbance(sys, node)
o, a, s′ = step(sys, node.state, x)
snew = RRTNode(s′, node, (; o, a, x), [], nothing)
push!(node.children, snew)
push!(tree, snew)
end
####################
#################### planning 5
random_goal(tree, lo, hi) = rand.(Distributions.Uniform.(lo, hi))
function distance_objectives(tree, sgoal)
return [norm(sgoal .- node.state) for node in tree]
end
function random_disturbance(sys, node)
D = DisturbanceDistribution(sys)
o, a, s′, x = step(sys, node.state, D)
return x
end
####################
#################### planning 6
function goal_disturbance(sys, node; m=10)
D = DisturbanceDistribution(sys)
steps = [step(sys, node.state, D) for i in 1:m]
distances = [norm(node.goal_state - step.s′) for step in steps]
return steps[argmin(distances)].x
end
####################
#################### planning 7
function average_dispersion(points, lo, hi, lengths)
points_norm = [(point .- lo) ./ (hi .- lo) for point in points]
ranges = [range(0, 1, length) for length in lengths]
δ = minimum(Float64(r.step) for r in ranges)
grid_dispersions = []
for grid_point in Iterators.product(ranges...)
dmin = minimum(norm(grid_point .- p) for p in points_norm)
push!(grid_dispersions, min(dmin, δ) / δ)
end
return mean(grid_dispersions)
end
####################
#################### planning 8
function star_discrepancy(points, lo, hi, lengths)
n, dim = length(points), length(lo)
𝒱 = [(point .- lo) ./ (hi .- lo) for point in points]
ranges = [range(0, 1, length)[1:end-1] for length in lengths]
steps = [Float64(r.step) for r in ranges]
ℬ = Hyperrectangle(low=zeros(dim), high=ones(dim))
lbs, ubs = [], []
for grid_point in Iterators.product(ranges...)
h⁻ = Hyperrectangle(low=zeros(dim), high=[grid_point...])
h⁺ = Hyperrectangle(low=zeros(dim), high=grid_point .+ steps)
𝒱h⁻ = length(filter(v -> v ∈ h⁻, 𝒱))
𝒱h⁺ = length(filter(v -> v ∈ h⁺, 𝒱))
push!(lbs, max(abs(𝒱h⁻ / n - volume(h⁻) / volume(ℬ)),
abs(𝒱h⁺ / n - volume(h⁺) / volume(ℬ))))
push!(ubs, max(𝒱h⁺ / n - volume(h⁻) / volume(ℬ),
volume(h⁺) / volume(ℬ) - 𝒱h⁻ / n))
end
return maximum(lbs), maximum(ubs)
end
####################
#################### planning 9
distance_c(node) = norm(node.parent.state .- node.state)
distance_h(node, sgoal) = norm(sgoal .- node.state)
function cost_objectives(tree, sgoal; c=distance_c, h=distance_h)
costs = Dict()
queue = [tree[1]]
while !isempty(queue)
node = popfirst!(queue)
if isnothing(node.parent)
costs[node] = 0.0
else
costs[node] = c(node) + costs[node.parent]
end
for child in node.children
push!(queue, child)
end
end
heuristics = [h(sgoal, node) for node in tree]
objectives = [costs[node] for node in tree] .+ heuristics
return objectives
end
####################
#################### planning 10
struct MCTS <: TreeSearch
estimate_value # v = estimate_value(sys, ψ, node)
c # exploration constant
k # progressive widening constant
α # progressive widening exponent
select_disturbance # x = select_disturbance(sys, node)
k_max # number of iterations
end
mutable struct MCTSNode
state # node state
parent # parent node
edge # (o, a, x)
children # vector of child nodes
N # visit count
Q # value estimate
end
function initialize_tree(alg::MCTS, sys)
return [MCTSNode(rand(Ps(sys.env)), nothing, nothing, [], 1, 0)]
end
function select(alg::MCTS, sys, ψ, tree)
c, k, α, node = alg.c, alg.k, alg.α, tree[1]
while length(node.children) > k * node.N^α
node = lcb(node, c)
end
return node
end
function extend!(alg::MCTS, sys, ψ, tree, node)
x = alg.select_disturbance(sys, node)
o, a, s′ = step(sys, node.state, x)
Q = alg.estimate_value(sys, ψ, s′)
snew = MCTSNode(s′, node, (; o, a, x), [], 1, Q)
push!(node.children, snew)
push!(tree, snew)
while !isnothing(node)
node.N += 1
node.Q += (Q - node.Q) / node.N
Q, node = node.Q, node.parent
end
end
####################
#################### planning 11
function lcb(node::MCTSNode, c)
Qs = [node.Q for node in node.children]
Ns = [node.N for node in node.children]
lcbs = [Q - c*sqrt(log(node.N)/N) for (Q, N) in zip(Qs, Ns)]
return node.children[argmin(lcbs)]
end
####################
#################### failure_distribution 1
struct RejectionSampling
p̄ # target density
q # proposal trajectory distribution
c # constant such that p̄(τ) ≤ cq(τ)
k_max # max iterations
end
function sample_failures(alg::RejectionSampling, sys, ψ)
p̄, q, c, k_max = alg.p̄, alg.q, alg.c, alg.k_max
τs = []
for k in 1:k_max
τ = rollout(sys, q)
if rand() < p̄(τ) / (c * pdf(q, τ))
push!(τs, τ)
end
end
return τs
end
####################
#################### failure_distribution 2
struct MCMCSampling
p̄ # target density
g # kernel: τ′ = rollout(sys, g(τ))
τ # initial trajectory
k_max # max iterations
m_burnin # number of samples to discard from burn-in
m_skip # number of samples to skip for thinning
end
function sample_failures(alg::MCMCSampling, sys, ψ)
p̄, g, τ = alg.p̄, alg.g, alg.τ
k_max, m_burnin, m_skip = alg.k_max, alg.m_burnin, alg.m_skip
τs = []
for k in 1:k_max
τ′ = rollout(sys, g(τ))
if rand() < (p̄(τ′) * pdf(g(τ′), τ)) / (p̄(τ) * pdf(g(τ), τ′))
τ = τ′
end
push!(τs, τ)
end
return τs[m_burnin:m_skip:end]
end
####################
#################### failure_distribution 3
struct ProbabilisticProgramming
Δ # distance function: Δ(𝐬)
mcmc_alg # e.g. Turing.NUTS()
k_max # number of samples
d # trajectory depth
ϵ # smoothing parameter
end
function sample_failures(alg::ProbabilisticProgramming, sys, ψ)
Δ, mcmc_alg = alg.Δ, alg.mcmc_alg
k_max, d, ϵ = alg.k_max, alg.d, alg.ϵ
@model function rollout(sys, d; xo=fill(missing, d),
xa=fill(missing, d),
xs=fill(missing, d))
p = NominalTrajectoryDistribution(sys, d)
s ~ initial_state_distribution(p)
𝐬 = [s, [zeros(length(s)) for i in 1:d]...]
for t in 1:d
D = disturbance_distribution(p, t)
s = 𝐬[t]
xo[t] ~ D.Do(s)
o = sys.sensor(s, xo[t])
xa[t] ~ D.Da(o)
a = sys.agent(o, xa[t])
xs[t] ~ D.Ds(s, a)
𝐬[t+1] = sys.env(s, a, xs[t])
end
Turing.@addlogprob! logpdf(Normal(0.0, ϵ), Δ(𝐬))
end
return Turing.sample(rollout(sys, d), mcmc_alg, k_max)
end
####################
#################### failure_probability 1
struct DirectEstimation
d # depth
m # number of samples
end
function estimate(alg::DirectEstimation, sys, ψ)
d, m = alg.d, alg.m
τs = [rollout(sys, d=d) for i in 1:m]
return mean(isfailure(ψ, τ) for τ in τs)
end
####################
#################### failure_probability 2
struct BayesianEstimation
prior::Beta # from Distributions.jl
d # depth
m # number of samples
end
function estimate(alg::BayesianEstimation, sys, ψ)
prior, d, m = alg.prior, alg.d, alg.m
τs = [rollout(sys, d=d) for i in 1:m]
n, m = sum(isfailure(ψ, τ) for τ in τs), length(τs)
return Beta(prior.α + n, prior.β + m - n)
end
####################
#################### failure_probability 3
struct ImportanceSamplingEstimation
p # nominal distribution
q # proposal distribution
m # number of samples
end
function estimate(alg::ImportanceSamplingEstimation, sys, ψ)
p, q, m = alg.p, alg.q, alg.m
τs = [rollout(sys, q) for i in 1:m]
ps = [pdf(p, τ) for τ in τs]
qs = [pdf(q, τ) for τ in τs]
ws = ps ./ qs
return mean(w * isfailure(ψ, τ) for (w, τ) in zip(ws, τs))
end
####################
#################### failure_probability 4
struct MultipleImportanceSamplingEstimation
p # nominal distribution
qs # proposal distributions
weighting # weighting scheme: ws = weighting(p, qs, τs)
end
smis(p, qs, τs) = [pdf(p, τ) / pdf(q, τ) for (q, τ) in zip(qs, τs)]
dmmis(p, qs, τs) = [pdf(p, τ) / mean(pdf(q, τ) for q in qs) for τ in τs]
function estimate(alg::MultipleImportanceSamplingEstimation, sys, ψ)
p, qs, weighting = alg.p, alg.qs, alg.weighting
τs = [rollout(sys, q) for q in qs]
ws = weighting(p, qs, τs)
return mean(w * isfailure(ψ, τ) for (w, τ) in zip(ws, τs))
end
####################
#################### failure_probability 5
struct CrossEntropyEstimation
p # nominal trajectory distribution
q₀ # initial proposal distribution
f # objective function f(τ, ψ)
k_max # number of iterations
m # number of samples per iteration
m_elite # number of elite samples
end
function estimate(alg::CrossEntropyEstimation, sys, ψ)
k_max, m, m_elite = alg.k_max, alg.m, alg.m_elite
p, q, f = alg.p, alg.q₀, alg.f
for k in 1:k_max
τs = [rollout(sys, q) for i in 1:m]
Y = [f(τ, ψ) for τ in τs]
order = sortperm(Y)
γ = max(0, Y[order[m_elite]])
ps = [pdf(p, τ) for τ in τs]
qs = [pdf(q, τ) for τ in τs]
ws = ps ./ qs
ws[Y .> γ] .= 0
q = fit(typeof(q), τs, ws=ws)
end
return estimate(ImportanceSamplingEstimation(p, q, m), sys, ψ)
end
####################
#################### failure_probability 6
struct PopulationMonteCarloEstimation
p # nominal trajectory distribution
qs # vector of initial proposal distributions
weighting # weighting scheme: ws = weighting(p, qs, τs)
k_max # number of iterations
end
function estimate(alg::PopulationMonteCarloEstimation, sys, ψ)
p, qs, weighting = alg.p, alg.qs, alg.weighting
k_max, m = alg.k_max, length(qs)
for k in 1:k_max
τs = [rollout(sys, q) for q in qs]
ws = [pdf(p, τ) * isfailure(ψ, τ) / pdf(q, τ)
for (q, τ) in zip(qs, τs)]
resampler = Categorical(ws ./ sum(ws))
qs = [proposal(qs[i], τs[i]) for i in rand(resampler, m)]
end
mis = MultipleImportanceSamplingEstimation(p, qs, weighting)
return estimate(mis, sys, ψ)
end
####################
#################### failure_probability 7
struct SequentialMonteCarloEstimation
p # nominal trajectory distribution
ḡs # intermediate distributions
perturb # τs′ = perturb(τs, ḡ)
m # number of samples
end
function estimate(alg::SequentialMonteCarloEstimation, sys, ψ)
p, ḡs, perturb, m = alg.p, alg.ḡs, alg.perturb, alg.m
p̄failure(τ) = isfailure(ψ, τ) * pdf(p, τ)
τs = [rollout(sys, p) for i in 1:m]
ws = [ḡs[1](τ) / p(τ) for τ in τs]
for (ḡ, ḡ′) in zip(ḡs, [ḡs[2:end]...; p̄failure])
τs′ = perturb(τs, ḡ)
ws .*= [ḡ′(τ) / ḡ(τ) for τ in τs′]
τs = τs′[rand(Categorical(ws ./ sum(ws)), m)]
ws .= mean(ws)
end
return mean(ws)
end
####################
#################### failure_probability 8
function bridge_sampling_estimator(g₁τs, ḡ₁, g₂τs, ḡ₂, ḡb)
ḡ₁s, ḡ₂s = ḡ₁.(g₁τs), ḡ₂.(g₂τs)
ḡb₁s, ḡb₂s = ḡb.(g₁τs), ḡb.(g₂τs)
return mean(ḡb₂s ./ ḡ₂s) / mean(ḡb₁s ./ ḡ₁s)
end
function optimal_bridge(g₁τs, ḡ₁, g₂τs, ḡ₂, k_max)
ratio = 1.0
m₁, m₂ = length(g₁τs), length(g₂τs)
ḡb(τ) = (ḡ₁(τ) * ḡ₂(τ)) / (m₁ * ḡ₁(τ) + m₂ * ratio * ḡ₂(τ))
for k in k_max
ratio = bridge_sampling_estimator(g₁τs, ḡ₁, g₂τs, ḡ₂, ḡb)
end
return ḡb
end
####################
#################### failure_probability 9
struct SelfImportanceSamplingEstimation
p # nominal distribution
q̄ # unnormalized proposal density
q̄_τs # samples from q̄
end
function estimate(alg::SelfImportanceSamplingEstimation, sys, ψ)
p, q̄, q̄_τs = alg.p, alg.q̄, alg.q̄_τs
ws = [pdf(p, τ) / q̄(τ) for τ in q̄_τs]
ws ./= sum(ws)
return mean(w * isfailure(ψ, τ) for (w, τ) in zip(ws, q̄_τs))
end
####################
#################### failure_probability 10
struct BridgeSamplingEstimation
p # nominal trajectory distribution
ḡs # intermediate distributions
perturb # samples′ = perturb(samples, ḡ′)
m # number of samples from each intermediate distribution
kb # number of iterations for estimating optimal bridge
end
function estimate(alg::BridgeSamplingEstimation, sys, ψ)
p, ḡs, perturb, m = alg.p, alg.ḡs, alg.perturb, alg.m
p̄failure(τ) = isfailure(ψ, τ) * pdf(p, τ)
τs = [rollout(sys, p) for i in 1:m]
p̂fail = 1.0
for (ḡ, ḡ′) in zip([p; ḡs...], [ḡs...; p̄failure])
ws = [ḡ′(τ) / ḡ(τ) for τ in τs]
τs′ = τs[rand(Categorical(ws ./ sum(ws)), m)]
τs′ = perturb(τs′, ḡ′)
ḡb = optimal_bridge(τs′, ḡ′, τs, ḡ, kb)
ratio = bridge_sampling_estimator(τs′, ḡ′, τs, ḡ, ḡb)
p̂fail *= ratio
τs = τs′
end
return p̂fail
end
####################
#################### failure_probability 11
struct AdaptiveMultilevelSplitting
p # nominal trajectory distribution
m # number of samples
m_elite # number of elite samples
k_max # maximum number of iterations
f # objective function f(τ, ψ)
perturb # τs′ = perturb(τs, p̄γ)
end
function estimate(alg::AdaptiveMultilevelSplitting, sys, ψ)
p, m, m_elite, k_max = alg.p, alg.m, alg.m_elite, alg.k_max
f, perturb = alg.f, alg.perturb
τs = [rollout(sys, p) for i in 1:m]
p̂fail = 1.0
for i in 1:k_max
Y = [f(τ, ψ) for τ in τs]
order = sortperm(Y)
γ = i == k_max ? 0 : max(0, Y[order[m_elite]])
p̂fail *= mean(Y .≤ γ)
γ == 0 && break
τs = rand(τs[order[1:m_elite]], m)
p̄γ(τ) = p(τ) * (f(τ, ψ) ≤ γ)
τs = perturb(τs, p̄γ)
end
return p̂fail
end
####################
#################### forward_reachability 1
struct AvoidSetSpecification <: Specification
set # avoid set
end
evaluate(ψ::AvoidSetSpecification, τ) = all(step.s ∉ ψ.set for step in τ)
####################
#################### forward_reachability 2
function get_matrices(sys)
return Ts(sys.env), Ta(sys.env), Πo(sys.agent), Os(sys.sensor)
end
function linear_set_propagation(sys, 𝒮, 𝒳)
Ts, Ta, Πo, Os = get_matrices(sys)
return (Ts + Ta * Πo * Os) * 𝒮 ⊕ Ta * Πo * 𝒳.xo ⊕ Ta * 𝒳.xa ⊕ 𝒳.xs
end
####################
#################### forward_reachability 3
abstract type ReachabilityAlgorithm end
struct SetPropagation <: ReachabilityAlgorithm
h # time horizon
end
function reachable(alg::SetPropagation, sys)
h = alg.h
𝒮, 𝒳 = 𝒮₁(sys.env), disturbance_set(sys)
ℛ = 𝒮
for t in 1:h
𝒮 = linear_set_propagation(sys, 𝒮, 𝒳)
ℛ = ℛ ∪ 𝒮
end
return ℛ
end
####################
#################### forward_reachability 4
¬(ψ::AvoidSetSpecification) = ψ.set
function satisfies(alg::SetPropagation, sys, ψ)
ℛ = reachable(alg, sys)
return !isempty(ℛ ∩ ¬ψ)
end
####################
#################### forward_reachability 5
struct OverapproximateSetPropagation <: ReachabilityAlgorithm
h # time horizon
freq # overapproximation frequency
ϵ # overapproximation tolerance
end
function reachable(alg::OverapproximateSetPropagation, sys)
h, freq, ϵ = alg.h, alg.freq, alg.ϵ
𝒮, 𝒳 = 𝒮₁(sys.env), disturbance_set(sys)
ℛ = 𝒮
for t in 1:h
𝒮 = linear_set_propagation(sys, 𝒮, 𝒳)
ℛ = ℛ ∪ 𝒮
𝒮 = t % freq == 0 ? overapproximate(𝒮, ϵ) : 𝒮
end
return ℛ
end
####################
#################### forward_reachability 6
Ab(𝒫) = tosimplehrep(constraints_list(𝒫))
function constrained_model(sys, d, 𝒮, 𝒳)
model = Model(SCS.Optimizer)
@variable(model, 𝐬[1:dim(𝒮),1:d])
@variable(model, 𝐱o[1:dim(𝒳.xo),1:d])
@variable(model, 𝐱s[1:dim(𝒳.xs),1:d])
@variable(model, 𝐱a[1:dim(𝒳.xa),1:d])
As, bs = Ab(𝒮)
(Axo, bxo), (Axs, bxs), (Axa, bxa) = Ab(𝒳.xo), Ab(𝒳.xs), Ab(𝒳.xa)
@constraint(model, As * 𝐬[:, 1] .≤ bs)
for i in 1:d
@constraint(model, Axo * 𝐱o[:, i] .≤ bxo)
@constraint(model, Axs * 𝐱s[:, i] .≤ bxs)
@constraint(model, Axa * 𝐱a[:, i] .≤ bxa)
end
Ts, Ta, Πo, Os = get_matrices(sys)
for i in 1:d-1
@constraint(model, (Ts + Ta*Πo*Os) * 𝐬[:, i] + Ta*Πo * 𝐱o[:, i]
+ Ta * 𝐱a[:, i] + 𝐱s[:, i] .== 𝐬[:, i+1])
end
return model
end
function ρ(model, 𝐝, d)
𝐬 = model.obj_dict[:𝐬]
@objective(model, Max, 𝐝' * 𝐬[:, d])
optimize!(model)
return objective_value(model)
end
####################
#################### forward_reachability 7
struct LinearProgramming <: ReachabilityAlgorithm
h # time horizon
𝒟 # set of directions to evaluate support function
tol # tolerance for checking satisfaction
end
function reachable(alg::LinearProgramming, sys)
h, 𝒟 = alg.h, alg.𝒟
𝒮, 𝒳 = 𝒮₁(sys.env), disturbance_set(sys)
ℛ = 𝒮
for d in 2:h
model = constrained_model(sys, d, 𝒮, 𝒳)
ρs = [ρ(model, 𝐝, d) for 𝐝 in 𝒟]
ℛ = ℛ ∪ HPolytope([HalfSpace(𝐝, ρ) for (𝐝, ρ) in zip(𝒟, ρs)])
end
return ℛ
end
####################
#################### forward_reachability 8
function satisfies(alg::LinearProgramming, sys, ψ)
𝒮, 𝒳 = 𝒮₁(sys.env), disturbance_set(sys)
for d in 1:alg.h
model = constrained_model(sys, d, 𝒮, 𝒳)
@variable(model, u[1:dim(𝒮)])
Au, bu = Ab(¬ψ)
@constraint(model, Au * u .≤ bu)
𝐬 = model.obj_dict[:𝐬]
@objective(model, Min, sum((𝐬[i, d] - u[i])^2 for i in 1:dim(𝒮)))
optimize!(model)
if isapprox(objective_value(model), 0.0, atol=alg.tol)
return false
end
end
return true
end
####################
#################### nonlinear_reach 1
struct NaturalInclusion <: ReachabilityAlgorithm
h # time horizon
end
function r(sys, x)
s, 𝐱 = extract(sys.env, x)
τ = rollout(sys, s, 𝐱)
return τ[end].s
end
to_hyperrectangle(𝐈) = Hyperrectangle(low=[i.lo for i in 𝐈],
high=[i.hi for i in 𝐈])
function reachable(alg::NaturalInclusion, sys)
𝐈′s = []
for d in 1:alg.h
𝐈 = intervals(sys, d)
push!(𝐈′s, r(sys, 𝐈))
end
return UnionSetArray([to_hyperrectangle(𝐈′) for 𝐈′ in 𝐈′s])
end
####################
#################### nonlinear_reach 2
struct TaylorInclusion <: ReachabilityAlgorithm
h # time horizon
order # order of Taylor inclusion function (supports 1 or 2)
end
function taylor_inclusion(sys, 𝐈, order)
c = mid.(𝐈)
fc = r(sys, c)
if order == 1
𝐈′ = [fc[i] + gradient(x->r(sys, x)[i], 𝐈)' * (𝐈 - c)
for i in eachindex(fc)]
else
𝐈′ = [fc[i] + gradient(x->r(sys, x)[i], c)' * (𝐈 - c) +
(𝐈 - c)' * hessian(x->r(sys, x)[i], 𝐈) * (𝐈 - c)
for i in eachindex(fc)]
end
return 𝐈′
end
function reachable(alg::TaylorInclusion, sys)
𝐈′s = []
for d in 1:alg.h
𝐈 = intervals(sys, d)
𝐈′ = taylor_inclusion(sys, 𝐈, alg.order)
push!(𝐈′s, 𝐈′)
end
return UnionSetArray([to_hyperrectangle(𝐈′) for 𝐈′ in 𝐈′s])
end
####################
#################### nonlinear_reach 3
struct ConservativeLinearization <: ReachabilityAlgorithm
h # time horizon
end
to_intervals(𝒫) = [interval(lo, hi) for (lo, hi) in zip(low(𝒫), high(𝒫))]
function conservative_linearization(sys, 𝒫)
𝐈 = to_intervals(interval_hull(𝒫))
c = mid.(𝐈)
fc = r(sys, c)
J = ForwardDiff.jacobian(x->r(sys, x), c)
α = to_hyperrectangle([(𝐈 - c)'*hessian(x->r(sys, x)[i], 𝐈)*(𝐈 - c)
for i in eachindex(fc)])
return fc + J * (𝒫 ⊕ -c) ⊕ α
end
function reachable(alg::ConservativeLinearization, sys)
ℛs = []
for d in 1:alg.h
𝒮, 𝒳 = sets(sys, d)