KmapSpecParser.py 12.9 KB
Newer Older
Damien Naudet's avatar
Damien Naudet committed
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
#!/usr/bin/python
# coding: utf8
# /*##########################################################################
#
# Copyright (c) 2015-2016 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.
#
# ###########################################################################*/

27
28
from __future__ import absolute_import

Damien Naudet's avatar
Damien Naudet committed
29
30
31
32
33
34
35
36
37
38
39
40
__authors__ = ["D. Naudet"]
__date__ = "20/04/2016"
__license__ = "MIT"

import re
import glob
import os.path
from collections import namedtuple

from threading import Thread

import h5py
41
from silx.io import convert
42
43
44
45
try:  # silx >= 0.14
    from silx.io.utils import h5py_read_dataset
except ImportError:  # Fall back for silx < 0.14
    from ...util.silx_io_utils import h5py_read_dataset
Damien Naudet's avatar
Damien Naudet committed
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


# regular expression matching the imageFile comment line
_IMAGEFILE_LINE_PATTERN = ('^#C imageFile '
                           'dir\[(?P<dir>[^\]]*)\] '
                           'prefix\[(?P<prefix>[^\]]*)\] '
                           '(idxFmt\[(?P<idxFmt>[^\]]*)\] ){0,1}'
                           'nextNr\[(?P<nextNr>[^\]]*)\] '
                           'suffix\[(?P<suffix>[^\]]*)\]$')

# #######################################################################


KmapParseResults = namedtuple('KmapParseResults',
                              ['img_info', 'no_img_info', 'error', 'spec_h5'])

KmapMatchResults = namedtuple('KmapMatchResults',
                              ['matched', 'not_matched',
                               'no_img_info', 'error',
                               'spec_h5'])

# #######################################################################


class KmapSpecParser(object):
Thomas Vincent's avatar
Thomas Vincent committed
71

Damien Naudet's avatar
Damien Naudet committed
72
73
    (READY, RUNNING, DONE,
     ERROR, CANCELED, UNKNOWN) = __STATUSES = range(6)
Thomas Vincent's avatar
Thomas Vincent committed
74
    """Available status codes"""
Damien Naudet's avatar
Damien Naudet committed
75
76

    status = property(lambda self: self.__status)
Thomas Vincent's avatar
Thomas Vincent committed
77
    """Current status code of this instance"""
Damien Naudet's avatar
Damien Naudet committed
78
79

    statusMsg = property(lambda self: self.__status_msg)
Thomas Vincent's avatar
Thomas Vincent committed
80
    """Status message if any, or None"""
Damien Naudet's avatar
Damien Naudet committed
81
82

    results = property(lambda self: self.__results)
Thomas Vincent's avatar
Thomas Vincent committed
83
    """Parse results. KmapMatchResults instance."""
Damien Naudet's avatar
Damien Naudet committed
84
85
86
87
88
89
90
91
92
93
94
95

    def __init__(self,
                 spec_fname,
                 spec_h5,
                 img_dir=None,
                 version=1,
                 nr_padding=None,
                 nr_offset=None,
                 callback=None):
        """
        Parser for the Kmap SPEC files. This loads a spec file, converts
            it to HDF5 and then tries to match scans and edf image files.
Thomas Vincent's avatar
Thomas Vincent committed
96

Damien Naudet's avatar
Damien Naudet committed
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
        :param spec_fname: Path to the spec file.
        :param spec_h5: Name of the HDF5 file that will be created and filled
            with the contents of the SPEC file
        .. seealso : silx.io.convert_spec_h5.convert
        :param img_dir: directory where the images are stored, if they are not
        stored where the path (#C imageFile line) in the SPEC file points to.
        :param version: version of the spec file. It is currently used to get
            the offset and padding to apply to the nextNr value found in the
            spec scan headers. This nextNr is then used to generate the image
            file name. Set it to 0 if you are merging data generated
            before April 2016 (TBC).
        :param nr_padding: zero padding to apply to the nextNr number found
            in the SPEC file.
        :param nr_offset: offset to apply to the nextNr number found
            in the SPEC file.
        :param callback: callback to call when the parsing is done
        """
        super(KmapSpecParser, self).__init__()

        self.__status = None

        self.__set_status(self.UNKNOWN, 'Init')

        self.__results = None

        self.__thread = None

        self.__spec_fname = spec_fname
        self.__spec_h5 = spec_h5
        self.__callback = callback
        self.__img_dir = img_dir
        self.__version = version

        self.__nr_padding = nr_padding
        self.__nr_offset = nr_offset

        self.__set_status(self.READY)

    def __set_status(self, status, msg=None):
