File: autocorr.py

package info (click to toggle)
python-scipy 0.6.0-12
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 32,016 kB
  • ctags: 46,675
  • sloc: cpp: 124,854; ansic: 110,614; python: 108,664; fortran: 76,260; objc: 424; makefile: 384; sh: 10
file content (357 lines) | stat: -rw-r--r-- 13,324 bytes parent folder | download
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
#! /usr/bin/env python
# Last Change: Fri Dec 15 10:00 PM 2006 J

# TODO: - proper test
# TODO: - proper profiling

from numpy.fft import fft, ifft
from numpy import correlate, log2, floor, conj, real, \
        concatenate, sum, max

from warnings import warn

# use ctype to have one sided c imp of autocorr
import ctypes
from ctypes import c_uint, c_int
from numpy.ctypeslib import ndpointer, load_library

ctypes_major    = int(ctypes.__version__.split('.')[0])
if ctypes_major < 1:
    msg =  "version of ctypes is %s, expected at least %s" \
            % (ctypes.__version__, '1.0.1')
    raise importerror(msg)

import numpy as N

# load autocorr lib
_autocorr   = load_library('gabsig.so', __file__)

#===============================
# define the functions with args
#===============================

# contiguous 1d
arg1    = ndpointer(dtype = N.float64, flags='CONTIGUOUS,ALIGNED')
arg2    = c_uint
arg3    = ndpointer(dtype = N.float64, flags='CONTIGUOUS,ALIGNED')
arg4    = c_uint
_autocorr.dbl_xcorr_nofft_1d.argtypes  = [arg1, arg2, arg3, arg4]
_autocorr.dbl_xcorr_nofft_1d.restype   = c_int

arg1    = ndpointer(dtype = N.float32, flags='CONTIGUOUS,ALIGNED')
arg2    = c_uint
arg3    = ndpointer(dtype = N.float32, flags='CONTIGUOUS,ALIGNED')
arg4    = c_uint
_autocorr.flt_xcorr_nofft_1d.argtypes  = [arg1, arg2, arg3, arg4]
_autocorr.flt_xcorr_nofft_1d.restype   = c_int

# non contiguous 1d
arg1    = ndpointer(dtype = N.float64, flags = 'ALIGNED')
arg2    = c_uint
arg3    = c_uint
arg4    = ndpointer(dtype = N.float64, flags = 'ALIGNED')
arg5    = c_uint
arg6    = c_uint
_autocorr.dbl_xcorr_nofft_1d_noncontiguous.argtypes  = [arg1, \
        arg2, arg3, arg4, arg5, arg6]
_autocorr.dbl_xcorr_nofft_1d_noncontiguous.restype   = c_int

arg1    = ndpointer(dtype = N.float32, flags = 'ALIGNED')
arg2    = c_uint
arg3    = c_uint
arg4    = ndpointer(dtype = N.float32, flags = 'ALIGNED')
arg5    = c_uint
arg6    = c_uint
_autocorr.flt_xcorr_nofft_1d_noncontiguous.argtypes  = [arg1, \
        arg2, arg3, arg4, arg5, arg6]
_autocorr.flt_xcorr_nofft_1d_noncontiguous.restype   = c_int

# contiguous 2d
arg1    = ndpointer(dtype = N.float64, flags='ALIGNED')
arg2    = c_uint
arg3    = c_uint
arg4    = ndpointer(dtype = N.float64, flags='ALIGNED')
arg5    = c_uint
_autocorr.dbl_xcorr_nofft_2d.argtypes  = [arg1, arg2, arg3, arg4, arg5]
_autocorr.dbl_xcorr_nofft_2d.restype   = c_int

arg1    = ndpointer(dtype = N.float32, flags='ALIGNED')
arg2    = c_uint
arg3    = c_uint
arg4    = ndpointer(dtype = N.float32, flags='ALIGNED')
arg5    = c_uint
_autocorr.flt_xcorr_nofft_2d.argtypes  = [arg1, arg2, arg3, arg4, arg5]
_autocorr.flt_xcorr_nofft_2d.restype   = c_int

