-
Notifications
You must be signed in to change notification settings - Fork 2
/
hdf5.pd
2757 lines (2193 loc) · 57.8 KB
/
hdf5.pd
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
use Config;
our $VERSION = '0.76';
pp_setversion(qq{'$VERSION'});
# Necessary includes for .xs file
pp_addhdr(<<'EOH');
#include <hdf5.h>
#define PDLchar pdl
#define PDLuchar pdl
#define PDLshort pdl
#define PDLint pdl
#define PDLlong pdl
#define PDLfloat pdl
#define PDLdouble pdl
#define uchar unsigned char
EOH
pp_bless ("PDL::IO::HDF5");
pp_addpm(<<'EOPM');
=head1 NAME
PDL::IO::HDF5 - PDL Interface to the HDF5 Data Format.
=head1 DESCRIPTION
This package provides an object-oriented interface for L<PDL>s to
the HDF5 data-format. Information on the HDF5 Format can be found
at the HDF Group's web site at http://www.hdfgroup.org .
=head2 LIMITATIONS
Currently this interface only provides a subset of the total HDF5 library's
capability.
=over 1
=item *
Only HDF5 Simple datatypes are supported. No HDF5 Compound datatypes are supported since PDL doesn't
support them.
=item *
Only HDF5 Simple dataspaces are supported.
=back
=head1 SYNOPSIS
use PDL::IO::HDF5;
# Files #######
my $newfile = new PDL::IO::HDF5("newfile.hdf"); # create new hdf5 or open existing file.
my $attrValue = $existingFile->attrGet('AttrName'); # Get attribute value for file
$existingFile->attSet('AttrName' => 'AttrValue'); # Set attribute value(s) for file
# Groups ######
my $group = $newfile->group("/mygroup"); # create a new or open existing group
my @groups = $existingFile->groups; # get a list of all the groups at the root '/'
# level.
my @groups = $group->groups; # get a list of all the groups at the "mygroup"
# level.
my $group2 = $group->group('newgroup'); # Create/open a new group in existing group "mygroup"
$group->unlink('datasetName'); # Delete a dataset from a group
$group->reference($dataset,'refName',\@start,\@count); # Create a scalar reference to a subregion of a
# dataset, with specified start index and count.
my $attrValue = $group->attrGet('AttrName'); # Get attribute value for a group
$group->attrSet('AttrName' => 'AttrValue'); # Set attribute value(s) for a group
$group->attrDel('AttrName1', 'AttrName2'); # Delete attribute(s) for a group
@attrs = $group->attrs; # Get List of attributes for a group
# Data Sets ########
my $dataset = $group->dataset( 'datasetName'); # create a new or open existing dataset
# in an existing group
my $dataset = $newfile->dataset( 'datasetName'); # create a new or open existing dataset
# in the root group of a file
my $dataset2 = $newfile->dataset( 'datasetName'); # create a new or open existing dataset
# in the root group.
my @datasets = $existingFile->datasets; # get a list of all datasets in the root '/' group
my @datasets = $group->datasets; # get a list of all datasets in a group
@dims = $dataset->dims; # get a list of dimensions for the dataset
$pdl = $dataset->get(); # Get the array data in the dataset
$pdl = $dataset->get($start,$length,$stride); # Get a slice or hyperslab of the array data in the dataset
$dataset->set($pdl, unlimited => 1); # Set the array data in the dataset
my $attrValue = $dataset->attrGet('AttrName'); # Get attribute value for a dataset
$dataset->attSet('AttrName' => 'AttrValue'); # Set attribute value(s) for a dataset
=head1 MEMBER DATA
=over 1
=item ID
ID number given to the file by the HDF5 library
=item filename
Name of the file.
=item accessMode
Access Mode?? ( read /write etc????)
=item attrIndex
Quick lookup index of group names to attribute values. Autogenerated as-needed by the
L<allAttrValues>, L<allAttrNames>, L<getGroupByAttr> methods. Any attribute writes or group
creations will delete this data member, because it will no longer be valid.
The index is of this form:
{
groupName1 => { attr1 => value, attr2 => value }.
groupName2 => { attr1 => value, attr3 => value }.
.
.
.
}
For the purposes of indexing groups by their attributes, the attributes are
applied hierarchically. i.e. any attributes of the higher level groups are assumed to be
apply for the lower level groups.
=item groupIndex
Quick lookup index of attribute names/values group names. This index is used by the
L<getGroupByAttr> method to quickly find any group(s) that have attribute that match a
desired set.
The index is of this form:
{ "attr1\0attt2" => { "value1\0value2' => [ group1, group2, ...],
"value3\0value3' => [ groupA ],
.
.
.
},
"att1" => { "value1' => [ group1, group2, ...],
"value3' => [ groupA ]
.
.
.
},
.
.
.
}
The first level of the index maps the attribute name combinations that have
indexes built to their index. The second level maps the corresponding attribute values
with the group(s) where these attributes take on these values.
groupName1 => { attr1 => value, attr2 => value }.
groupName2 => { attr1 => value, attr3 => value }.
.
.
.
}
For the purposes of indexing groups by their attributes, the attributes are
applied hierarchically. i.e. any attributes of the higher level groups are assumed to be
apply for the lower level groups.
=back
=head1 METHODS
=head2 new
=for ref
PDL::IO::HDF5 constructor - creates PDL::IO::HDF5 object for reading or
writing data.
B<Usage:>
=for usage
$a = new PDL::IO::HDF5( $filename );
Arguments:
1) The name of the file.
If this file exists and you want to write to it,
prepend the name with the '>' character: ">name.nc"
Returns undef on failure.
B<Example:>
=for example
$hdf5obj = new PDL::IO::HDF5( "file.hdf" );
=cut
sub new {
my $type = shift;
my $file = shift;
my $self = {};
my $rc;
my $write;
if (substr($file, 0, 1) eq '>') { # open for writing
$file = substr ($file, 1); # chop off >
$write = 1;
}
my $fileID; # HDF file id
if (-e $file) { # Existing File
if ($write) {
$fileID = H5Fopen($file, H5F_ACC_RDWR(), H5P_DEFAULT());
if( $fileID < 0){
carp("Can't Open Existing HDF file '$file' for writing\n");
return undef;
}
$self->{accessMode} = 'w';
} else { # Open read-only
$fileID = H5Fopen($file, H5F_ACC_RDONLY(), H5P_DEFAULT());
if( $fileID < 0){
carp("Can't Open Existing HDF file '$file' for reading\n");
return undef;
}
$self->{accessMode} = 'r';
}
}
else{ # File doesn't exist, create it:
$fileID = H5Fcreate($file, H5F_ACC_TRUNC(), H5P_DEFAULT(), H5P_DEFAULT());
if( $fileID < 0){
carp("Can't Open New HDF file '$file' for writing\n");
return undef;
}
$self->{accessMode} = 'w';
}
# Record file name, ID
$self->{filename} = $file;
$self->{ID} = $fileID;
$self->{attrIndex} = undef; # Initialize attrIndex
$self->{groupIndex} = undef; # Initialize groupIndex
bless $self, $type;
}
=head2 filename
=for ref
Get the filename for the HDF5 file
B<Usage:>
=for usage
my $filename = $HDFfile->filename;
=cut
sub filename {
my $self = shift;
return $self->{filename};
}
=head2 group
=for ref
Open or create a group in the root "/" group (i.e. top level)
of the HDF5 file.
B<Usage:>
=for usage
$HDFfile->group("groupName");
Returns undef on failure, 1 on success.
=cut
sub group {
my $self = shift;
my $name = $_[0]; # get the group name
my $parentID = $self->{ID};
my $parentName = '';
my $group = new PDL::IO::HDF5::Group( 'name'=> $name, parent => $self,
fileObj => $self );
}
=head2 groups
=for ref
Get a list of groups in the root "/" group (i.e. top level)
of the HDF5 file.
B<Usage:>
=for usage
@groups = $HDFfile->groups;
=cut
sub groups {
my $self = shift;
my @groups = $self->group("/")->groups;
return @groups;
}
=head2 unlink
=for ref
Unlink an object from the root "/" group (i.e. top level)
of the HDF5 file.
B<Usage:>
=for usage
$HDFfile->unlink($name);
=cut
sub unlink {
my $self = shift;
my $name = $_[0];
$self->group("/")->unlink($name);
return 1;
}
=head2 dataset
=for ref
Open or create a dataset in the root "/" group (i.e. top level)
of the HDF5 file.
B<Usage:>
=for usage
$HDFfile->dataset("groupName");
Returns undef on failure, 1 on success.
Note: This is a convenience method that is equivalent to:
$HDFfile->group("/")->dataset("groupName");
=cut
sub dataset {
my $self = shift;
my $name = $_[0]; # get the dataset name
return $self->group("/")->dataset($name);
}
=head2 datasets
=for ref
Get a list of all dataset names in the root "/" group.
B<Usage:>
=for usage
@datasets = $HDF5file->datasets;
Note: This is a convenience method that is equivalent to:
$HDFfile->group("/")->datasets;
=cut
sub datasets{
my $self = shift;
my $name = $_[0]; # get the dataset name
return $self->group("/")->datasets;
}
=head2 attrSet
=for ref
Set the value of an attribute(s) in the root '/' group of the file.
Currently attribute types supported are null-terminated strings and
any PDL type.
B<Usage:>
=for usage
$HDFfile->attrSet( 'attr1' => 'attr1Value',
'attr2' => 'attr2 value',
'attr3' => $pdl,
.
.
.
);
Returns undef on failure, 1 on success.
Note: This is a convenience method that is equivalent to:
$HDFfile->group("/")->attrSet( 'attr1' => 'attr1Value',
'attr2' => 'attr2 value',
'attr3' => $pdl,
.
.
.
);
=cut
sub attrSet {
my $self = shift;
my %attrs = @_; # get atribute hash
return $self->group("/")->attrSet(%attrs);
}
=head2 attrGet
=for ref
Get the value of an attribute(s) in the root '/' group of the file.
Currently the attribute types supported are null-terminated strings
and PDLs.
B<Usage:>
=for usage
@attrValues = $HDFfile->attrGet( 'attr1', 'attr2' );
=cut
sub attrGet {
my $self = shift;
my @attrs = @_; # get atribute hash
return $self->group("/")->attrGet(@attrs);
}
=head2 attrDel
=for ref
Delete attribute(s) in the root "/" group of the file.
B<Usage:>
=for usage
$HDFfile->attrDel( 'attr1',
'attr2',
.
.
.
);
Returns undef on failure, 1 on success.
Note: This is a convenience method that is equivalent to:
$HDFfile->group("/")->attrDel( 'attr1',
'attr2',
.
.
.
);
=cut
sub attrDel {
my $self = shift;
my @attrs = @_; # get atribute names
return $self->group("/")->attrDel(@attrs);
}
=head2 attrs
=for ref
Get a list of all attribute names in the root "/" group of the file.
B<Usage:>
=for usage
@attrs = $HDFfile->attrs;
Note: This is a convenience method that is equivalent to:
$HDFfile->group("/")->attrs
=cut
sub attrs {
my $self = shift;
return $self->group("/")->attrs;
}
=head2 reference
=for ref
Create a reference to part of a dataset in the root "/" group of the file.
B<Usage:>
=for usage
$HDFfile->reference;
Note: This is a convenience method that is equivalent to:
$HDFfile->group("/")->reference($referenceName,$datasetObj,@regionStart,@regionCount);
Create a reference named $referenceName within the root group "/" to a subroutine of
the dataset $datasetObj. The region to be referenced is defined by the @regionStart
and @regionCount arrays.
=cut
sub reference {
my $self = shift;
my $datasetObj = shift;
my $referenceName = shift;
my @regionStart = shift;
my @regionCount = shift;
return $self->group("/")->reference($datasetObj,$referenceName,\@regionStart,\@regionCount);
}
=head2 _buildAttrIndex
=for ref
Internal Method to build the attribute index hash
for the object
B<Usage:>
=for usage
$hdf5obj->_buildAttrIndex;
Output:
Updated attrIndex data member
=cut
sub _buildAttrIndex{
my ($self) = @_;
# Take care of any attributes in the current group
my @attrs = $self->attrs;
my @attrValues = $self->attrGet(@attrs);
my $index = $self->{attrIndex} = {};
my %indexElement; # element of the index for this group
@indexElement{@attrs} = @attrValues;
$index->{'/'} = \%indexElement;
my $topLevelAttrs = { %indexElement };
# Now Do any subgroups:
my @subGroups = $self->groups;
my $subGroup;
foreach $subGroup(@subGroups){
$self->group($subGroup)->_buildAttrIndex($index,$topLevelAttrs);
}
}
=head2 clearAttrIndex
=for ref
Method to clear the attribute index hash
for the object. This is a mostly internal method that is
called whenever some part of the HDF5 file has changed and the
L<attrIndex> index is no longer valid.
B<Usage:>
=for usage
$hdf5obj->clearAttrIndex;
=cut
sub clearAttrIndex{
my $self = shift;
$self->{attrIndex} = undef;
}
=head2 _buildGroupIndex
=for ref
Internal Method to build the groupIndex hash
for the object
B<Usage:>
=for usage
$hdf5obj->_buildGroupIndex(@attrs);
where:
@attrs List of attribute names to build
a group index on.
Output:
Updated groupIndex data member
=cut
sub _buildGroupIndex{
my ($self,@attrs) = @_;
@attrs = sort @attrs; # Sort the attributes so the order won't matter
# Generate attrIndex if not there yet
defined( $self->{attrIndex}) || $self->_buildAttrIndex;
my $attrIndex = $self->{attrIndex};
my $groupIndexElement = {}; # Element of the group index that we will build
my $group;
my $attrIndexElement; # Attr index for the current group
my @attrValues; # attr values corresponding to @attrs for the current group
my $key; # group index key
# Go Thru All Groups
foreach $group(sort keys %$attrIndex){
$attrIndexElement = $attrIndex->{$group};
@attrValues = map defined($_) ? $_ : '_undef_', @$attrIndexElement{@attrs}; # Groups with undefined attr will get a '_undef_' string for the value
# Use multi-dimensional array emulation for the hash
# key here because it should be quicker.
if( defined( $groupIndexElement->{$key = join($;,@attrValues)}) ) { # if already defined, add to the list
push @{$groupIndexElement->{$key}}, $group;
}
else{ # not already defined create new element
$groupIndexElement->{$key} = [ $group ];
}
}
# initialize group index if it doesn't exist.
unless( defined $self->{groupIndex} ){ $self->{groupIndex} = {} };
# Use multi-dimensional array emulation for the hash
# key here because it should be quicker.
$self->{groupIndex}{join($;,@attrs)} = $groupIndexElement;
}
=head2 clearGroupIndex
=for ref
Method to clear the group index hash
for the object. This is a mostly internal method that is
called whenever some part of the HDF5 file has changed and the
L<groupIndex> index is no longer valid.
B<Usage:>
=for usage
$hdf5obj->clearGroupIndex;
=cut
sub clearGroupIndex{
my $self = shift;
$self->{groupIndex} = undef;
}
=head2 getGroupsByAttr
=for ref
Get the group names which attributes match a given set of values. This method
enables database-like queries to be made. I.e. you can get answers to
questions like 'Which groups have attr1 = value1, and attr3 = value2?'.
B<Usage:>
=for usage
@groupNames = $hdf5Obj->getGroupsByAttr( 'attr1' => 'value1',
'attr2' => 'value2' );
=cut
sub getGroupsByAttr{
my $self = shift;
my %attrHash = @_;
my @keys = sort keys %attrHash;
# Use multi-dimensional array emulation for the hash
# key here because it should be quicker.
my $compositeKey = join($;, @keys);
# Generate groupIndex if not there yet
defined( $self->{groupIndex}{$compositeKey} ) || $self->_buildGroupIndex(@keys);
$groupIndex = $self->{groupIndex}{$compositeKey};
my @values = @attrHash{@keys};
my $compositeValues = join($;, @values);
if( defined($groupIndex->{$compositeValues} )){
return @{$groupIndex->{$compositeValues}};
}
else{
return ();
}
}
=head2 allAttrValues
=for ref
Returns information about group attributes defined in the HDF5 datafile.
B<Usage:>
=for usage
# Single Attr Usage. Returns an array of all
# values of attribute 'attrName' in the file.
$hdf5obj->allAttrValues('attrName');
# Multiple Attr Usage. Returns an 2D array of all
# values of attributes 'attr1', 'attr2' in the file.
# Higher-Level
$hdf5obj->allAttrValues('attr1', 'attr2');
=cut
sub allAttrValues{
my $self = shift;
my @attrs = @_;
# Generate attrIndex if not there yet
defined( $self->{attrIndex}) || $self->_buildAttrIndex;
my $attrIndex = $self->{attrIndex};
if( @attrs == 1) { # Single Argument Processing
my $attr = $attrs[0];
my $group;
my @values;
my $grpAttrHash; # attr hash for a particular group
# Go thru each group and look for instances of $attr
foreach $group( keys %$attrIndex){
$grpAttrHash = $attrIndex->{$group};
if( defined($grpAttrHash->{$attr})){
push @values, $grpAttrHash->{$attr};
}
}
return @values;
}
else{ # Multiple argument processing
my $group;
my @values;
my $grpAttrHash; # attr hash for a particular group
my $attr; # individual attr name
my $allAttrSeen; # flag = 0 if we have not seen all of the
# desired attributes in the current group
my $value; # Current value of the @values array that we
# will return
# Go thru each group and look for instances of $attr
foreach $group( keys %$attrIndex){
$grpAttrHash = $attrIndex->{$group};
# Go thru each attribute
$allAttrSeen = 1; # assume we will se all atributes, set to zero if we don't
$value = [];
foreach $attr(@attrs){
if( defined($grpAttrHash->{$attr})){
push @$value, $grpAttrHash->{$attr};
}
else{
$allAttrSeen = 0;
}
}
push @values, $value if $allAttrSeen; #add to values array if we got anything
}
return @values;
}
}
=head2 allAttrNames
=for ref
Returns a sorted list of all the group attribute names that are defined
in the file.
B<Usage:>
=for usage
my @attrNames = $hdf5obj->allAttrNames;
=cut
sub allAttrNames{
my $self = shift;
# Generate attrIndex if not there yet
defined( $self->{attrIndex}) || $self->_buildAttrIndex;
my $attrIndex = $self->{attrIndex};
my $group;
my %names;
my $grpAttrHash; # attr hash for a particular group
my @currentNames;
# Go thru each group and look for instances of $attr
foreach $group( keys %$attrIndex){
$grpAttrHash = $attrIndex->{$group};
@currentNames = keys %$grpAttrHash;
@names{@currentNames} = @currentNames;
}
return sort keys %names;
}
=head2 IDget
=for ref
Returns the HDF5 library ID for this object
B<Usage:>
=for usage
my $ID = $hdf5obj->IDget;