summaryrefslogtreecommitdiff
path: root/silx/gui/data/Hdf5TableView.py
blob: 57d6f7b0bb448a9b7b43e68cd31bfc8f7c2ea30e (plain)
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
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2017-2020 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__ = "12/02/2019"

import collections
import functools
import os.path
import logging
import h5py
import numpy

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
from ..hdf5._utils import htmlFromDict


_logger = logging.getLogger(__name__)


class _CellData(object):
    """Store a table item
    """
    def __init__(self, value=None, isHeader=False, span=None, tooltip=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
        self.__tooltip = tooltip

    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

    def tooltip(self):
        """Returns the tooltip of the item.

        :rtype: tuple
        """
        return self.__tooltip

    def invalidateValue(self):
        self.__value = None

    def invalidateToolTip(self):
        self.__tooltip = None

    def data(self, role):
        return None


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, tooltip=None):
        """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), tooltip=tooltip)
        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 _CellFilterAvailableData(_CellData):
    """Cell rendering for availability of a filter"""

    _states = {
        True: ("Available", qt.QColor(0x000000), None, None),
        False: ("Not available", qt.QColor(0xFFFFFF), qt.QColor(0xFF0000),
                "You have to install this filter on your system to be able to read this dataset"),
        "na": ("n.a.", qt.QColor(0x000000), None,
               "This version of h5py/hdf5 is not able to display the information"),
    }

    def __init__(self, filterId):
        if h5py.version.hdf5_version_tuple >= (1, 10, 2):
            # Previous versions only returns True if the filter was first used
            # to decode a dataset
            self.__availability = h5py.h5z.filter_avail(filterId)
        else:
            self.__availability = "na"
        _CellData.__init__(self)

    def value(self):
        state = self._states[self.__availability]
        return state[0]

    def tooltip(self):
        state = self._states[self.__availability]
        return state[3]

    def data(self, role=qt.Qt.DisplayRole):
        state = self._states[self.__availability]
        if role == qt.Qt.TextColorRole:
            return state[1]
        elif role == qt.Qt.BackgroundColorRole:
            return state[2]
        else:
            return None


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=5)
        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 in (qt.Qt.DisplayRole, qt.Qt.EditRole):
            value = cell.value()
            if callable(value):
                try:
                    value = value(self.__obj)
                except Exception:
                    cell.invalidateValue()
                    raise
            return value
        elif role == qt.Qt.ToolTipRole:
            value = cell.tooltip()
            if callable(value):
                try:
                    value = value(self.__obj)
                except Exception:
                    cell.invalidateToolTip()
                    raise
            return value
        else:
            return cell.data(role)
        return None

    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 __attributeTooltip(self, attribute):
        attributeDict = collections.OrderedDict()
        if hasattr(attribute, "shape"):
            attributeDict["Shape"] = self.__hdf5Formatter.humanReadableShape(attribute)
        attributeDict["Data type"] = self.__hdf5Formatter.humanReadableType(attribute, full=True)
        html = htmlFromDict(attributeDict, title="HDF5 Attribute")
        return html

    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 __formatChunks(self, dataset):
        """Format the shape"""
        chunks = dataset.chunks
        if chunks is None:
            return ""
        shape = " \u00D7 ".join([str(i) for i in chunks])
        sizes = numpy.product(chunks)
        text = "%s = %s" % (shape, sizes)
        return text

    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)
            if obj.file is not None:
                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
                elif obj.file is not None:
                        physical = lambda x: x.file.filename + SEPARATOR + x.name
                else:
                    # Guess it is a virtual node
                    physical = "No physical location"
                self.__data.addHeaderValueRow("Physical", physical)

        if hasattr(obj, "dtype"):

            self.__data.addHeaderRow(headerLabel="Data info")

            if hasattr(obj, "id") and hasattr(obj.id, "get_type"):
                # 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", self.__formatChunks)

        # 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"):
            if hasattr(obj.id, "get_create_plist"):
                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)
                    availability = _CellData(value="", isHeader=True)
                    self.__data.addRow(pos, hdf5id, name, options, availability)
                for index in range(dcpl.get_nfilters()):
                    filterId, name, options = self.__getFilterInfo(obj, index)
                    pos = _CellData(value=str(index))
                    hdf5id = _CellData(value=str(filterId))
                    name = _CellData(value=name)
                    options = _CellData(value=options)
                    availability = _CellFilterAvailableData(filterId=filterId)
                    self.__data.addRow(pos, hdf5id, name, options, availability)

        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])
                    callbackTooltip = lambda key, x: self.__attributeTooltip(x.attrs[key])
                    self.__data.addHeaderValueRow(headerLabel=key,
                                                  value=functools.partial(callback, key),
                                                  tooltip=functools.partial(callbackTooltip, key))

    def __getFilterInfo(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 (filterId, name, options)
        except Exception:
            _logger.debug("Backtrace", exc_info=True)
        return (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 Hdf5TableItemDelegate(HierarchicalTableView.HierarchicalItemDelegate):
    """Item delegate the :class:`Hdf5TableView` with read-only text editor"""

    def createEditor(self, parent, option, index):
        """See :meth:`QStyledItemDelegate.createEditor`"""
        editor = super().createEditor(parent, option, index)
        if isinstance(editor, qt.QLineEdit):
            editor.setReadOnly(True)
            editor.deselect()
            editor.textChanged.connect(self.__textChanged, qt.Qt.QueuedConnection)
            self.installEventFilter(editor)
        return editor

    def __textChanged(self, text):
        sender = self.sender()
        if sender is not None:
            sender.deselect()

    def eventFilter(self, watched, event):
        eventType = event.type()
        if eventType == qt.QEvent.FocusIn:
            watched.selectAll()
            qt.QTimer.singleShot(0, watched.selectAll)
        elif eventType == qt.QEvent.FocusOut:
            watched.deselect()
        return super().eventFilter(watched, event)


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))
        self.setItemDelegate(Hdf5TableItemDelegate(self))
        self.setSelectionMode(qt.QAbstractItemView.NoSelection)

    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 data: 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.
        """
        model = self.model()

        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.ResizeToContents)
        setResizeMode(2, qt.QHeaderView.Stretch)
        setResizeMode(3, qt.QHeaderView.ResizeToContents)
        setResizeMode(4, qt.QHeaderView.ResizeToContents)
        header.setStretchLastSection(False)

        for row in range(model.rowCount()):
            for column in range(model.columnCount()):
                index = model.index(row, column)
                if (index.isValid() and index.data(
                        HierarchicalTableView.HierarchicalTableModel.IsHeaderRole) is False):
                    self.openPersistentEditor(index)