File: helpers.py

package info (click to toggle)
insighttoolkit5 5.4.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 704,588 kB
  • sloc: cpp: 784,579; ansic: 628,724; xml: 44,704; fortran: 34,250; python: 22,934; sh: 4,078; pascal: 2,636; lisp: 2,158; makefile: 461; yacc: 328; asm: 205; perl: 203; lex: 146; tcl: 132; javascript: 98; csh: 81
file content (422 lines) | stat: -rw-r--r-- 13,983 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# ==========================================================================
#
#   Copyright NumFOCUS
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#          https://www.apache.org/licenses/LICENSE-2.0.txt
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
# ==========================================================================*/

import importlib
from importlib.metadata import metadata
import os
import re
import functools

import numpy as np

_HAVE_XARRAY = False
try:
    metadata('xarray')

    _HAVE_XARRAY = True
except ImportError:
    pass
_HAVE_TORCH = False
try:
    metadata('torch')

    _HAVE_TORCH = True
except importlib.metadata.PackageNotFoundError:
    pass


def snake_to_camel_case(keyword: str):
    # Helpers for set_inputs snake case to CamelCase keyword argument conversion
    _snake_underscore_re = re.compile("(_)([a-z0-9A-Z])")

    def _underscore_upper(match_obj):
        return match_obj.group(2).upper()

    camel = keyword[0].upper()
    if _snake_underscore_re.search(keyword[1:]):
        return camel + _snake_underscore_re.sub(_underscore_upper, keyword[1:])
    return camel + keyword[1:]

def camel_to_snake_case(name):
    snake = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
    snake = re.sub("([a-z0-9])([A-Z])", r"\1_\2", snake)
    return snake.replace("__", "_").lower()


def is_arraylike(arr):
    return (
        hasattr(arr, "shape")
        and hasattr(arr, "dtype")
        and hasattr(arr, "__array__")
        and hasattr(arr, "ndim")
    )


def move_first_dimension_to_last(arr):
    import numpy as np

    dest = list(range(arr.ndim))
    source = dest.copy()
    end = source.pop()
    source.insert(0, end)
    arr_contiguous_channels = np.moveaxis(arr, source, dest).copy()
    return arr_contiguous_channels


def move_last_dimension_to_first(arr):
    import numpy as np

    dest = list(range(arr.ndim))
    source = dest.copy()
    end = source.pop()
    source.insert(0, end)
    arr_interleaved_channels = np.moveaxis(arr, dest, source).copy()
    return arr_interleaved_channels


