normalization.py 12.7 KB
Newer Older
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-2017 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.
#
# ###########################################################################*/
"""
material for radio and sinogram normalization
"""


__authors__ = [
    "H. Payno",
]
__license__ = "MIT"
__date__ = "25/06/2021"


37
from tomwer.core.process.task import Task
38
39
40
from .params import (
    IntensityNormalizationParams,
    _ValueCalculationFct,
41
    _ValueSource,
42
)
payno's avatar
payno committed
43
from tomoscan.normalization import Method as NormMethod
44
from processview.core.superviseprocess import SuperviseProcess
45
from silx.io.url import DataUrl
46
from silx.io.utils import get_data
47
from processview.core.dataset import DatasetIdentifier
48
import tomoscan.esrf.utils
49
import tomwer.version
50
import silx.io.utils
51
import functools
52
import numpy
53
import logging
54

55
56

_logger = logging.getLogger(__name__)
57
58


59
class IntensityNormalizationTask(
60
61
    Task, SuperviseProcess, input_names=("data",), output_names=("data",)
):
62
    """
63
    Task to define the normalization to apply to a sinogram
64
65
    """

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
    def __init__(
        self,
        process_id=None,
        varinfo=None,
        inputs=None,
        node_id=None,
        node_attrs=None,
        execinfo=None,
    ):
        Task.__init__(
            self,
            varinfo=varinfo,
            inputs=inputs,
            node_id=node_id,
            node_attrs=node_attrs,
            execinfo=execinfo,
        )
83
84
        SuperviseProcess.__init__(self, process_id=process_id)
        self._dry_run = False
85
86
        if "configuration" in inputs:
            self.set_configuration(inputs["configuration"])
87
88
89
90

    def set_properties(self, properties):
        if isinstance(properties, IntensityNormalizationParams):
            self._settings = properties.to_dict()
91
92
        else:
            self._settings = properties
93
94
95
96

    def set_configuration(self, configuration: dict) -> None:
        self.set_properties(configuration)

97
98
    def run(self):
        scan = self.inputs.data
99
        if scan is None:
100
            return
payno's avatar
payno committed
101
102
103
104
105
106
107
        extra_infos = scan.intensity_normalization.get_extra_infos()
        extra_infos.update(
            {
                "tomwer_processing_res_code": None,
            }
        )
        scan.intensity_normalization.set_extra_infos(extra_infos)
108
        params = IntensityNormalizationParams.from_dict(self._settings)
Henri Payno's avatar
Henri Payno committed
109
110
111
        # define the method used to the scan
        scan.intensity_normalization.method = params.method
        # after this processing the source
112
        try:
113
            if params.method in (NormMethod.NONE, NormMethod.CHEBYSHEV):
payno's avatar
payno committed
114
115
                final_norm_info = {}
            elif params.source is _ValueSource.MANUAL_ROI:
Henri Payno's avatar
Henri Payno committed
116
                value = self._compute_from_manual_roi(scan)
117
                # need_conversion_to_tomoscan = True
Henri Payno's avatar
Henri Payno committed
118
119
120
121
122
123
124
                # insure this could be hashable (for caches)
                if isinstance(value, numpy.ndarray):
                    value = tuple(value)
                final_norm_info = {
                    "value": value,
                    "source": _ValueSource.MANUAL_SCALAR.value,
                }
125
            elif params.source is _ValueSource.AUTO_ROI:
Henri Payno's avatar
Henri Payno committed
126
                value = self._compute_from_automatic_roi(scan)
127
                # need_conversion_to_tomoscan = True
Henri Payno's avatar
Henri Payno committed
128
129
130
131
132
133
134
                # insure this could be hashable (for caches)
                if isinstance(value, numpy.ndarray):
                    value = tuple(value)
                final_norm_info = {
                    "value": value,
                    "source": _ValueSource.MANUAL_SCALAR.value,
                }
135
            elif params.source is _ValueSource.DATASET:
