-
Notifications
You must be signed in to change notification settings - Fork 137
/
HDF5.jl
2075 lines (1809 loc) · 72.2 KB
/
HDF5.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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
module HDF5
using Base: unsafe_convert, StringVector
using Requires: @require
# needed for filter(f, tuple) in julia 1.3
using Compat
import Libdl
import Mmap
### PUBLIC API ###
export
@read, @write,
h5open, h5read, h5write, h5rewrite, h5writeattr, h5readattr,
create_attribute, open_attribute, read_attribute, write_attribute, delete_attribute, attributes,
create_dataset, open_dataset, read_dataset, write_dataset,
create_group, open_group,
copy_object, open_object, delete_object,
create_datatype, commit_datatype, open_datatype,
create_property,
group_info, object_info,
dataspace, datatype
### The following require module scoping ###
# file, filename, name,
# get_chunk, get_datasets,
# get_access_properties, get_create_properties,
# root, readmmap, set_dims!,
# iscontiguous, iscompact, ischunked,
# ishdf5, ismmappable,
# refresh
# start_swmr_write
# create_external, create_external_dataset
### Types
# H5DataStore, Attribute, File, Group, Dataset, Datatype, Opaque,
# Dataspace, Object, Properties, VLen, ChunkStorage, Reference
const depsfile = joinpath(dirname(@__DIR__), "deps", "deps.jl")
if isfile(depsfile)
include(depsfile)
else
error("HDF5 is not properly installed. Please run Pkg.build(\"HDF5\") ",
"and restart Julia.")
end
# Core API ccall wrappers
include("api_types.jl")
include("api.jl")
include("api_helpers.jl")
### Generic H5DataStore interface ###
# Common methods that could be applicable to any interface for reading/writing variables from a file, e.g. HDF5, JLD, or MAT files.
# Types inheriting from H5DataStore should have names, read, and write methods.
# Supertype of HDF5.File, HDF5.Group, JldFile, JldGroup, Matlabv5File, and MatlabHDF5File.
abstract type H5DataStore end
# Convenience macros
macro read(fid, sym)
!isa(sym, Symbol) && error("Second input to @read must be a symbol (i.e., a variable)")
esc(:($sym = read($fid, $(string(sym)))))
end
macro write(fid, sym)
!isa(sym, Symbol) && error("Second input to @write must be a symbol (i.e., a variable)")
esc(:(write($fid, $(string(sym)), $sym)))
end
# Read a list of variables, read(parent, "A", "B", "x", ...)
function Base.read(parent::H5DataStore, name::AbstractString...)
tuple((read(parent, x) for x in name)...)
end
# Read every variable in the file
function Base.read(f::H5DataStore)
vars = keys(f)
vals = Vector{Any}(undef,length(vars))
for i = 1:length(vars)
vals[i] = read(f, vars[i])
end
Dict(zip(vars, vals))
end
### Base HDF5 structs ###
# High-level reference handler
struct Reference
r::hobj_ref_t
end
Reference() = Reference(HOBJ_REF_T_NULL) # NULL reference to compare to
Base.cconvert(::Type{Ptr{T}}, ref::Reference) where {T<:Union{Reference,hobj_ref_t,Cvoid}} = Ref(ref)
# Single character types
# These are needed to safely handle VLEN objects
abstract type CharType <: AbstractString end
struct ASCIIChar <: CharType
c::UInt8
end
Base.length(c::ASCIIChar) = 1
struct UTF8Char <: CharType
c::UInt8
end
Base.length(c::UTF8Char) = 1
chartype(::Type{String}) = ASCIIChar
stringtype(::Type{ASCIIChar}) = String
stringtype(::Type{UTF8Char}) = String
cset(::Type{<:AbstractString}) = H5T_CSET_UTF8
cset(::Type{UTF8Char}) = H5T_CSET_UTF8
cset(::Type{ASCIIChar}) = H5T_CSET_ASCII
## Conversion between Julia types and HDF5 atomic types
hdf5_type_id(::Type{Bool}) = H5T_NATIVE_B8
hdf5_type_id(::Type{Int8}) = H5T_NATIVE_INT8
hdf5_type_id(::Type{UInt8}) = H5T_NATIVE_UINT8
hdf5_type_id(::Type{Int16}) = H5T_NATIVE_INT16
hdf5_type_id(::Type{UInt16}) = H5T_NATIVE_UINT16
hdf5_type_id(::Type{Int32}) = H5T_NATIVE_INT32
hdf5_type_id(::Type{UInt32}) = H5T_NATIVE_UINT32
hdf5_type_id(::Type{Int64}) = H5T_NATIVE_INT64
hdf5_type_id(::Type{UInt64}) = H5T_NATIVE_UINT64
hdf5_type_id(::Type{Float32}) = H5T_NATIVE_FLOAT
hdf5_type_id(::Type{Float64}) = H5T_NATIVE_DOUBLE
hdf5_type_id(::Type{Reference}) = H5T_STD_REF_OBJ
hdf5_type_id(::Type{<:AbstractString}) = H5T_C_S1
const BitsType = Union{Bool,Int8,UInt8,Int16,UInt16,Int32,UInt32,Int64,UInt64,Float32,Float64}
const ScalarType = Union{BitsType,Reference}
# It's not safe to use particular id codes because these can change, so we use characteristics of the type.
function _hdf5_type_map(class_id, is_signed, native_size)
if class_id == H5T_INTEGER
if is_signed == H5T_SGN_2
return native_size === Csize_t(1) ? Int8 :
native_size === Csize_t(2) ? Int16 :
native_size === Csize_t(4) ? Int32 :
native_size === Csize_t(8) ? Int64 :
throw(KeyError(class_id, is_signed, native_size))
else
return native_size === Csize_t(1) ? UInt8 :
native_size === Csize_t(2) ? UInt16 :
native_size === Csize_t(4) ? UInt32 :
native_size === Csize_t(8) ? UInt64 :
throw(KeyError(class_id, is_signed, native_size))
end
else
return native_size === Csize_t(4) ? Float32 :
native_size === Csize_t(8) ? Float64 :
throw(KeyError(class_id, is_signed, native_size))
end
end
# global configuration for complex support
const COMPLEX_SUPPORT = Ref(true)
const COMPLEX_FIELD_NAMES = Ref(("r", "i"))
enable_complex_support() = COMPLEX_SUPPORT[] = true
disable_complex_support() = COMPLEX_SUPPORT[] = false
set_complex_field_names(real::AbstractString, imag::AbstractString) = COMPLEX_FIELD_NAMES[] = ((real, imag))
## HDF5 uses a plain integer to refer to each file, group, or
## dataset. These are wrapped into special types in order to allow
## method dispatch.
# Note re finalizers: we use them to ensure that objects passed back
# to the user will eventually be cleaned up properly. However, since
# finalizers don't run on a predictable schedule, we also call close
# directly on function exit. (This avoids certain problems, like those
# that occur when passing a freshly-created file to some other
# application).
# This defines an "unformatted" HDF5 data file. Formatted files are defined in separate modules.
mutable struct File <: H5DataStore
id::hid_t
filename::String
function File(id, filename, toclose::Bool=true)
f = new(id, filename)
if toclose
finalizer(close, f)
end
f
end
end
Base.cconvert(::Type{hid_t}, f::File) = f.id
mutable struct Group <: H5DataStore
id::hid_t
file::File # the parent file
function Group(id, file)
g = new(id, file)
finalizer(close, g)
g
end
end
Base.cconvert(::Type{hid_t}, g::Group) = g.id
mutable struct Properties
id::hid_t
class::hid_t
function Properties(id = H5P_DEFAULT, class = H5P_DEFAULT)
p = new(id, class)
finalizer(close, p) # Essential, otherwise we get a memory leak, since closing file with CLOSE_STRONG is not doing it for us
p
end
end
Base.cconvert(::Type{hid_t}, p::Properties) = p.id
mutable struct Dataset
id::hid_t
file::File
xfer::Properties
function Dataset(id, file, xfer = DEFAULT_PROPERTIES)
dset = new(id, file, xfer)
finalizer(close, dset)
dset
end
end
Base.cconvert(::Type{hid_t}, dset::Dataset) = dset.id
mutable struct Datatype
id::hid_t
toclose::Bool
file::File
function Datatype(id, toclose::Bool=true)
nt = new(id, toclose)
if toclose
finalizer(close, nt)
end
nt
end
function Datatype(id, file::File, toclose::Bool=true)
nt = new(id, toclose, file)
if toclose
finalizer(close, nt)
end
nt
end
end
Base.cconvert(::Type{hid_t}, dtype::Datatype) = dtype.id
Base.hash(dtype::Datatype, h::UInt) = hash(dtype.id, hash(Datatype, h))
Base.:(==)(dt1::Datatype, dt2::Datatype) = h5t_equal(dt1, dt2)
# Define an H5O Object type
const Object = Union{Group,Dataset,Datatype}
mutable struct Dataspace
id::hid_t
function Dataspace(id)
dspace = new(id)
finalizer(close, dspace)
dspace
end
end
Base.cconvert(::Type{hid_t}, dspace::Dataspace) = dspace.id
Base.:(==)(dspace1::Dataspace, dspace2::Dataspace) = h5s_extent_equal(checkvalid(dspace1), checkvalid(dspace2))
Base.hash(dspace::Dataspace, h::UInt) = hash(dspace.id, hash(Dataspace, h))
Base.copy(dspace::Dataspace) = Dataspace(h5s_copy(checkvalid(dspace)))
mutable struct Attribute
id::hid_t
file::File
function Attribute(id, file)
dset = new(id, file)
finalizer(close, dset)
dset
end
end
Base.cconvert(::Type{hid_t}, attr::Attribute) = attr.id
struct Attributes
parent::Union{File,Group,Dataset}
end
attributes(p::Union{File,Group,Dataset}) = Attributes(p)
# Methods for reference types
function Reference(parent::Union{File,Group,Dataset}, name::AbstractString)
ref = Ref{hobj_ref_t}()
h5r_create(ref, checkvalid(parent), name, H5R_OBJECT, -1)
return Reference(ref[])
end
Base.:(==)(a::Reference, b::Reference) = a.r == b.r
Base.hash(x::Reference, h::UInt) = hash(x.r, h)
# Opaque types
struct Opaque
data
tag::String
end
# An empty array type
struct EmptyArray{T} <: AbstractArray{T,0} end
# Required AbstractArray interface
Base.size(::EmptyArray) = ()
Base.IndexStyle(::Type{<:EmptyArray}) = IndexLinear()
Base.getindex(::EmptyArray, ::Int) = error("cannot index an `EmptyArray`")
Base.setindex!(::EmptyArray, v, ::Int) = error("cannot assign to an `EmptyArray`")
# Optional interface
Base.similar(::EmptyArray{T}) where {T} = EmptyArray{T}()
Base.similar(::EmptyArray, ::Type{S}) where {S} = EmptyArray{S}()
Base.similar(::EmptyArray, ::Type{S}, dims::Dims) where {S} = Array{S}(undef, dims)
# Override behavior for 0-dimensional Array
Base.length(::EmptyArray) = 0
# Required to avoid indexing during printing
Base.show(io::IO, E::EmptyArray) = print(io, typeof(E), "()")
Base.show(io::IO, ::MIME"text/plain", E::EmptyArray) = show(io, E)
# FIXME: Concatenation doesn't work for this type (it's treated as a length-1 array like
# Base's 0-dimensional arrays), so just forceably abort.
Base.cat_size(::EmptyArray) = error("concatenation of HDF5.EmptyArray is unsupported")
Base.cat_size(::EmptyArray, d) = error("concatenation of HDF5.EmptyArray is unsupported")
# Stub types to encode fixed-size arrays for H5T_ARRAY
struct FixedArray{T,D,L}
data::NTuple{L,T}
end
Base.size(::Type{FixedArray{T,D,L}}) where {T,D,L} = D
Base.size(x::FixedArray) = size(typeof(x))
Base.eltype(::Type{FixedArray{T,D,L}}) where {T,D,L} = T
Base.eltype(x::FixedArray) = eltype(typeof(x))
struct FixedString{N,PAD}
data::NTuple{N,UInt8}
end
Base.length(::Type{FixedString{N,PAD}}) where {N,PAD} = N
Base.length(str::FixedString) = length(typeof(str))
pad(::Type{FixedString{N,PAD}}) where {N,PAD} = PAD
pad(x::T) where {T<:FixedString} = pad(T)
struct VariableArray{T}
len::Csize_t
p::Ptr{Cvoid}
end
Base.eltype(::Type{VariableArray{T}}) where T = T
# VLEN objects
struct VLen{T}
data::Array
end
VLen(strs::Array{S}) where {S<:String} = VLen{chartype(S)}(strs)
VLen(A::Array{Array{T}}) where {T<:ScalarType} = VLen{T}(A)
VLen(A::Array{Array{T,N}}) where {T<:ScalarType,N} = VLen{T}(A)
function Base.cconvert(::Type{Ptr{Cvoid}}, v::VLen)
len = length(v.data)
h = Vector{hvl_t}(undef, len)
for ii in 1:len
d = v.data[ii]
p = unsafe_convert(Ptr{UInt8}, d)
h[ii] = hvl_t(length(d), p)
end
return h
end
include("show.jl")
# Blosc compression:
include("blosc_filter.jl")
# heuristic chunk layout (return empty array to disable chunking)
function heuristic_chunk(T, shape)
Ts = sizeof(T)
sz = prod(shape)
sz == 0 && return Int[] # never return a zero-size chunk
chunk = [shape...]
nd = length(chunk)
# simplification of ugly heuristic target chunk size from PyTables/h5py:
target = min(1500000, max(12000, floor(Int, 300*cbrt(Ts*sz))))
Ts > target && return ones(chunk)
# divide last non-unit dimension by 2 until we get <= target
# (since Julia default to column-major, favor contiguous first dimension)
while Ts*prod(chunk) > target
i = nd
while chunk[i] == 1
i -= 1
end
chunk[i] >>= 1
end
return chunk
end
heuristic_chunk(T, ::Tuple{}) = Int[]
heuristic_chunk(A::AbstractArray{T}) where {T} = heuristic_chunk(T, size(A))
heuristic_chunk(x) = Int[]
# (strings are saved as scalars, and hence cannot be chunked)
### High-level interface ###
# Open or create an HDF5 file
function _h5open(filename::AbstractString, rd::Bool, wr::Bool, cr::Bool, tr::Bool, ff::Bool,
cpl::Properties = DEFAULT_PROPERTIES, apl::Properties = DEFAULT_PROPERTIES; swmr::Bool = false)
if ff && !wr
error("HDF5 does not support appending without writing")
end
close_apl = false
if apl == DEFAULT_PROPERTIES
apl = create_property(H5P_FILE_ACCESS)
close_apl = true
# With garbage collection, the other modes don't make sense
apl[:fclose_degree] = H5F_CLOSE_STRONG
end
if cr && (tr || !isfile(filename))
flag = swmr ? H5F_ACC_TRUNC|H5F_ACC_SWMR_WRITE : H5F_ACC_TRUNC
fid = h5f_create(filename, flag, cpl, apl)
else
if !h5f_is_hdf5(filename)
error("This does not appear to be an HDF5 file")
end
if wr
flag = swmr ? H5F_ACC_RDWR|H5F_ACC_SWMR_WRITE : H5F_ACC_RDWR
else
flag = swmr ? H5F_ACC_RDONLY|H5F_ACC_SWMR_READ : H5F_ACC_RDONLY
end
fid = h5f_open(filename, flag, apl)
end
if close_apl
# Close properties manually to avoid errors when the file is
# closed before the properties are gc'ed
close(apl)
end
File(fid, filename)
end
"""
h5open(filename::AbstractString, mode::AbstractString="r"; swmr=false, pv...)
Open or create an HDF5 file where `mode` is one of:
- "r" read only
- "r+" read and write
- "cw" read and write, create file if not existing, do not truncate
- "w" read and write, create a new file (destroys any existing contents)
Pass `swmr=true` to enable (Single Writer Multiple Reader) SWMR write access for "w" and
"r+", or SWMR read access for "r".
"""
function h5open(filename::AbstractString, mode::AbstractString = "r"; swmr::Bool = false, pv...)
apl = create_property(H5P_FILE_ACCESS; pv...) # file access property list
# With garbage collection, the other modes don't make sense
# (Set this first, so that the user-passed properties can overwrite this.)
apl[:fclose_degree] = H5F_CLOSE_STRONG
cpl = create_property(H5P_FILE_CREATE; pv...) # file create property list
rd, wr, cr, tr, ff =
mode == "r" ? (true, false, false, false, false) :
mode == "r+" ? (true, true, false, false, true ) :
mode == "cw" ? (false, true, true, false, true ) :
mode == "w" ? (false, true, true, true, false) :
# mode == "w+" ? (true, true, true, true, false) :
# mode == "a" ? (true, true, true, true, true ) :
error("invalid open mode: ", mode)
if ff && !wr
error("HDF5 does not support appending without writing")
end
close_apl = false
if apl == DEFAULT_PROPERTIES
apl = create_property(H5P_FILE_ACCESS)
close_apl = true
# With garbage collection, the other modes don't make sense
apl[:fclose_degree] = H5F_CLOSE_STRONG
end
if cr && (tr || !isfile(filename))
flag = swmr ? H5F_ACC_TRUNC|H5F_ACC_SWMR_WRITE : H5F_ACC_TRUNC
fid = h5f_create(filename, flag, cpl, apl)
else
if !h5f_is_hdf5(filename)
error("This does not appear to be an HDF5 file")
end
if wr
flag = swmr ? H5F_ACC_RDWR|H5F_ACC_SWMR_WRITE : H5F_ACC_RDWR
else
flag = swmr ? H5F_ACC_RDONLY|H5F_ACC_SWMR_READ : H5F_ACC_RDONLY
end
fid = h5f_open(filename, flag, apl)
end
if close_apl
# Close properties manually to avoid errors when the file is
# closed before the properties are gc'ed
close(apl)
end
File(fid, filename)
end
"""
function h5open(f::Function, args...; swmr=false, pv...)
Apply the function f to the result of `h5open(args...;kwargs...)` and close the resulting
`HDF5.File` upon completion. For example with a `do` block:
h5open("foo.h5","w") do h5
h5["foo"]=[1,2,3]
end
"""
function h5open(f::Function, args...; swmr=false, pv...)
fid = h5open(args...; swmr=swmr, pv...)
try
f(fid)
finally
close(fid)
end
end
function h5rewrite(f::Function, filename::AbstractString, args...)
tmppath,tmpio = mktemp(dirname(filename))
close(tmpio)
try
val = h5open(f, tmppath, "w", args...)
Base.Filesystem.rename(tmppath, filename)
return val
catch
Base.Filesystem.unlink(tmppath)
rethrow()
end
end
function h5write(filename, name::AbstractString, data; pv...)
fid = h5open(filename, "cw"; pv...)
try
write(fid, name, data)
finally
close(fid)
end
end
function h5read(filename, name::AbstractString; pv...)
local dat
fid = h5open(filename, "r"; pv...)
try
obj = getindex(fid, name; pv...)
dat = read(obj)
close(obj)
finally
close(fid)
end
dat
end
function h5read(filename, name_type_pair::Pair{<:AbstractString,DataType}; pv...)
local dat
fid = h5open(filename, "r"; pv...)
try
obj = getindex(fid, name_type_pair[1]; pv...)
dat = read(obj, name_type_pair[2])
close(obj)
finally
close(fid)
end
dat
end
function h5read(filename, name::AbstractString, indices::Tuple{Vararg{Union{AbstractRange{Int},Int,Colon}}}; pv...)
local dat
fid = h5open(filename, "r"; pv...)
try
dset = getindex(fid, name; pv...)
dat = dset[indices...]
close(dset)
finally
close(fid)
end
dat
end
function h5writeattr(filename, name::AbstractString, data::Dict)
fid = h5open(filename, "r+")
try
obj = fid[name]
attrs = attributes(obj)
for x in keys(data)
attrs[x] = data[x]
end
close(obj)
finally
close(fid)
end
end
function h5readattr(filename, name::AbstractString)
local dat
fid = h5open(filename,"r")
try
obj = fid[name]
a = attributes(obj)
dat = Dict(x => read(a[x]) for x in keys(a))
close(obj)
finally
close(fid)
end
dat
end
# Ensure that objects haven't been closed
Base.isvalid(obj::Union{File,Properties,Datatype,Dataspace}) = obj.id != -1 && h5i_is_valid(obj)
Base.isvalid(obj::Union{Group,Dataset,Attribute}) = obj.id != -1 && obj.file.id != -1 && h5i_is_valid(obj)
Base.isvalid(obj::Attributes) = isvalid(obj.parent)
checkvalid(obj) = isvalid(obj) ? obj : error("File or object has been closed")
# Close functions
# Close functions that should try calling close regardless
function Base.close(obj::File)
if obj.id != -1
h5f_close(obj)
obj.id = -1
end
nothing
end
"""
isopen(obj::HDF5.File)
Returns `true` if `obj` has not been closed, `false` if it has been closed.
"""
Base.isopen(obj::File) = obj.id != -1
# Close functions that should first check that the file is still open. The common case is a
# file that has been closed with CLOSE_STRONG but there are still finalizers that have not run
# for the datasets, etc, in the file.
function Base.close(obj::Union{Group,Dataset})
if obj.id != -1
if obj.file.id != -1 && isvalid(obj)
h5o_close(obj)
end
obj.id = -1
end
nothing
end
function Base.close(obj::Attribute)
if obj.id != -1
if obj.file.id != -1 && isvalid(obj)
h5a_close(obj)
end
obj.id = -1
end
nothing
end
function Base.close(obj::Datatype)
if obj.toclose && obj.id != -1
if (!isdefined(obj, :file) || obj.file.id != -1) && isvalid(obj)
h5o_close(obj)
end
obj.id = -1
end
nothing
end
function Base.close(obj::Dataspace)
if obj.id != -1
if isvalid(obj)
h5s_close(obj)
end
obj.id = -1
end
nothing
end
function Base.close(obj::Properties)
if obj.id != -1
if isvalid(obj)
h5p_close(obj)
end
obj.id = -1
end
nothing
end
"""
ishdf5(name::AbstractString)
Returns `true` if `name` is a path to a valid hdf5 file, `false` otherwise.
"""
ishdf5(name::AbstractString) = h5f_is_hdf5(name)
# Extract the file
file(f::File) = f
file(o::Union{Object,Attribute}) = o.file
fd(obj::Object) = h5i_get_file_id(checkvalid(obj))
# Flush buffers
Base.flush(f::Union{Object,Attribute,Datatype,File}, scope = H5F_SCOPE_GLOBAL) = h5f_flush(checkvalid(f), scope)
# Open objects
open_group(parent::Union{File,Group}, name::AbstractString, apl::Properties=DEFAULT_PROPERTIES) = Group(h5g_open(checkvalid(parent), name, apl), file(parent))
open_dataset(parent::Union{File,Group}, name::AbstractString, apl::Properties=DEFAULT_PROPERTIES, xpl::Properties=DEFAULT_PROPERTIES) = Dataset(h5d_open(checkvalid(parent), name, apl), file(parent), xpl)
open_datatype(parent::Union{File,Group}, name::AbstractString, apl::Properties=DEFAULT_PROPERTIES) = Datatype(h5t_open(checkvalid(parent), name, apl), file(parent))
open_attribute(parent::Union{File,Object}, name::AbstractString, apl::Properties=DEFAULT_PROPERTIES) = Attribute(h5a_open(checkvalid(parent), name, apl), file(parent))
# Object (group, named datatype, or dataset) open
function h5object(obj_id::hid_t, parent)
obj_type = h5i_get_type(obj_id)
obj_type == H5I_GROUP ? Group(obj_id, file(parent)) :
obj_type == H5I_DATATYPE ? Datatype(obj_id, file(parent)) :
obj_type == H5I_DATASET ? Dataset(obj_id, file(parent)) :
error("Invalid object type for path ", path)
end
open_object(parent, path::AbstractString) = h5object(h5o_open(checkvalid(parent), path, H5P_DEFAULT), parent)
function gettype(parent, path::AbstractString)
obj_id = h5o_open(checkvalid(parent), path, H5P_DEFAULT)
obj_type = h5i_get_type(obj_id)
h5o_close(obj_id)
return obj_type
end
# Get the root group
root(h5file::File) = open_group(h5file, "/")
root(obj::Union{Group,Dataset}) = open_group(file(obj), "/")
# getindex syntax: obj2 = obj1[path]
Base.getindex(dset::Dataset, name::AbstractString) = open_attribute(dset, name)
Base.getindex(x::Attributes, name::AbstractString) = open_attribute(x.parent, name)
function Base.getindex(parent::Union{File,Group}, path::AbstractString; pv...)
obj_type = gettype(parent, path)
if obj_type == H5I_DATASET
dapl = isempty(pv) ? DEFAULT_PROPERTIES : create_property(H5P_DATASET_ACCESS; pv...)
dxpl = isempty(pv) ? DEFAULT_PROPERTIES : create_property(H5P_DATASET_XFER; pv...)
return open_dataset(parent, path, dapl, dxpl)
elseif obj_type == H5I_GROUP
gapl = isempty(pv) ? DEFAULT_PROPERTIES : create_property(H5P_GROUP_ACCESS; pv...)
return open_group(parent, path, gapl)
else#if obj_type == H5I_DATATYPE # only remaining choice
tapl = isempty(pv) ? DEFAULT_PROPERTIES : create_property(H5P_DATATYPE_ACCESS; pv...)
return open_datatype(parent, path, tapl)
end
end
# Path manipulation
function split1(path::AbstractString)
ind = findfirst('/', path)
isnothing(ind) && return path, nothing
if ind == 1 # matches root group
return "/", path[2:end]
else
indm1, indp1 = prevind(path, ind), nextind(path, ind)
return path[1:indm1], path[indp1:end] # better to use begin:indm1, but only available on v1.5
end
end
function create_group(parent::Union{File,Group}, path::AbstractString,
lcpl::Properties=_link_properties(path),
gcpl::Properties=DEFAULT_PROPERTIES)
Group(h5g_create(checkvalid(parent), path, lcpl, gcpl, H5P_DEFAULT), file(parent))
end
function create_dataset(parent::Union{File,Group}, path::AbstractString, dtype::Datatype, dspace::Dataspace,
lcpl::Properties, dcpl::Properties,
dapl::Properties, dxpl::Properties)
Dataset(h5d_create(checkvalid(parent), path, dtype, dspace, lcpl, dcpl, dapl), file(parent), dxpl)
end
# Setting dset creation properties with name/value pairs
function create_dataset(parent::Union{File,Group}, path::AbstractString, dtype::Datatype, dspace::Dataspace; pv...)
dcpl = isempty(pv) ? DEFAULT_PROPERTIES : create_property(H5P_DATASET_CREATE; pv...)
dxpl = isempty(pv) ? DEFAULT_PROPERTIES : create_property(H5P_DATASET_XFER; pv...)
dapl = isempty(pv) ? DEFAULT_PROPERTIES : create_property(H5P_DATASET_ACCESS; pv...)
Dataset(h5d_create(checkvalid(parent), path, dtype, dspace, _link_properties(path), dcpl, dapl), file(parent), dxpl)
end
create_dataset(parent::Union{File,Group}, path::AbstractString, dtype::Datatype, dspace_dims::Dims; pv...) = create_dataset(checkvalid(parent), path, dtype, dataspace(dspace_dims); pv...)
create_dataset(parent::Union{File,Group}, path::AbstractString, dtype::Datatype, dspace_dims::Tuple{Dims,Dims}; pv...) = create_dataset(checkvalid(parent), path, dtype, dataspace(dspace_dims[1], max_dims=dspace_dims[2]); pv...)
create_dataset(parent::Union{File,Group}, path::AbstractString, dtype::Type, dspace_dims::Tuple{Dims,Dims}; pv...) = create_dataset(checkvalid(parent), path, datatype(dtype), dataspace(dspace_dims[1], max_dims=dspace_dims[2]); pv...)
# Note that H5Tcreate is very different; H5Tcommit is the analog of these others
create_datatype(class_id, sz) = Datatype(h5t_create(class_id, sz))
function commit_datatype(parent::Union{File,Group}, path::AbstractString, dtype::Datatype,
lcpl::Properties=create_property(H5P_LINK_CREATE), tcpl::Properties=DEFAULT_PROPERTIES, tapl::Properties=DEFAULT_PROPERTIES)
h5p_set_char_encoding(lcpl, cset(typeof(path)))
h5t_commit(checkvalid(parent), path, dtype, lcpl, tcpl, tapl)
dtype.file = file(parent)
return dtype
end
function create_attribute(parent::Union{File,Object}, name::AbstractString, dtype::Datatype, dspace::Dataspace)
attrid = h5a_create(checkvalid(parent), name, dtype, dspace, _attr_properties(name), H5P_DEFAULT)
return Attribute(attrid, file(parent))
end
function _prop_get(p::Properties, name::Symbol)
class = p.class
if class == H5P_FILE_CREATE
return name === :userblock ? h5p_get_userblock(p) :
name === :track_times ? h5p_get_obj_track_times(p) : # H5P_OBJECT_CREATE
error("unknown file create property ", name)
end
if class == H5P_FILE_ACCESS
return name === :alignment ? h5p_get_alignment(p) :
name === :driver ? h5p_get_driver(p) :
name === :driver_info ? h5p_get_driver_info(p) :
name === :fapl_mpio ? h5p_get_fapl_mpio(p) :
name === :fclose_degree ? h5p_get_fclose_degree(p) :
name === :libver_bounds ? h5p_get_libver_bounds(p) :
error("unknown file access property ", name)
end
if class == H5P_GROUP_CREATE
return name === :local_heap_size_hint ? h5p_get_local_heap_size_hint(p) :
name === :track_times ? h5p_get_obj_track_times(p) : # H5P_OBJECT_CREATE
error("unknown group create property ", name)
end
if class == H5P_LINK_CREATE
return name === :char_encoding ? h5p_get_char_encoding(p) :
name === :create_intermediate_group ? h5p_get_create_intermediate_group(p) :
error("unknown link create property ", name)
end
if class == H5P_DATASET_CREATE
return name === :alloc_time ? h5p_get_alloc_time(p) :
name === :chunk ? get_chunk(p) :
#name === :external ? h5p_get_external(p) :
name === :layout ? h5p_get_layout(p) :
name === :track_times ? h5p_get_obj_track_times(p) : # H5P_OBJECT_CREATE
error("unknown dataset create property ", name)
end
if class == H5P_DATASET_XFER
return name === :dxpl_mpio ? h5p_get_dxpl_mpio(p) :
error("unknown dataset transfer property ", name)
end
if class == H5P_ATTRIBUTE_CREATE
return name === :char_encoding ? h5p_get_char_encoding(p) :
error("unknown attribute create property ", name)
end
error("unknown property class ", class)
end
function _prop_set!(p::Properties, name::Symbol, val, check::Bool = true)
class = p.class
if class == H5P_FILE_CREATE
return name === :userblock ? h5p_set_userblock(p, val...) :
name === :track_times ? h5p_set_obj_track_times(p, val...) : # H5P_OBJECT_CREATE
check ? error("unknown file create property ", name) : nothing
end
if class == H5P_FILE_ACCESS
return name === :alignment ? h5p_set_alignment(p, val...) :
name === :fapl_mpio ? h5p_set_fapl_mpio(p, val...) :
name === :fclose_degree ? h5p_set_fclose_degree(p, val...) :
name === :libver_bounds ? h5p_set_libver_bounds(p, val...) :
check ? error("unknown file access property ", name) : nothing
end
if class == H5P_GROUP_CREATE
return name === :local_heap_size_hint ? h5p_set_local_heap_size_hint(p, val...) :
name === :track_times ? h5p_set_obj_track_times(p, val...) : # H5P_OBJECT_CREATE
check ? error("unknown group create property ", name) : nothing
end
if class == H5P_LINK_CREATE
return name === :char_encoding ? h5p_set_char_encoding(p, val...) :
name === :create_intermediate_group ? h5p_set_create_intermediate_group(p, val...) :
check ? error("unknown link create property ", name) : nothing
end
if class == H5P_DATASET_CREATE
return name === :alloc_time ? h5p_set_alloc_time(p, val...) :
name === :blosc ? h5p_set_blosc(p, val...) :
name === :chunk ? set_chunk(p, val...) :
name === :compress ? h5p_set_deflate(p, val...) :
name === :deflate ? h5p_set_deflate(p, val...) :
name === :external ? h5p_set_external(p, val...) :
name === :layout ? h5p_set_layout(p, val...) :
name === :shuffle ? h5p_set_shuffle(p, val...) :
name === :track_times ? h5p_set_obj_track_times(p, val...) : # H5P_OBJECT_CREATE
check ? error("unknown dataset create property ", name) : nothing
end
if class == H5P_DATASET_XFER
return name === :dxpl_mpio ? h5p_set_dxpl_mpio(p, val...) :
check ? error("unknown dataset transfer property ", name) : nothing
end
if class == H5P_ATTRIBUTE_CREATE
return name === :char_encoding ? h5p_set_char_encoding(p, val...) :
check ? error("unknown attribute create property ", name) : nothing
end
return check ? error("unknown property class ", class) : nothing
end
function create_property(class; pv...)
p = Properties(h5p_create(class), class)
for (k, v) in pairs(pv)
_prop_set!(p, k, v, false)
end
return p
end
# Delete objects
delete_attribute(parent::Union{File,Object}, path::AbstractString) = h5a_delete(checkvalid(parent), path)
delete_object(parent::Union{File,Group}, path::AbstractString, lapl::Properties=DEFAULT_PROPERTIES) = h5l_delete(checkvalid(parent), path, lapl)
delete_object(obj::Object) = delete_object(parent(obj), ascii(split(name(obj),"/")[end])) # FIXME: remove ascii?
# Copy objects
copy_object(src_parent::Union{File,Group}, src_path::AbstractString, dst_parent::Union{File,Group}, dst_path::AbstractString) = h5o_copy(checkvalid(src_parent), src_path, checkvalid(dst_parent), dst_path, H5P_DEFAULT, _link_properties(dst_path))
copy_object(src_obj::Object, dst_parent::Union{File,Group}, dst_path::AbstractString) = h5o_copy(checkvalid(src_obj), ".", checkvalid(dst_parent), dst_path, H5P_DEFAULT, _link_properties(dst_path))
# Assign syntax: obj[path] = value
# Creates a dataset unless obj is a dataset, in which case it creates an attribute
Base.setindex!(dset::Dataset, val, name::AbstractString) = write_attribute(dset, name, val)
Base.setindex!(x::Attributes, val, name::AbstractString) = write_attribute(x.parent, name, val)
# Getting and setting properties: p[:chunk] = dims, p[:compress] = 6
Base.getindex(p::Properties, name::Symbol) = _prop_get(checkvalid(p), name)
function Base.setindex!(p::Properties, val, name::Symbol)
_prop_set!(checkvalid(p), name, val, true)
return p
end
# Create a dataset with properties: obj[path, prop = val, ...] = val
function Base.setindex!(parent::Union{File,Group}, val, path::AbstractString; pv...)
need_chunks = any(k in keys(chunked_props) for k in keys(pv))
have_chunks = any(k == :chunk for k in keys(pv))
chunk = need_chunks ? heuristic_chunk(val) : Int[]
# ignore chunked_props (== compression) for empty datasets (issue #246):
discard_chunks = need_chunks && isempty(chunk)
if discard_chunks
pv = pairs(Base.structdiff((; pv...), chunked_props))
else
if need_chunks && !have_chunks
pv = pairs((; chunk = chunk, pv...))
end
end
write(parent, path, val; pv...)
end
# Check existence
function Base.haskey(parent::Union{File,Group}, path::AbstractString, lapl::Properties = DEFAULT_PROPERTIES)
first, rest = split1(path)
if first == "/"
parent = root(parent)
elseif !h5l_exists(parent, first, lapl)
return false
end
exists = true
if !isnothing(rest) && !isempty(rest)
obj = parent[first]
exists = haskey(obj, rest, lapl)
close(obj)
end
return exists
end
Base.haskey(attr::Attributes, path::AbstractString) = h5a_exists(checkvalid(attr.parent), path)
Base.haskey(dset::Union{Dataset,Datatype}, path::AbstractString) = h5a_exists(checkvalid(dset), path)
# Querying items in the file
group_info(obj::Union{Group,File}) = h5g_get_info(checkvalid(obj))
object_info(obj::Union{File,Object}) = h5o_get_info(checkvalid(obj))
Base.length(obj::Union{Group,File}) = h5g_get_num_objs(checkvalid(obj))
Base.length(x::Attributes) = object_info(x.parent).num_attrs
Base.isempty(x::Union{Group,File}) = length(x) == 0
Base.eltype(dset::Union{Dataset,Attribute}) = get_jl_type(dset)
# filename and name
filename(obj::Union{File,Group,Dataset,Attribute,Datatype}) = h5f_get_name(checkvalid(obj))
name(obj::Union{File,Group,Dataset,Datatype}) = h5i_get_name(checkvalid(obj))
name(attr::Attribute) = h5a_get_name(attr)
function Base.keys(x::Union{Group,File})
checkvalid(x)
n = length(x)
return [h5l_get_name_by_idx(x, ".", H5_INDEX_NAME, H5_ITER_INC, i-1, H5P_DEFAULT) for i = 1:n]
end
function Base.keys(x::Attributes)
checkvalid(x.parent)
n = length(x)
return [h5a_get_name_by_idx(x.parent, ".", H5_INDEX_NAME, H5_ITER_INC, i-1, H5P_DEFAULT) for i = 1:n]
end
# iteration by objects
function Base.iterate(parent::Union{File,Group}, iter = (1,nothing))
n, prev_obj = iter
prev_obj ≢ nothing && close(prev_obj)
n > length(parent) && return nothing
obj = h5object(h5o_open_by_idx(checkvalid(parent), ".", H5_INDEX_NAME, H5_ITER_INC, n-1, H5P_DEFAULT), parent)
return (obj, (n+1,obj))
end
Base.lastindex(dset::Dataset) = length(dset)
Base.lastindex(dset::Dataset, d::Int) = size(dset, d)
function Base.parent(obj::Union{File,Group,Dataset})