edfscan.py 21 KB
Newer Older
payno's avatar
payno 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
27
28
29
30
31
32
33
34
35
36
# coding: utf-8
#/*##########################################################################
# Copyright (C) 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.
#
#############################################################################*/


__authors__ = ["H.Payno"]
__license__ = "MIT"
__date__ = "10/10/2019"


import os
import re
import fabio
from lxml import etree
import json
import io
payno's avatar
payno committed
37
from typing import Union
payno's avatar
payno committed
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
from silx.io.url import DataUrl
from ..scanbase import TomoScanBase
from .utils import get_parameters_frm_par_or_info, extract_urls_from_edf
from ..unitsystem import metricsystem
from tomoscan.utils import docstring
import logging

_logger = logging.getLogger(__name__)


class EDFTomoScan(TomoScanBase):
    """
    TomoScanBase instanciation for scan defined from .edf files

    :param scan: path to the root folder containing the scan.
    :type: Union[str,None]
    """
    _TYPE = 'edf'

    INFO_EXT = '.info'

    ABORT_FILE = '.abo'

    _REFHST_PREFIX = 'refHST'

    _DARKHST_PREFIX = 'dark.edf'

    _SCHEME = 'fabio'

payno's avatar
payno committed
67
    def __init__(self, scan: Union[str, None]):
payno's avatar
payno committed
68
69
70
71
        TomoScanBase.__init__(self, scan=scan, type_=self._TYPE)

        # data caches
        self._darks = None
payno's avatar
payno committed
72
73
        self._flats = None
        self._projections = None
payno's avatar
payno committed
74
75
76
77
78
79
80
81
82
83
84
        self.__tomo_n = None
        self.__ref_n = None
        self.__dark_n = None
        self.__dim1 = None
        self.__dim2 = None
        self.__pixel_size = None
        self.__ref_on = None
        self.__scan_range = None

    @docstring(TomoScanBase.tomo_n)
    @property
payno's avatar
payno committed
85
    def tomo_n(self) -> Union[None, int]:
payno's avatar
payno committed
86
87
88
89
90
91
        if self.__tomo_n is None:
            self.__tomo_n = EDFTomoScan.get_tomo_n(scan=self.path)
        return self.__tomo_n

    @property
    @docstring(TomoScanBase.dark_n)
payno's avatar
payno committed
92
    def dark_n(self) -> Union[None, int]:
payno's avatar
payno committed
93
94
95
96
97
98
        if self.__dark_n is None:
            self.__dark_n = EDFTomoScan.get_dark_n(scan=self.path)
        return self.__dark_n

    @property
    @docstring(TomoScanBase.ref_n)
payno's avatar
payno committed
99
    def ref_n(self) -> Union[None, int]:
payno's avatar
payno committed
100
101
102
103
104
105
        if self.__ref_n is None:
            self.__ref_n = EDFTomoScan.get_ref_n(scan=self.path)
        return self.__ref_n

    @property
    @docstring(TomoScanBase.pixel_size)
payno's avatar
payno committed
106
    def pixel_size(self) -> Union[None, int]:
payno's avatar
payno committed
107
108
109
110
111
112
113
114
115
116
117
        """

        :return: pixel size
        :rtype: float
        """
        if self.__pixel_size is None:
            self.__pixel_size = EDFTomoScan.get_pixel_size(scan=self.path)
        return self.__pixel_size

    @property
    @docstring(TomoScanBase.dim_1)
payno's avatar
payno committed
118
    def dim_1(self) -> Union[None, int]:
payno's avatar
payno committed
119
120
121
122
123
124
125
126
127
128
129
        """

        :return: image dim1
        :rtype: int
        """
        if self.__dim1 is None:
            self.__dim1, self.__dim2 = EDFTomoScan.get_dim1_dim2(scan=self.path)
        return self.__dim1

    @property
    @docstring(TomoScanBase.dim_2)
payno's avatar
payno committed
130
    def dim_2(self) -> Union[None, int]:
payno's avatar
payno committed
131
132
133
134
135
136
137
138
139
140
        """

        :return: image dim2
        :rtype: int
        """
        if self.__dim2 is None:
            self.__dim1, self.__dim2 = EDFTomoScan.get_dim1_dim2(scan=self.path)
        return self.__dim2

    @property
payno's avatar
payno committed
141
142
    @docstring(TomoScanBase.ff_interval)
    def ff_interval(self) -> Union[None, int]:
