Eric Bal
Eric Bal

Reputation: 1185

How to know if scipy function uses C code?

Does anyone knows whether scipy.signal.argrelmax and scipy.integrate.simps uses C code in in their sourcecodes or are they in pure python? I wan to speed up using Numba, so asking it.

http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.argrelmax.html http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.integrate.simps.html

Upvotes: 0

Views: 176

Answers (1)

hpaulj
hpaulj

Reputation: 231738

Tracing through a couple of levels of calls, it looks like argrelmax ends up using this loop:

def _boolrelextrema(data, comparator...)
    # comparator - a function
    ....
    results = np.ones(data.shape, dtype=bool)
    main = data.take(locs, axis=axis, mode=mode)
    for shift in xrange(1, order + 1):
        plus = data.take(locs + shift, axis=axis, mode=mode)
        minus = data.take(locs - shift, axis=axis, mode=mode)
        results &= comparator(main, plus)
        results &= comparator(main, minus)
        if(~results.any()):
            return results

    order :  How many points on each side to use for the comparison

So if order isn't very large, the amount of iteration is small, and shouldn't affect the speed too much.

simps after setup uses

def _basic_simps(y,start,stop,x,dx,axis):
    nd = len(y.shape)
    if start is None:
        start = 0
    step = 2
    all = (slice(None),)*nd
    slice0 = tupleset(all, axis, slice(start, stop, step))
    slice1 = tupleset(all, axis, slice(start+1, stop+1, step))
    slice2 = tupleset(all, axis, slice(start+2, stop+2, step))

    if x is None:  # Even spaced Simpson's rule.
        result = add.reduce(dx/3.0 * (y[slice0]+4*y[slice1]+y[slice2]),
                                    axis)
    else:
        # Account for possibly different spacings.
        ...
    return result

By using add.reduce with a predefined set of slices, I'd guess it's as fast as you can get.

So these aren't specially coded in C, but they make efficient use of numpy vectorized operations. My guess is that speeding them up with numpy and/or cython will take a lot of work - unless you focus a few special cases.

Upvotes: 2

Related Questions