edfscan.py 25.7 KB
Newer Older
payno's avatar
payno committed
1
# coding: utf-8
payno's avatar
payno committed
2
# /*##########################################################################
payno's avatar
payno committed
3
# Copyright (C) 2016-2020 European Synchrotron Radiation Facility
payno's avatar
payno committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#
# 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.
#
#############################################################################*/

payno's avatar
payno committed
25
26
"""contains EDFTomoScan, class to be used with EDF acquisition"""

payno's avatar
payno committed
27
28
29
30
31
32
33
34
35

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


import os
import re
import fabio
36
import copy
payno's avatar
payno committed
37
38
39
from lxml import etree
import json
import io
Pierre Paleo's avatar
Pierre Paleo committed
40
from typing import Union, Iterable
payno's avatar
payno committed
41
42
from ..scanbase import TomoScanBase
from .utils import get_parameters_frm_par_or_info, extract_urls_from_edf
43
from ..unitsystem.metricsystem import MetricSystem
Pierre Paleo's avatar
Pierre Paleo committed
44
from ..utils import docstring
payno's avatar
payno committed
45
46
47
48
49
50
51
52
53
54
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.
payno's avatar
payno committed
55
    :type scan: Union[str,None]
56
57
    :param n_frames: Number of frames in each EDF file.
        If not provided, it will be inferred by reading the files.
58
        In this case, the frame number is guessed from the file name.
payno's avatar
payno committed
59
    :type n_frames: Union[int, None]=None
