Debian Codegraph @

gavo/grammars/directhdf5.py

raw
1 """
2 Helpers for generating boosters for HDF5 data.
3
4 HDF5 is fairly complex, and directgrammar is too long as is. Also, I don't
5 want to require h5py as a fixed dependency of DaCHS; if it's not
6 there, you should still be able to use other sorts of direct grammars.
7
8 TODO: Most of the hdf interface functions return 0 on success, != on
9 failure; we'd like a macro to catch these.
10 """
11
12 #c Copyright 2008-2025, the GAVO project <[email protected]>
13 #c
14 #c This program is free software, covered by the GNU GPL. See the
15 #c COPYING file in the source distribution.
16
17
18 import h5py
19
20 from gavo import base
21 from gavo import utils
22
23 # See directgrammar.HDF5vaexCodeGenerator for how this import works
24 from gavo.grammars import directgrammar
25
26
27 class BaseHDF5CodeGenerator(directgrammar._NumpyMetaCodeGenerator):
28 """An abstract base for generating boosters for various sorts of
29 HDF5 files.
30
31 Our strategy when parsing from them is to read CHUNK_SIZE items
32 at a time into the corresponding arrays, and then iterating
33 over these chunks, building the records.
34
35 The difference between the various flavours is where the column
36 metadata is taken from and where the data is then pulled from.
37 """
38 _h5typemap = {
39 "byte": "H5T_NATIVE_CHAR",
40 "int8": "H5T_NATIVE_CHAR",
41 "ubyte": "H5T_NATIVE_UCHAR",
42 "uint8": "H5T_NATIVE_UCHAR",
43 "short": "H5T_NATIVE_SHORT",
44 "int16": "H5T_NATIVE_SHORT",
45 "ushort": "H5T_NATIVE_USHORT",
46 "uint16": "H5T_NATIVE_USHORT",
47 "cint": "H5T_NATIVE_INT",
48 "int32": "H5T_NATIVE_INT",
49 "uint": "H5T_NATIVE_UINT",
50 "uintc": "H5T_NATIVE_UINT",
51 "int64": "H5T_NATIVE_LLONG",
52 "uint64": "H5T_NATIVE_ULLONG",
53 "ulonglong": "H5T_NATIVE_ULLONG",
54 "single": "H5T_NATIVE_FLOAT",
55 "float16": "H5T_NATIVE_FLOAT",
56 "float32": "H5T_NATIVE_FLOAT",
57 "double": "H5T_NATIVE_DOUBLE",
58 "float64": "H5T_NATIVE_DOUBLE",
59 }
60
61 def __init__(self, grammar, tableDef):
62 directgrammar._NumpyMetaCodeGenerator.__init__(self, grammar, tableDef)
63
64 if self.grammar.parent.sources is None:
65 raise base.StructureError("Cannot make HDF5 vaex booster without"
66 " a sources element on the embedding data.")
67 try:
68 self.sampleSource = next(self.grammar.parent.sources.iterSources())
69 hdf = h5py.File(self.sampleSource)
70 except StopIteration:
71 raise base.StructureError("Building an HDF5 booster requires"
72 " at least one matching source.")
73
74 cols = self.getColumns(hdf)
75
76 self.inputColumns = []
77 for name, numpyType in cols:
78 if numpyType.ndim!=0:
79 raise NotImplementedError("Cannot handle arrays in vaex"
80 " HDF5 yet. Please contact the authors.")
81 try:
82 cType = self.numpyTypes[str(numpyType)]
83 except KeyError:
84 raise NotImplementedError("Cannot handle the numpy type"
85 f" {numpyType} yet. Please contact the authors.")
86 self.inputColumns.append((name, numpyType, cType))
87 hdf.close()
88
89 nameMap = {}
90 if self.grammar.mapKeys:
91 nameMap = self.grammar.mapKeys.maps
92
93 self.byName = utils.CaseSemisensitiveDict(
94 (nameMap.get(t[0], t[0]), t)
95 for t in self.inputColumns)
96
97 def _getStructDefinition(self):
98 """returns a definition for a C structure for holding one record.
99 """
100 res = ["typedef struct InRec_s {"]
101 for name, _, cType in self.inputColumns:
102 res.append(f" {cType} {name};")
103 res.append("} InRec;")
104 return "\n".join(res)
105
106 def _getArrayDecls(self):
107 """returns the declarations for the buffer arrays.
108 """
109 return "\n".join(
110 f" {cType} arr_{name}[CHUNK_SIZE];"
111 for name, _, cType in self.inputColumns)
112
113 def _getRefillCode(self):
114 """returns code to (up to) CHUNK_SIZE items into the column
115 arrays.
116 """
117 res = [
118 "offsets[0] = total_read;",
119 "if (total_read+chunk_size[0]>nrecs) {",
120 " chunk_size[0] = nrecs-total_read;",
121 " HDFGUARD(H5Sselect_hyperslab(memspace, H5S_SELECT_SET,"
122 " null_offset, NULL, chunk_size, NULL));",
123 "}",
124 "HDFGUARD(H5Sselect_hyperslab(colspace, H5S_SELECT_SET,"
125 " offsets, NULL, chunk_size, NULL));",]
126
127 for index, (name, npType, cType) in enumerate(self.inputColumns):
128 memTypeId = self._h5typemap[str(npType)]
129 res.append(
130 f"HDFGUARD(H5Dread(datasets[{index}], {memTypeId}, memspace,"
131 f" colspace, H5P_DEFAULT, arr_{name}));")
132
133 return "\n".join(res)
134
135
136 def _getTupleBuilder(self):
137 """returns code to build the InRec struct passed to getTuple.
138 """
139 res = []
140 for index, (name, _, cType) in enumerate(self.inputColumns):
141 res.append(f"cur_rec.{name} = arr_{name}[index_in_chunk];");
142 return "\n".join(res)
143
144 def getPreamble(self):
145 n_cols = len(self.inputColumns)
146
147 return directgrammar._NumpyMetaCodeGenerator.getPreamble(self
148 )+[
149 "#include <inttypes.h>",
150 "#include <stdlib.h>",
151 "#include <hdf5.h>",
152 f"#define N_COLS {n_cols}",
153 # how many rows to process in one go?
154 "#define CHUNK_SIZE {}".format(
155 self.grammar.getProperty("chunkSize", 5000)),
156 self._getStructDefinition(),
157 "#define HDFGUARD(x) if ((x)<0) abort();",]
158
159 def getPrototype(self):
160 return "Field *getTuple(InRec *data, int rowIndex)"
161
162 def getFooter(self):
163 return "\n".join([
164 directgrammar.COMMON_MAIN_HEADER,
165 " hid_t input_id;"
166 " hid_t datasets[N_COLS];",
167 " hid_t colspace;",
168 " size_t nrecs;",
169 " int rank;",
170 " hsize_t dims[1], offsets[1];",
171 " hsize_t null_offset[1] = {0};",
172 " hsize_t chunk_size[1] = {CHUNK_SIZE};",
173 " hid_t memspace = H5Screate_simple(1, chunk_size, NULL);",
174 # index_in_chunk set so we immediately read a chunk at startup
175 " size_t index_in_chunk = CHUNK_SIZE;",
176 " size_t total_read = 0;",
177 " InRec cur_rec;",
178 "",
179 directgrammar.COMMON_MAIN_INTRO,
180 " input_id = H5Fopen(argv[1], H5F_ACC_RDONLY, H5P_DEFAULT);",
181 " if (input_id<0) abort();",
182 " HDFGUARD(H5Sselect_hyperslab(memspace, H5S_SELECT_SET,"
183 " null_offset, NULL, chunk_size, NULL));",
184 self._getArrayDecls(),
185 self._getDatasetsCode(),
186 ' colspace = H5Dget_space(datasets[0]);',
187 ' rank = H5Sget_simple_extent_ndims(colspace);',
188 ' if (rank>1) abort();',
189 ' H5Sget_simple_extent_dims(colspace, dims, NULL);',
190 ' nrecs = dims[0];',
191
192 " while (total_read<nrecs) {",
193 directgrammar.LOOP_BODY_INTRO,
194 " if (index_in_chunk>=CHUNK_SIZE) { ",
195 utils.fixIndentation(self._getRefillCode(), " "),
196 " index_in_chunk = 0;",
197 " }",
198 utils.fixIndentation(self._getTupleBuilder(), " "),
199 " total_read += 1;",
200 " index_in_chunk += 1;",
201 " tuple = getTuple(&cur_rec, total_read-1);",
202 directgrammar.LOOP_BODY_FOOT,
203 " }",
204 directgrammar.COMMON_MAIN_FOOT,])
205
206 def getItemParser(self, item, index):
207 nameForItem = directgrammar.getNameForItem(item)
208 typeMacro = directgrammar._getMakeMacro(item)
209 res = [
210 f"/* {item.description} ({item.type}) */",]
211 if item.name not in self.byName:
212 res.append(
213 f"MAKE_NULL({nameForItem});"
214 f"/* {typeMacro}({nameForItem}, FILL IN VALUE); */")
215
216 else:
217 origName, _, castTo = self.byName[item.name]
218 # there is a source column in the HDF5, make a default map
219 res.append(
220 f"{typeMacro}({nameForItem}, (({castTo})(data->{origName})));")
221
222 return res
223
224 def getColumns(self):
225 """has to return a sequence of (name, type) pairs for the columns
226 of the relation encoded in the HDF5 file.
227 """
228 raise NotImplementedError("HDF5 getColumns")
229
230 def _getDatasetsCode(self):
231 """has to return C code to fill datasets[0...input_columns] with
232 the values the C code should to process.
233 """
234 raise NotImplementedError("HDF5 _getDatasetsCode")
235
236
237 class HDF5vaexCodeGenerator(BaseHDF5CodeGenerator):
238 """A code generator for boosters importing HDF5 files in VAEX convention.
239
240 These have one array per column in a "columns" group; the actual data
241 is in a "data" group.
242
243 Our strategy when parsing from them is to read CHUNK_SIZE items
244 at a time into the corresponding arrays, and then iterating
245 over these chunks, building the records.
246 """
247
248 def getColumns(self, hdf):
249 # SIDE EFFECT: self.dsName is the dataset name to read from after
250 # this function.
251 try:
252 self.dsName = self.grammar.getProperty("dataset", "table")
253 cols = hdf[self.dsName]["columns"]
254 except KeyError:
255 raise base.StructureError(f"Cannot access dataset {self.dsName} in"
256 f" {self.sampleSource}. Override the grammar's dataset property"
257 " to point it to the right dataset.")
258 return [(name, col["data"].dtype) for name, col in cols.items()]
259
260 def _getDatasetsCode(self):
261 """returns code to create the datasets for the columns; the
262 result is kept in a datasets array.
263 """
264 res = []
265 for index, (name, _, cType) in enumerate(self.inputColumns):
266 col_ds_name = "/".join([self.dsName, "columns", name, "data"])
267 res.extend([
268 f" datasets[{index}] = H5Dopen2("
269 f'input_id, "{col_ds_name}", H5P_DEFAULT);',
270 f" if (datasets[{index}]<0) abort();"])
271 return "\n".join(res)
272
273
274 class HDF5rootarrCodeGenerator(BaseHDF5CodeGenerator):
275 """A code generator for boosters importing HDF5 files having
276 their columns in arrays in the root dataset.
277 """
278
279 def getColumns(self, hdf):
280 return [(name, col.dtype) for name, col in hdf.items()]
281
282 def _getDatasetsCode(self):
283 """returns code to create the datasets for the columns; the
284 result is kept in a datasets array.
285 """
286 res = []
287 for index, (name, _, cType) in enumerate(self.inputColumns):
288 res.extend([
289 f" datasets[{index}] = H5Dopen2("
290 f'input_id, "{name}", H5P_DEFAULT);',
291 f" if (datasets[{index}]<0) abort();"])
292 return "\n".join(res)