Skip to content

Commit

Permalink
Construct TimeArray with NamedTuple (#395)
Browse files Browse the repository at this point in the history
  • Loading branch information
scls19fr authored and iblislin committed Nov 25, 2018
1 parent 311ce76 commit 4985916
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/timearray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,14 @@ abstract type AbstractTimeSeries{T,N,D} end
TimeArray(timestamp, values[, colnames, meta=nothing])
TimeArray(ta::TimeArray; timestamp, values, colnames, meta)
TimeArray(data::NamedTuple, timestamp=:datetime, meta)
The second constructor will yields a new TimeArray with the new given fields.
Note that the unchanged fields will be shared, there aren't any copy for the
underlying arrays.
The third constructor build a TimeArray from a NamedTuple.
# Arguments
- `timestamp::AbstractVector{<:TimeType}`: a vector of sorted timestamps,
Expand All @@ -30,6 +33,12 @@ underlying arrays.
the column of `values`.
- `meta::Any`: a user-defined metadata.
# Examples
data = (datetime=[DateTime(2018, 11, 21, 12, 0), DateTime(2018, 11, 21, 13, 0)], col1=[10.2, 11.2], col2=[20.2, 21.2], col3=[30.2, 31.2])
ta = TimeArray(data; timestamp=:datetime, meta="Example")
"""
struct TimeArray{T,N,D<:TimeType,A<:AbstractArray{T,N}} <: AbstractTimeSeries{T,N,D}

Expand Down Expand Up @@ -80,6 +89,12 @@ TimeArray(ta::TimeArray;
colnames = _colnames(ta), meta = _meta(ta), args...) =
TimeArray(timestamp, values, colnames, meta; args...)

function TimeArray(data::NamedTuple; timestamp::Symbol, meta=nothing, args...)
columns = (key for key in keys(data) if key != timestamp)
dat = hcat((data[key] for key in columns)...)
TimeArray(data[timestamp], dat, collect(columns), meta; args...)
end

###### conversion ###############

convert(::Type{TimeArray{Float64,N}}, x::TimeArray{Bool,N}) where N =
Expand Down
9 changes: 9 additions & 0 deletions test/timearray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,15 @@ end
end
end

@testset "construct with NamedTuple" begin
data = (datetime=[DateTime(2018, 11, 21, 12, 0), DateTime(2018, 11, 21, 13, 0)], col1=[10.2, 11.2], col2=[20.2, 21.2], col3=[30.2, 31.2])
ta = TimeArray(data; timestamp=:datetime, meta="Example")
@test size(ta) == (2, 3)
@test colnames(ta) == [:col1, :col2, :col3]
@test timestamp(ta) == [DateTime(2018, 11, 21, 12, 0), DateTime(2018, 11, 21, 13, 0)]
@test values(ta) == [10.2 20.2 30.2; 11.2 21.2 31.2]
@test meta(ta) == "Example"
end

@testset "conversion methods" begin
@testset "convert works " begin
Expand Down

0 comments on commit 4985916

Please sign in to comment.