File: dtrekimage.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 (313 lines) | stat: -rw-r--r-- 11,294 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
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
# coding: utf-8
#
#    Project: X-ray image reader
#             https://github.com/silx-kit/fabio
#
#
#    Copyright (C) European Synchrotron Radiation Facility, Grenoble, France
#
#    Principal author:       Jérôme Kieffer (Jerome.Kieffer@ESRF.eu)
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
"""

Authors: Henning O. Sorensen & Erik Knudsen
         Center for Fundamental Research: Metal Structures in Four Dimensions
         Risoe National Laboratory
         Frederiksborgvej 399
         DK-4000 Roskilde
         email:erik.knudsen@risoe.dk

+ mods for fabio by JPW

"""

import numpy
import re

import logging

from .fabioimage import FabioImage

logger = logging.getLogger(__name__)

_DATA_TYPES = {
    "signed char": numpy.int8,
    "unsigned char": numpy.uint8,
    "short int": numpy.int16,
    "unsigned short int": numpy.uint16,
    "long int": numpy.int32,
    "unsigned long int": numpy.uint32,
    "float IEEE": numpy.float32,
    # Valid but unsupported
    "Compressed": None,
    # Valid but unsupported
    "Other_type": None,
}
"""Mapping from Data_type content to numpy equicalent"""


