File: hdf5image.py

package info (click to toggle)
python-fabio 0.11.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 9,092 kB
  • sloc: python: 19,244; ansic: 1,085; makefile: 219; sh: 215
file content (189 lines) | stat: -rw-r--r-- 6,110 bytes parent folder | download | duplicates (4)
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
# coding: utf-8
#
#    Project: FabIO X-ray image reader
#
#    Copyright (C) 2010-2016 European Synchrotron Radiation Facility
#                       Grenoble, France
#
# 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.
#

"""HDF5 image for FabIO

Authors: Jerome Kieffer
email:  Jerome.Kieffer@terre-adelie.org

Specifications:
input should being the form:

filename::path

Only supports ndim=2 or 3 (exposed as a stack of images
"""

__authors__ = ["Jérôme Kieffer"]
__contact__ = "Jerome.Kieffer@terre-adelie.org"
__license__ = "MIT"
__copyright__ = "Jérôme Kieffer"
__date__ = "03/04/2020"

import logging
import os
import posixpath
from . import fabioimage

logger = logging.getLogger(__name__)

try:
    import h5py
except ImportError:
    h5py = None
from .fabioutils import previous_filename, next_filename


class Hdf5Frame(fabioimage.FabioFrame):
    """Identify a slice of dataset from an HDF5 file"""

    def __init__(self, hdf5image, frame_num):
        if not isinstance(hdf5image, Hdf5Image):
            raise TypeError("Expected class %s", Hdf5Image)
        data = hdf5image.dataset[frame_num, :, :]
        super(Hdf5Frame, self).__init__(data=data, header=hdf5image.header)
        self.hdf5 = hdf5image.hdf5
        self.dataset = hdf5image.dataset
        self.filename = hdf5image.filename
        self._nframes = hdf5image.nframes
        self.header = hdf5image.header
        self.currentframe = frame_num


class Hdf5Image(fabioimage.FabioImage):
    """
    FabIO image class for Images from an HDF file

    filename::dataset
    """

    DESCRIPTION = "Hierarchical Data Format HDF5 flat reader"

    DEFAULT_EXTENSIONS = ["h5"]

    def __init__(self, *arg, **kwargs):
        """
        Generic constructor
        """
        if not h5py:
            raise RuntimeError("fabio.Hdf5Image cannot be used without h5py. Please install h5py and restart")

        fabioimage.FabioImage.__init__(self, *arg, **kwargs)
        self.hdf5 = None
        self.dataset = None

    def read(self, fname, frame=None):
        """
        try to read image
        :param fname: filename::datasetpath
        """

        self.resetvals()
        if "::" not in fname:
            err = "the '::' separator in mandatory for HDF5 container, absent in %s" % fname
            logger.error(err)
            raise RuntimeError(err)
        filename, datapath = fname.split("::", 1)

        self.filename = filename
        if os.path.isfile(self.filename):
            self.hdf5 = h5py.File(self.filename, mode="r")
        else:
            error = "No such file or directory: %s" % self.filename
            logger.error(error)
            raise RuntimeError(error)
        try:
            self.dataset = self.hdf5[datapath]
        except Exception as err:
            logger.error("No such datapath %s in %s, %s", datapath, filename, err)
            raise
        if isinstance(self.dataset, h5py.Group) and ("data" in self.dataset):
            datapath = posixpath.join(datapath, "data")
            logger.warning("The actual dataset is ")
            self.dataset = self.dataset["data"]

        # ndim does not exist for external links ?
        ndim = len(self.dataset.shape)
        if ndim == 3:
            self._nframes = self.dataset.shape[0]
            if frame is not None:
                self.currentframe = int(frame)
            else:
                self.currentframe = 0
            self.data = self.dataset[self.currentframe, :, :]
        elif ndim == 2:
            self.data = self.dataset[:, :]
        else:
            err = "Only 2D and 3D datasets are supported by FabIO, here %sD" % self.dataset.ndim
            logger.error(err)
            raise RuntimeError(err)
        return self

    def _get_frame(self, num):
        return self.getframe(num)

    def getframe(self, num):
        """
        Returns a frame as a new FabioImage object
        :param num: frame number
        """
        if num < 0 or num >= self.nframes:
            raise IndexError("Requested frame number %i is out of range [0, %i[ " % (num, self.nframes))
        # Do a deep copy of the header to make a new one
        frame = Hdf5Frame(self, num)
        frame._set_container(self, num)
        frame._set_file_container(self, num)
        return frame

    def next(self):
        """
        Get the next image in a series as a fabio image
        """
        if self.currentframe < (self.nframes - 1):
            return self.getframe(self.currentframe + 1)
        else:
            newobj = Hdf5Image()
            newobj.read(next_filename(self.filename))
            return newobj

    def previous(self):
        """
        Get the previous image in a series as a fabio image
        """
        if self.currentframe > 0:
            return self.getframe(self.currentframe - 1)
        else:
            newobj = Hdf5Image()
            newobj.read(previous_filename(self.filename))
            return newobj

    def close(self):
        if self.hdf5 is not None:
            self.hdf5.close()
            self.dataset = None


hdf5image = Hdf5Image