File: interpolation.py

package info (click to toggle)
python-numarray 1.5.2-4
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 8,668 kB
  • ctags: 11,384
  • sloc: ansic: 113,864; python: 22,422; makefile: 197; sh: 11
file content (390 lines) | stat: -rw-r--r-- 17,439 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
# Copyright (C) 2003-2005 Peter J. Verveer
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met: 
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above
#    copyright notice, this list of conditions and the following
#    disclaimer in the documentation and/or other materials provided
#    with the distribution.
#
# 3. The name of the author may not be used to endorse or promote
#    products derived from this software without specific prior
#    written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.      

import types
import math
import numarray
import _ni_support
import _nd_image

def spline_filter1d(input, order = 3, axis = -1, output = numarray.Float64,
                    output_type = None):
    """Calculates a one-dimensional spline filter along the given axis.

    The lines of the array along the given axis are filtered by a
    spline filter. The order of the spline must be >= 2 and <= 5.
    """
    if order < 0 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    output, return_value = _ni_support._get_output(output, input,
                                                    output_type)
    if order in [0, 1]:
        output[...] = numarray.array(input)
    else:
        axis = _ni_support._check_axis(axis, input.rank)
        _nd_image.spline_filter1d(input, order, axis, output)
    return return_value


def spline_filter(input, order = 3, output = numarray.Float64,
                  output_type = None):
    """Multi-dimensional spline filter.

    Note: The multi-dimensional filter is implemented as a sequence of
    one-dimensional spline filters. The intermediate arrays are stored
    in the same data type as the output. Therefore, for output types
    with a limited precision, the results may be imprecise because
    intermediate results may be stored with insufficient precision.
    """
    if order < 2 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    output, return_value = _ni_support._get_output(output, input,
                                                    output_type)
    if order not in [0, 1] and input.rank > 0:
        for axis in range(input.rank):
            spline_filter1d(input, order, axis, output = output)
            input = output
    else:
        output[...] = input[...]
    return return_value

def geometric_transform(input, mapping, output_shape = None,
                        output_type = None, output = None, order = 3,
                        mode = 'constant', cval = 0.0, prefilter = True, 
                        extra_arguments = (), extra_keywords = {}):
    """Apply an arbritrary geometric transform.

    The given mapping function is used to find for each point in the 
    output the corresponding coordinates in the input. The value of the 
    input at those coordinates is determined by spline interpolation of 
    the requested order. Points outside the boundaries of the input are 
    filled according to the given mode. The output shape can optionally be 
    given. If not given, it is equal to the input shape. The parameter 
    prefilter determines if the input is pre-filtered before 
    interpolation, if False it is assumed that the input is already 
    filtered. The extra_arguments and extra_keywords arguments can be 
    used to provide extra arguments and keywords that are passed to the 
    mapping function at each call.
    """
    if order < 0 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if output_shape == None:
        output_shape = input.shape
    if input.rank < 1 or len(output_shape) < 1:
        raise RuntimeError, 'input and output rank must be > 0'
    mode = _ni_support._extend_mode_to_code(mode)
    if prefilter and order > 1:
        filtered = spline_filter(input, order, output = numarray.Float64)
    else:
        filtered = input
    output, return_value = _ni_support._get_output(output, input,
                                        output_type, shape = output_shape)
    _nd_image.geometric_transform(filtered, mapping, None, None, None,
               output, order, mode, cval, extra_arguments, extra_keywords)
    return return_value


