BELFEM 0.9.4
Berkeley Lab Finite Element Framework
Loading...
Searching...
No Matches
hdf5_tools.hpp
Go to the documentation of this file.
1/*
2 * BELFEM -- The Berkeley Lab Finite Element Framework
3 * Copyright (c) 2026, The Regents of the University of California,
4 * through Lawrence Berkeley National Laboratory (subject to receipt of any required
5 * approvals from the U.S. Dept. of Energy). All rights reserved.
6 *
7 * Developers: Christian Messe, Gregory Giard
8 *
9 * See the top-level LICENSE file for the complete license and disclaimer.
10 */
11
12#ifndef BELFEM_HDF5_TOOLS_HPP
13#define BELFEM_HDF5_TOOLS_HPP
14
15#include <cstring>
16
17#include "stringtools.hpp"
18#include "assert.hpp"
19#include "hdf5_types.hpp"
20#include "cl_Vector.hpp"
21#include "cl_Matrix.hpp"
22#include "cl_Cell.hpp"
23
24namespace belfem
25{
26 namespace hdf5
27 {
28//------------------------------------------------------------------------------
29
30#ifdef BELFEM_HDF5
38 struct DatasetHandles
39 {
40 hid_t mDataSet = H5I_INVALID_HID ;
41 hid_t mDataType = H5I_INVALID_HID ;
42 hid_t mDataSpace = H5I_INVALID_HID ;
43
44 DatasetHandles() = default ;
45
46 // a copy or a move would close the same identifiers twice
47 DatasetHandles( const DatasetHandles & ) = delete ;
48 DatasetHandles & operator=( const DatasetHandles & ) = delete ;
49 DatasetHandles( DatasetHandles && ) = delete ;
50 DatasetHandles & operator=( DatasetHandles && ) = delete ;
51
52 ~DatasetHandles()
53 {
54 if( mDataSpace >= 0 )
55 {
56 H5Sclose( mDataSpace );
57 }
58 if( mDataType >= 0 )
59 {
60 H5Tclose( mDataType );
61 }
62 if( mDataSet >= 0 )
63 {
64 H5Dclose( mDataSet );
65 }
66 }
67 };
68#endif
69
70//------------------------------------------------------------------------------
71
76 inline bool
77 dataset_exists( hid_t aLoc, const std::string & aLabel )
78 {
79#ifdef BELFEM_HDF5
80 hid_t tDataSet = 0;
81 return H5Lexists( aLoc, aLabel.c_str(), tDataSet );
82#else
83 return false;
84#endif
85 }
86
87//------------------------------------------------------------------------------
88
93 inline bool
94 group_exists( hid_t aLoc, const std::string & aLabel )
95 {
96#ifdef BELFEM_HDF5
97 hid_t tGroup = 0;
98 return H5Lexists( aLoc, aLabel.c_str(), tGroup );
99#else
100 return false;
101#endif
102 }
103
104//------------------------------------------------------------------------------
105
106// The whole function is guarded, not just its body: its SIGNATURE names
107// H5L_info2_t, which hdf5_types.hpp does not stub. With the body alone guarded
108// this header stopped compiling under -DUSE_HDF5=OFF, and since cl_HDF5.hpp
109// includes it and src/io always compiles cl_HDF5.cpp, that broke the whole
110// tree rather than only the HDF5 callers
111#ifdef BELFEM_HDF5
112
113// collect_names() and get_groups() below are written against the 1.12 link and
114// object interfaces ( H5L_info2_t, H5O_info2_t, H5Literate2,
115// H5Oget_info_by_name3 ). belfem_find_package carries no version test, so the
116// requirement is stated here, where it is created -- and this header is
117// included across the whole tree, so on an older HDF5 the failure would
118// otherwise be a wall of template errors in every module rather than one line
119#if ! H5_VERSION_GE( 1, 12, 0 )
120#error "BELFEM requires HDF5 1.12 or newer ( hdf5_tools.hpp uses H5Literate2 and H5Oget_info_by_name3 )."
121#endif
122
123 inline herr_t
124 collect_names(
125 hid_t aLoc,
126 const char * aLabel,
127 const H5L_info2_t * aInfo,
128 void * aData )
129 {
130 auto * tLabels = static_cast<std::vector<std::string> *>( aData );
131
132 // GROUPS only. H5Literate2 visits every link at the location,
133 // datasets and named datatypes included, and a caller that opens
134 // each returned name as a group fails on the first one that is not.
135 // A soft or external link is skipped as well rather than followed:
136 // resolving it can leave the location, which is not what listing a
137 // location means
138 if( aInfo != nullptr && aInfo->type != H5L_TYPE_HARD )
139 {
140 return 0;
141 }
142
143 H5O_info2_t tInfo ;
144
145 // a failed query is an ERROR, not an entry to skip. Returning 0
146 // here would let a permission failure or a corrupt object produce a
147 // short list that the caller cannot tell from a complete one. The
148 // callback contract is: negative aborts the iteration and becomes
149 // H5Literate2's return value, which get_groups() checks
150 if( H5Oget_info_by_name3( aLoc, aLabel, & tInfo,
151 H5O_INFO_BASIC, H5P_DEFAULT ) < 0 )
152 {
153 return -1;
154 }
155
156 // not a group is not an error -- it is the thing this filter exists
157 // to drop, so the iteration continues
158 if( tInfo.type != H5O_TYPE_GROUP )
159 {
160 return 0;
161 }
162
163 tLabels->emplace_back( aLabel );
164
165 return 0;
166 }
167
168#endif
169
173 inline Cell< std::string >
175 {
176#ifdef BELFEM_HDF5
177 Cell< std::string > tGroups ;
178
179 hsize_t tIndex = 0 ;
180
181 // H5_ITER_INC, not H5_ITER_NATIVE : native order is documented as
182 // whatever the library finds fastest, and callers that treat the
183 // first entry as a reference ( db2exo picks the grid of the first
184 // table it sees ) would then depend on it
185 const herr_t tStatus = H5Literate2(
186 aLoc,
187 H5_INDEX_NAME,
188 H5_ITER_INC,
189 & tIndex,
190 collect_names,
191 & tGroups.vector_data() );
192
193 // runs once per file, so the always-active tier is affordable and
194 // the message survives a release build. Silently returning a short
195 // list here would be indistinguishable from a location that really
196 // holds fewer groups
197 BELFEM_ERROR( tStatus >= 0,
198 "H5Literate2 failed while listing the groups of an HDF5 location." );
199
200 return tGroups ;
201
202#else
203 return {};
204#endif
205 }
206
207//------------------------------------------------------------------------------
208
213 template < typename T >
214 bool
216 {
217#ifdef BELFEM_HDF5
218 return H5Tget_size( datatype<T>() ) == sizeof( T );
219#else
220 return false;
221#endif
222 }
223
224//------------------------------------------------------------------------------
225
241 template < typename T >
242 void
243 check_read_datatype( const hid_t aFileType, const std::string & aLabel )
244 {
245#ifdef BELFEM_HDF5
246 BELFEM_ERROR( H5Tget_class( aFileType ) == H5Tget_class( datatype<T>() ),
247 "datatype class mismatch reading '%s': the file holds class %i, but %s is class %i.\n"
248 "HDF5 can convert between widths, not between classes - this file does not hold what the reader expects.",
249 aLabel.c_str(),
250 ( int ) H5Tget_class( aFileType ),
251 datatype_string<T>().c_str(),
252 ( int ) H5Tget_class( datatype<T>() ) );
253#endif
254 }
255
256//------------------------------------------------------------------------------
257
267 template < typename T >
268 void
270 hid_t & aLoc,
271 const std::string & aLabel,
272 const T & aValue,
273 herr_t & aStatus
274 )
275 {
276#ifdef BELFEM_HDF5
277 BELFEM_ERROR( ! hdf5::dataset_exists( aLoc, aLabel ),
278 "Dataset %s of type %s does already exist.",
279 aLabel.c_str(),
280 datatype_string<T>().c_str() );
281
283 "Error in datatype size of type %s.",
284 datatype_string<T>().c_str() );
285
286 // FILE type: fixed width and little endian, so the on-disk
287 // layout does not depend on this build's native type widths
288 hid_t tDataType = H5Tcopy( filetype<T>() );
289
290 hsize_t tDims[ 1 ] = { 1 };
291
292 hid_t tDataSpace
293 = H5Screate_simple( 1, tDims, nullptr );
294
295 hid_t tDataSet = H5Dcreate(
296 aLoc,
297 aLabel.c_str(),
298 tDataType,
299 tDataSpace,
300 H5P_DEFAULT,
301 H5P_DEFAULT,
302 H5P_DEFAULT );
303
304 aStatus = H5Dwrite(
305 tDataSet,
306 datatype< T >(), // MEMORY type: native, not the file type
307 H5S_ALL,
308 H5S_ALL,
309 H5P_DEFAULT,
310 & aValue );
311
312 H5Sclose( tDataSpace );
313 H5Tclose( tDataType );
314 H5Dclose( tDataSet );
315
316 BELFEM_ERROR( aStatus >= 0,
317 "Something went wrong while trying to store scalar %s of type %s",
318 aLabel.c_str(),
319 datatype_string<T>().c_str());
320#endif
321 }
322//------------------------------------------------------------------------------
323
324 template < typename T >
325 void
327 hid_t & aLoc,
328 const std::string & aLabel,
329 T & aValue,
330 herr_t & aStatus
331 )
332 {
333#ifdef BELFEM_HDF5
334 BELFEM_ERROR( hdf5::dataset_exists( aLoc, aLabel ),
335 "Dataset %s of type %s does not exist.",
336 aLabel.c_str(),
337 datatype_string<T>().c_str() );
338
340 "Error in datatype size of type %s.",
341 datatype_string<T>().c_str() );
342
343 DatasetHandles tHandles ;
344
345 tHandles.mDataSet = H5Dopen1( aLoc, aLabel.c_str() );
346
347 tHandles.mDataType = H5Dget_type( tHandles.mDataSet );
348
349 // the file type must be convertible into T; the read
350 // below then uses datatype<T>() so HDF5 does the conversion
351 check_read_datatype< T >( tHandles.mDataType, aLabel );
352
353 tHandles.mDataSpace = H5Dget_space( tHandles.mDataSet );
354
355 aStatus = H5Dread(
356 tHandles.mDataSet,
357 datatype< T >(), // MEMORY type: let HDF5 convert
358 H5S_ALL,
359 H5S_ALL,
360 H5P_DEFAULT,
361 &aValue );
362
363 BELFEM_ERROR( aStatus >= 0,
364 "Something went wrong while trying to load scalar %s of type %s",
365 aLabel.c_str(),
366 datatype_string<T>().c_str() );
367
368#endif
369 }
370
371//------------------------------------------------------------------------------
372
373 void
375 hid_t & aLoc,
376 const std::string & aLabel,
377 const bool & aValue,
378 herr_t & aStatus );
379
380//------------------------------------------------------------------------------
381
382 void
384 hid_t & aLoc,
385 const std::string & aLabel,
386 bool & aValue,
387 herr_t & aStatus );
388
389//------------------------------------------------------------------------------
390
391 void
393 hid_t & aLoc,
394 const std::string & aLabel,
395 const std::string & aValue,
396 herr_t & aStatus );
397
398//------------------------------------------------------------------------------
399
400 void
402 hid_t & aLoc,
403 const std::string & aLabel,
404 std::string & aValue,
405 herr_t & aStatus );
406
407//------------------------------------------------------------------------------
408 template < typename T >
409 void
411 hid_t & aLoc,
412 const std::string & aLabel,
413 const T * aData,
414 const hsize_t & aLength,
415 herr_t & aStatus )
416 {
417#ifdef BELFEM_HDF5
418 BELFEM_ERROR( ! hdf5::dataset_exists( aLoc, aLabel ),
419 "Dataset %s of type Vector<%s> does already exist.",
420 aLabel.c_str(),
421 datatype_string<T>().c_str() );
422
424 "Error in datatype size of type %s.",
425 datatype_string<T>().c_str() );
426
427 // FILE type: fixed width and little endian, so the on-disk
428 // layout does not depend on this build's native type widths
429 hid_t tDataType = H5Tcopy( filetype<T>() );
430
431 hsize_t tDims[ 1 ];
432 tDims[ 0 ] = aLength;
433
434 hid_t tDataSpace
435 = H5Screate_simple( 1, tDims, nullptr );
436
437 hid_t tDataSet = H5Dcreate(
438 aLoc,
439 aLabel.c_str(),
440 tDataType,
441 tDataSpace,
442 H5P_DEFAULT,
443 H5P_DEFAULT,
444 H5P_DEFAULT );
445
446 // an empty object skips the write, so its status cannot report a
447 // failed create; the open handles are closed before the error
448 if ( tDataSet < 0 )
449 {
450 H5Sclose( tDataSpace );
451 H5Tclose( tDataType );
452 BELFEM_ERROR( false, "Could not create dataset %s", aLabel.c_str() );
453 }
454
455 aStatus = 0 ;
456
457 if( aLength > 0 )
458 {
459 aStatus = H5Dwrite(
460 tDataSet,
461 datatype< T >(), // MEMORY type: native, not the file type
462 H5S_ALL,
463 H5S_ALL,
464 H5P_DEFAULT,
465 &aData[ 0 ] );
466 }
467
468 H5Sclose( tDataSpace );
469 H5Tclose( tDataType );
470 H5Dclose( tDataSet );
471
472 BELFEM_ERROR( aStatus >= 0,
473 "Something went wrong while trying to store vector %s of type %s",
474 aLabel.c_str(),
475 datatype_string<T>().c_str() );
476#endif
477 }
478
479//------------------------------------------------------------------------------
480
481 hsize_t
483 hid_t & aLoc,
484 const std::string & aLabel );
485
486//------------------------------------------------------------------------------
487
488 template < typename T >
489 void
491 hid_t & aLoc,
492 const std::string & aLabel,
493 T * aData,
494 const hsize_t aLength,
495 herr_t & aStatus )
496 {
497#ifdef BELFEM_HDF5
498
499 BELFEM_ERROR( hdf5::dataset_exists( aLoc, aLabel ),
500 "Dataset %s of type Vector<%s> does not exist.",
501 aLabel.c_str(),
502 datatype_string<T>().c_str() );
503
505 "Error in datatype size of type %s.",
506 datatype_string<T>().c_str() );
507
508 DatasetHandles tHandles ;
509
510 tHandles.mDataSet = H5Dopen1( aLoc, aLabel.c_str() );
511
512 tHandles.mDataType = H5Dget_type( tHandles.mDataSet );
513
514 // the file type must be convertible into T; the read
515 // below then uses datatype<T>() so HDF5 does the conversion
516 check_read_datatype< T >( tHandles.mDataType, aLabel );
517
518 tHandles.mDataSpace = H5Dget_space( tHandles.mDataSet );
519
520 hsize_t tDims[ 1 ];
521
522 // the extent buffer holds one entry; a dataset of another rank is
523 // refused before the extents are read into it
524 const int tRank = H5Sget_simple_extent_ndims( tHandles.mDataSpace );
525
526 BELFEM_ERROR( tRank == 1, "Dataset %s is not a 1-D array (rank %i)",
527 aLabel.c_str(), tRank );
528
529 aStatus = H5Sget_simple_extent_dims( tHandles.mDataSpace, tDims, nullptr );
530
531 BELFEM_ERROR( tDims[ 0 ] == aLength, "Lengths do not match: is %lu, expect %lu.",
532 ( long unsigned int ) tDims[ 0 ], ( long unsigned int ) aLength );
533
534 if( aLength > 0 )
535 {
536 aStatus = H5Dread(
537 tHandles.mDataSet,
538 datatype< T >(), // MEMORY type: let HDF5 convert
539 H5S_ALL,
540 H5S_ALL,
541 H5P_DEFAULT,
542 &aData[ 0 ] );
543 }
544 else
545 {
546 aStatus = 0;
547 }
548
549 BELFEM_ERROR( aStatus >= 0,
550 "Something went wrong while trying to load vector %s of type %s",
551 aLabel.c_str(),
552 datatype_string<T>().c_str() );
553#endif
554 }
555//------------------------------------------------------------------------------
556
557 template < typename T >
558 void
560 hid_t & aLoc,
561 const std::string & aLabel,
562 const Vector< T > & aVector,
563 herr_t & aStatus )
564 {
565#ifdef BELFEM_HDF5
566
567 BELFEM_ERROR( ! hdf5::dataset_exists( aLoc, aLabel ),
568 "Dataset %s of type Vector<%s> does already exist.",
569 aLabel.c_str(),
570 datatype_string<T>().c_str() );
571
573 "Error in datatype size of type %s.",
574 datatype_string<T>().c_str() );
575
576 // FILE type: fixed width and little endian, so the on-disk
577 // layout does not depend on this build's native type widths
578 hid_t tDataType = H5Tcopy( filetype<T>() );
579 hid_t tDataSet = 0;
580
581 hsize_t tLength = aVector.length();
582 hsize_t tDims[ 1 ];
583 tDims[ 0 ] = tLength;
584
585 hid_t tDataSpace
586 = H5Screate_simple( 1, tDims, nullptr );
587
588 tDataSet = H5Dcreate(
589 aLoc,
590 aLabel.c_str(),
591 tDataType,
592 tDataSpace,
593 H5P_DEFAULT,
594 H5P_DEFAULT,
595 H5P_DEFAULT );
596
597 // an empty object skips the write, so its status cannot report a
598 // failed create; the open handles are closed before the error
599 if ( tDataSet < 0 )
600 {
601 H5Sclose( tDataSpace );
602 H5Tclose( tDataType );
603 BELFEM_ERROR( false, "Could not create dataset %s", aLabel.c_str() );
604 }
605
606 aStatus = 0 ;
607
608 if( tLength > 0 )
609 {
610 T* tData = ( T* ) malloc( tLength * sizeof( T ) );
611
612 std::memcpy(
613 tData,
614 aVector.data(),
615 tLength * sizeof( T ) );
616
617 aStatus = H5Dwrite(
618 tDataSet,
619 datatype< T >(), // MEMORY type: native, not the file type
620 H5S_ALL,
621 H5S_ALL,
622 H5P_DEFAULT,
623 & tData[ 0 ]);
624
625 free( tData );
626 }
627
628 H5Sclose( tDataSpace );
629 H5Tclose( tDataType );
630 H5Dclose( tDataSet );
631
632 BELFEM_ERROR( aStatus >= 0,
633 "Something went wrong while trying to store vector %s of type %s",
634 aLabel.c_str(),
635 datatype_string<T>().c_str() );
636#endif
637 }
638
639//------------------------------------------------------------------------------
640
641 template < typename T >
642 void
644 hid_t & aLoc,
645 const std::string & aLabel,
646 Vector< T > & aVector,
647 herr_t & aStatus )
648 {
649#ifdef BELFEM_HDF5
650 BELFEM_ERROR( hdf5::dataset_exists( aLoc, aLabel ),
651 "Dataset %s of type Vector<%s> does not exist.",
652 aLabel.c_str(),
653 datatype_string<T>().c_str() );
654
656 "Error in datatype size of type %s.",
657 datatype_string<T>().c_str() );
658
659 DatasetHandles tHandles ;
660
661 tHandles.mDataSet = H5Dopen1( aLoc, aLabel.c_str() );
662
663 tHandles.mDataType = H5Dget_type( tHandles.mDataSet );
664
665 // the file type must be convertible into T; the read
666 // below then uses datatype<T>() so HDF5 does the conversion
667 check_read_datatype< T >( tHandles.mDataType, aLabel );
668
669 tHandles.mDataSpace = H5Dget_space( tHandles.mDataSet );
670
671 hsize_t tDims[ 1 ];
672
673 // the extent buffer holds one entry; a dataset of another rank is
674 // refused before the extents are read into it
675 const int tRank = H5Sget_simple_extent_ndims( tHandles.mDataSpace );
676
677 BELFEM_ERROR( tRank == 1, "Dataset %s is not a 1-D array (rank %i)",
678 aLabel.c_str(), tRank );
679
680 aStatus = H5Sget_simple_extent_dims( tHandles.mDataSpace, tDims, nullptr );
681
682 hsize_t tLength = tDims[ 0 ];
683
684 aVector.set_size( tLength );
685
686 if( tLength > 0 )
687 {
688 T* tData = ( T* ) malloc( tLength * sizeof( T ) );
689
690 aStatus = H5Dread(
691 tHandles.mDataSet,
692 datatype< T >(), // MEMORY type: let HDF5 convert
693 H5S_ALL,
694 H5S_ALL,
695 H5P_DEFAULT,
696 &tData[ 0 ] );
697
698 std::memcpy(
699 aVector.data(),
700 tData,
701 tLength * sizeof( T ) );
702
703 free( tData );
704 }
705 else
706 {
707 aStatus = 0;
708 }
709
710 BELFEM_ERROR( aStatus >= 0,
711 "Something went wrong while trying to load vector %s of type %s",
712 aLabel.c_str(),
713 datatype_string<T>().c_str() );
714#endif
715 }
716//------------------------------------------------------------------------------
717
718 template < typename T >
719 void
721 hid_t & aLoc,
722 const std::string & aLabel,
723 const Matrix< T > & aMatrix,
724 herr_t & aStatus,
725 const bool aTranspose = false )
726 {
727#ifdef BELFEM_HDF5
728 BELFEM_ERROR( ! hdf5::dataset_exists( aLoc, aLabel ),
729 "Dataset %s of type Matrix<%s> does already exist.",
730 aLabel.c_str(),
731 datatype_string<T>().c_str() );
732
734 "Error in datatype size of type %s.",
735 datatype_string<T>().c_str() );
736
737 // FILE type: fixed width and little endian, so the on-disk
738 // layout does not depend on this build's native type widths
739 hid_t tDataType = H5Tcopy( filetype<T>() );
740 hid_t tDataSet = 0;
741
742 hsize_t tDims[ 2 ];
743
744 if ( aTranspose )
745 {
746 tDims[ 0 ] = aMatrix.n_cols();
747 tDims[ 1 ] = aMatrix.n_rows();
748
749 }
750 else
751 {
752 tDims[ 0 ] = aMatrix.n_rows();
753 tDims[ 1 ] = aMatrix.n_cols();
754 }
755
756 hid_t tDataSpace
757 = H5Screate_simple( 2, tDims, nullptr );
758
759 tDataSet = H5Dcreate(
760 aLoc,
761 aLabel.c_str(),
762 tDataType,
763 tDataSpace,
764 H5P_DEFAULT,
765 H5P_DEFAULT,
766 H5P_DEFAULT );
767
768 // an empty object skips the write, so its status cannot report a
769 // failed create; the open handles are closed before the error
770 if ( tDataSet < 0 )
771 {
772 H5Sclose( tDataSpace );
773 H5Tclose( tDataType );
774 BELFEM_ERROR( false, "Could not create dataset %s", aLabel.c_str() );
775 }
776
777 aStatus = 0 ;
778
779 if( tDims[ 0 ]*tDims[ 1 ] > 0 )
780 {
781 T** tData = ( T** ) malloc( tDims[ 0 ] * sizeof( T * ) );
782 tData[ 0 ] = ( T* ) malloc( tDims[ 0 ]*tDims[ 1 ] * sizeof( T ) );
783
784 for( hsize_t i=0; i<tDims[ 0 ]; ++i )
785 {
786 tData[ i ] = tData[ 0 ]+ i*tDims[ 1 ];
787 }
788
789 if ( aTranspose )
790 {
791 for ( hsize_t i = 0; i < tDims[ 0 ]; ++i )
792 {
793 for ( hsize_t j = 0; j < tDims[ 1 ]; ++j )
794 {
795 tData[ i ][ j ] = aMatrix( j, i );
796 }
797 }
798 }
799 else
800 {
801 for ( hsize_t i = 0; i < tDims[ 0 ]; ++i )
802 {
803 for ( hsize_t j = 0; j < tDims[ 1 ]; ++j )
804 {
805 tData[ i ][ j ] = aMatrix( i, j );
806 }
807 }
808 }
809 aStatus = H5Dwrite(
810 tDataSet,
811 datatype< T >(), // MEMORY type: native, not the file type
812 H5S_ALL,
813 H5S_ALL,
814 H5P_DEFAULT,
815 & tData[ 0 ][ 0 ]);
816
817 free( tData[ 0 ] );
818 free( tData );
819 }
820
821 H5Sclose( tDataSpace );
822 H5Tclose( tDataType );
823 H5Dclose( tDataSet );
824
825 BELFEM_ERROR( aStatus >= 0,
826 "Something went wrong while trying to store matrix %s of type %s",
827 aLabel.c_str(),
828 datatype_string<T>().c_str() );
829#endif
830 }
831
832//------------------------------------------------------------------------------
833
834 template < typename T >
835 void
837 hid_t & aLoc,
838 const std::string & aLabel,
839 Matrix< T > & aMatrix,
840 herr_t & aStatus,
841 const bool aTranspose = false )
842 {
843#ifdef BELFEM_HDF5
844
845 BELFEM_ERROR( hdf5::dataset_exists( aLoc, aLabel ),
846 "Dataset %s of type Matrix<%s> does not exist.",
847 aLabel.c_str(),
848 datatype_string<T>().c_str() );
849
851 "Error in datatype size of type %s.",
852 datatype_string<T>().c_str() );
853
854 DatasetHandles tHandles ;
855
856 tHandles.mDataSet = H5Dopen1( aLoc, aLabel.c_str() );
857
858 tHandles.mDataType = H5Dget_type( tHandles.mDataSet );
859
860 // the file type must be convertible into T; the read
861 // below then uses datatype<T>() so HDF5 does the conversion
862 check_read_datatype< T >( tHandles.mDataType, aLabel );
863
864 tHandles.mDataSpace = H5Dget_space( tHandles.mDataSet );
865
866 hsize_t tDims[ 2 ];
867
868 aStatus = H5Sget_simple_extent_dims( tHandles.mDataSpace, tDims, nullptr );
869
870 // allocate memory for output (transpose swaps the on-disk dimensions)
871 if ( aTranspose )
872 {
873 aMatrix.set_size( tDims[ 1 ], tDims[ 0 ] );
874 }
875 else
876 {
877 aMatrix.set_size( tDims[ 0 ], tDims[ 1 ] );
878 }
879
880 if( tDims[ 0 ]*tDims[ 1 ] > 0 )
881 {
882 T** tData = ( T** )
883 malloc( tDims[ 0 ]*sizeof( T* ) );
884
885 tData[ 0 ] = ( T* )
886 malloc( tDims[ 0 ]* tDims[ 1 ] * sizeof( T ) );
887
888 for( hsize_t i=1; i<tDims[ 0 ]; ++i )
889 {
890 tData[ i ] = tData[ 0 ]+ i*tDims[ 1 ];
891 }
892
893 aStatus = H5Dread(
894 tHandles.mDataSet,
895 datatype< T >(), // MEMORY type: let HDF5 convert
896 H5S_ALL,
897 H5S_ALL,
898 H5P_DEFAULT,
899 &tData[ 0 ][ 0 ] );
900
901 if ( aTranspose )
902 {
903 // on-disk (tDims[0] x tDims[1]) -> memory (tDims[1] x tDims[0])
904 for ( hsize_t i = 0; i < tDims[ 0 ]; ++i )
905 {
906 for ( hsize_t j = 0; j < tDims[ 1 ]; ++j )
907 {
908 aMatrix( j, i ) = tData[ i ][ j ];
909 }
910 }
911 }
912 else
913 {
914 for ( hsize_t j = 0; j < tDims[ 1 ]; ++j )
915 {
916 for ( hsize_t i = 0; i < tDims[ 0 ]; ++i )
917 {
918 aMatrix( i, j ) = tData[ i ][ j ];
919 }
920 }
921 }
922 free( tData[ 0 ] );
923 free( tData );
924 }
925 else if( aStatus == 2 )
926 {
927 aStatus = 0;
928 }
929
930 BELFEM_ERROR( aStatus >= 0,
931 "Something went wrong while trying to load matrix %s of type %s",
932 aLabel.c_str(),
933 datatype_string<T>().c_str() );
934#endif
935 }
936
937 inline void
939 const std::string & aLabel,
940 const Cell< string > & aCell,
941 herr_t & aStatus )
942 {
943#ifdef BELFEM_HDF5
944
945 DatasetHandles tHandles ;
946
947 hsize_t tNumStrings = aCell.size();
948 hsize_t tDim[ 1 ] = { tNumStrings };
949 tHandles.mDataSpace = H5Screate_simple( 1, tDim, NULL );
950
951 tHandles.mDataType = H5Tcopy( H5T_C_S1 );
952 H5Tset_size( tHandles.mDataType, H5T_VARIABLE );
953
954 tHandles.mDataSet = H5Dcreate2(
955 aLoc,
956 aLabel.c_str(),
957 tHandles.mDataType,
958 tHandles.mDataSpace,
959 H5P_DEFAULT,
960 H5P_DEFAULT,
961 H5P_DEFAULT );
962
963 BELFEM_ERROR( tHandles.mDataSet > -1, "Error creating dataset" );
964
965 Cell< const char * > tBuffer( tNumStrings, nullptr );
966 for ( hsize_t i=0; i<tNumStrings; ++i )
967 {
968 tBuffer( i ) = aCell( i ).c_str();
969 }
970
971 aStatus = H5Dwrite(
972 tHandles.mDataSet,
973 tHandles.mDataType,
974 H5S_ALL,
975 H5S_ALL,
976 H5P_DEFAULT,
977 tBuffer.data() );
978
979 BELFEM_ERROR( aStatus ==0, "Error writing data" );
980#endif
981 }
982
983 inline void
985 const std::string & aLabel,
986 Cell< string > & aCell,
987 herr_t & aStatus )
988 {
989#ifdef BELFEM_HDF5
990 aCell.clear();
991
992 BELFEM_ERROR( hdf5::dataset_exists( aLoc, aLabel ),
993 "Dataset %s does not exist at expected location.", aLabel.c_str() );
994
995 DatasetHandles tHandles ;
996
997 tHandles.mDataSet = H5Dopen1( aLoc, aLabel.c_str() );
998
999 tHandles.mDataSpace = H5Dget_space( tHandles.mDataSet );
1000
1001 hsize_t tDim[ 1 ] ;
1002
1003 // the extent buffer holds one entry; a dataset of another rank is
1004 // refused before the extents are read into it
1005 const int tRank = H5Sget_simple_extent_ndims( tHandles.mDataSpace );
1006
1007 BELFEM_ERROR( tRank == 1, "Dataset %s is not a 1-D array (rank %i)",
1008 aLabel.c_str(), tRank );
1009
1010 BELFEM_ERROR( H5Sget_simple_extent_dims( tHandles.mDataSpace, tDim, nullptr ) > -1 ,
1011 "Error getting dataspace dimensions" );
1012
1013 hsize_t tNumStrings = tDim[ 0 ];
1014
1015 // This must match the datatype used in writing -- INCLUDING the
1016 // character set: H5T_C_S1 defaults to ASCII, but h5py writes
1017 // vlen strings as UTF-8, and HDF5 refuses the UTF-8 -> ASCII
1018 // conversion path, failing the H5Dread below with no better
1019 // diagnostic than a nonzero status. Copy the cset from the
1020 // dataset itself so BELFEM-written ASCII files behave as before
1021 // and Python-written UTF-8 files become readable.
1022 tHandles.mDataType = H5Tcopy( H5T_C_S1 );
1023 H5Tset_size( tHandles.mDataType, H5T_VARIABLE );
1024
1025 hid_t tFileType = H5Dget_type( tHandles.mDataSet );
1026 H5Tset_cset( tHandles.mDataType, H5Tget_cset( tFileType ) );
1027 H5Tclose( tFileType );
1028
1029 // HDF5 allocates the strings during the read. The null slots let
1030 // the reclaim below free exactly what a failed read left allocated,
1031 // so it runs on both paths, before the refusal and before the owner
1032 // closes the type and the dataspace it needs. An empty Cell may
1033 // hand out a null data(), which H5Dread accepts at zero elements
1034 // and H5Dvlen_reclaim refuses, hence the size guard.
1035 Cell< char * > tBuffer( tNumStrings, nullptr );
1036
1037 const herr_t tReadStatus = H5Dread( tHandles.mDataSet, tHandles.mDataType,
1038 H5S_ALL, H5S_ALL, H5P_DEFAULT, tBuffer.data() );
1039
1040 if( tReadStatus == 0 )
1041 {
1042 aCell.set_size( tNumStrings, "" );
1043
1044 for ( hsize_t i=0; i<tNumStrings; ++i )
1045 {
1046 aCell( i ) = std::string( tBuffer( i ) );
1047 }
1048 }
1049
1050 if( tNumStrings > 0 )
1051 {
1052 H5Dvlen_reclaim( tHandles.mDataType, tHandles.mDataSpace, H5P_DEFAULT, tBuffer.data() );
1053 }
1054
1055 BELFEM_ERROR( tReadStatus == 0, "Failed to read strings from file." );
1056#endif
1057 }
1058//------------------------------------------------------------------------------
1059
1060 inline hid_t
1061 open_group( const std::string & aLabel, hid_t aParent )
1062 {
1063#ifdef BELFEM_HDF5
1064 if ( hdf5::group_exists( aParent, aLabel ) )
1065 {
1066
1067 return H5Gopen2(
1068 aParent,
1069 aLabel.c_str(),
1070 H5P_DEFAULT );
1071 }
1072 else
1073 {
1074 BELFEM_ERROR( false,
1075 "Group %s does not exist.",
1076 aLabel.c_str() );
1077
1078 return -1;
1079 }
1080#else
1081 return 0 ;
1082#endif
1083 }
1084
1085//------------------------------------------------------------------------------
1086
1087 inline herr_t
1089 {
1090#ifdef BELFEM_HDF5
1091 return H5Gclose( aGroup );
1092#else
1093 return 0 ;
1094#endif
1095 }
1096
1097//------------------------------------------------------------------------------
1098
1099 string
1100 create_tree( const Cell< string > & aTree, const string & aLabel );
1101
1102//------------------------------------------------------------------------------
1103
1104//------------------------------------------------------------------------------
1105 } /* namespace hdf5 */
1106} /* namespace belfem */
1107
1108#endif //BELFEM_HDF5_TOOLS_HPP
#define BELFEM_ERROR(aCheck,...)
Definition assert.hpp:264
#define BELFEM_ASSERT(aCheck,...)
Definition assert.hpp:244
A bounds-checked wrapper around std::vector.
Definition cl_Cell.hpp:45
void set_size(const size_t aSize)
New elements are value-initialized ( zero for arithmetic T, nullptr for pointers ).
Definition cl_Cell.hpp:199
size_t size() const
Definition cl_Cell.hpp:189
void clear()
Empties the Cell.
Definition cl_Cell.hpp:249
std::vector< T > & vector_data()
The underlying vector.
Definition cl_Cell.hpp:146
T * data()
Returns a borrowed pointer into contiguous storage, possibly nullptr when the Cell is empty ( test si...
Definition cl_Cell.hpp:129
Dense column-major matrix.
Definition cl_BZ_Matrix.hpp:28
void set_size(const size_t aNumRows, const size_t aNumCols)
Definition cl_AR_Matrix.hpp:168
size_t n_rows() const
Definition cl_AR_Matrix.hpp:187
size_t n_cols() const
Definition cl_AR_Matrix.hpp:195
Column vector.
Definition cl_BZ_Vector.hpp:42
T * data()
Returns a borrowed raw buffer under the layout contract stated in cl_Vector.hpp; may be nullptr when ...
Definition cl_AR_Vector.hpp:261
void set_size(const size_t aNumRows)
change the size of the vector
Definition cl_AR_Vector.hpp:313
size_t length() const
get the length of the vector
Definition cl_AR_Vector.hpp:333
Definition cl_HDF5_Dataset.hpp:21
void save_vector_to_file(hid_t &aLoc, const std::string &aLabel, const Vector< T > &aVector, herr_t &aStatus)
Definition hdf5_tools.hpp:559
bool group_exists(hid_t aLoc, const std::string &aLabel)
test if a group exists ( tests for a link of that name; the link type is not checked )
Definition hdf5_tools.hpp:94
void save_string_to_file(hid_t &aFileID, const std::string &aLabel, const std::string &aValue, herr_t &aStatus)
Definition hdf5_tools.cpp:121
void load_scalar_from_file(hid_t &aLoc, const std::string &aLabel, T &aValue, herr_t &aStatus)
Definition hdf5_tools.hpp:326
void save_array_to_file(hid_t &aLoc, const std::string &aLabel, const T *aData, const hsize_t &aLength, herr_t &aStatus)
Definition hdf5_tools.hpp:410
void load_bool_from_file(hid_t &aFileID, const std::string &aLabel, bool &aValue, herr_t &aStatus)
Definition hdf5_tools.cpp:75
void save_strings_to_file(hid_t &aLoc, const std::string &aLabel, const Cell< string > &aCell, herr_t &aStatus)
Definition hdf5_tools.hpp:938
void save_scalar_to_file(hid_t &aLoc, const std::string &aLabel, const T &aValue, herr_t &aStatus)
saves a scalar value to a file file must be open
Definition hdf5_tools.hpp:269
hid_t open_group(const std::string &aLabel, hid_t aParent)
Definition hdf5_tools.hpp:1061
void load_strings_from_file(hid_t &aLoc, const std::string &aLabel, Cell< string > &aCell, herr_t &aStatus)
Definition hdf5_tools.hpp:984
void load_matrix_from_file(hid_t &aLoc, const std::string &aLabel, Matrix< T > &aMatrix, herr_t &aStatus, const bool aTranspose=false)
Definition hdf5_tools.hpp:836
void save_matrix_to_file(hid_t &aLoc, const std::string &aLabel, const Matrix< T > &aMatrix, herr_t &aStatus, const bool aTranspose=false)
Definition hdf5_tools.hpp:720
bool check_datatye_size()
this function returns true of both the HDF5 datatype and the passed datatype have the same size
Definition hdf5_tools.hpp:215
hid_t datatype()
Definition hdf5_types.hpp:36
Cell< std::string > get_groups(hid_t aLoc)
list groups that exist in location
Definition hdf5_tools.hpp:174
hid_t filetype()
Definition hdf5_types.hpp:56
hsize_t get_array_size(hid_t &aFileID, const std::string &aLabel)
Definition hdf5_tools.cpp:223
bool dataset_exists(hid_t aLoc, const std::string &aLabel)
test if a dataset exists ( tests for a link of that name; the link type is not checked )
Definition hdf5_tools.hpp:77
string create_tree(const Cell< string > &aTree, const string &aLabel)
Definition hdf5_tools.cpp:258
void load_vector_from_file(hid_t &aLoc, const std::string &aLabel, Vector< T > &aVector, herr_t &aStatus)
Definition hdf5_tools.hpp:643
void check_read_datatype(const hid_t aFileType, const std::string &aLabel)
Guard for every read: the FILE datatype must be convertible into T.
Definition hdf5_tools.hpp:243
void load_string_from_file(hid_t &aFileID, const std::string &aLabel, std::string &aValue, herr_t &aStatus)
Definition hdf5_tools.cpp:178
void load_array_from_file(hid_t &aLoc, const std::string &aLabel, T *aData, const hsize_t aLength, herr_t &aStatus)
Definition hdf5_tools.hpp:490
void save_bool_to_file(hid_t &aFileID, const std::string &aLabel, const bool &aValue, herr_t &aStatus)
Definition hdf5_tools.cpp:21
herr_t close_group(hid_t aGroup)
Definition hdf5_tools.hpp:1088
USER GUIDES:
Definition cl_Capacitor.cpp:16
std::string datatype_string()
Definition stringtools.hpp:64
int hsize_t
Definition hdf5_types.hpp:22
int hid_t
Definition hdf5_types.hpp:20
int herr_t
Definition hdf5_types.hpp:21