Thomas Vincent's avatar
Thomas Vincent committed
136
137
        """Sets the status of this instance.

Damien Naudet's avatar
Damien Naudet committed
138
139
140
141
142
143
144
145
        :param status:
        :param msg:
        """
        assert status in self.__STATUSES
        self.__status = status
        self.__status_msg = msg

    def parse(self, blocking=True):
Thomas Vincent's avatar
Thomas Vincent committed
146
147
        """Starts the parsing.

Damien Naudet's avatar
Damien Naudet committed
148
149
150
151
152
        :param blocking: if False, the parsing will be done in a separate
         thread and this method will return immediately.
        """

        if self.__thread and self.__thread.is_alive():
Thomas Vincent's avatar
Thomas Vincent committed
153
154
            raise RuntimeError(
                'This KmapSpecParser instance is already parsing.')
Damien Naudet's avatar
Damien Naudet committed
155
156
157
158
159
160
161
162
163
164

        self.__results = None

        if blocking:
            self.__run_parse()
        else:
            thread = self.__thread = Thread(target=self.__run_parse)
            thread.start()

    def __run_parse(self):
Thomas Vincent's avatar
Thomas Vincent committed
165
        """Runs the parsing."""
Damien Naudet's avatar
Damien Naudet committed
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

        self.__set_status(self.RUNNING)

        try:
            _spec_to_h5(self.__spec_fname, self.__spec_h5)

            self.__results = _find_scan_img_files(self.__spec_h5,
                                                  img_dir=self.__img_dir,
                                                  version=self.__version,
                                                  nr_padding=self.__nr_padding,
                                                  nr_offset=self.__nr_offset)
            self.__set_status(self.DONE)
        except Exception as ex:
            self.__set_status(self.ERROR, str(ex))

        # TODO : catch exception?
        if self.__callback:
            self.__callback()

    def wait(self):
        """
        Waits until parsing is done, or returns if it is not running.
        :return:
        """
        if self.__thread:
            self.__thread.join()


# #######################################################################
# #######################################################################


def _spec_to_h5(spec_filename, h5_filename):
    """
    Converts a spec file into a HDF5 file.

    :param spec_filename: name of the spec file to convert to HDF5.
    :type spec_filename: str

    :param h5_filename: name of the HDF5 file to create.
    :type h5_filename: str

208
    .. seealso : silx.io.convert.convert
Damien Naudet's avatar
Damien Naudet committed
209
    """
210
211
212
    convert.convert(spec_filename,
                    h5_filename,
                    mode='w')
Damien Naudet's avatar
Damien Naudet committed
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


# ########################################################################
# ########################################################################


def _spec_get_img_filenames(spec_h5_filename):
    """
    Parsed spec scans headers to retrieve the associated image files.

    :param spec_h5_filename: name of the HDF5 file containing spec data.
    :type spec_h5_filename: str

    .. todo : can we suppose that there's
        only one scan per scan number?
        i.e : no 0.2, 1.2, ...
    .. todo : expecting only one imageFile comment line per scan. Is this
        always true?

    :return: 3 elements tuple : a dict containing the scans that have valid
        image file info, a list with the scans that dont have any image files,
        and a list of the scans that have more that one image files.
    :rtype: *list* (*dict*, *list*, *list*)
    """
    with h5py.File(spec_h5_filename, 'r') as h5_f:

        # scans for which a file name was found
        with_file = {}

        # scans for which no file name was found
        without_file = []

        # scans for which more than one file name was found
        # -> this case is not expected/handled atm
        error_scans = []

        # regular expression to find the imagefile line
        regx = re.compile(_IMAGEFILE_LINE_PATTERN)

        for k_scan, v_scan in h5_f.items():
