andres::graph
hdf5/grid-graph.hxx
1 #pragma once
2 #ifndef ANDRES_GRAPH_GRID_GRAPH_HDF5_HXX
3 #define ANDRES_GRAPH_GRID_GRAPH_HDF5_HXX
4 
5 #include <stdexcept>
6 #include <string>
7 #include <array>
8 #include <vector>
9 
10 #include "hdf5.hxx"
11 #include "../grid-graph.hxx"
12 
13 namespace andres {
14 namespace graph {
15 namespace hdf5 {
16 
17 template<>
18 template<unsigned char D, class VISITOR>
19 struct GraphTraitsHDF5<GridGraph<D, VISITOR> > {
20  static const int ID;
21 };
22 template<unsigned char D, class VISITOR>
23  const int GraphTraitsHDF5<GridGraph<D, VISITOR> >::ID = 10003;
24 
25 template<unsigned char D, class VISITOR>
26 void save(const hid_t, const std::string&, const GridGraph<D, VISITOR>&);
27 
28 template<unsigned char D, class VISITOR>
29 void load(const hid_t, const std::string&, GridGraph<D, VISITOR>&);
30 
31 template<unsigned char D, class VISITOR>
32 void
34  const hid_t parentHandle,
35  const std::string& graphName,
36  const GridGraph<D, VISITOR>& graph
37 ) {
38  HandleCheck<ANDRES_GRAPH_HDF5_DEBUG> handleCheck;
39  hid_t groupHandle = openGroup(parentHandle, graphName, true);
40 
41  std::string sError;
42  try {
43  save(groupHandle, "graph-type-id", GraphTraitsHDF5<GridGraph<D, VISITOR> >::ID);
44 
45  std::array<std::size_t, D> shape;
46  for(std::size_t i=0; i<D; ++i) {
47  shape[i] = graph.shape(i);
48  }
49  save(groupHandle, "shape", {D}, &shape[0]);
50  } catch(std::exception& e) {
51  sError = e.what();
52  }
53  closeGroup(groupHandle);
54  if(!sError.empty()) {
55  throw std::runtime_error("error saving grid graph: " + sError);
56  }
57 }
58 
59 template<unsigned char D, class VISITOR>
60 void
62  const hid_t parentHandle,
63  const std::string& graphName,
65 ) {
66  HandleCheck<ANDRES_GRAPH_HDF5_DEBUG> handleCheck;
67  hid_t groupHandle = openGroup(parentHandle, graphName);
68 
69  std::string sError;
70  try {
71  int id;
72  load(groupHandle, "graph-type-id", id);
73  if(id != GraphTraitsHDF5<GridGraph<D, VISITOR> >::ID) {
74  sError = "graph type id mismatch.";
75  goto cleanup;
76  }
77 
78  std::vector<std::size_t> nDims;
79  std::vector<std::size_t> shape;
80  load(groupHandle, "shape", nDims, shape);
81  if(nDims.size() != 1 || nDims[0] != D) {
82  sError = "shape mismatch.";
83  goto cleanup;
84  }
85 
87  std::copy(shape.begin(), shape.end(), vc.begin());
88  graph.assign(vc);
89  } catch(std::exception& e) {
90  sError = "failed to load grid graph: " + std::string(e.what());
91  goto cleanup;
92  }
93 
94 cleanup:
95  closeGroup(groupHandle);
96  if(!sError.empty()) {
97  throw std::runtime_error("error loading grid graph: " + sError);
98  }
99 }
100 
101 } //namespace hdf
102 } //namespace graph
103 } //namespace andres
104 
105 #endif // #ifndef ANDRES_GRAPH_GRID_GRAPH_HDF5_HXX