payno's avatar
payno committed
143
144
145
146
147
148
        if self.__ref_on is None:
            self.__ref_on = EDFTomoScan.get_ff_interval(scan=self.path)
        return self.__ref_on

    @property
    @docstring(TomoScanBase.scan_range)
payno's avatar
payno committed
149
    def scan_range(self) -> Union[None, int]:
payno's avatar
payno committed
150
151
152
153
154
155
        if self.__scan_range is None:
            self.__scan_range = EDFTomoScan.get_scan_range(scan=self.path)
        return self.__scan_range

    @property
    @docstring(TomoScanBase.flats)
payno's avatar
payno committed
156
157
158
159
160
161
162
    def flats(self) -> Union[None, dict]:
        """
        flats are given as a dictionary with index as key and DataUrl as
        value"""
        if self._flats is None:
            self._flats = self.get_refs_url(scan_path=self.path)
        return self._flats
payno's avatar
payno committed
163
164
165

    @docstring(TomoScanBase.is_tomoscan_dir)
    @staticmethod
payno's avatar
payno committed
166
    def is_tomoscan_dir(directory: str, **kwargs) -> bool:
payno's avatar
payno committed
167
168
169
170
        return os.path.isfile(EDFTomoScan.get_info_file(directory=directory,
                                                        kwargs=kwargs))

    @staticmethod
payno's avatar
payno committed
171
    def get_info_file(directory: str, **kwargs) -> str:
payno's avatar
payno committed
172
173
174
175
176
177
178
        basename = os.path.basename(directory)
        assert basename != ''
        info_file = os.path.join(directory, basename + EDFTomoScan.INFO_EXT)

        if 'src_pattern' in kwargs and kwargs['srx_pattern'] is not None:
            assert 'dest_pattern' in kwargs
            info_file = info_file.replace(kwargs['src_pattern'],
payno's avatar
payno committed
179
180
                                          kwargs['dest_pattern'],
                                          1)
payno's avatar
payno committed
181
182
183
        return info_file

    @docstring(TomoScanBase.is_abort)
payno's avatar
payno committed
184
    def is_abort(self,  **kwargs) -> bool:
payno's avatar
payno committed
185
186
187
188
189
190
191
192
193
194
        abort_file = os.path.basename(self.path) + self.ABORT_FILE
        abort_file = os.path.join(self.path, abort_file)
        if 'src_pattern' in kwargs and kwargs['src_pattern' is not None]:
            assert 'dest_pattern' in kwargs
            abort_file = abort_file.replace(kwargs['src_pattern'],
                                            kwargs['dest_pattern'])
        return os.path.isfile(abort_file)

    @property
    @docstring(TomoScanBase.darks)
payno's avatar
payno committed
195
    def darks(self) -> dict:
payno's avatar
payno committed
196
197
198
199
        if self._darks is None:
            self._darks = self.get_darks_url(scan_path=self.path)
        return self._darks

payno's avatar
payno committed
200
201
    @docstring(TomoScanBase.get_proj_angle_url)
    def get_proj_angle_url(self) -> dict:
payno's avatar
payno committed
202
203
204
205
206
        # TODO: we might use fabio.open_serie instead
        if self.path is None:
            _logger.warning('no path specified for scan, unable to retrieve'
                            ' the projections')
            return {}
payno's avatar
payno committed
207
        n_projection = self.tomo_n
payno's avatar
payno committed
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
        radios = EDFTomoScan.get_proj_paths(self.path)
        sorted_keys = list(radios.keys())
        sorted_keys.sort()

        data_urls = []
        # create one DataUrl per projection
        for key in sorted_keys:
            radio = radios[key]
            edf_reader = fabio.open(radio)
            if edf_reader.nframes is 1:
                data_urls.append(DataUrl(file_path=radio, scheme='fabio'))
            else:
                data_urls.extend(extract_urls_from_edf(file_=radio))

        if n_projection is None:
            raise ValueError('unable to get n projection')
        if len(data_urls) < n_projection:
            mes = 'incoherence between the number of projection found (%s)' \
                  'and the number of theoretical projection (%s). Maybe the ' \
                  'acquisition is not complete ?' % (len(data_urls), n_projection)
            _logger.warning(mes)

        return TomoScanBase.map_urls_on_scan_range(urls=data_urls,
                                                   n_projection=n_projection,
                                                   scan_range=self.scan_range)

    @docstring(TomoScanBase.update)
    def update(self):