payno's avatar
payno committed
60
61
    """

payno's avatar
payno committed
62
    _TYPE = "edf"
payno's avatar
payno committed
63

payno's avatar
payno committed
64
    INFO_EXT = ".info"
payno's avatar
payno committed
65

payno's avatar
payno committed
66
    ABORT_FILE = ".abo"
payno's avatar
payno committed
67

payno's avatar
payno committed
68
    _REFHST_PREFIX = "refHST"
payno's avatar
payno committed
69

payno's avatar
payno committed
70
    _DARKHST_PREFIX = "dark.edf"
payno's avatar
payno committed
71

payno's avatar
payno committed
72
73
    _SCHEME = "fabio"

74
75
76
77
    def __init__(
        self,
        scan: Union[str, None],
        n_frames: Union[int, None] = None,
Pierre Paleo's avatar
Pierre Paleo committed
78
        ignore_projections: Union[None, Iterable] = None,
79
80
81
82
    ):
        TomoScanBase.__init__(
            self, scan=scan, type_=self._TYPE, ignore_projections=ignore_projections
        )
payno's avatar
payno committed
83
84
85

        # data caches
        self._darks = None
payno's avatar
payno committed
86
        self._flats = None
payno's avatar
payno committed
87
88
89
90
91
92
93
94
        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
95
        self._edf_n_frames = n_frames
Pierre Paleo's avatar
Pierre Paleo committed
96
        self.__distance = None
97
        self.__energy = None
payno's avatar
payno committed
98
        self.__estimated_cor_frm_motor = None
99
        self.update()
payno's avatar
payno committed
100

101
102
    @docstring(TomoScanBase.clear_caches)
    def clear_caches(self):
payno's avatar
payno committed
103
        super().clear_caches()
104
105
106
107
108
109
110
111
112
113
114
115
        self._darks = None
        self._flats = None
        self._projections = None
        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

payno's avatar
payno committed
116
117
    @docstring(TomoScanBase.tomo_n)
    @property
payno's avatar
payno committed
118
    def tomo_n(self) -> Union[None, int]:
payno's avatar
payno committed
119
120
121
122
123
124
        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
125
    def dark_n(self) -> Union[None, int]:
payno's avatar
payno committed
126
127
128
129
130
131
        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
132
    def ref_n(self) -> Union[None, int]:
payno's avatar
payno committed
133
134
135
136
137
138
        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
139
    def pixel_size(self) -> Union[None, int]:
payno's avatar
payno committed
140
141
142
143
144
145
        """

        :return: pixel size
        :rtype: float
        """
        if self.__pixel_size is None:
146
            self.__pixel_size = EDFTomoScan._get_pixel_size(scan=self.path)
payno's avatar
payno committed
147
148
149
150
        return self.__pixel_size

    @property
    @docstring(TomoScanBase.dim_1)
payno's avatar
payno committed
151
    def dim_1(self) -> Union[None, int]:
payno's avatar
payno committed
152
153
154
155
156
        """

        :return: image dim1
        :rtype: int
        """
157
        if self.__dim1 is None and self.path is not None:
payno's avatar
payno committed
158
159
160
161
162
            self.__dim1, self.__dim2 = EDFTomoScan.get_dim1_dim2(scan=self.path)
        return self.__dim1

    @property
    @docstring(TomoScanBase.dim_2)
payno's avatar
payno committed
163
    def dim_2(self) -> Union[None, int]:
payno's avatar
payno committed
164
165
166
167
168
        """

        :return: image dim2
        :rtype: int
        """
169
        if self.__dim2 is None and self.path is not None:
payno's avatar
payno committed
170
171
172
            self.__dim1, self.__dim2 = EDFTomoScan.get_dim1_dim2(scan=self.path)
        return self.__dim2

173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
    @property
    @docstring(TomoScanBase.x_translation)
    def x_translation(self) -> Union[None, tuple]:
        raise NotImplementedError("Not supported for EDF")

    @property
    @docstring(TomoScanBase.y_translation)
    def y_translation(self) -> Union[None, tuple]:
        raise NotImplementedError("Not supported for EDF")

    @property
    @docstring(TomoScanBase.z_translation)
    def z_translation(self) -> Union[None, tuple]:
        raise NotImplementedError("Not supported for EDF")

payno's avatar
payno committed
188
    @property
payno's avatar
payno committed
189
190
    @docstring(TomoScanBase.ff_interval)
    def ff_interval(self) -> Union[None, int]:
191
        if self.__ref_on is None and self.path is not None:
payno's avatar
payno committed
192
193
194
195
196
            self.__ref_on = EDFTomoScan.get_ff_interval(scan=self.path)
        return self.__ref_on

    @property
    @docstring(TomoScanBase.scan_range)
payno's avatar
payno committed
197
    def scan_range(self) -> Union[None, int]:
198
        if self.__scan_range is None and self.path is not None:
payno's avatar
payno committed
199
200
201
202
203
            self.__scan_range = EDFTomoScan.get_scan_range(scan=self.path)
        return self.__scan_range

    @property
    @docstring(TomoScanBase.flats)
payno's avatar
payno committed
204
205
206
207
    def flats(self) -> Union[None, dict]:
        """
        flats are given as a dictionary with index as key and DataUrl as
        value"""
208
        if self._flats is None and self.path is not None:
payno's avatar
payno committed
209
210
            self._flats = self.get_refs_url(scan_path=self.path)
        return self._flats
payno's avatar
payno committed
211
212
213

    @docstring(TomoScanBase.is_tomoscan_dir)
    @staticmethod
payno's avatar
payno committed
214
    def is_tomoscan_dir(directory: str, **kwargs) -> bool:
payno's avatar
payno committed
215
216
217
        return os.path.isfile(
            EDFTomoScan.get_info_file(directory=directory, kwargs=kwargs)
        )
payno's avatar
payno committed
218
219

    @staticmethod
payno's avatar
payno committed
220
    def get_info_file(directory: str, **kwargs) -> str:
payno's avatar
payno committed
221
        basename = os.path.basename(directory)
payno's avatar
payno committed
222
        assert basename != ""
payno's avatar
payno committed
223
224
        info_file = os.path.join(directory, basename + EDFTomoScan.INFO_EXT)

payno's avatar
payno committed
225
226
227
228
229
        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"], kwargs["dest_pattern"], 1
            )
payno's avatar
payno committed
230
231
232
        return info_file

    @docstring(TomoScanBase.is_abort)
payno's avatar
payno committed
233
    def is_abort(self, **kwargs) -> bool:
payno's avatar
payno committed
234
235
        abort_file = os.path.basename(self.path) + self.ABORT_FILE
        abort_file = os.path.join(self.path, abort_file)
payno's avatar
payno committed
236
237
238
239
240
        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"]
            )
payno's avatar
payno committed
241
242
243
244
        return os.path.isfile(abort_file)

    @property
    @docstring(TomoScanBase.darks)
payno's avatar
payno committed
245
    def darks(self) -> dict:
246
        if self._darks is None and self.path is not None:
payno's avatar
payno committed
247
248
249
            self._darks = self.get_darks_url(scan_path=self.path)
        return self._darks

payno's avatar
payno committed
250
251
    @docstring(TomoScanBase.get_proj_angle_url)
    def get_proj_angle_url(self) -> dict:
payno's avatar
payno committed
252
253
        # TODO: we might use fabio.open_serie instead
        if self.path is None:
payno's avatar
payno committed
254
255
256
            _logger.warning(
                "no path specified for scan, unable to retrieve" " the projections"
            )
payno's avatar
payno committed
257
            return {}
payno's avatar
payno committed
258
        n_projection = self.tomo_n
259
        data_urls = EDFTomoScan.get_proj_urls(self.path)
payno's avatar
payno committed
260
261
262
        return TomoScanBase.map_urls_on_scan_range(
            urls=data_urls, n_projection=n_projection, scan_range=self.scan_range
        )
payno's avatar
payno committed
263
264
265

    @docstring(TomoScanBase.update)
    def update(self):
266
        if self.path is not None:
payno's avatar
payno committed
267
            all_projections = EDFTomoScan.get_proj_urls(
payno's avatar
payno committed
268
269
                self.path, n_frames=self._edf_n_frames
            )
payno's avatar
payno committed
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286

            def select_proj(ddict, from_, to_):
                indexes = sorted(set(ddict.keys()))
                sel_indexes = indexes[from_:to_]
                res = {}
                for index in sel_indexes:
                    res[index] = ddict[index]
                return res

            if self.tomo_n is not None and len(all_projections) > self.tomo_n:
                self._projections = select_proj(all_projections, 0, self.tomo_n)
                self._alignment_projections = select_proj(
                    all_projections, self.tomo_n, None
                )
            else:
                self._projections = all_projections
                self._alignment_projections = {}
Pierre Paleo's avatar
Pierre Paleo committed
287
288
            if self.ignore_projections is not None:
                for idx in self.ignore_projections:
289
                    self._projections.pop(idx, None)
payno's avatar
payno committed
290

291
292
            self._darks = EDFTomoScan.get_darks_url(self.path)
            self._flats = EDFTomoScan.get_refs_url(self.path)
payno's avatar
payno committed
293
294

    @docstring(TomoScanBase.load_from_dict)
payno's avatar
payno committed
295
    def load_from_dict(self, desc: Union[dict, io.TextIOWrapper]):
payno's avatar
payno committed
296
297
298
299
        if isinstance(desc, io.TextIOWrapper):
            data = json.load(desc)
        else:
            data = desc
300
        if not (self.DICT_TYPE_KEY in data and data[self.DICT_TYPE_KEY] == self._TYPE):
payno's avatar
payno committed
301
            raise ValueError("Description is not an EDFScan json description")
payno's avatar
payno committed
302

303
304
        assert self.DICT_PATH_KEY in data
        self.path = data[self.DICT_PATH_KEY]
payno's avatar
payno committed
305
306
307
        return self

    @staticmethod
payno's avatar
payno committed
308
    def get_proj_urls(scan: str, n_frames: Union[int, None] = None) -> dict:
payno's avatar
payno committed
309
310
311
312
313
314
315
        """
        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