# non contiguous 2d
arg1    = ndpointer(dtype = N.float64, flags='ALIGNED')
arg2    = c_uint
arg3    = c_uint
arg4    = c_uint
arg5    = c_uint
arg6    = ndpointer(dtype = N.float64, flags='ALIGNED')
arg7    = c_uint
arg8    = c_uint
arg9    = c_uint
_autocorr.dbl_xcorr_nofft_2d_noncontiguous.argtypes  = [arg1, arg2, \
        arg3, arg4, arg5, arg6, arg7, arg8, arg9]
_autocorr.dbl_xcorr_nofft_2d_noncontiguous.restype   = c_int

arg1    = ndpointer(dtype = N.float32, flags='ALIGNED')
arg2    = c_uint
arg3    = c_uint
arg4    = c_uint
arg5    = c_uint
arg6    = ndpointer(dtype = N.float32, flags='ALIGNED')
arg7    = c_uint
arg8    = c_uint
arg9    = c_uint
_autocorr.flt_xcorr_nofft_2d_noncontiguous.argtypes  = [arg1, arg2, \
        arg3, arg4, arg5, arg6, arg7, arg8, arg9]
_autocorr.flt_xcorr_nofft_2d_noncontiguous.restype   = c_int

#======================================
# Fonctions to be used for testing only
#======================================
def _raw_autocorr_1d(signal, lag):
    assert signal.ndim == 1
    assert signal.flags['CONTIGUOUS']
    
    if lag >= signal.size:
        raise RuntimeError("lag should be < to input size")

    if signal.dtype == N.float64:
        res = N.zeros((lag+1), N.float64)
        _autocorr.dbl_xcorr_nofft_1d(signal, signal.size, res, lag) 
    elif signal.dtype == N.float32:
        res = N.zeros((lag+1), N.float32)
        _autocorr.flt_xcorr_nofft_1d(signal, signal.size, res, lag) 
    else:
        raise TypeError("only float 32 and 64 bits supported for now")

    return res

def _raw_autocorr_1d_noncontiguous(signal, lag):
    assert signal.ndim == 1
    
    if lag >= signal.size:
        raise RuntimeError("lag should be < to input size")

    if signal.dtype == N.float64:
        res = N.zeros((lag+1), N.float64)
        _autocorr.dbl_xcorr_nofft_1d_noncontiguous(signal, signal.size, 
                signal.strides[0], res, res.strides[0], lag) 
    elif signal.dtype == N.float32:
        res = N.zeros((lag+1), N.float32)
        _autocorr.flt_xcorr_nofft_1d_noncontiguous(signal, signal.size, 
                signal.strides[0], res, res.strides[0], lag) 
    else:
        raise TypeError("only float 32 and 64 bits supported for now")

    return res

# python implementation of autocorr for rank <= 2
def _autocorr_oneside_nofft_py(signal, lag, axis = -1):
    if signal.ndim > 2:
        raise NotImplemented("only for rank <=2")
    
    if axis  % 2 == 0:
        res     = N.zeros((lag+1, signal.shape[1]), signal.dtype)
        center  = signal.shape[0] - 1
        for i in range(signal.shape[1]):
            #print "compute corr of " + str(signal[:, i])
            res[:, i]   = correlate(signal[:, i], signal[:, i], \
                    'full')[center:center+lag+1]
    elif axis % 2 == 1:
        res     = N.zeros((signal.shape[0], lag+1), signal.dtype)
        center  = signal.shape[1] - 1
        for i in range(signal.shape[0]):
            #print "compute corr of " + str(signal[i])
            res[i]  = correlate(signal[i], signal[i], \
                    'full')[center:center+lag+1]
    else:
        raise RuntimeError("this should bnot happen, please fill a bug")

    return res

