-
Notifications
You must be signed in to change notification settings - Fork 20
/
hdf5_time_series_storage.jl
835 lines (744 loc) · 26.7 KB
/
hdf5_time_series_storage.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
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
import HDF5
import H5Zblosc
const HDF5_TS_ROOT_PATH = "time_series"
const HDF5_TS_METADATA_ROOT_PATH = "time_series_metadata"
const TIME_SERIES_DATA_FORMAT_VERSION = "2.0.0"
const TIME_SERIES_VERSION_KEY = "data_format_version"
"""
Stores all time series data in an HDF5 file.
The file used is assumed to be temporary and will be automatically deleted when there are
no more references to the storage object.
"""
mutable struct Hdf5TimeSeriesStorage <: TimeSeriesStorage
file_path::String
compression::CompressionSettings
file::Union{Nothing, HDF5.File}
# If you add any fields, ensure they are managed in deepcopy_internal below.
end
"""
Constructs Hdf5TimeSeriesStorage by creating a temp file.
"""
function Hdf5TimeSeriesStorage()
return Hdf5TimeSeriesStorage(true)
end
"""
Constructs Hdf5TimeSeriesStorage.
# Arguments
- `create_file::Bool`: create new file
- `filename=nothing`: if nothing, create a temp file, else use this name.
- `directory=nothing`: if set and filename is nothing, create a temp file in this
directory. If it is not set, use the environment variable SIENNA_TIME_SERIES_DIRECTORY.
If that is not set, use tempdir(). This should be set if the time series data is larger
than the tmp filesystem can hold.
"""
function Hdf5TimeSeriesStorage(
create_file::Bool;
filename = nothing,
directory = nothing,
compression = CompressionSettings(),
)
if create_file
if isnothing(filename)
directory = _get_time_series_parent_dir(directory)
filename, io = mktemp(directory)
close(io)
end
storage = Hdf5TimeSeriesStorage(filename, compression, nothing)
_make_file(storage)
else
storage = Hdf5TimeSeriesStorage(filename, compression, nothing)
end
@debug "Constructed new Hdf5TimeSeriesStorage" _group = LOG_GROUP_TIME_SERIES storage.file_path compression
return storage
end
function open_store!(
func::Function,
storage::Hdf5TimeSeriesStorage,
mode = "r",
args...;
kwargs...,
)
HDF5.h5open(storage.file_path, mode) do file
storage.file = file
try
func(args...; kwargs...)
finally
storage.file = nothing
end
end
end
"""
Constructs Hdf5TimeSeriesStorage from an existing file.
"""
function from_file(
::Type{Hdf5TimeSeriesStorage},
filename::AbstractString;
read_only = false,
directory = nothing,
)
if !isfile(filename)
error("time series storage $filename does not exist")
end
if read_only
file_path = abspath(filename)
else
parent = _get_time_series_parent_dir(directory)
file_path, io = mktemp(parent)
close(io)
copy_h5_file(filename, file_path)
end
storage = Hdf5TimeSeriesStorage(false; filename = file_path)
if !read_only
_deserialize_compression_settings!(storage)
end
@info "Loaded time series from storage file existing=$filename new=$(storage.file_path) compression=$(storage.compression)"
return storage
end
function _get_time_series_parent_dir(directory = nothing)
# Ensure that a user-passed directory has highest precedence.
if !isnothing(directory)
if !isdir(directory)
error("User passed time series directory, $directory, does not exist.")
end
return directory
end
directory = get(ENV, "SIENNA_TIME_SERIES_DIRECTORY", nothing)
if !isnothing(directory)
if !isdir(directory)
error(
"The directory specified by the environment variable " *
"SIENNA_TIME_SERIES_DIRECTORY, $directory, does not exist.",
)
end
@debug "Use time series directory specified by the environment variable" _group =
LOG_GROUP_TIME_SERIES directory
return directory
end
return tempdir()
end
Base.isempty(storage::Hdf5TimeSeriesStorage) = _isempty(storage, storage.file)
function _isempty(storage::Hdf5TimeSeriesStorage, ::Nothing)
return HDF5.h5open(storage.file_path, "r") do file
_isempty(storage, file)
end
end
function _isempty(storage::Hdf5TimeSeriesStorage, file::HDF5.File)
root = _get_root(storage, file)
return isempty(keys(root))
end
function Base.deepcopy_internal(storage::Hdf5TimeSeriesStorage, dict::IdDict)
if !isnothing(storage.file) && isopen(storage.file)
error("This operation is not allowed when the HDF5 file handle is open.")
end
if haskey(dict, storage)
return dict[storage]
end
directory = _get_time_series_parent_dir(dirname(storage.file_path))
filename, io = mktemp(directory)
close(io)
copy_h5_file(get_file_path(storage), filename)
new_compression = deepcopy(storage.compression)
new_storage = Hdf5TimeSeriesStorage(filename, new_compression, nothing)
dict[storage.compression] = new_compression
dict[storage] = new_storage
return new_storage
end
"""
Copies an HDF5 file to a new file. This should be used instead of a system call to copy
because it won't copy unused space that results from deleting datasets.
"""
function copy_h5_file(src::AbstractString, dst::AbstractString)
HDF5.h5open(dst, "w") do fw
HDF5.h5open(src, "r") do fr
HDF5.copy_object(fr[HDF5_TS_ROOT_PATH], fw, HDF5_TS_ROOT_PATH)
if HDF5_TS_METADATA_ROOT_PATH in keys(fr)
HDF5.copy_object(
fr[HDF5_TS_METADATA_ROOT_PATH],
fw,
HDF5_TS_METADATA_ROOT_PATH,
)
end
end
end
return
end
get_compression_settings(storage::Hdf5TimeSeriesStorage) = storage.compression
get_file_path(storage::Hdf5TimeSeriesStorage) = storage.file_path
function read_data_format_version(storage::Hdf5TimeSeriesStorage)
return _read_data_format_version(storage, storage.file)
end
function _read_data_format_version(storage::Hdf5TimeSeriesStorage, ::Nothing)
HDF5.h5open(storage.file_path, "r") do file
return _read_data_format_version(storage, file)
end
end
function _read_data_format_version(storage::Hdf5TimeSeriesStorage, file::HDF5.File)
root = _get_root(storage, file)
return HDF5.read(HDF5.attributes(root)[TIME_SERIES_VERSION_KEY])
end
function serialize_time_series!(
storage::Hdf5TimeSeriesStorage,
ts::TimeSeriesData,
)
_serialize_time_series!(storage, ts, storage.file)
return
end
function _serialize_time_series!(
storage::Hdf5TimeSeriesStorage,
ts::TimeSeriesData,
::Nothing,
)
HDF5.h5open(storage.file_path, "r+") do file
_serialize_time_series!(storage, ts, file)
end
return
end
function _serialize_time_series!(
storage::Hdf5TimeSeriesStorage,
ts::TimeSeriesData,
file::HDF5.File,
)
root = _get_root(storage, file)
uuid = string(get_uuid(ts))
if !haskey(root, uuid)
TimerOutputs.@timeit_debug SYSTEM_TIMERS "HDF5 serialize_time_series" begin
group = HDF5.create_group(root, uuid)
data = get_array_for_hdf(ts)
settings = storage.compression
if settings.enabled
if settings.type == CompressionTypes.BLOSC
group["data", blosc = settings.level] = data
elseif settings.type == CompressionTypes.DEFLATE
if settings.shuffle
group["data", shuffle = (), deflate = settings.level] = data
else
group["data", deflate = settings.level] = data
end
else
error("not implemented for type=$(settings.type)")
end
else
group["data"] = data
end
_write_time_series_attributes!(ts, group)
@debug "Create new time series entry." _group = LOG_GROUP_TIME_SERIES uuid
end
end
return
end
"""
Return a String for the data type of the forecast data, this implementation avoids the use of `eval` on arbitrary code stored in HDF dataset.
"""
get_data_type(ts::TimeSeriesData) = get_type_label(eltype_data(ts))
get_type_label(::Type{CONSTANT}) = "CONSTANT"
get_type_label(::Type{<:Integer}) = get_type_label(CONSTANT)
# A hopefully temporary hack to keep track of the number of fields in a tuple
get_type_label(T::Type{<:Tuple{Vararg{Float64}}}) = "FLOATTUPLE " * string(fieldcount(T))
get_type_label(data_type::Type{<:Any}) = string(nameof(data_type))
function _write_time_series_attributes!(
ts::T,
path,
) where {T <: TimeSeriesData}
data_type = get_data_type(ts)
HDF5.attributes(path)["module"] = string(parentmodule(typeof(ts)))
HDF5.attributes(path)["type"] = string(nameof(typeof(ts)))
HDF5.attributes(path)["data_type"] = data_type
return
end
function _read_time_series_attributes(path)
return Dict(
"type" => _read_time_series_type(path),
"dataset_size" => size(path["data"]),
"data_type" => parse_type(HDF5.read(HDF5.attributes(path)["data_type"])),
)
end
# A different approach would be needed to support time series containing non-IS types
function parse_type(type_str)
type_str == "CONSTANT" && return CONSTANT
startswith(type_str, "FLOATTUPLE ") && # See above, hopefully temporary hack
return NTuple{parse(Int, (last(split(type_str, " ")))), Float64}
return getproperty(InfrastructureSystems, Symbol(type_str))
end
function _read_time_series_type(path)
module_str = HDF5.read(HDF5.attributes(path)["module"])
type_str = HDF5.read(HDF5.attributes(path)["type"])
return get_type_from_strings(module_str, type_str)
end
# TODO: This needs to change if we want to directly convert Hdf5TimeSeriesStorage to
# InMemoryTimeSeriesStorage, which is currently not supported at System deserialization.
function iterate_time_series(storage::Hdf5TimeSeriesStorage)
Channel() do channel
HDF5.h5open(storage.file_path, "r") do file
root = _get_root(storage, file)
for uuid in keys(root)
data = HDF5.read(root[uuid]["data"])
put!(channel, (Base.UUID(uuid), data))
end
end
end
end
#=
# This could be used if we deserialize the type directly from HDF.
function _make_rows_columns(dataset, ::Type{T}) where T <: StaticTimeSeries
rows = UnitRange(1, size(dataset)[1])
columns = UnitRange(1, 1)
return (rows, columns)
end
function _make_rows_columns(dataset, ::Type{T}) where T <: Forecast
rows = UnitRange(1, size(dataset)[1])
columns = UnitRange(1, size(dataset)[2])
return (rows, columns)
end
=#
function remove_time_series!(storage::Hdf5TimeSeriesStorage, uuid::UUIDs.UUID)
_remove_time_series!(storage, uuid, storage.file)
end
function _remove_time_series!(
storage::Hdf5TimeSeriesStorage,
uuid::UUIDs.UUID,
::Nothing,
)
HDF5.h5open(storage.file_path, "r+") do file
_remove_time_series!(storage, uuid, file)
end
end
function _remove_time_series!(
storage::Hdf5TimeSeriesStorage,
uuid::UUIDs.UUID,
file::HDF5.File,
)
root = _get_root(storage, file)
path = _get_time_series_path(root, uuid)
HDF5.delete_object(path)
return
end
function deserialize_time_series(
::Type{T},
storage::Hdf5TimeSeriesStorage,
metadata::TimeSeriesMetadata,
rows::UnitRange,
columns::UnitRange,
) where {T <: StaticTimeSeries}
@assert_op columns == 1:1
_deserialize_time_series(T, storage, metadata, rows, columns, storage.file)
end
function _deserialize_time_series(
::Type{T},
storage::Hdf5TimeSeriesStorage,
metadata::TimeSeriesMetadata,
rows::UnitRange,
columns::UnitRange,
::Nothing,
) where {T <: StaticTimeSeries}
return HDF5.h5open(storage.file_path, "r") do file
_deserialize_time_series(T, storage, metadata, rows, columns, file)
end
end
function _deserialize_time_series(
::Type{T},
storage::Hdf5TimeSeriesStorage,
metadata::TimeSeriesMetadata,
rows::UnitRange,
columns::UnitRange,
file::HDF5.File,
) where {T <: StaticTimeSeries}
# Note that all range checks must occur at a higher level.
TimerOutputs.@timeit_debug SYSTEM_TIMERS "HDF5 deserialize StaticTimeSeries" begin
root = _get_root(storage, file)
uuid = get_time_series_uuid(metadata)
path = _get_time_series_path(root, uuid)
attributes = _read_time_series_attributes(path)
@debug "deserializing a StaticTimeSeries" _group = LOG_GROUP_TIME_SERIES T
data_type = attributes["data_type"]
data = get_hdf_array(path["data"], data_type, rows)
resolution = get_resolution(metadata)
start_time = get_initial_timestamp(metadata) + resolution * (rows.start - 1)
timestamps = range(
start_time;
length = length(rows),
step = resolution,
)
return T(metadata, TimeSeries.TimeArray(timestamps, data))
end
end
function deserialize_time_series(
::Type{T},
storage::Hdf5TimeSeriesStorage,
metadata::TimeSeriesMetadata,
rows::UnitRange,
columns::UnitRange,
) where {T <: AbstractDeterministic}
# Note that all range checks must occur at a higher level.
_deserialize_time_series(T, storage, metadata, rows, columns, storage.file)
end
function _deserialize_time_series(
::Type{T},
storage::Hdf5TimeSeriesStorage,
metadata::TimeSeriesMetadata,
rows::UnitRange,
columns::UnitRange,
::Nothing,
) where {T <: AbstractDeterministic}
return HDF5.h5open(storage.file_path, "r") do file
_deserialize_time_series(T, storage, metadata, rows, columns, file)
end
end
function _deserialize_time_series(
::Type{T},
storage::Hdf5TimeSeriesStorage,
metadata::TimeSeriesMetadata,
rows::UnitRange,
columns::UnitRange,
file::HDF5.File,
) where {T <: AbstractDeterministic}
root = _get_root(storage, file)
uuid = get_time_series_uuid(metadata)
path = _get_time_series_path(root, uuid)
actual_type = _read_time_series_type(path)
if actual_type === SingleTimeSeries
last_index = size(path["data"])[1]
return deserialize_deterministic_from_single_time_series(
storage,
metadata,
rows,
columns,
last_index,
)
end
TimerOutputs.@timeit_debug SYSTEM_TIMERS "HDF5 deserialize Deterministic" begin
@assert actual_type <: T "actual_type = $actual_type T = $T"
@debug "deserializing a Forecast" _group = LOG_GROUP_TIME_SERIES T
attributes = _read_time_series_attributes(path)
data = get_hdf_array(path["data"], attributes["data_type"], metadata, rows, columns)
return actual_type(metadata, data)
end
end
function get_hdf_array(
dataset,
::Type{<:CONSTANT},
metadata::TimeSeriesMetadata,
rows::UnitRange{Int},
columns::UnitRange{Int},
)
data = SortedDict{Dates.DateTime, Vector{Float64}}()
resolution = get_resolution(metadata)
initial_timestamp = get_initial_timestamp(metadata) + resolution * (rows.start - 1)
interval = get_interval(metadata)
start_time = initial_timestamp + interval * (columns.start - 1)
if length(columns) == 1
data[start_time] = dataset[rows, columns.start]
else
data_read = dataset[rows, columns]
for (i, it) in
enumerate(range(start_time; length = length(columns), step = interval))
data[it] = @view data_read[1:length(rows), i]
end
end
return data
end
function get_hdf_array(
dataset,
T,
metadata::TimeSeriesMetadata,
rows::UnitRange{Int},
columns::UnitRange{Int},
)
data = SortedDict{Dates.DateTime, Vector{T}}()
resolution = get_resolution(metadata)
initial_timestamp = get_initial_timestamp(metadata) + resolution * (rows.start - 1)
interval = get_interval(metadata)
start_time = initial_timestamp + interval * (columns.start - 1)
colons = repeat([:], ndims(dataset) - 2)
if length(columns) == 1
data[start_time] = retransform_hdf_array(dataset[rows, columns.start, colons...], T)
else
data_read = retransform_hdf_array(dataset[rows, columns, colons...], T)
for (i, it) in
enumerate(range(start_time; length = length(columns), step = interval))
data[it] = @view data_read[1:length(rows), i]
end
end
return data
end
function get_hdf_array(
dataset,
type::Type{<:CONSTANT},
rows::UnitRange{Int},
)
data = retransform_hdf_array(dataset[rows], type)
return data
end
function get_hdf_array(
dataset,
T,
rows::UnitRange{Int},
)
colons = repeat([:], ndims(dataset) - 1)
data = retransform_hdf_array(dataset[rows, colons...], T)
return data
end
function retransform_hdf_array(data::Array, ::Type{<:CONSTANT})
return data
end
function retransform_hdf_array(
data::Array,
T::Union{Type{LinearFunctionData}, Type{QuadraticFunctionData}},
)
length_req = fieldcount(get_raw_data_type(T))
(size(data)[end] != length_req) && throw(
ArgumentError(
"Last dimension of data must have length $length_req, got size $(size(data))",
),
)
dims_to_keep = Tuple(1:(ndims(data) - 1))
# Pop off the last dimension and call the constructor on that data
return map(x -> T(x...), eachslice(data; dims = dims_to_keep)) # PERF possibly preallocation would be better
end
function retransform_hdf_array(
data::Array,
T::Union{Type{<:Tuple}},
)
length_req = fieldcount(T)
(size(data)[end] != length_req) && throw(
ArgumentError(
"Last dimension of data must have length $length_req, got size $(size(data))",
),
)
dims_to_keep = Tuple(1:(ndims(data) - 1))
# Pop off the last dimension and call the constructor on that data
return map(T, eachslice(data; dims = dims_to_keep)) # PERF possibly preallocation would be better
end
retransform_hdf_array(data::Array, ::Type{PiecewiseLinearData}) =
PiecewiseLinearData.(retransform_hdf_array(data, Vector{NamedTuple}))
function retransform_hdf_array(data::Array, ::Type{<:Vector{<:Union{Tuple, NamedTuple}}})
length_req = 2
(size(data)[end] != length_req) && throw(
ArgumentError(
"Last dimension of data must have length $length_req, got size $(size(data))",
),
)
dims_to_keep = Tuple(1:(ndims(data) - 2))
# Pop off the last dimension and call the constructor on that data
return map(
x -> [Tuple(pair) for pair in eachrow(x)],
eachslice(data; dims = dims_to_keep),
) # PERF possibly preallocation would be better
end
retransform_hdf_array(data::Array, ::Type{PiecewiseStepData}) =
PiecewiseStepData.(retransform_hdf_array(data, Matrix))
function retransform_hdf_array(data::Array, ::Type{Matrix})
length_req = 2
(size(data)[end] != length_req) && throw(
ArgumentError(
"Last dimension of data must have length $length_req, got size $(size(data))",
),
)
dims_to_keep = Tuple(1:(ndims(data) - 2))
return eachslice(data; dims = dims_to_keep)
end
function deserialize_time_series(
::Type{T},
storage::Hdf5TimeSeriesStorage,
metadata::TimeSeriesMetadata,
rows::UnitRange,
columns::UnitRange,
) where {T <: Probabilistic}
_deserialize_time_series(T, storage, metadata, rows, columns, storage.file)
end
function _deserialize_time_series(
::Type{T},
storage::Hdf5TimeSeriesStorage,
metadata::TimeSeriesMetadata,
rows::UnitRange,
columns::UnitRange,
::Nothing,
) where {T <: Probabilistic}
return HDF5.h5open(storage.file_path, "r") do file
_deserialize_time_series(T, storage, metadata, rows, columns, file)
end
end
function _deserialize_time_series(
::Type{T},
storage::Hdf5TimeSeriesStorage,
metadata::TimeSeriesMetadata,
rows::UnitRange,
columns::UnitRange,
file::HDF5.File,
) where {T <: Probabilistic}
# Note that all range checks must occur at a higher level.
TimerOutputs.@timeit_debug SYSTEM_TIMERS "HDF5 deserialize Probabilistic" begin
total_percentiles = length(get_percentiles(metadata))
root = _get_root(storage, file)
uuid = get_time_series_uuid(metadata)
path = _get_time_series_path(root, uuid)
attributes = _read_time_series_attributes(path)
@assert_op length(attributes["dataset_size"]) == 3
@debug "deserializing a Forecast" _group = LOG_GROUP_TIME_SERIES T
data = SortedDict{Dates.DateTime, Matrix{attributes["data_type"]}}()
initial_timestamp = get_initial_timestamp(metadata)
interval = get_interval(metadata)
start_time = initial_timestamp + interval * (first(columns) - 1)
if length(columns) == 1
data[start_time] =
transpose(path["data"][1:total_percentiles, rows, first(columns)])
else
data_read = PermutedDimsArray(
path["data"][1:total_percentiles, rows, columns],
[3, 2, 1],
)
for (i, it) in enumerate(
range(start_time; length = length(columns), step = interval),
)
data[it] = @view data_read[i, 1:length(rows), 1:total_percentiles]
end
end
return T(metadata, data)
end
end
function deserialize_time_series(
::Type{T},
storage::Hdf5TimeSeriesStorage,
metadata::TimeSeriesMetadata,
rows::UnitRange,
columns::UnitRange,
) where {T <: Scenarios}
_deserialize_time_series(T, storage, metadata, rows, columns, storage.file)
end
function _deserialize_time_series(
::Type{T},
storage::Hdf5TimeSeriesStorage,
metadata::TimeSeriesMetadata,
rows::UnitRange,
columns::UnitRange,
::Nothing,
) where {T <: Scenarios}
return HDF5.h5open(storage.file_path, "r") do file
_deserialize_time_series(T, storage, metadata, rows, columns, file)
end
end
function _deserialize_time_series(
::Type{T},
storage::Hdf5TimeSeriesStorage,
metadata::TimeSeriesMetadata,
rows::UnitRange,
columns::UnitRange,
file::HDF5.File,
) where {T <: Scenarios}
# Note that all range checks must occur at a higher level.
TimerOutputs.@timeit_debug SYSTEM_TIMERS "HDF5 deserialize Scenarios" begin
total_scenarios = get_scenario_count(metadata)
root = _get_root(storage, file)
uuid = get_time_series_uuid(metadata)
path = _get_time_series_path(root, uuid)
attributes = _read_time_series_attributes(path)
@assert_op attributes["type"] == T
@assert_op length(attributes["dataset_size"]) == 3
@debug "deserializing a Forecast" _group = LOG_GROUP_TIME_SERIES T
data = SortedDict{Dates.DateTime, Matrix{attributes["data_type"]}}()
initial_timestamp = get_initial_timestamp(metadata)
interval = get_interval(metadata)
start_time = initial_timestamp + interval * (first(columns) - 1)
if length(columns) == 1
data[start_time] =
transpose(path["data"][1:total_scenarios, rows, first(columns)])
else
data_read =
PermutedDimsArray(path["data"][1:total_scenarios, rows, columns], [3, 2, 1])
for (i, it) in enumerate(
range(start_time; length = length(columns), step = interval),
)
data[it] = @view data_read[i, 1:length(rows), 1:total_scenarios]
end
end
return T(metadata, data)
end
end
function clear_time_series!(storage::Hdf5TimeSeriesStorage)
# Re-create the file. HDF5 will not actually free up the deleted space until h5repack
# is run on the file.
_make_file(storage)
@info "Cleared all time series."
end
get_num_time_series(storage::Hdf5TimeSeriesStorage) =
_get_num_time_series(storage, storage.file)
function _get_num_time_series(storage::Hdf5TimeSeriesStorage, ::Nothing)
HDF5.h5open(storage.file_path, "r") do file
_get_num_time_series(storage, file)
end
end
_get_num_time_series(storage::Hdf5TimeSeriesStorage, file::HDF5.File) =
length(_get_root(storage, file))
_make_file(storage::Hdf5TimeSeriesStorage) = _make_file(storage, storage.file)
function _make_file(storage::Hdf5TimeSeriesStorage, ::Nothing)
HDF5.h5open(storage.file_path, "w") do file
_make_file(storage, file)
end
end
function _make_file(storage::Hdf5TimeSeriesStorage, file::HDF5.File)
root = HDF5.create_group(file, HDF5_TS_ROOT_PATH)
HDF5.attributes(root)[TIME_SERIES_VERSION_KEY] = TIME_SERIES_DATA_FORMAT_VERSION
_serialize_compression_settings(storage, root)
return
end
function _serialize_compression_settings(storage::Hdf5TimeSeriesStorage, root)
HDF5.attributes(root)["compression_enabled"] = storage.compression.enabled
HDF5.attributes(root)["compression_type"] = string(storage.compression.type)
HDF5.attributes(root)["compression_level"] = storage.compression.level
HDF5.attributes(root)["compression_shuffle"] = storage.compression.shuffle
return
end
function _deserialize_compression_settings!(storage::Hdf5TimeSeriesStorage)
_deserialize_compression_settings!(storage, storage.file)
end
function _deserialize_compression_settings!(storage::Hdf5TimeSeriesStorage, ::Nothing)
HDF5.h5open(storage.file_path, "r+") do file
_deserialize_compression_settings!(storage, file)
end
end
function _deserialize_compression_settings!(storage::Hdf5TimeSeriesStorage, file::HDF5.File)
root = _get_root(storage, file)
storage.compression = CompressionSettings(;
enabled = HDF5.read(HDF5.attributes(root)["compression_enabled"]),
type = CompressionTypes(HDF5.read(HDF5.attributes(root)["compression_type"])),
level = HDF5.read(HDF5.attributes(root)["compression_level"]),
shuffle = HDF5.read(HDF5.attributes(root)["compression_shuffle"]),
)
return
end
_get_root(storage::Hdf5TimeSeriesStorage, file) = file[HDF5_TS_ROOT_PATH]
function _get_time_series_path(root::HDF5.Group, uuid::UUIDs.UUID)
uuid_str = string(uuid)
if !haskey(root, uuid_str)
throw(ArgumentError("UUID $uuid_str does not exist"))
end
return root[uuid_str]
end
function compare_values(
x::Hdf5TimeSeriesStorage,
y::Hdf5TimeSeriesStorage;
compare_uuids = false,
kwargs...,
)
item_x = sort!(collect(iterate_time_series(x)); by = z -> z[1])
item_y = sort!(collect(iterate_time_series(y)); by = z -> z[1])
if length(item_x) != length(item_y)
@error "lengths don't match" length(item_x) length(item_y)
return false
end
if !compare_uuids
# TODO: This could be improved. But we still get plenty of verification when
# UUIDs are not changed.
return true
end
for ((uuid_x, data_x), (uuid_y, data_y)) in zip(item_x, item_y)
if uuid_x != uuid_y
@error "UUIDs don't match" uuid_x uuid_y
return false
end
if !isequal(data_x, data_y)
@error "data doesn't match" data_x data_y
return false
end
end
return true
end