payno's avatar
payno committed
316
        :type scan: str
Pierre Paleo's avatar
Pierre Paleo committed
317
        :param n_frames: Number of frames in each EDF file.
318
            If not provided, it is inferred by reading each file.
payno's avatar
payno committed
319
        :type n_frames: int
payno's avatar
payno committed
320
321
322
        :return: dict of radios files with radio index as key and file as value
        :rtype: dict
        """
323
        urls = dict({})
payno's avatar
payno committed
324
        if (scan is None) or not (os.path.isdir(scan)):
325
            return urls
payno's avatar
payno committed
326
327
328

        if os.path.isdir(scan):
            for f in os.listdir(scan):
329
                if EDFTomoScan.is_a_proj_path(fileName=f, scanID=scan):
payno's avatar
payno committed
330
                    gfile = os.path.join(scan, f)
payno's avatar
payno committed
331
332
333
334
335
336
337
338
                    index = EDFTomoScan.guess_index_frm_file_name(
                        gfile, basename=os.path.basename(scan)
                    )
                    urls.update(
                        extract_urls_from_edf(
                            start_index=index, file_=gfile, n_frames=n_frames
                        )
                    )
payno's avatar
payno committed
339

340
        return urls
payno's avatar
payno committed
341
342

    @staticmethod
payno's avatar
payno committed
343
    def is_a_proj_path(fileName: str, scanID: str) -> bool:
payno's avatar
payno committed
344
        """Return True if the given fileName can fit to a Radio name"""
payno's avatar
payno committed
345
346
347
348
        fileBasename = os.path.basename(fileName)
        folderBasename = os.path.basename(scanID)

        if fileBasename.endswith(".edf") and fileBasename.startswith(folderBasename):
payno's avatar
payno committed
349
            localstring = fileName.rstrip(".edf")
payno's avatar
payno committed
350
            # remove the scan
payno's avatar
payno committed
351
352
            localstring = re.sub(folderBasename, "", localstring)
            if "slice_" in localstring:
payno's avatar
payno committed
353
354
                # case of a reconstructed file
                return False
payno's avatar
payno committed
355
            if "refHST" in localstring:
payno's avatar
payno committed
356
                return False
payno's avatar
payno committed
357
            s = localstring.split("_")
payno's avatar
payno committed
358
359
360
361
362
363
364
            if s[-1].isdigit():
                # check that the next value is a digit
                return True

        return False

    @staticmethod
365
366
367
368
369
370
371
372
373
374
375
376
    def guess_index_frm_file_name(_file: str, basename: str) -> Union[None, int]:
        """
        Guess the index of the file. Index is most of the an integer but can be
        a float for 'ref' for example if several are taken.

        :param _file:
        :param basename:
        """

        def extract_index(my_str, type_):
            res = []
            modified_str = copy.copy(my_str)
377
            while modified_str != "" and modified_str[-1].isdigit():
378
379
380
381
382
383
384
                res.append(modified_str[-1])
                modified_str = modified_str[:-1]
            if len(res) == 0:
                return None, modified_str
            else:
                orignalOrder = res[::-1]
                if type_ is int:
payno's avatar
payno committed
385
                    return int("".join(orignalOrder)), modified_str
386
                else:
payno's avatar
payno committed
387
388
                    return float(".".join(("0", "".join(orignalOrder)))), modified_str

389
        _file = os.path.basename(_file)
payno's avatar
payno committed
390
391
392
        if _file.endswith(".edf"):
            name = _file.replace(basename, "", 1)
            name = name.rstrip(".edf")
393
394

            part_1, name = extract_index(name, type_=int)
payno's avatar
payno committed
395
396
            if name.endswith("_"):
                name = name.rstrip("_")
397
398
399
400
                part_2, name = extract_index(name, type_=float)
            else:
                part_2 = None

401
402
            if part_1 is None:
                return None
403
            if part_2 is None:
404
405
406
407
                if part_1 is None:
                    return None
                else:
                    return int(part_1)
408
409
            else:
                return float(part_1) + part_2
payno's avatar
payno committed
410
        else:
payno's avatar
payno committed
411
            raise ValueError("only edf files are managed")
payno's avatar
payno committed
412
413

    @staticmethod
payno's avatar
payno committed
414
    def get_tomo_n(scan: str) -> Union[None, int]:
payno's avatar
payno committed
415
416
417
418
419
420
421
        return EDFTomoScan.retrieve_information(
            scan=os.path.abspath(scan),
            ref_file=None,
            key="TOMO_N",
            type_=int,
            key_aliases=["tomo_N", "Tomo_N"],
        )
payno's avatar
payno committed
422
423

    @staticmethod
payno's avatar
payno committed
424
425
426
427
428
429
430
431
432
433
    def get_dark_n(scan: str) -> Union[None, int]:
        return EDFTomoScan.retrieve_information(
            scan=os.path.abspath(scan),
            ref_file=None,
            key="DARK_N",
            type_=int,
            key_aliases=[
                "dark_N",
            ],
        )
payno's avatar
payno committed
434
435

    @staticmethod
payno's avatar
payno committed
436
437
438
439
440
441
442
443
444
445
    def get_ref_n(scan: str) -> Union[None, int]:
        return EDFTomoScan.retrieve_information(
            scan=os.path.abspath(scan),
            ref_file=None,
            key="REF_N",
            type_=int,
            key_aliases=[
                "ref_N",
            ],
        )
payno's avatar
payno committed
446
447

    @staticmethod
payno's avatar
payno committed
448
    def get_ff_interval(scan: str) -> Union[None, int]:
payno's avatar
payno committed
449
450
451
452
453
454
455
456
457
        return EDFTomoScan.retrieve_information(
            scan=os.path.abspath(scan),
            ref_file=None,
            key="REF_ON",
            type_=int,
            key_aliases=[
                "ref_On",
            ],
        )
payno's avatar
payno committed
458
459

    @staticmethod
payno's avatar
payno committed
460
    def get_scan_range(scan: str) -> Union[None, int]:
payno's avatar
payno committed
461
462
463
464
465
466
467
468
469
        return EDFTomoScan.retrieve_information(
            scan=os.path.abspath(scan),
            ref_file=None,
            key="ScanRange",
            type_=int,
            key_aliases=[
                "scanRange",
            ],
        )
payno's avatar
payno committed
470
471

    @staticmethod
payno's avatar
payno committed
472
    def get_dim1_dim2(scan: str) -> Union[None, tuple]:
payno's avatar
payno committed
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
        _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,
        )
payno's avatar
payno committed
488
489
490

        return d1, d2

payno's avatar
payno committed
491
492
493
494
    @property
    @docstring(TomoScanBase.distance)
    def distance(self) -> Union[None, float]:
        if self.__distance is None:
payno's avatar
payno committed
495
496
497
            self.__distance = EDFTomoScan.retrieve_information(
                self.path, None, "Distance", type_=float, key_aliases=("distance",)
            )
payno's avatar
payno committed
498
499
500
        if self.__distance is None:
            return None
        else:
501
            return self.__distance * MetricSystem.MILLIMETER.value
payno's avatar
payno committed
502

payno's avatar
payno committed
503
    @property
payno's avatar
payno committed
504
    @docstring(TomoScanBase.field_of_view)
payno's avatar
payno committed
505
    def field_of_view(self):
payno's avatar
payno committed
506
507
        # not managed for EDF files
        return None
payno's avatar
payno committed
508

payno's avatar
payno committed
509
510
511
    @property
    @docstring(TomoScanBase.estimated_cor_frm_motor)
    def estimated_cor_frm_motor(self):
payno's avatar
payno committed
512
513
514
        # not managed for EDF files
        return None

payno's avatar
payno committed
515
516
517
518
    @property
    @docstring(TomoScanBase.energy)
    def energy(self):
        if self.__energy is None:
payno's avatar
payno committed
519
520
521
            self.__energy = EDFTomoScan.retrieve_information(
                self.path, None, "Energy", type_=float, key_aliases=("energy",)
            )
payno's avatar
payno committed
522
523
        return self.__energy

payno's avatar
payno committed
524
    @staticmethod
payno's avatar
payno committed
525
    def _get_pixel_size(scan: str) -> Union[None, float]:
payno's avatar
payno committed
526
527
        if os.path.isdir(scan) is False:
            return None
payno's avatar
payno committed
528
529
530
531
532
533
534
535
536
        value = EDFTomoScan.retrieve_information(
            scan=scan,
            ref_file=None,
            key="PixelSize",
            type_=float,
            key_aliases=[
                "pixelSize",
            ],
        )
payno's avatar
payno committed
537
        if value is None:
payno's avatar
payno committed
538
            parFile = os.path.join(scan, os.path.basename(scan) + ".par")
payno's avatar
payno committed
539
540
541
542
543
            if os.path.exists(parFile):
                try:
                    ddict = get_parameters_frm_par_or_info(parFile)
                except ValueError as e:
                    _logger.error(e)
payno's avatar
payno committed
544
545
                if "IMAGE_PIXEL_SIZE_1".lower() in ddict:
                    value = float(ddict["IMAGE_PIXEL_SIZE_1".lower()])
payno's avatar
payno committed
546
547
548
        # for now pixel size are stored in microns.
        # We want to return them in meter
        if value is not None:
549
            return value * MetricSystem.MICROMETER.value
payno's avatar
payno committed
550
551
552
553
        else:
            return None

    @staticmethod
payno's avatar
payno committed
554
555
556
    def get_darks_url(
        scan_path: str, prefix: str = "dark", file_ext: str = ".edf"
    ) -> dict:
payno's avatar
payno committed
557
558
559
        """

        :param scan_path:
payno's avatar
payno committed
560
        :type scan_path: str
payno's avatar
payno committed
561
        :param prefix: ref / flat field file prefix
payno's avatar
payno committed
562
        :type prefix: str
payno's avatar
payno committed
563
        :param file_ext: ref / flat field file extension
payno's avatar
payno committed
564
        :type file_ext: str
payno's avatar
payno committed
565
566
        :return: list of refs as silx's `DataUrl`
        """
payno's avatar
payno committed
567
        res = {}
payno's avatar
payno committed
568
        if os.path.isdir(scan_path) is False:
payno's avatar
payno committed
569
570
571
            _logger.error(
                scan_path + " is not a directory. Cannot extract " "DarkHST files"
            )
payno's avatar
payno committed
572
            return res
payno's avatar
payno committed
573
        for file_ in os.listdir(scan_path):
payno's avatar
payno committed
574
575
576
            _prefix = prefix
            if prefix.endswith(file_ext):
                _prefix = prefix.rstrip(file_ext)
payno's avatar
payno committed
577
578
579
            if file_.startswith(_prefix) and file_.endswith(file_ext):
                # usuelly the dark file name should be dark.edf, but some
                # darkHSTXXXX remains...
payno's avatar
payno committed
580
581
582
583
584
585
586
587
                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=file_, basename=os.path.basename(scan_path)
                    )
                    urls = extract_urls_from_edf(
                        os.path.join(scan_path, file_), start_index=index
                    )
payno's avatar
payno committed
588
                    res.update(urls)
payno's avatar
payno committed
589
590
591
        return res

    @staticmethod
payno's avatar
payno committed
592
593
594
    def get_refs_url(
        scan_path: str, prefix: str = "refHST", file_ext: str = ".edf", ignore=None
    ) -> dict:
payno's avatar
payno committed
595
596
597
        """

        :param scan_path:
payno's avatar
payno committed
598
        :type scan_path: str
payno's avatar
payno committed
599
        :param prefix: ref / flat field file prefix
payno's avatar
payno committed
600
        :type prefix: str
payno's avatar
payno committed
601
        :param file_ext: ref / flat field file extension
payno's avatar
payno committed
602
        :type file_ext: str
payno's avatar
payno committed
603
604
        :return: list of refs as silx's `DataUrl`
        """
payno's avatar
payno committed
605
        res = {}
payno's avatar
payno committed
606
        if os.path.isdir(scan_path) is False:
payno's avatar
payno committed
607
608
609
            _logger.error(
                scan_path + " is not a directory. Cannot extract " "RefHST files"
            )
payno's avatar
payno committed
610
            return res
611

612
613
614
615
616
617
618
        def get_next_free_index(key, keys):
            """return next free key from keys by converting it to a string
            with `key_value (n)` after it
            """
            new_key = key
            index = 2
            while new_key in keys:
payno's avatar
payno committed
619
                new_key = "%s (%s)" % (key, index)
620
621
                index += 1
            return new_key
payno's avatar
payno committed
622

623
624
625
626
627
628
629
630
        def ignore_file(file_name, to_ignore):
            if to_ignore is None:
                return False
            for pattern in to_ignore:
                if pattern in file_name:
                    return True
            return False

payno's avatar
payno committed
631
        for file_ in os.listdir(scan_path):
payno's avatar
payno committed
632
633
634
635
636
637
638
639
            if (
                file_.startswith(prefix)
                and file_.endswith(file_ext)
                and not ignore_file(file_, ignore)
            ):
                index = EDFTomoScan.guess_index_frm_file_name(
                    _file=file_, basename=os.path.basename(scan_path)
                )
payno's avatar
payno committed
640
641
                file_fp = os.path.join(scan_path, file_)
                urls = extract_urls_from_edf(start_index=index, file_=file_fp)
642
643
644
645
646
647
                for key in urls:
                    if key in res:
                        key_ = get_next_free_index(key, res.keys())
                    else:
                        key_ = key
                    res[key_] = urls[key]
payno's avatar
payno committed
648
649
650
        return res

    @staticmethod
payno's avatar
payno committed
651
652
653
654
655
656
657
    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
658
659
        """
        Try to retrieve information a .info file, an .xml or a flat field file.
Pierre Paleo's avatar
Pierre Paleo committed
660

payno's avatar
payno committed
661
662
663
664
665
666
667
        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
payno's avatar
payno committed
668
        :type key: str
payno's avatar
payno committed
669
670
671
        :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
payno's avatar
payno committed
672
        :type key_aliases: list
payno's avatar
payno committed
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
        :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):
payno's avatar
payno committed
703
704
705
706
                text = text.replace(alias, "")
                text = text.replace("\n", "")
                text = text.replace(" ", "")
                text = text.replace("=", "")
payno's avatar
payno committed
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
                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)
payno's avatar
payno committed
722
723
        infoFiles = [os.path.join(scan, baseName + ".info")]
        infoOnDataVisitor = infoFiles[0].replace("lbsram", "")
payno's avatar
payno committed
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
        # 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

payno's avatar
payno committed
751
752
        xmlFiles = [os.path.join(scan, baseName + ".xml")]
        xmlOnDataVisitor = xmlFiles[0].replace("lbsram", "")
payno's avatar
payno committed
753
754
755
756
757
758
759
760
761
762
        # 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
payno's avatar
payno committed
763
764
765
766
767
768

    def get_range(self):
        if self.path is not None:
            return self.get_scan_range(self.path)
        else:
            return None