Henri Payno's avatar
Henri Payno committed
136
137
138
139
140
141
142
143
144
                final_norm_info = {
                    "dataset_url": params.extra_infos.get("dataset_url", None),
                    "source": _ValueSource.DATASET.value,
                }
            elif params.source is _ValueSource.MANUAL_SCALAR:
                final_norm_info = {
                    "value": params.extra_infos.get("value", None),
                    "source": _ValueSource.MANUAL_SCALAR.value,
                }
145
146
147
148
            else:
                raise ValueError("method {} is not handled".format(params.method))
        except Exception as e:
            _logger.error(e)
payno's avatar
payno committed
149
            final_norm_info = {"tomwer_processing_res_code": False}
150
        else:
payno's avatar
payno committed
151
            final_norm_info.update({"tomwer_processing_res_code": True})
Henri Payno's avatar
Henri Payno committed
152
        scan.intensity_normalization.set_extra_infos(final_norm_info)
153
        self.outputs.data = scan
154
155

    def _compute_from_manual_roi(self, scan):
156
        params = IntensityNormalizationParams.from_dict(self.get_configuration())
157
158
159
160
161
        extra_info = params.extra_infos
        start_x = extra_info.get("start_x", None)
        end_x = extra_info.get("end_x", None)
        start_y = extra_info.get("start_y", None)
        end_y = extra_info.get("end_y", None)
162

163
164
165
166
167
168
        calc_fct = extra_info.get("calc_fct", None)
        if calc_fct is None:
            raise ValueError("calc_fct should be provided")
        else:
            calc_fct = _ValueCalculationFct.from_value(calc_fct)

169
        try:
Henri Payno's avatar
Henri Payno committed
170
            value = self._cache_compute_from_manual_roi(
171
172
173
174
175
                dataset_identifier=scan.get_dataset_identifier(),
                start_x=start_x,
                start_y=start_y,
                end_x=end_x,
                end_y=end_y,
payno's avatar
payno committed
176
            )[calc_fct.value]
177
178
179
        except Exception as e:
            _logger.error(e)
            return None
Henri Payno's avatar
Henri Payno committed
180
181
        else:
            return value
182
183
184
185

    @staticmethod
    @functools.lru_cache(
        maxsize=6
186
187
    )  # maxsize=6 to at most keep info at volume and at frame level for 3 scans
    def _cache_compute_from_manual_roi(
188
189
190
191
192
        dataset_identifier: DatasetIdentifier,
        start_x,
        end_x,
        start_y,
        end_y,
193
    ) -> dict:
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
        """
        compute mean and median on a volume or a slice.
        To improve io performances compute both mean and median for both
        cases one per frame or one for the entire volume

        :param projections:
        :param start_x:
        :param end_x:
        :param start_y:
        :param end_y:
        :param calc_area:
        :return:
        :rtype: dict
        """
        if start_x is None or end_x is None or start_y is None or end_y is None:
            raise ValueError("min_x, max_x, min_y and max_y should all be provided.")
        else:
            start_x = int(start_x)
            start_y = int(start_y)
            end_x = int(end_x)
            end_y = int(end_y)
215
216
217
218
219
        # clamp ROI with 0 border
        start_x = max(0, start_x)
        start_y = max(0, start_y)
        end_x = max(0, end_x)
        end_y = max(0, end_y)
220
221
        scan = dataset_identifier.recreate_dataset()
        projections = scan.projections
222

payno's avatar
payno committed
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
        roi_area = numpy.zeros(
            (len(projections), int(end_y - start_y), int(end_x - start_x))
        )
        # as dataset can be large we try to split the load of
        # the data
        proj_compacted = tomoscan.esrf.utils.get_compacted_dataslices(
            projections,
            max_grp_size=20,
        )
        proj_indexes = sorted(proj_compacted.keys())
        # small hack to avoid loading several time the same url
        url_treated = set()

        def url_has_been_treated(url: DataUrl):
            return (
                url.file_path(),
                url.data_path(),
                url.data_slice().start,
                url.data_slice().stop,
                url.data_slice().step,
                url.scheme(),
            ) in url_treated

        def append_url(url: DataUrl):
            url_treated.add(
                (
249
250
251
252
253
254
255
                    url.file_path(),
                    url.data_path(),
                    url.data_slice().start,
                    url.data_slice().stop,
                    url.data_slice().step,
                    url.scheme(),
                )
payno's avatar
payno committed
256
            )
