scipyinterpolator.py 5.63 KB
Newer Older
1
#!/usr/bin/env python
inhuszar's avatar
inhuszar committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# -*- coding: utf-8 -*-

#   _______   _____   _____    _
#  |__   __| |_   _| |  __ \  | |
#     | |      | |   | |__) | | |
#     | |      | |   |  _  /  | |
#     | |     _| |_  | | \ \  | |____
#     |_|    |_____| |_|  \_\ |______|
#
# Copyright (C) 2018-2020 University of Oxford
# Part of the FMRIB Software Library (FSL)
# Author: Istvan N. Huszar


# SHBASECOPYRIGHT


# DEPENDENCIES

21
import warnings
inhuszar's avatar
inhuszar committed
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import numpy as np


# TIRL IMPORTS

from tirl import settings as ts
from tirl.interpolators.interpolator import Interpolator


# IMPLEMENTATION

class ScipyInterpolator(Interpolator):
    """
    ScipyInterpolator class - wrapper around Scipy.ndimage.map_coordinates

    """

    def interpolate(self, coordinates, input_array=None, **ipkwargs):

        from scipy.ndimage.interpolation import map_coordinates

        kw = {k: v for k, v in self.kwargs.get("ipkwargs", dict()).items()}
        # Override the ones that were specified for the call
        kw.update(ipkwargs)
46
47
48
49
50
51
52
        mode = kw.get("mode", None)

        # Set default fill value unless the mode parameter was given
        if mode is None:
            mode = "constant"
            cval = self.kwargs.get("fill_value")
            kw.update(mode=mode, cval=cval)
inhuszar's avatar
inhuszar committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

        if isinstance(coordinates, (tuple, list)):
            coordinates = np.asarray(coordinates).reshape((1, -1))
        try:
            res = map_coordinates(input_array, coordinates.T, **kw)
        except Exception:
            print("Interpolation failed with the following input: ",
                  input_array.shape, coordinates.shape, kw)
            raise
        return res


class ScipyRegularGridInterpolator(Interpolator):

    def __init__(self, source, tensor_axes=(), radius=1, hold=False,
68
69
                 threads=-1, verbose=False, ipkwargs=None, fill_value=None,
                 **kwargs):
inhuszar's avatar
inhuszar committed
70
71
72
73
74
75
76
        """
        Initialisation of ScipyRegularGridInterpolator

        """
        # Set default arguments for the RegularGridInterpolator.
        # These parameters will repress out-of-bounds errors when values need
        # to be interpolated outside the domain of known values.
77
        default_ipkwargs = dict(bounds_error=False, fill_value=fill_value)
inhuszar's avatar
inhuszar committed
78
79
80
81
82
83
84
        if isinstance(ipkwargs, dict):
            default_ipkwargs.update(ipkwargs)
        ipkwargs = default_ipkwargs

        # Call parent-class initialisation
        super(ScipyRegularGridInterpolator, self).__init__(
            source, tensor_axes=tensor_axes, radius=radius, hold=hold,
85
86
            threads=threads, verbose=verbose, ipkwargs=ipkwargs,
            fill_value=fill_value, **kwargs)
inhuszar's avatar
inhuszar committed
87

88
89
        if self.ipkwargs.get("fill_value", None) is None:
            self.ipkwargs.update(fill_value=ts.FILL_VALUE)
inhuszar's avatar
inhuszar committed
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

    def interpolate(self, coordinates, input_array=None, **ipkwargs):
        """
        Interpolation routine.

        """
        from scipy.interpolate import RegularGridInterpolator

        kw = {k: v for k, v in self.kwargs.get("ipkwargs", dict()).items()}
        # Override the ones that were specified for the call
        kw.update(ipkwargs)

        if isinstance(coordinates, (tuple, list)):
            coordinates = np.asarray(coordinates).reshape((1, -1))
        try:
            grid = tuple(np.arange(dim) for dim in input_array.shape)
            ip = RegularGridInterpolator(grid, input_array, **kw)
            res = ip(coordinates)
        except:
            print("Interpolation failed with the following input: ",
                  input_array.shape, coordinates.shape, kw)
            raise
        else:
            return res


class ScipyNearestNeighbours(Interpolator):

    def __init__(self, source, tensor_axes=(), radius=1, hold=False,
119
120
                 threads=-1, verbose=False, ipkwargs=None, fill_value=None,
                 **kwargs):
inhuszar's avatar
inhuszar committed
121
        """
122
        Initialisation of ScipyNearestNeighboursr
inhuszar's avatar
inhuszar committed
123
124
125
126
127
128
129
130
131
132

        """
        # Set default arguments for the RegularGridInterpolator.
        # These parameters will repress out-of-bounds errors when values need
        # to be interpolated outside the domain of known values.
        default_ipkwargs = dict(rescale=False)
        if isinstance(ipkwargs, dict):
            default_ipkwargs.update(ipkwargs)
        ipkwargs = default_ipkwargs

133
134
135
136
137
138
        # Note: the fill_value parameter lands in the kwargs, as it is not used
        # by this interpolator.
        if fill_value is not None:
            warnings.warn(f"The fill_value parameter was ignored by "
                          f"{self.__class__.__name__}")

inhuszar's avatar
inhuszar committed
139
140
141
142
143
        # Call parent-class initialisation
        super(ScipyNearestNeighbours, self).__init__(
            source, tensor_axes=tensor_axes, radius=radius, hold=hold,
            threads=threads, verbose=verbose, ipkwargs=ipkwargs, **kwargs)

144

inhuszar's avatar
inhuszar committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
    def interpolate(self, coordinates, input_array=None, **ipkwargs):

        from scipy.interpolate import NearestNDInterpolator

        kw = {k: v for k, v in self.kwargs.get("ipkwargs", dict()).items()}
        # Override the ones that were specified for the call
        kw.update(ipkwargs)

        if isinstance(coordinates, (tuple, list)):
            coordinates = np.asarray(coordinates).reshape((1, -1))
        try:
            vcoords = np.stack(
                np.meshgrid(*tuple(range(dim) for dim in input_array.shape),
                            indexing="ij"), axis=-1)
            ip = NearestNDInterpolator(vcoords.reshape((-1, input_array.ndim)),
                input_array.ravel(), **kw)
            res = ip(coordinates)
        except:
            print("Interpolation failed with the following input: ",
                  input_array.shape, coordinates.shape, kw)
            raise
        else:
            return res