def accept_array_like_xarray_torch(image_filter):
    """Decorator that allows itk.ProcessObject snake_case functions to accept
    NumPy array-like, PyTorch Tensor's or xarray DataArray inputs for itk.Image inputs.

    If a NumPy array-like is passed as an input, output itk.Image's are converted to numpy.ndarray's.
    If a torch.Tensor is passed as an input, output itk.Image's are converted to torch.Tensors.
    If a xarray DataArray is passed as an input, output itk.Image's are converted to xarray.DataArray's."""
    import numpy as np
    import itk
    if _HAVE_XARRAY:
        import xarray as xr
    if _HAVE_TORCH:
        import torch

    @functools.wraps(image_filter)
    def image_filter_wrapper(*args, **kwargs):
        have_array_input = False
        have_xarray_input = False
        have_torch_input = False

        args_list = list(args)
        for index, arg in enumerate(args):
            if _HAVE_XARRAY and isinstance(arg, xr.DataArray):
                have_xarray_input = True
                image = itk.image_from_xarray(arg)
                args_list[index] = image
            elif _HAVE_TORCH and isinstance(arg, torch.Tensor):
                have_torch_input = True
                channels = arg.shape[0]  # assume first dimension is channels
                arr = np.asarray(arg)
                if channels > 1:  # change from contiguous to interleaved channel order
                    arr = move_last_dimension_to_first(arr)
                image = itk.image_view_from_array(arr, is_vector=channels > 1)
                args_list[index] = image
            elif not isinstance(arg, itk.Object) and is_arraylike(arg):
                have_array_input = True
                array = np.asarray(arg)
                image = itk.image_view_from_array(array)
                args_list[index] = image

        potential_image_input_kwargs = ("input", "input1", "input2", "input3")
        for key, value in kwargs.items():
            if key.lower() in potential_image_input_kwargs or "image" in key.lower():
                if _HAVE_XARRAY and isinstance(value, xr.DataArray):
                    have_xarray_input = True
                    image = itk.image_from_xarray(value)
                    kwargs[key] = image
                elif _HAVE_TORCH and isinstance(value, torch.Tensor):
                    have_torch_input = True
                    channels = value.shape[0]  # assume first dimension is channels
                    arr = np.asarray(value)
                    if (
                        channels > 1
                    ):  # change from contiguous to interleaved channel order
                        arr = move_last_dimension_to_first(arr)
                    image = itk.image_view_from_array(arr, is_vector=channels > 1)
                    kwargs[key] = image
                elif not isinstance(value, itk.Object) and is_arraylike(value):
                    have_array_input = True
                    array = np.asarray(value)
                    image = itk.image_view_from_array(array)
                    kwargs[key] = image

        if have_xarray_input or have_torch_input or have_array_input:
            # Convert output itk.Image's to numpy.ndarray's
            output = image_filter(*tuple(args_list), **kwargs)
            if isinstance(output, tuple):
                output_list = list(output)
                for index, value in enumerate(output_list):
                    if isinstance(value, itk.Image):
                        if have_xarray_input:
                            data_array = itk.xarray_from_image(value)
                            output_list[index] = data_array
                        elif have_torch_input:
                            channels = value.GetNumberOfComponentsPerPixel()
                            data_array = itk.array_view_from_image(value)
                            if (
                                channels > 1
                            ):  # change from interleaved to contiguous channel order
                                data_array = move_first_dimension_to_last(data_array)
                            torch_tensor = torch.from_numpy(data_array)
                            output_list[index] = torch_tensor
                        else:
                            array = itk.array_view_from_image(value)
                            output_list[index] = array
                return tuple(output_list)
            else:
                if isinstance(output, itk.Image):
                    if have_xarray_input:
                        output = itk.xarray_from_image(output)
                    elif have_torch_input:
                        channels = output.GetNumberOfComponentsPerPixel()
                        output = itk.array_view_from_image(output)
                        if (
                            channels > 1
                        ):  # change from interleaved to contiguous channel order
                            output = move_first_dimension_to_last(output)
                        output = torch.from_numpy(output)
                    else:
                        output = itk.array_view_from_image(output)
                return output
        else:
            return image_filter(*args, **kwargs)

    return image_filter_wrapper


def python_to_js(name):
    import itk

    def _long_type():
        if os.name == "nt":
            return "int32"
        else:
            return "int64"

    _python_to_js = {
        itk.SC: "int8",
        itk.UC: "uint8",
        itk.SS: "int16",
        itk.US: "uint16",
        itk.SI: "int32",
        itk.UI: "uint32",
        itk.F: "float32",
        itk.D: "float64",
        itk.B: "uint8",
        itk.SL: _long_type(),
        itk.UL: "u" + _long_type(),
        itk.SLL: "int64",
        itk.ULL: "uint64",
    }

    return _python_to_js[name]


def js_to_python(name):
    def _long_type():
        if os.name == "nt":
            return "LL"
        else:
            return "L"

    _js_to_python = {
        "int8": "SC",
        "uint8": "UC",
        "int16": "SS",
        "uint16": "US",
        "int32": "SI",
        "uint32": "UI",
        "int64": "S" + _long_type(),
        "uint64": "U" + _long_type(),
        "float32": "F",
        "float64": "D",
    }

    return _js_to_python[name]


def pixelType_to_prefix(name):
    _pixelType_to_prefix = {
        "Scalar": "",
        "RGB": "RGB",
        "RGBA": "RGBA",
        "Offset": "O",
        "Vector": "V",
        "CovariantVector": "CV",
        "SymmetricSecondRankTensor": "SSRT",
        "FixedArray": "FA",
        "Array": "A",
        "VariableLengthVector": "VLV",
    }

    return _pixelType_to_prefix[name]