payno's avatar
payno committed
236
        self.projections = EDFTomoScan.get_proj_angle_url(self.path)
payno's avatar
payno committed
237
        self._darks = EDFTomoScan.get_darks_url(self.path)
payno's avatar
payno committed
238
        self._flats = EDFTomoScan.get_refs_url(self.path)
payno's avatar
payno committed
239
240

    @docstring(TomoScanBase.load_from_dict)
payno's avatar
payno committed
241
    def load_from_dict(self, desc: Union[dict, io.TextIOWrapper]):
payno's avatar
payno committed
242
243
244
245
246
247
248
249
250
251
252
253
        if isinstance(desc, io.TextIOWrapper):
            data = json.load(desc)
        else:
            data = desc
        if not (self._DICT_TYPE_KEY in data and data[self._DICT_TYPE_KEY] == self._TYPE):
            raise ValueError('Description is not an EDFScan json description')

        assert self._DICT_PATH_KEY in data
        self.path = data[self._DICT_PATH_KEY]
        return self

    @staticmethod
payno's avatar
payno committed
254
    def get_proj_paths(scan: str) -> dict:
payno's avatar
payno committed
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
        """
        Return the dict of radios / projection for the given scan.
        Keys of the dictionary is the slice number
        Return all the file on the root of scan starting by the name of scan and
        ending by .edf

        :param scan: is the path to the folder of acquisition
        :type: str
        :return: dict of radios files with radio index as key and file as value
        :rtype: dict
        """
        files = dict({})
        if(scan is None) or not(os.path.isdir(scan)):
            return files

        if os.path.isdir(scan):
            for f in os.listdir(scan):
                if EDFTomoScan.is_a_proj_path(f, scan):
                    gfile = os.path.join(scan, f)
payno's avatar
payno committed
274
275
276
                    index = EDFTomoScan.guess_index_frm_file_name(gfile)
                    files.update(extract_urls_from_edf(start_index=index,
                                                       file_=gfile))
payno's avatar
payno committed
277
278
279
280

        return files

    @staticmethod
payno's avatar
payno committed
281
    def is_a_proj_path(fileName: str, scanID: str) -> bool:
payno's avatar
payno committed
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
        """Return True if the given fileName can fit to a Radio name
        """
        fileBasename = os.path.basename(fileName)
        folderBasename = os.path.basename(scanID)

        if fileBasename.endswith(".edf") and fileBasename.startswith(folderBasename):
            localstring = fileName.rstrip('.edf')
            # remove the scan
            localstring = re.sub(folderBasename, '', localstring)
            if 'slice_' in localstring:
                # case of a reconstructed file
                return False
            if 'refHST' in localstring:
                return False
            s = localstring.split('_')
            if s[-1].isdigit():
                # check that the next value is a digit
                return True

        return False

    @staticmethod
payno's avatar
payno committed
304
    def guess_index_frm_file_name(_file: str) -> Union[None, int]:
payno's avatar
payno committed
305
306
307
308
309
310
311
312
313
314
315
316
317
        name = _file.rstrip('.edf')
        ic = []
        while name[-1].isdigit():
            ic.append(name[-1])
            name = name[:-1]

        if len(ic) is 0:
            return None
        else:
            orignalOrder = ic[::-1]
            return int(''.join(orignalOrder))

    @staticmethod
payno's avatar
payno committed
318
    def get_tomo_n(scan: str) -> Union[None, int]:
payno's avatar
payno committed
319
320
321
322
323
324
325
        return EDFTomoScan.retrieve_information(scan=os.path.abspath(scan),
                                                ref_file=None,
                                                key='TOMO_N',
                                                type_=int,
                                                key_aliases=['tomo_N', 'Tomo_N'])

    @staticmethod
payno's avatar
payno committed
326
    def get_dark_n(scan:str) -> Union[None, int]:
payno's avatar
payno committed
327
328
329
330
331
332
333
        return EDFTomoScan.retrieve_information(scan=os.path.abspath(scan),
                                                ref_file=None,
                                                key='DARK_N',
                                                type_=int,
                                                key_aliases=['dark_N', ])

    @staticmethod
payno's avatar
payno committed
334
    def get_ref_n(scan :str) -> Union[None, int]:
payno's avatar
payno committed
335
336
337
338
339
340
341
        return EDFTomoScan.retrieve_information(scan=os.path.abspath(scan),
                                                ref_file=None,
                                                key='REF_N',
                                                type_=int,
                                                key_aliases=['ref_N', ])

    @staticmethod
payno's avatar
payno committed
342
    def get_ff_interval(scan: str) -> Union[None, int]:
payno's avatar
payno committed
343
344
345
346
347
348
349
        return EDFTomoScan.retrieve_information(scan=os.path.abspath(scan),
                                                ref_file=None,
                                                key='REF_ON',
                                                type_=int,
                                                key_aliases=['ref_On', ])

    @staticmethod
payno's avatar
payno committed
350
    def get_scan_range(scan: str) -> Union[None, int]:
payno's avatar
payno committed
351
352
353
354
355
356
357
        return EDFTomoScan.retrieve_information(scan=os.path.abspath(scan),
                                                ref_file=None,
                                                key='ScanRange',
                                                type_=int,
                                                key_aliases=['scanRange', ])

    @staticmethod
payno's avatar
payno committed
358
    def get_dim1_dim2(scan: str) -> Union[None, tuple]:
payno's avatar
payno committed
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
        _info_file = os.path.join(scan, os.path.basename(scan) + '.info')
        d1 = EDFTomoScan.retrieve_information(scan=os.path.abspath(scan),
                                              ref_file=None,
                                              key='Dim_1',
                                              key_aliases=['projectionSize/DIM_1'],
                                              type_=int)
        d2 = EDFTomoScan.retrieve_information(scan=os.path.abspath(scan),
                                              ref_file=None,
                                              key='Dim_2',
                                              key_aliases=['projectionSize/DIM_2'],
                                              type_=int)

        return d1, d2

    @staticmethod
payno's avatar
payno committed
374
    def get_pixel_size(scan: str) -> Union[None, int]:
payno's avatar
payno committed
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
        if os.path.isdir(scan) is False:
            return None
        value = EDFTomoScan.retrieve_information(scan=scan,
                                                 ref_file=None,
                                                 key='PixelSize',
                                                 type_=float,
                                                 key_aliases=['pixelSize', ])
        if value is None:
            parFile = os.path.join(scan, os.path.basename(scan) + '.par')
            if os.path.exists(parFile):
                try:
                    ddict = get_parameters_frm_par_or_info(parFile)
                except ValueError as e:
                    _logger.error(e)
                if 'IMAGE_PIXEL_SIZE_1'.lower() in ddict:
                    value = float(ddict['IMAGE_PIXEL_SIZE_1'.lower()])
        # for now pixel size are stored in microns.
        # We want to return them in meter
        if value is not None:
            return value * metricsystem.micrometer
        else:
            return None

    @staticmethod
payno's avatar
payno committed
399
400
    def get_darks_url(scan_path: str, prefix: str='dark',
                      file_ext: str='.edf') -> dict:
payno's avatar
payno committed
401
402
403
404
405
406
407
408
409
410
        """

        :param scan_path:
        :type: str
        :param prefix: ref / flat field file prefix
        :type: str
        :param file_ext: ref / flat field file extension
        :type: str
        :return: list of refs as silx's `DataUrl`
        """
payno's avatar
payno committed
411
        res = {}
payno's avatar
payno committed
412
413
414
415
        if os.path.isdir(scan_path) is False:
            _logger.error(scan_path + ' is not a directory. Cannot extract '
                                     'DarkHST files')
            return res
payno's avatar
payno committed
416
        for file_ in os.listdir(scan_path):
payno's avatar
payno committed
417
418
419
            _prefix = prefix
            if prefix.endswith(file_ext):
                _prefix = prefix.rstrip(file_ext)
payno's avatar
payno committed
420
421
422
423
424
425
426
427
428
            if file_.startswith(_prefix) and file_.endswith(file_ext):
                # usuelly the dark file name should be dark.edf, but some
                # darkHSTXXXX remains...
                file_fp = file_.lstrip(_prefix).rstrip(file_ext).lstrip('HST')
                if file_fp == '' or file_fp.isnumeric() is True:
                    index = EDFTomoScan.guess_index_frm_file_name(file_)
                    urls = extract_urls_from_edf(os.path.join(scan_path, file_),
                                                 start_index=index)
                    res.update(urls)
payno's avatar
payno committed
429
430
431
        return res

    @staticmethod
payno's avatar
payno committed
432
433
    def get_refs_url(scan_path: str,  prefix: str='refHST',
                     file_ext: str='.edf') -> dict:
payno's avatar
payno committed
434
435
436
437
438
439
440
441
442
443
        """

        :param scan_path:
        :type: str
        :param prefix: ref / flat field file prefix
        :type: str
        :param file_ext: ref / flat field file extension
        :type: str
        :return: list of refs as silx's `DataUrl`
        """
payno's avatar
payno committed
444
        res = {}
payno's avatar
payno committed
445
446
447
448
449
        if os.path.isdir(scan_path) is False:
            _logger.error(scan_path + ' is not a directory. Cannot extract '
                                      'RefHST files')
            return res

payno's avatar
payno committed
450
451
452
453
454
455
        for file_ in os.listdir(scan_path):
            if file_.startswith(prefix) and file_.endswith(file_ext):
                index = EDFTomoScan.guess_index_frm_file_name(file_)
                file_fp = os.path.join(scan_path, file_)
                urls = extract_urls_from_edf(start_index=index, file_=file_fp)
                res.update(urls)
payno's avatar
payno committed
456
457
458
        return res

    @staticmethod
payno's avatar
payno committed
459
460
461
    def retrieve_information(scan: str, ref_file: Union[str, None], key: str,
                             type_: type,
                             key_aliases: Union[list, tuple, None] = None):
payno's avatar
payno committed
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
        """
        Try to retrieve information a .info file, an .xml or a flat field file.
        
        file.
        Look for the key 'key' or one of it aliases.

        :param scan: root folder of an acquisition. Must be an absolute path
        :param ref_file: the refXXXX_YYYY which should contain information
                         about the scan.
        :param key: the key (information) we are looking for
        :type: str
        :param type_: requestde out type if the information is found
        :type type_: return type if the information is found.
        :param key_aliases: aliases of the key in the different file
        :type: list
        :return: the requested information or None if not found
        """
        info_aliases = [key]
        if key_aliases is not None:
            assert type(key_aliases) in (tuple, list)
            [info_aliases.append(alias) for alias in key_aliases]

        if not os.path.isdir(scan):
            return None

        # 1st look for ref file if any given
        def parseRefFile(filePath):
            header = fabio.open(filePath).header
            for k in key_aliases:
                if k in header:
                    return type_(header[k])
            return None

        if ref_file is not None and os.path.isfile(ref_file):
            try:
                info = parseRefFile(ref_file)
            except IOError as e:
                _logger.warning(e)
            else:
                if info is not None:
                    return info

        # 2nd look for .info file
        def parseInfoFile(filePath):
            def extractInformation(text, alias):
                text = text.replace(alias, '')
                text = text.replace('\n', '')
                text = text.replace(' ', '')
                text = text.replace('=', '')
                return type_(text)

            info = None
            f = open(filePath, "r")
            line = f.readline()
            while line:
                for alias in info_aliases:
                    if alias in line:
                        info = extractInformation(line, alias)
                        break
                line = f.readline()
            f.close()
            return info

        baseName = os.path.basename(scan)
        infoFiles = [os.path.join(scan, baseName + '.info')]
        infoOnDataVisitor = infoFiles[0].replace('lbsram', '')
        # hack to check in lbsram, would need to be removed to add some consistency
        if os.path.isfile(infoOnDataVisitor):
            infoFiles.append(infoOnDataVisitor)
        for infoFile in infoFiles:
            if os.path.isfile(infoFile) is True:
                info = parseInfoFile(infoFile)
                if info is not None:
                    return info

        # 3td look for xml files
        def parseXMLFile(filePath):
            try:
                for alias in info_aliases:
                    tree = etree.parse(filePath)
                    elmt = tree.find("acquisition/" + alias)
                    if elmt is None:
                        continue
                    else:
                        info = type_(elmt.text)
                        if info == -1:
                            return None
                        else:
                            return info
            except etree.XMLSyntaxError as e:
                _logger.warning(e)
                return None

        xmlFiles = [os.path.join(scan, baseName + '.xml')]
        xmlOnDataVisitor = xmlFiles[0].replace('lbsram', '')
        # hack to check in lbsram, would need to be removed to add some consistency
        if os.path.isfile(xmlOnDataVisitor):
            xmlFiles.append(xmlOnDataVisitor)
        for xmlFile in xmlFiles:
            if os.path.isfile(xmlFile) is True:
                info = parseXMLFile(xmlFile)
                if info is not None:
                    return info

        return None