def map_coordinates(input, coordinates, output_type = None, output = None,
                order = 3, mode = 'constant', cval = 0.0, prefilter = True):
    """Apply an arbritrary coordinate transformation.

    The array of coordinates is used to find for each point in the output 
    the corresponding coordinates in the input. The value of the input at 
    that coordinates is determined by spline interpolation of the 
    requested order. Points outside the boundaries of the input are filled 
    according to the given mode. The parameter prefilter determines if the 
    input is pre-filtered before interpolation, if False it is assumed 
    that the input is already filtered.
    """
    if order < 0 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    coordinates = numarray.asarray(coordinates)
    if isinstance(coordinates.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    output_shape = coordinates.shape[1:]
    if input.rank < 1 or len(output_shape) < 1:
        raise RuntimeError, 'input and output rank must be > 0'
    if coordinates.shape[0] != input.rank:
        raise RuntimeError, 'invalid shape for coordinate array'
    mode = _ni_support._extend_mode_to_code(mode)
    if prefilter and order > 1:
        filtered = spline_filter(input, order, output = numarray.Float64)
    else:
        filtered = input
    output, return_value = _ni_support._get_output(output, input,
                                        output_type, shape = output_shape)
    _nd_image.geometric_transform(filtered, None, coordinates, None, None,
               output, order, mode, cval, None, None)
    return return_value


def affine_transform(input, matrix, offset = 0.0, output_shape = None,
                     output_type = None, output = None, order = 3,
                     mode = 'constant', cval = 0.0, prefilter = True):
    """Apply an affine transformation.

    The given matrix and offset are used to find for each point in the 
    output the corresponding coordinates in the input by an affine 
    transformation. The value of the input at those coordinates is 
    determined by spline interpolation of the requested order. Points 
    outside the boundaries of the input are filled according to the given 
    mode. The output shape can optionally be given. If not given it is 
    equal to the input shape. The parameter prefilter determines if the 
    input is pre-filtered before interpolation, if False it is assumed 
    that the input is already filtered.

    The matrix must be two-dimensional or can also be given as a
    one-dimensional sequence or array. In the latter case, it is
    assumed that the matrix is diagonal. A more efficient algorithms
    is then applied that exploits the separability of the problem.
    """
    if order < 0 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if output_shape == None:
        output_shape = input.shape
    if input.rank < 1 or len(output_shape) < 1:
        raise RuntimeError, 'input and output rank must be > 0'
    mode = _ni_support._extend_mode_to_code(mode)
    if prefilter and order > 1:
        filtered = spline_filter(input, order, output = numarray.Float64)
    else:
        filtered = input
    output, return_value = _ni_support._get_output(output, input,
                                        output_type, shape = output_shape)
    matrix = numarray.asarray(matrix, type = numarray.Float64)
    if matrix.rank not in [1, 2] or matrix.shape[0] < 1:
        raise RuntimeError, 'no proper affine matrix provided'
    if matrix.shape[0] != input.rank:
        raise RuntimeError, 'affine matrix has wrong number of rows'
    if matrix.rank == 2 and matrix.shape[1] != output.rank:
        raise RuntimeError, 'affine matrix has wrong number of columns'
    if not matrix.iscontiguous():
        matrix = matrix.copy()
    offset = _ni_support._normalize_sequence(offset, input.rank)
    offset = numarray.asarray(offset, type = numarray.Float64)
    if offset.rank != 1 or offset.shape[0] < 1:
        raise RuntimeError, 'no proper offset provided'
    if not offset.iscontiguous():
        offset = offset.copy()
    if matrix.rank == 1:
        _nd_image.zoom_shift(filtered, matrix, offset, output, order,
                             mode, cval)
    else:
        _nd_image.geometric_transform(filtered, None, None, matrix, offset,
                            output, order, mode, cval, None, None)
    return return_value
    

def shift(input, shift, output_type = None, output = None, order = 3,
          mode = 'constant', cval = 0.0, prefilter = True):
    """Shift an array.

    The array is shifted using spline interpolation of the requested 
    order. Points outside the boundaries of the input are filled according 
    to the given mode. The parameter prefilter determines if the input is 
    pre-filtered before interpolation, if False it is assumed that the 
    input is already filtered.
    """
    if order < 0 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if input.rank < 1:
        raise RuntimeError, 'input and output rank must be > 0'
    mode = _ni_support._extend_mode_to_code(mode)
    if prefilter and order > 1:
        filtered = spline_filter(input, order, output = numarray.Float64)
    else:
        filtered = input
    output, return_value = _ni_support._get_output(output, input,
                                                    output_type)
    shift = _ni_support._normalize_sequence(shift, input.rank)
    shift = [-ii for ii in shift]
    shift = numarray.asarray(shift, type = numarray.Float64)
    if not shift.iscontiguous():
        shift = shift.copy()
    _nd_image.zoom_shift(filtered, None, shift, output, order, mode, cval)
    return return_value


def zoom(input, zoom, output_type = None, output = None, order = 3,
         mode = 'constant', cval = 0.0, prefilter = True):
    """Zoom an array.

    The array is zoomed using spline interpolation of the requested order. 
    Points outside the boundaries of the input are filled according to the 
    given mode. The parameter prefilter determines if the input is pre-
    filtered before interpolation, if False it is assumed that the input 
    is already filtered.
    """
    if order < 0 or order > 5:
        raise RuntimeError, 'spline order not supported'
    input = numarray.asarray(input)
    if isinstance(input.type(), numarray.ComplexType):
        raise TypeError, 'Complex type not supported'
    if input.rank < 1:
        raise RuntimeError, 'input and output rank must be > 0'
    mode = _ni_support._extend_mode_to_code(mode)
    if prefilter and order > 1:
        filtered = spline_filter(input, order, output = numarray.Float64)
    else:
        filtered = input
    zoom = _ni_support._normalize_sequence(zoom, input.rank)
    output_shape = [int(ii * jj) for ii, jj in zip(input.shape, zoom)]
    zoom = [1.0 / ii for ii in zoom]
    output, return_value = _ni_support._get_output(output, input,
                                        output_type, shape = output_shape)
    zoom = numarray.asarray(zoom, type = numarray.Float64)
    if not zoom.iscontiguous():
        zoom = shift.copy()
    _nd_image.zoom_shift(filtered, zoom, None, output, order, mode, cval)
    return return_value

def _minmax(coor, minc, maxc):
    if coor[0] < minc[0]:
        minc[0] = coor[0]
    if coor[0] > maxc[0]:
        maxc[0] = coor[0]
    if coor[1] < minc[1]:
        minc[1] = coor[1]
    if coor[1] > maxc[1]:
        maxc[1] = coor[1]
    return minc, maxc

def rotate(input, angle, axes = (-1, -2), reshape = True,
           output_type = None, output = None, order = 3,
           mode = 'constant', cval = 0.0, prefilter = True):
    """Rotate an array.

    The array is rotated in the plane defined by the two axes given by the 
    axes parameter using spline interpolation of the requested order. The 
    angle is given in degrees. Points outside the boundaries of the input 
    are filled according to the given mode. If reshape is true, the output 
    shape is adapted so that the input array is contained completely in 
    the output. The parameter prefilter determines if the input is pre-
    filtered before interpolation, if False it is assumed that the input 
    is already filtered.
    """
    input = numarray.asarray(input)
    axes = list(axes)
    rank = input.rank
    if axes[0] < 0:
        axes[0] += rank
    if axes[1] < 0:
        axes[1] += rank
    if axes[0] < 0 or axes[1] < 0 or axes[0] > rank or axes[1] > rank:
        raise RuntimeError, 'invalid rotation plane specified'
    if axes[0] > axes[1]:
        axes = axes[1], axes[0]
    angle = numarray.pi / 180 * angle
    m11 = math.cos(angle)
    m12 = math.sin(angle)
    m21 = -math.sin(angle)
    m22 = math.cos(angle)
    matrix = numarray.array([[m11, m12],
                             [m21, m22]], type = numarray.Float64)
    iy = input.shape[axes[0]]
    ix = input.shape[axes[1]]
    if reshape:
        mtrx = numarray.array([[ m11, -m21],
                               [-m12,  m22]], type = numarray.Float64)
        minc = [0, 0]
        maxc = [0, 0]
        coor = numarray.matrixmultiply(mtrx, [0, ix])
        minc, maxc = _minmax(coor, minc, maxc)
        coor = numarray.matrixmultiply(mtrx, [iy, 0])
        minc, maxc = _minmax(coor, minc, maxc)
        coor = numarray.matrixmultiply(mtrx, [iy, ix])
        minc, maxc = _minmax(coor, minc, maxc)
        oy = int(maxc[0] - minc[0] + 0.5)
        ox = int(maxc[1] - minc[1] + 0.5)
    else:
        oy = input.shape[axes[0]]
        ox = input.shape[axes[1]]
    offset = numarray.zeros((2,), type = numarray.Float64)
    offset[0] = float(oy) / 2.0 - 0.5
    offset[1] = float(ox) / 2.0 - 0.5
    offset = numarray.matrixmultiply(matrix, offset)
    tmp = numarray.zeros((2,), type = numarray.Float64)
    tmp[0] = float(iy) / 2.0 - 0.5
    tmp[1] = float(ix) / 2.0 - 0.5
    offset = tmp - offset
    output_shape = list(input.shape)
    output_shape[axes[0]] = oy
    output_shape[axes[1]] = ox
    output_shape = tuple(output_shape)
    output, return_value = _ni_support._get_output(output, input,
                                        output_type, shape = output_shape)
    if input.rank <= 2:
        affine_transform(input, matrix, offset, output_shape, None, output, 
                         order, mode, cval, prefilter)
    else:
        coordinates = []
        size = input.nelements() 
        size /= input.shape[axes[0]]
        size /= input.shape[axes[1]]
        for ii in range(input.rank):
            if ii not in axes:
                coordinates.append(0)
            else:
                coordinates.append(slice(None, None, None))
        iter_axes = range(input.rank)
        iter_axes.reverse()
        iter_axes.remove(axes[0])
        iter_axes.remove(axes[1])
        os = (output_shape[axes[0]], output_shape[axes[1]])
        for ii in range(size):
            ia = input[tuple(coordinates)]
            oa = output[tuple(coordinates)]
            affine_transform(ia, matrix, offset, os, None, oa, order, mode,
                             cval, prefilter)
            for jj in iter_axes:
                if coordinates[jj] < input.shape[jj] - 1:
                    coordinates[jj] += 1
                    break
                else:
                    coordinates[jj] = 0
    return return_value