#=============
# Public API
#=============
def autocorr_oneside_nofft(signal, lag, axis = -1):
    """Compute the righ side of autocorrelation along the axis, for lags up to lag.
    
    This implementation does NOT use FFT."""
    # TODO  For rank < 2, the overhead of python code may be significant. Should
    # TODO not be difficult to do in C anyway (we can still use ctypes)

    # rank 0, 1
    if signal.ndim < 2:
        size    = signal.shape[-1]
        if lag >= size:
            raise RuntimeError("lag should be < to input size")

        res = N.zeros((lag+1), signal.dtype)

        if signal.flags['CONTIGUOUS']:
            if signal.dtype == N.float64:
                _autocorr.dbl_xcorr_nofft_1d(signal, size, res, lag) 
            elif signal.dtype == N.float32:
                _autocorr.flt_xcorr_nofft_1d(signal, size, res, lag) 
            else:
                raise TypeError("only float 32 and 64 bits supported for now")
        else:
            istride = signal.strides[0]
            ostride = signal.itemsize
            if signal.dtype == N.float64:
                _autocorr.dbl_xcorr_nofft_1d_noncontiguous(signal, size, istride, 
                        res, ostride,  lag) 
            elif signal.dtype == N.float32:
                _autocorr.flt_xcorr_nofft_1d_noncontiguous(signal, size, istride, 
                        res, ostride,  lag) 
            else:
                raise TypeError("only float 32 and 64 bits supported for now")

    # rank 2 case 
    elif signal.ndim == 2:
        size    = signal.shape[axis]
        if lag >= size:
            raise RuntimeError("lag should be < to input size")
            res = N.zeros((signal.shape[0], lag+1), signal.dtype)
        else:
            res = N.zeros((lag+1, signal.shape[1]), signal.dtype)

        if signal.dtype == N.float64:
            # contiguous case
            if signal.flags['C'] and axis % 2 == 1:
                res = N.zeros((signal.shape[0], lag+1), signal.dtype)
                _autocorr.dbl_xcorr_nofft_2d(signal, signal.shape[0], signal.shape[1], 
                        res, lag) 
            # contiguous case
            elif signal.flags['F'] and axis % 2 == 0:
                res = N.zeros((lag+1, signal.shape[1]), signal.dtype, order = 'F')
                _autocorr.dbl_xcorr_nofft_2d(signal, signal.shape[1], signal.shape[0], 
                        res, lag) 
            # non contiguous case
            elif axis % 2 == 0:
                res = N.zeros((lag+1, signal.shape[1]), signal.dtype)
                warn("non contiguous used, this will be slow")
                _autocorr.dbl_xcorr_nofft_2d_noncontiguous(signal, 
                        signal.shape[1], signal.shape[0], 
                        signal.strides[1], signal.strides[0],
                        res, res.strides[1], res.strides[0], lag) 
            elif axis % 2 == 1:
                res = N.zeros((signal.shape[0], lag+1), signal.dtype)
                warn("non contiguous used, this will be slow")
                _autocorr.dbl_xcorr_nofft_2d_noncontiguous(signal, 
                        signal.shape[0], signal.shape[1], 
                        signal.strides[0], signal.strides[1],
                        res, res.strides[0], res.strides[1], lag) 
        elif signal.dtype == N.float32:
            # contiguous case
            if signal.flags['C'] and axis % 2 == 1:
                res = N.zeros((signal.shape[0], lag+1), signal.dtype)
                _autocorr.flt_xcorr_nofft_2d(signal, signal.shape[0], signal.shape[1], 
                        res, lag) 
            # contiguous case
            elif signal.flags['F'] and axis % 2 == 0:
                res = N.zeros((lag+1, signal.shape[1]), signal.dtype, order = 'F')
                _autocorr.flt_xcorr_nofft_2d(signal, signal.shape[1], signal.shape[0], 
                        res, lag) 
            # non contiguous case
            elif axis % 2 == 0:
                res = N.zeros((lag+1, signal.shape[1]), signal.dtype)
                warn("non contiguous used, this will be slow")
                _autocorr.flt_xcorr_nofft_2d_noncontiguous(signal, 
                        signal.shape[1], signal.shape[0], 
                        signal.strides[1], signal.strides[0],
                        res, res.strides[1], res.strides[0], lag) 
            elif axis % 2 == 1:
                res = N.zeros((signal.shape[0], lag+1), signal.dtype)
                warn("non contiguous used, this will be slow")
                _autocorr.flt_xcorr_nofft_2d_noncontiguous(signal, 
                        signal.shape[0], signal.shape[1], 
                        signal.strides[0], signal.strides[1],
                        res, res.strides[0], res.strides[1], lag) 
        else:
            raise TypeError("only float 32 and 64 bits supported for now")
    else:
        raise RuntimeError("rank > 2 not supported yet")

    return res