def wasm_type_from_image_type(itkimage):  # noqa: C901
    import itk

    component = itk.template(itkimage)[1][0]
    componentType = None
    pixelType = "Scalar"
    if component in (
        itk.SC,
        itk.UC,
        itk.SS,
        itk.US,
        itk.SI,
        itk.UI,
        itk.F,
        itk.D,
        itk.B,
        itk.SL,
        itk.SLL,
        itk.UL,
        itk.ULL,
    ):
        componentType = python_to_js(component)
    elif component in [i[1] for i in itk.Vector.items()]:
        componentType = python_to_js(itk.template(component)[1][0])
        pixelType = "Vector"
    elif component == itk.complex[itk.F]:
        componentType = "float32"
        pixelType = "Complex"
    elif component == itk.complex[itk.D]:
        componentType = "float64"
        pixelType = "Complex"
    elif component in [i[1] for i in itk.CovariantVector.items()]:
        componentType = python_to_js(itk.template(component)[1][0])
        pixelType = "CovariantVector"
    elif component in [i[1] for i in itk.Offset.items()]:
        componentType = "int64"
        pixelType = "Offset"
    elif component in [i[1] for i in itk.FixedArray.items()]:
        componentType = python_to_js(itk.template(component)[1][0])
        pixelType = "FixedArray"
    elif component in [i[1] for i in itk.RGBAPixel.items()]:
        componentType = python_to_js(itk.template(component)[1][0])
        pixelType = "RGBA"
    elif component in [i[1] for i in itk.RGBPixel.items()]:
        componentType = python_to_js(itk.template(component)[1][0])
        pixelType = "RGB"
    elif component in [i[1] for i in itk.SymmetricSecondRankTensor.items()]:
        # SymmetricSecondRankTensor
        componentType = python_to_js(itk.template(component)[1][0])
        pixelType = "SymmetrySecondRankTensor"
    else:
        raise RuntimeError(f"Unrecognized component type: {str(component)}")

    if isinstance(itkimage, itk.VectorImage):
        pixelType = "VariableLengthVector"

    imageType = dict(
        dimension=itkimage.GetImageDimension(),
        componentType=componentType,
        pixelType=pixelType,
        components=itkimage.GetNumberOfComponentsPerPixel(),
    )
    return imageType


def image_type_from_wasm_type(jstype):
    import itk

    pixelType = jstype["pixelType"]
    dimension = jstype["dimension"]
    if pixelType == "Complex":
        if jstype["componentType"] == "float32":
            return itk.Image[itk.complex, itk.F], np.float32
        else:
            return itk.Image[itk.complex, itk.D], np.float64

    postfix = ''
    if pixelType != "Offset":
        postfix += js_to_python(jstype["componentType"])
    if pixelType not in ("Scalar", "RGB", "RGBA", "Complex", "VariableLengthVector"):
        postfix += str(dimension)
    postfix += str(dimension)

    if pixelType == "VariableLengthVector":
        return getattr(itk.VectorImage, postfix)
    else:
        prefix = pixelType_to_prefix(pixelType)
        return getattr(itk.Image, f"{prefix}{postfix}")


def wasm_type_from_mesh_type(itkmesh):
    import itk

    component = itk.template(itkmesh)[1][0]
    mangle = None
    pixelType = "Scalar"
    pixel_type_components = 1

    if component in (itk.F, itk.D):
        mangle = component
    elif component in [i[1] for i in itk.Array.items()]:
        mangle = itk.template(component)[1][0]
        pixelType = "Array"

    return pixelType, python_to_js(mangle), pixel_type_components


def mesh_type_from_wasm_type(jstype):
    import itk

    pixelType = jstype["pointPixelType"]
    dimension = jstype["dimension"]
    pointPixelComponentType = jstype["pointPixelComponentType"]

    prefix = pixelType_to_prefix(pixelType)
    if pixelType == "Array":
        prefix += "D"
    else:
        prefix = prefix + js_to_python(pointPixelComponentType)

    prefix += str(dimension)
    return getattr(itk.Mesh, prefix)


def wasm_type_from_pointset_type(itkpointset):
    import itk

    component = itk.template(itkpointset)[1][0]
    mangle = None
    pixelType = "Scalar"
    pixel_type_components = 1

    if component in (itk.F, itk.D):
        mangle = component
    elif component in [i[1] for i in itk.Array.items()]:
        mangle = itk.template(component)[1][0]
        pixelType = "Array"

    return pixelType, python_to_js(mangle), pixel_type_components


def pointset_type_from_wasm_type(jstype):
    import itk

    pixelType = jstype["pointPixelType"]
    dimension = jstype["dimension"]
    pointPixelComponentType = jstype["pointPixelComponentType"]

    prefix = pixelType_to_prefix(pixelType)
    if pixelType == "Array":
        prefix += "D"
    else:
        prefix = prefix + js_to_python(pointPixelComponentType)

    prefix += str(dimension)
    return getattr(itk.PointSet, prefix)