-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
box.jl
68 lines (61 loc) · 2.02 KB
/
box.jl
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
# TODO: seed, copy
"""
A box in R^n.
I.e., each coordinate is bounded.
Example usage:
box_obj.action_space = Box(-10, 10, (1,))
Two kinds of valid input:
Box(low=-1.0, high=1.0, shape=(3,4)) # low and high are scalars, and shape is provided
Box(low=[-1.0,-2.0], high=[2.0,4.0]) # low and high are arrays of the same shape
"""
mutable struct Box <: AbstractSpace
low::Array
high::Array
shape::Tuple
dtype::DataType
#seed::Int
end
function Box(low::Number, high::Number, shape::Union{Tuple, Array{Int64, 1}}, dtype::Union{DataType, Nothing}=nothing)
if isnothing(dtype)
dtype = high == 255 ? UInt8 : Float32
@warn "dtype was autodetected as $(dtype). Please provide explicit data type."
end
if dtype <: Integer
low = floor(dtype, low)
high = floor(dtype, high)
end
Low = dtype(low) .+ zeros(dtype, shape)
High = dtype(high) .+ zeros(dtype, shape)
return Box(Low, High, shape, dtype)
end
function Box(low::Array, high::Array, dtype::Union{DataType, Nothing}=nothing)
@assert size(low) == size(high)
shape = size(low)
if isnothing(dtype)
dtype = all(high .== 255) ? UInt8 : Float32
@warn "dtype was autodetected as $(dtype). Please provide explicit data type."
end
if dtype <: Integer
low = floor.(dtype, low)
high = floor.(dtype, high)
else
low = dtype.(low)
high = dtype.(high)
end
return Box(low, high, shape, dtype)
end
#=
function seed!(box_obj::Box, seed::Int)
box_obj.seed = seed
end
=#
function sample(box_obj::Box)
box_obj.dtype <: AbstractFloat ?
rand(box_obj.dtype, box_obj.shape) .* (box_obj.high .- box_obj.low) .+ box_obj.low :
rand.(UnitRange.(box_obj.low, box_obj.high))
end
function contains(box_obj::Box, x)
isa(x, Number) && box_obj.shape == (1,) && (x = [x])
size(x) == box_obj.shape && all(box_obj.low .<= x .<= box_obj.high)
end
Base.:(==)(box_obj::Box, other::Box) = isapprox(box_obj.low, other.low) && isapprox(box_obj.high, other.high)