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
|
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2017 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/
"""
This module define model and widget to display 1D slices from numpy
array using compound data types or hdf5 databases.
"""
from __future__ import division
__authors__ = ["V. Valls"]
__license__ = "MIT"
__date__ = "29/09/2017"
import functools
import os.path
import logging
from silx.gui import qt
import silx.io
from .TextFormatter import TextFormatter
import silx.gui.hdf5
from silx.gui.widgets import HierarchicalTableView
from ..hdf5.Hdf5Formatter import Hdf5Formatter
try:
import h5py
except ImportError:
h5py = None
_logger = logging.getLogger(__name__)
class _CellData(object):
"""Store a table item
"""
def __init__(self, value=None, isHeader=False, span=None):
"""
Constructor
:param str value: Label of this property
:param bool isHeader: True if the cell is an header
:param tuple span: Tuple of row, column span
"""
self.__value = value
self.__isHeader = isHeader
self.__span = span
def isHeader(self):
"""Returns true if the property is a sub-header title.
:rtype: bool
"""
return self.__isHeader
def value(self):
"""Returns the value of the item.
"""
return self.__value
def span(self):
"""Returns the span size of the cell.
:rtype: tuple
"""
return self.__span
class _TableData(object):
"""Modelize a table with header, row and column span.
It is mostly defined as a row based table.
"""
def __init__(self, columnCount):
"""Constructor.
:param int columnCount: Define the number of column of the table
"""
self.__colCount = columnCount
self.__data = []
def rowCount(self):
"""Returns the number of rows.
:rtype: int
"""
return len(self.__data)
def columnCount(self):
"""Returns the number of columns.
:rtype: int
"""
return self.__colCount
def clear(self):
"""Remove all the cells of the table"""
self.__data = []
def cellAt(self, row, column):
"""Returns the cell at the row column location. Else None if there is
nothing.
:rtype: _CellData
"""
if row < 0:
return None
if column < 0:
return None
if row >= len(self.__data):
return None
cells = self.__data[row]
if column >= len(cells):
return None
return cells[column]
def addHeaderRow(self, headerLabel):
"""Append the table with header on the full row.
:param str headerLabel: label of the header.
"""
item = _CellData(value=headerLabel, isHeader=True, span=(1, self.__colCount))
self.__data.append([item])
def addHeaderValueRow(self, headerLabel, value):
"""Append the table with a row using the first column as an header and
other cells as a single cell for the value.
:param str headerLabel: label of the header.
:param object value: value to store.
"""
header = _CellData(value=headerLabel, isHeader=True)
value = _CellData(value=value, span=(1, self.__colCount))
self.__data.append([header, value])
def addRow(self, *args):
"""Append the table with a row using arguments for each cells
:param list[object] args: List of cell values for the row
"""
row = []
for value in args:
if not isinstance(value, _CellData):
value = _CellData(value=value)
row.append(value)
self.__data.append(row)
class Hdf5TableModel(HierarchicalTableView.HierarchicalTableModel):
"""This data model provides access to HDF5 node content (File, Group,
Dataset). Main info, like name, file, attributes... are displayed
"""
def __init__(self, parent=None, data=None):
"""
Constructor
:param qt.QObject parent: Parent object
:param object data: An h5py-like object (file, group or dataset)
"""
super(Hdf5TableModel, self).__init__(parent)
self.__obj = None
self.__data = _TableData(columnCount=4)
self.__formatter = None
self.__hdf5Formatter = Hdf5Formatter(self)
formatter = TextFormatter(self)
self.setFormatter(formatter)
self.setObject(data)
def rowCount(self, parent_idx=None):
"""Returns number of rows to be displayed in table"""
return self.__data.rowCount()
def columnCount(self, parent_idx=None):
"""Returns number of columns to be displayed in table"""
return self.__data.columnCount()
def data(self, index, role=qt.Qt.DisplayRole):
"""QAbstractTableModel method to access data values
in the format ready to be displayed"""
if not index.isValid():
return None
cell = self.__data.cellAt(index.row(), index.column())
if cell is None:
return None
if role == self.SpanRole:
return cell.span()
elif role == self.IsHeaderRole:
return cell.isHeader()
elif role == qt.Qt.DisplayRole:
value = cell.value()
if callable(value):
value = value(self.__obj)
return value
return None
def flags(self, index):
"""QAbstractTableModel method to inform the view whether data
is editable or not.
"""
return qt.QAbstractTableModel.flags(self, index)
def isSupportedObject(self, h5pyObject):
"""
Returns true if the provided object can be modelized using this model.
"""
isSupported = False
isSupported = isSupported or silx.io.is_group(h5pyObject)
isSupported = isSupported or silx.io.is_dataset(h5pyObject)
isSupported = isSupported or isinstance(h5pyObject, silx.gui.hdf5.H5Node)
return isSupported
def setObject(self, h5pyObject):
"""Set the h5py-like object exposed by the model
:param h5pyObject: A h5py-like object. It can be a `h5py.Dataset`,
a `h5py.File`, a `h5py.Group`. It also can be a,
`silx.gui.hdf5.H5Node` which is needed to display some local path
information.
"""
if qt.qVersion() > "4.6":
self.beginResetModel()
if h5pyObject is None or self.isSupportedObject(h5pyObject):
self.__obj = h5pyObject
else:
_logger.warning("Object class %s unsupported. Object ignored.", type(h5pyObject))
self.__initProperties()
if qt.qVersion() > "4.6":
self.endResetModel()
else:
self.reset()
def __formatHdf5Type(self, dataset):
"""Format the HDF5 type"""
return self.__hdf5Formatter.humanReadableHdf5Type(dataset)
def __formatDType(self, dataset):
"""Format the numpy dtype"""
return self.__hdf5Formatter.humanReadableType(dataset, full=True)
def __formatShape(self, dataset):
"""Format the shape"""
if dataset.shape is None or len(dataset.shape) <= 1:
return self.__hdf5Formatter.humanReadableShape(dataset)
size = dataset.size
shape = self.__hdf5Formatter.humanReadableShape(dataset)
return u"%s = %s" % (shape, size)
def __initProperties(self):
"""Initialize the list of available properties according to the defined
h5py-like object."""
self.__data.clear()
if self.__obj is None:
return
obj = self.__obj
hdf5obj = obj
if isinstance(obj, silx.gui.hdf5.H5Node):
hdf5obj = obj.h5py_object
if silx.io.is_file(hdf5obj):
objectType = "File"
elif silx.io.is_group(hdf5obj):
objectType = "Group"
elif silx.io.is_dataset(hdf5obj):
objectType = "Dataset"
else:
objectType = obj.__class__.__name__
self.__data.addHeaderRow(headerLabel="HDF5 %s" % objectType)
SEPARATOR = "::"
self.__data.addHeaderRow(headerLabel="Path info")
if isinstance(obj, silx.gui.hdf5.H5Node):
# helpful informations if the object come from an HDF5 tree
self.__data.addHeaderValueRow("Basename", lambda x: x.local_basename)
self.__data.addHeaderValueRow("Name", lambda x: x.local_name)
local = lambda x: x.local_filename + SEPARATOR + x.local_name
self.__data.addHeaderValueRow("Local", local)
physical = lambda x: x.physical_filename + SEPARATOR + x.physical_name
self.__data.addHeaderValueRow("Physical", physical)
else:
# it's a real H5py object
self.__data.addHeaderValueRow("Basename", lambda x: os.path.basename(x.name))
self.__data.addHeaderValueRow("Name", lambda x: x.name)
self.__data.addHeaderValueRow("File", lambda x: x.file.filename)
if hasattr(obj, "path"):
# That's a link
if hasattr(obj, "filename"):
link = lambda x: x.filename + SEPARATOR + x.path
else:
link = lambda x: x.path
self.__data.addHeaderValueRow("Link", link)
else:
if silx.io.is_file(obj):
physical = lambda x: x.filename + SEPARATOR + x.name
else:
physical = lambda x: x.file.filename + SEPARATOR + x.name
self.__data.addHeaderValueRow("Physical", physical)
if hasattr(obj, "dtype"):
self.__data.addHeaderRow(headerLabel="Data info")
if h5py is not None and hasattr(obj, "id"):
# display the HDF5 type
self.__data.addHeaderValueRow("HDF5 type", self.__formatHdf5Type)
self.__data.addHeaderValueRow("dtype", self.__formatDType)
if hasattr(obj, "shape"):
self.__data.addHeaderValueRow("shape", self.__formatShape)
if hasattr(obj, "chunks") and obj.chunks is not None:
self.__data.addHeaderValueRow("chunks", lambda x: x.chunks)
# relative to compression
# h5py expose compression, compression_opts but are not initialized
# for external plugins, then we use id
# h5py also expose fletcher32 and shuffle attributes, but it is also
# part of the filters
if hasattr(obj, "shape") and hasattr(obj, "id"):
dcpl = obj.id.get_create_plist()
if dcpl.get_nfilters() > 0:
self.__data.addHeaderRow(headerLabel="Compression info")
pos = _CellData(value="Position", isHeader=True)
hdf5id = _CellData(value="HDF5 ID", isHeader=True)
name = _CellData(value="Name", isHeader=True)
options = _CellData(value="Options", isHeader=True)
self.__data.addRow(pos, hdf5id, name, options)
for index in range(dcpl.get_nfilters()):
callback = lambda index, dataIndex, x: self.__get_filter_info(x, index)[dataIndex]
pos = _CellData(value=functools.partial(callback, index, 0))
hdf5id = _CellData(value=functools.partial(callback, index, 1))
name = _CellData(value=functools.partial(callback, index, 2))
options = _CellData(value=functools.partial(callback, index, 3))
self.__data.addRow(pos, hdf5id, name, options)
if hasattr(obj, "attrs"):
if len(obj.attrs) > 0:
self.__data.addHeaderRow(headerLabel="Attributes")
for key in sorted(obj.attrs.keys()):
callback = lambda key, x: self.__formatter.toString(x.attrs[key])
self.__data.addHeaderValueRow(headerLabel=key, value=functools.partial(callback, key))
def __get_filter_info(self, dataset, filterIndex):
"""Get a tuple of readable info from dataset filters
:param h5py.Dataset dataset: A h5py dataset
:param int filterId:
"""
try:
dcpl = dataset.id.get_create_plist()
info = dcpl.get_filter(filterIndex)
filterId, _flags, cdValues, name = info
name = self.__formatter.toString(name)
options = " ".join([self.__formatter.toString(i) for i in cdValues])
return (filterIndex, filterId, name, options)
except Exception:
_logger.debug("Backtrace", exc_info=True)
return [filterIndex, None, None, None]
def object(self):
"""Returns the internal object modelized.
:rtype: An h5py-like object
"""
return self.__obj
def setFormatter(self, formatter):
"""Set the formatter object to be used to display data from the model
:param TextFormatter formatter: Formatter to use
"""
if formatter is self.__formatter:
return
self.__hdf5Formatter.setTextFormatter(formatter)
if qt.qVersion() > "4.6":
self.beginResetModel()
if self.__formatter is not None:
self.__formatter.formatChanged.disconnect(self.__formatChanged)
self.__formatter = formatter
if self.__formatter is not None:
self.__formatter.formatChanged.connect(self.__formatChanged)
if qt.qVersion() > "4.6":
self.endResetModel()
else:
self.reset()
def getFormatter(self):
"""Returns the text formatter used.
:rtype: TextFormatter
"""
return self.__formatter
def __formatChanged(self):
"""Called when the format changed.
"""
self.reset()
class Hdf5TableView(HierarchicalTableView.HierarchicalTableView):
"""A widget to display metadata about a HDF5 node using a table."""
def __init__(self, parent=None):
super(Hdf5TableView, self).__init__(parent)
self.setModel(Hdf5TableModel(self))
def isSupportedData(self, data):
"""
Returns true if the provided object can be modelized using this model.
"""
return self.model().isSupportedObject(data)
def setData(self, data):
"""Set the h5py-like object exposed by the model
:param h5pyObject: A h5py-like object. It can be a `h5py.Dataset`,
a `h5py.File`, a `h5py.Group`. It also can be a,
`silx.gui.hdf5.H5Node` which is needed to display some local path
information.
"""
self.model().setObject(data)
header = self.horizontalHeader()
if qt.qVersion() < "5.0":
setResizeMode = header.setResizeMode
else:
setResizeMode = header.setSectionResizeMode
setResizeMode(0, qt.QHeaderView.Fixed)
setResizeMode(1, qt.QHeaderView.Stretch)
header.setStretchLastSection(True)
|