File: sparseimage.py

package info (click to toggle)
python-fabio 0.14.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 10,068 kB
  • sloc: python: 20,053; ansic: 1,085; makefile: 217; sh: 215
file content (256 lines) | stat: -rw-r--r-- 9,691 bytes parent folder | download
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
# coding: utf-8
#
#    Project: X-ray image reader
#             https://github.com/silx-kit/fabio
#
#    Copyright 2020-2021(C) 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.

"""Image format generated with sparsify-Bragg from pyFAI

This format contains the average background with its associated deviation in addition to all
pixels corresponding to Bragg peaks (positive outliers)

This class is able to regenerate images with or without background noise.  
"""

__authors__ = ["Jérôme Kieffer"]
__contact__ = "jerome.kieffer@esrf.fr"
__license__ = "MIT"
__copyright__ = "2020 ESRF"
__date__ = "02/06/2022"

import logging
logger = logging.getLogger(__name__)
import numpy
try:
    import h5py
except ImportError:
    h5py = None
else:
    try:
        import hdf5plugin
    except:
        pass
from .fabioutils import NotGoodReader
from .fabioimage import FabioImage, OrderedDict
try:
    from .ext import dense as cython_densify
except ImportError:
    cython_densify = None


def densify(mask,
            radius,
            index,
            intensity,
            dummy,
            background,
            background_std=None,
            normalization=None,
            seed=None):
    """Generate a dense image of its sparse representation
    
    :param mask: 2D array with NaNs for mask and pixel radius for the valid pixels
    :param radius: 1D array with the radial distance
    :param index: position of non-background pixels
    :param intensity: intensities of non background pixels (at index position)
    :param dummy: numerical value for masked-out pixels in dense image
    :return: dense frame as 2D array
    :param background: 1D array with the background values at given distance from the center
    :param background_std: 1D array with the background std at given distance from the center
    :param normalization: flat*solidangle*polarization*... array
    :return dense array
    """
    dense = numpy.interp(mask, radius, background)
    if background_std is not None:
        if seed is not None:
            numpy.random.seed(seed)
        std = numpy.interp(mask, radius, background_std)
        numpy.maximum(0.0, numpy.random.normal(dense, std), out=dense)
    if normalization is not None:
        dense *= normalization

    flat = dense.ravel()
    flat[index] = intensity
    dtype = intensity.dtype
    if numpy.issubdtype(dtype, numpy.integer):
        #dense = numpy.round(dense) # Foolded by banker's rounding !!!!
        dense += 0.5
    dense = numpy.ascontiguousarray(dense, dtype=dtype)
    dense[numpy.logical_not(numpy.isfinite(mask))] = dummy
    return dense


class SparseImage(FabioImage):
    """FabIO image class for images compressed by sparsification of Bragg peaks 

    While the sparsification requires pyFAI and substential resources, re-densifying the data is easy.
    
    The program used for the sparsification is `sparsify-Bragg` from the pyFAI suite
    
    Set the noisy attribute to re-generate background noise
    """

    DESCRIPTION = "spasify-Bragg"

    DEFAULT_EXTENSIONS = [".h5", ".hdf5", ".nxs"]

    NOISY = False

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

        FabioImage.__init__(self, *arg, **kwargs)
        self.mask = None
        self.normalization = None  # Correspond to the flat/polarization/solid-angle correction
        self.radius = None
        self.background_avg = None
        self.background_std = None
        self.frame_ptr = None
        self.index = None
        self.intensity = None
        self.dummy = None
        self.noisy = float(self.__class__.NOISY)
        self.h5 = None

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

    def _readheader(self, infile):
        """
        Read and decode the header of an image:

        :param infile: Opened python file (can be stringIO or bzipped file)
        """
        # list of header key to keep the order (when writing)
        self.header = self.check_header()

    def read(self, fname, frame=None):
        """
        Try to read image

        :param fname: name of the file
        :param frame: number of the frame
        """

        self.resetvals()
        self._readheader(fname)
        self.h5 = h5py.File(fname, mode="r")
        default_entry = self.h5.attrs.get("default")
        if default_entry is None or default_entry not in self.h5:
            raise NotGoodReader("HDF5 file does not contain any default entry.")
        entry = self.h5[default_entry]
        default_data = entry.attrs.get("default")
        if default_data is None or default_data not in entry:
            raise NotGoodReader("HDF5 file does not contain any default NXdata.")
        nx_data = entry[default_data]
        self.mask = nx_data["mask"][()]
        self.radius = nx_data["radius"][()]
        self.background_avg = nx_data["background_avg"][()]
        self.background_std = nx_data["background_std"][()]
        self.frame_ptr = nx_data["frame_ptr"][()]
        self.index = nx_data["index"][()]
        self.intensity = nx_data["intensity"][()]
        self.dummy = self.intensity.dtype.type(nx_data["dummy"][()])
        self._nframes = self.frame_ptr.shape[0] - 1
        if "normalization" in nx_data:
            self.normalization = numpy.ascontiguousarray(nx_data["normalization"][()], dtype=numpy.float32)

        if frame is not None:
            return self.getframe(int(frame))
        else:
            self.currentframe = 0
            self.data = self._generate_data(self.currentframe)
            self._shape = None
            return self

    def _generate_data(self, index=0):
        "Actually rebuilds the data for one frame"
        if self.h5 is None:
            logger.warning("Not data have been read from disk")
            return
        start, stop = self.frame_ptr[index:index + 2]
        if cython_densify is not None:
            return cython_densify.densify(self.mask,
                                 self.radius,
                                 self.index[start:stop],
                                 self.intensity[start:stop],
                                 self.dummy,
                                 self.intensity.dtype,
                                 self.background_avg[index],
                                 self.background_std[index] * self.noisy if self.noisy else None,
                                 self.normalization)
        else:
            # Fall-back on numpy code.
            return densify(self.mask,
                           self.radius,
                           self.index[start:stop],
                           self.intensity[start:stop],
                           self.dummy,
                           self.background_avg[index],
                           self.background_std[index] * self.noisy if self.noisy else None,
                           self.normalization)

    def getframe(self, num):
        """ returns the frame numbered 'num' in the stack if applicable"""
        if self.nframes > 1:
            new_img = None
            if (num >= 0) and num < self.nframes:
                data = self._generate_data(num)
                new_img = self.__class__(data=data, header=self.header)
                new_img.mask = self.mask
                new_img.radius = self.radius
                new_img.background_avg = self.background_avg
                new_img.background_std = self.background_std
                new_img.frame_ptr = self.frame_ptr
                new_img.index = self.index
                new_img.intensity = self.intensity
                new_img.dummy = self.dummy
                new_img.noisy = self.noisy
                new_img.h5 = self.h5
                new_img._nframes = self.nframes
                new_img.currentframe = num
                new_img.normalization = self.normalization
            else:
                raise IOError("getframe %s out of range [%s %s[" % (num, 0, self.nframes))
        else:
            new_img = FabioImage.getframe(self, num)
        return new_img

    def previous(self):
        """ returns the previous frame in the series as a fabioimage """
        return self.getframe(self.currentframe - 1)

    def next(self):
        """ returns the next frame in the series as a fabioimage """
        return self.getframe(self.currentframe + 1)


# This is not compatibility with old code:
sparseimage = SparseImage