class DtrekImage(FabioImage):
    """Read an image using the d*TREK format.

    This format is used to process X-ray diffraction data from area detectors.
    It supports processing of data from multiple detector types (imaging plates,
    CCDs and pixel arrays) and from multiple vendors (Rigaku, Mar, Dectris,
    Bruker and ADSC).

    Rigaku providing a `specification <https://www.rigaku.com/downloads/software/free/dTREK%20Image%20Format%20v1.1.pdf>`_.
    """

    DESCRIPTION = "D*trek format (Rigaku specification 1.1)"

    DEFAULT_EXTENSIONS = ["img"]

    _keyvalue_pattern = None

    def __init__(self, *args, **kwargs):
        FabioImage.__init__(self, *args, **kwargs)
        if DtrekImage._keyvalue_pattern is None:
            DtrekImage._keyvalue_pattern = re.compile(b"[^\n]+")

    def read(self, fname, frame=None):
        """ read in the file """
        with self._open(fname, "rb") as infile:
            try:
                self._readheader(infile)
            except Exception:
                logger.debug("Backtrace", exc_info=True)
                raise IOError("Error processing d*TREK header")

            # FIXME: It would be good to read only the expected data
            binary = infile.read()

        # Read information of the binary data type
        data_type = self.header.get("Data_type", None)
        if data_type is None:
            # Compatibility with old supported files
            data_type = self.header.get("TYPE", None)
            if data_type is not None and data_type == "unsigned_short":
                pass
            else:
                logger.warning("Data_type key is mandatory. Fallback to unsigner integer 16-bits.")
            numpy_type = numpy.uint16
        else:
            if data_type not in _DATA_TYPES:
                raise IOError("Data_type key contains an invalid/unsupported value: %s", data_type)
            numpy_type = _DATA_TYPES[data_type]
            if type is None:
                raise IOError("Data_type %s is not supported by fabio", data_type)

        # Stored in case data reading fails
        self._dtype = numpy.dtype(numpy_type)

        dim = self.header.get("DIM", None)
        if dim is None:
            logger.warning("DIM key is mandatory. Fallback using DIM=2.")
            dim = 2
        else:
            dim = int(dim)

        shape = []
        for i in range(dim):
            value = int(self.header['SIZE%d' % (i + 1)])
            shape.insert(0, value)
        self._shape = shape

        if sum(shape) == 0:
            data = None
        else:
            # Read the data into the array
            data = numpy.frombuffer(binary, numpy_type).copy()
            if self.swap_needed():
                try:
                    data.byteswap(inplace=True)
                except TypeError:
                    # Older numpy without inplace
                    data = data.byteswap()
            try:
                data.shape = self._shape
            except ValueError:
                    raise IOError('Size spec in d*TREK header does not match ' +
                                  'size of image data field %s != %s' % (self._shape, data.size))
        self.data = data
        self._shape = None
        self._dtype = None
        self.resetvals()
        return self

    def _split_meta(self, line):
        """Split a line into key and value.

        :param bytes line: A line of bytes
        :rtype: Tuple[str,str]
        """
        if b"=" not in line:
            raise ValueError("No meta")
        line = line.decode("ascii")
        key, value = line.split('=')
        return key.strip(), value.strip(' ;\n\r')

    def _readheader(self, infile):
        """Read a d*TREK header.

        After the execusion of this function, the cursor on infile will point
        at the end of the header (at the start of the binary data block).

        :param FileObject infile: A file object pointing at the first character
            of the header.
        """
        header_line = infile.readline()
        assert(header_line.startswith(b"{"))
        header_bytes_line = infile.readline()
        key, header_bytes = self._split_meta(header_bytes_line)
        assert(key == "HEADER_BYTES")
        self.header[key] = header_bytes
        header_bytes = int(header_bytes)

        # Read the remining block
        # For robustness, cause that's in fact a const
        header_bytes -= len(header_line) + len(header_bytes_line)
        header_block = infile.read(header_bytes)

        for line in DtrekImage._keyvalue_pattern.finditer(header_block):
            line = line.group(0)
            if line.startswith(b'}'):
                # Remining part is padding
                return
            try:
                key, value = self._split_meta(line)
                self.header[key] = value
            except ValueError:
                pass

        # It means there was no end of block
        logger.warning("The end of block '}' was not reachable. File may be corrupted.")

    def write(self, fname):
        """
        Write d*TREK format
        """

        # From specification
        HEADER_START = b"{\n"
        HEADER_END = b"}\n\x0C\n"
        HEADER_BYTES_TEMPLATE = "HEADER_BYTES=% 5d;\n"
        # start + end + header_bytes_key + header_bytes_value + header_bytes_end
        MINIMAL_HEADER_SIZE = 2 + 4 + 13 + 5 + 2

        data = self.data
        if data is not None:
            dtrek_data_type = None
            for key, value in _DATA_TYPES.items():
                if data.dtype.type == value:
                    dtrek_data_type = key
                    break

            if dtrek_data_type is None:
                if data.dtype.kind == 'f':
                    dtrek_data_type = "float IEEE"
                elif data.dtype.kind == 'u':
                    dtrek_data_type = "unsigned long int"
                elif data.dtype.kind == 'i':
                    dtrek_data_type = "long int"
                else:
                    raise TypeError("Unsupported data type %s", data.dtype)
                new_dtype = numpy.dtype(_DATA_TYPES[dtrek_data_type])
                logger.warning("Data type %s unsupported. Store it as %s.", data.dtype, new_dtype)
                data = data.astype(new_dtype)

            byte_order = self._get_dtrek_byte_order(default_little_endian=numpy.little_endian)
            little_endian = byte_order == "little_endian"
            if little_endian != numpy.little_endian:
                data = data.byteswap()

            # Patch header to match the data
            self.header["Data_type"] = dtrek_data_type
            self.header['DIM'] = str(len(data.shape))
            for i, size in enumerate(reversed(data.shape)):
                self.header['SIZE%d' % (i + 1)] = str(size)
            self.header["BYTE_ORDER"] = byte_order
        else:
            # No data
            self.header["Data_type"] = "long int"
            self.header['DIM'] = "2"
            self.header["SIZE1"] = "0"
            self.header["SIZE2"] = "0"
            self.header["BYTE_ORDER"] = "little_endian"

        out = b""
        for key in self.header:
            if key == "HEADER_BYTES":
                continue
            line = "%s= %s;\n" % (key, self.header[key])
            out += line.encode("utf-8")

        # FIXME: This code do not take into account the size of "HEADER_BYTES"
        if "HEADER_BYTES" in self.header:
            hsize = int(self.header["HEADER_BYTES"])
            pad = hsize - len(out) - MINIMAL_HEADER_SIZE
            if pad < 0:
                logger.warning("HEADER_BYTES have to be patched.")
                minimal_hsize = hsize - pad
                hsize = (minimal_hsize + 512) & ~(512 - 1)
                pad = hsize - minimal_hsize
        else:
            minimal_hsize = len(out) + MINIMAL_HEADER_SIZE
            hsize = (minimal_hsize + 512) & ~(512 - 1)
            pad = hsize - minimal_hsize

        header_bytes = HEADER_BYTES_TEMPLATE % hsize
        out = HEADER_START + header_bytes.encode("ascii") + out + HEADER_END + (b' ' * pad)
        assert len(out) % 512 == 0, "Header is not multiple of 512"

        with open(fname, "wb") as outf:
            outf.write(out)
            if data is not None:
                data.tofile(outf)

    def _get_dtrek_byte_order(self, default_little_endian=None):
        """Returns the byte order value in d*TREK format."""
        if "BYTE_ORDER" not in self.header:
            if default_little_endian is None:
                logger.warning("No byte order specified, assuming little_endian")
                little_endian = True
            else:
                little_endian = default_little_endian
        else:
            byte_order = self.header["BYTE_ORDER"]
            little_endian = "little" in byte_order
            big_endian = "big" in byte_order
            if not little_endian and not big_endian:
                logger.warning("Invalid BYTE_ORDER value. Found '%s', assuming little_endian", byte_order)
                little_endian = True

        if little_endian:
            return "little_endian"
        else:
            return "big_endian"

        return byte_order

    def swap_needed(self, check=True):
        """
        Returns True if the header does not use the same endianness than the
        system.

        :rtype: bool
        """
        byte_order = self._get_dtrek_byte_order()
        little_endian = byte_order == "little_endian"
        return little_endian != numpy.little_endian