253
254
            header = h5py_read_dataset(
                v_scan['instrument/specfile/scan_header'], decode_ascii=True)
Damien Naudet's avatar
Damien Naudet committed
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
            imgfile_match = [m for line in header
                             if line.startswith('#C imageFile')
                             for m in [regx.match(line.strip())] if m]

            # TODO : provide some more info
            # expecting only one imagefile line per scan
            if len(imgfile_match) > 1:
                error_scans.append(k_scan)
                continue

            # if no imagefile line
            if len(imgfile_match) == 0:
                without_file.append(k_scan)
                continue

            # extracting the named subgroups
            imgfile_grpdict = imgfile_match[0].groupdict()
            with_file[k_scan] = imgfile_grpdict

        return KmapParseResults(img_info=with_file,
                                no_img_info=without_file,
                                error=error_scans,
                                spec_h5=spec_h5_filename)


# ########################################################################
# ########################################################################


def _find_scan_img_files(spec_h5_filename,
                         img_dir=None,
                         version=1,
                         nr_padding=None,
                         nr_offset=None):
    """
    Parses the provided "*spec*" HDF5 file and tries to find the edf file
    associated  with each scans. will look for the files in img_dir if
    provided (instead of looking for the files in the path written
    in the spec file).

    :param spec_h5_filename: name of the HDF5 file containing spec data.
    :type spec_h5_filename: str

    :param img_dir: directory path. If provided the image files will be
        looked for into that folder instead of the one found in the scan
        headers.
    :type img_dir: *optional* str

    :param version: version of the spec file. It is currently used to get
    the offset and padding to apply to the nextNr value found in the spec scan
    headers. This nextNr is then used to generate the image file name. Set it
    to 0 if you are merging data generated before April 2016 (TBC).
    :type img_dir: *optional* int

    :returns: 4 elements tuple : a dict containing the scans whose image file
        has been found, a dict containing the scans that have that have
        valid image file info in the scan header but whose image file has not
        been found, a list with the scans that dont have any image file info,
        and a list of the scans that have more that one image file info line.
    :rtype: *list* (*dict*, *dict*, *list*, *list*)
    """

    if img_dir and not os.path.exists(img_dir):
        raise ValueError('Image folder not found : {0}'
                         ''.format(img_dir))

    imgfile_info = _spec_get_img_filenames(spec_h5_filename)
    with_files = imgfile_info.img_info
    complete_scans = {}
    incomplete_scans = {}

    if version == 0:
        nextnr_ofst = -1
        nextnr_pattern = '{0:0>4}'
    else:
        nextnr_ofst = 0
        nextnr_pattern = '{0:0>5}'

    if nr_padding is not None:
        nextnr_pattern = '{{0:0>{0}}}'.format(nr_padding)

    if nr_offset is not None:
        nextnr_ofst = nr_offset

    if img_dir:
        img_dir = os.path.expanduser(os.path.expandvars(img_dir))

    for scan_id, infos in with_files.items():
        parsed_fname = (infos['prefix'] +
                        nextnr_pattern.format(int(infos['nextNr']) +
                                              nextnr_ofst) +
                        infos['suffix'])
        img_file = None

        if not img_dir:
            parsed_fname = os.path.join(infos['dir'], parsed_fname)
            if os.path.isfile(parsed_fname):
                img_file = parsed_fname
        else:
            edf_fullpath = glob.glob(os.path.join(img_dir, parsed_fname))
            if edf_fullpath:
                img_file = edf_fullpath[0]

        if img_file:
            complete_scans[scan_id] = {'spec': infos, 'image': img_file}
        else:
            incomplete_scans[scan_id] = {'spec': infos, 'image': None}

    result = KmapMatchResults(matched=complete_scans,
                              not_matched=incomplete_scans,
                              no_img_info=imgfile_info.no_img_info,
                              error=imgfile_info.error,
                              spec_h5=spec_h5_filename)

    return result