@@ -43,13 +43,61 @@ Box(lower::Array, upper::Array) = Box(lower, upper; convert_to_static=true)
43
43
44
44
SpaceStyle (:: Box ) = ContinuousSpaceStyle ()
45
45
46
- function Base. rand (rng:: AbstractRNG , sp:: Random.SamplerTrivial{<:Box} )
46
+ """
47
+ Base.rand(::AbstractRNG, ::Random.SamplerTrivial{<:Box})
48
+
49
+ Generate an array where each element is sampled from a dimension of a Box space.
50
+
51
+ * Finite intervals [a,b] are sampled from uniform distributions.
52
+ * Semi-infinite intervals (a,Inf) and (-Inf,b) are sampled from shifted exponential distributions.
53
+ * Infinite intervals (-Inf,Inf) are sampled from normal distributions.
54
+
55
+ #Example
56
+ ```julia
57
+ julia> using Random: seed!
58
+
59
+ julia> using Distributions: Uniform, Normal, Exponential
60
+
61
+ julia> box = Box([-10, -Inf, 3], [10, Inf, Inf])
62
+ Box{StaticArraysCore.SVector{3, Float64}}([-10.0, -Inf, 3.0], [10.0, Inf, Inf])
63
+
64
+ julia> seed!(0); rand(box)
65
+ 3-element StaticArraysCore.SVector{3, Float64} with indices SOneTo(3):
66
+ -1.8860105821594164
67
+ 0.13392275765318448
68
+ 3.837385552384043
69
+
70
+ julia> seed!(0); [rand(Uniform(-10,10)), rand(Normal()), 3+rand(Exponential())]
71
+ 3-element Vector{Float64}:
72
+ -1.8860105821594164
73
+ 0.13392275765318448
74
+ 3.837385552384043
75
+ ```
76
+ """
77
+ function Base. rand (rng:: AbstractRNG , sp:: Random.SamplerTrivial{Box{T}} ) where {T}
47
78
box = sp[]
48
- return box. lower + rand_similar (rng, box. lower) .* (box. upper- box. lower)
79
+ x = [rand_interval (rng, lb, ub) for (lb, ub) in zip (box. lower, box. upper)]
80
+ return T (x)
49
81
end
50
82
51
- rand_similar (rng:: AbstractRNG , a:: StaticArray ) = rand (rng, typeof (a))
52
- rand_similar (rng:: AbstractRNG , a:: AbstractArray ) = rand (rng, eltype (a), size (a)... )
83
+ function rand_interval (rng:: AbstractRNG , lb:: T , ub:: T ) where {T <: Real }
84
+ offset, sign = zero (T), one (T)
85
+
86
+ if isfinite (lb) && isfinite (ub)
87
+ dist = Uniform (lb, ub)
88
+ elseif isfinite (lb) && ! isfinite (ub)
89
+ offset = lb
90
+ dist = Exponential (one (T))
91
+ elseif ! isfinite (lb) && isfinite (ub)
92
+ offset = ub
93
+ sign = - one (T)
94
+ dist = Exponential (one (T))
95
+ else
96
+ dist = Normal (zero (T), one (T))
97
+ end
98
+
99
+ return offset + sign * rand (rng, dist)
100
+ end
53
101
54
102
Base. in (x:: AbstractArray , b:: Box ) = all (b. lower .<= x .<= b. upper)
55
103
0 commit comments