def nextpow2(n):
    """Returns p such as 2 ** p >= n """
    p   = N.floor(N.log2(n))
    if 2 **  p ==  n:
        return p
    else:
        return p + 1

def autocorr_fft(signal, axis = -1):
    """Return full autocorrelation along specified axis. Use fft
    for computation."""
    if N.ndim(signal) == 0:
        return signal
    elif signal.ndim == 1:
        n       = signal.shape[0]
        nfft    = int(2 ** nextpow2(2 * n - 1))
        lag     = n - 1
        a       = fft(signal, n = nfft, axis = -1)
        au      = ifft(a * N.conj(a), n = nfft, axis = -1)
        return N.require(N.concatenate((au[-lag:], au[:lag+1])), dtype = signal.dtype)
    elif signal.ndim == 2:
        n       = signal.shape[axis]
        lag     = n - 1
        nfft    = int(2 ** nextpow2(2 * n - 1))
        a       = fft(signal, n = nfft, axis = axis)
        au      = ifft(a * N.conj(a), n = nfft, axis = axis)
        if axis == 0:
            return N.require(N.concatenate( (au[-lag:], au[:lag+1]), axis = axis), \
                    dtype = signal.dtype)
        else:
            return N.require(N.concatenate( (au[:, -lag:], au[:, :lag+1]), 
                        axis = axis), dtype = signal.dtype)
    else:
        raise RuntimeError("rank >2 not supported yet")
        
def bench():
    size    = 256
    nframes = 4000
    lag     = 24

    X       = N.random.randn(nframes, size)
    X       = N.require(X, requirements = 'C')

    niter   = 10

    # Contiguous
    print "Running optimized with ctypes"
    def contig(*args, **kargs):
        return autocorr_oneside_nofft(*args, **kargs)
    for i in range(niter):
        Yt  = contig(X, lag, axis = 1)

    Yr  = _autocorr_oneside_nofft_py(X, lag, axis = 1)
    N.testing.assert_array_almost_equal(Yt, Yr, 10)

    # Non contiguous
    print "Running optimized with ctypes (non contiguous)"
    def ncontig(*args, **kargs):
        return autocorr_oneside_nofft(*args, **kargs)
    X       = N.require(X, requirements = 'F')
    for i in range(niter):
        Yt  = ncontig(X, lag, axis = 1)

    Yr  = _autocorr_oneside_nofft_py(X, lag, axis = 1)
    N.testing.assert_array_almost_equal(Yt, Yr, 10)

    print "Benchmark func done"

if __name__ == '__main__':
    import hotshot, hotshot.stats
    profile_file    = 'autocorr.prof'
    prof    = hotshot.Profile(profile_file, lineevents=1)
    prof.runcall(bench)
    p = hotshot.stats.load(profile_file)
    print p.sort_stats('cumulative').print_stats(20)
    prof.close()