257

payno's avatar
payno committed
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
        current_idx = 0
        url_idxs = {v.path(): k for k, v in scan.projections.items()}
        for proj_index in proj_indexes:
            url = proj_compacted[proj_index]
            if url_has_been_treated(url):
                continue

            append_url(url)
            data = silx.io.get_data(url)
            if data.ndim < 2:
                raise ValueError("data is expected to be at least 2D")
            # clamp ROI with frame size
            start_x = min(data.shape[-1], start_x)
            start_y = min(data.shape[-2], start_y)
            end_x = min(data.shape[-1], end_x)
            end_y = min(data.shape[-2], end_y)

            def retrieve_data_proj_indexes(url_):
                urls = []
                for slice in range(
                    url_.data_slice().start,
                    url_.data_slice().stop,
                    url_.data_slice().step or 1,
                ):
                    urls.append(
                        DataUrl(
                            file_path=url_.file_path(),
                            data_path=url_.data_path(),
                            scheme=url_.scheme(),
                            data_slice=slice,
288
                        )
payno's avatar
payno committed
289
                    )
290

payno's avatar
payno committed
291
292
293
294
295
296
297
298
299
300
301
302
303
304
                # try to retrieve the index from the projections else
                # keep the slice index as the frame index (should be the
                # case in most case
                res = []
                for my_url in urls:
                    my_url_path = my_url.path()
                    if my_url_path in url_idxs:
                        res.append(url_idxs[my_url_path])
                    else:
                        _logger.warning(
                            "unable to retrieve frame index from url {}. "
                            "Take the slice index as frame index".format(my_url_path)
                        )
                return res
305

payno's avatar
payno committed
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
            data_indexes = retrieve_data_proj_indexes(url)
            # apply flat field correction
            if data.ndim == 2:
                projs = (data,)
            else:
                projs = list(data)
            data = scan.flat_field_correction(projs=projs, proj_indexes=data_indexes)
            if data is None:
                continue
            data = numpy.asarray(data)
            if data.ndim == 2:
                roi_area[current_idx] = data[start_y:end_y, start_x:end_x]
                current_idx += 1
            elif data.ndim == 3:
                length = data.shape[0]
                roi_area[current_idx : current_idx + length] = data[
                    :, start_y:end_y, start_x:end_x
                ]
                current_idx += length
            else:
                raise ValueError(
                    "Frame where expected and not a " "{}D object".format(data.ndim)
328
                )
329
        return IntensityNormalizationTask.compute_stats(roi_area)
330
331
332

    @staticmethod
    def compute_stats(data):
333
        results = {}
payno's avatar
payno committed
334
335
336
337
338
339
340
341
342
343
        for calc_fct in _ValueCalculationFct:
            if data.ndim == 3:
                res = getattr(numpy, calc_fct.value)(data, axis=(-2, -1))
            elif data.ndim == 2:
                res = getattr(numpy, calc_fct.value)(data, axis=(-1))
            elif data.ndim in (0, 1):
                res = data
            else:
                raise ValueError("dataset dimension not handled ({})".format(data.ndim))
            results[calc_fct.value] = res
344
        return results
345
346

    def _compute_from_automatic_roi(self, scan):
347
348
        raise NotImplementedError("Not implemented yet")

349
350
351
352
353
354
355
356
357
358
359
360
361
362
    @staticmethod
    def program_name():
        """Name of the program used for this processing"""
        return "Intensity normalization"

    @staticmethod
    def program_version():
        """version of the program used for this processing"""
        return tomwer.version.version

    @staticmethod
    def definition():
        """definition of the process"""
        return "Normalize intensity."