This commit is contained in:
Mike J Innes 2017-06-05 18:00:44 +01:00
parent 8e019e0f30
commit ce6c96c2be
3 changed files with 25 additions and 25 deletions

View File

@ -3,7 +3,7 @@ module Batches
using Juno, Lazy
using Juno: Tree, Row
export CatMat, rawbatch,
export Storage, rawbatch,
Batch, Batched, batchone, tobatch, rebatch,
Seq, BatchSeq, rebatchseq

View File

@ -1,12 +1,12 @@
# Batches
struct Batch{T,S} <: ABatch{T}
data::CatMat{T,S}
struct Batch{T,S} <: BatchLike{T,S}
data::Storage{T,S}
end
@forward Batch.data size, eltype, getindex, setindex!, rawbatch
Batch(xs) = Batch(CatMat(xs))
Batch(xs) = Batch(Storage(xs))
convert{T,S}(::Type{Batch{T,S}},storage::S) =
Batch{T,S}(storage)
@ -37,13 +37,13 @@ tobatch(xs) = tobatch(batchone(xs))
# Sequences
struct Seq{T,S} <: ABatch{T}
data::CatMat{T,S}
struct Seq{T,S} <: BatchLike{T,S}
data::Storage{T,S}
end
@forward Seq.data size, eltype, getindex, setindex!, rawbatch
Seq(xs) = Seq(CatMat(xs))
Seq(xs) = Seq(Storage(xs))
convert{T,S}(::Type{Seq{T,S}},storage::S) =
Seq{T,S}(storage)

View File

@ -1,24 +1,24 @@
import Base: eltype, size, getindex, setindex!, convert
abstract type ABatch{T} <: AbstractVector{T}
abstract type BatchLike{T,S} <: AbstractVector{T}
end
struct CatMat{T,S} <: ABatch{T}
struct Storage{T,S} <: BatchLike{T,S}
data::S
end
convert{T,S}(::Type{CatMat{T,S}},storage::S) =
CatMat{T,S}(storage)
convert{T,S}(::Type{Storage{T,S}},storage::S) =
Storage{T,S}(storage)
eltype{T}(::CatMat{T}) = T
eltype{T}(::Storage{T}) = T
size(b::CatMat) = (size(b.data, 1),)
size(b::Storage) = (size(b.data, 1),)
getindex(b::CatMat, i)::eltype(b) = slicedim(b.data, 1, i)
getindex(b::Storage, i)::eltype(b) = slicedim(b.data, 1, i)
setindex!(b::CatMat, v, i::Integer) = b.data[i, :] = v
setindex!(b::Storage, v, i::Integer) = b.data[i, :] = v
function setindex!(b::CatMat, xs, ::Colon)
function setindex!(b::Storage, xs, ::Colon)
for (i, x) in enumerate(xs)
b[i] = x
end
@ -26,32 +26,32 @@ end
allequal(xs) = all(x -> x == first(xs), xs)
function (::Type{CatMat{T,S}}){T,S}(xs, storage::S)
function (::Type{Storage{T,S}}){T,S}(xs, storage::S)
@assert allequal(map(size, xs))
@assert size(storage) == (length(xs), size(first(xs))...)
for i = 1:length(xs)
storage[i, :] = xs[i]
end
return CatMat{T,S}(storage)
return Storage{T,S}(storage)
end
function (::Type{CatMat{T}}){T}(xs)
function (::Type{Storage{T}}){T}(xs)
xs = map(rawbatch, xs)
storage = similar(first(xs), (length(xs), size(first(xs))...))
CatMat{T,typeof(storage)}(xs, storage)
Storage{T,typeof(storage)}(xs, storage)
end
function CatMat(xs)
function Storage(xs)
xs = promote(xs...)
CatMat{eltype(xs)}(xs)
Storage{eltype(xs)}(xs)
end
@render Juno.Inline b::CatMat begin
Tree(Row(Text("CatMat of "), eltype(b),
@render Juno.Inline b::Storage begin
Tree(Row(Text("Storage of "), eltype(b),
Juno.fade("[$(length(b))]")),
Juno.trim(collect(b)))
end
rawbatch(xs) = xs
rawbatch(xs::CatMat) = xs.data
rawbatch(xs::Storage) = xs.data