pavlos163
pavlos163

Reputation: 2890

Zero Crossings Rate

I was reading a piece of code from here:

def freq_from_ZCR(sig, fs):
    # Find all indices right before a rising-edge zero crossing
    indices = find((sig[1:] >= 0) & (sig[:-1] < 0))

    crossings = interpolate(indices, sig)

    return fs / np.mean(np.diff(crossings))

I want to check my understanding of this, as I doesn't really make sense right now. According to the mlab docs, find "returns the indices where some condition is true". I would like some explanation to how this works. As I see it now, (sig[1:] >= 0) & (sig[:-1] < 0) is a statement that is either true or false. Also, why is there a bitwise & there instead of an and?

Finally, if I assume that the first line returns an array of the indices right before a rising-edge zero crossing. Then we'll have something like (for example):

indices = [1, 4, 7, 11, 15]

It makes sense then to find the np.mean(np.diff(indices)). Why do we need the interpolate function and where is it from? From a quick search I didn't find anything.

Upvotes: 3

Views: 1856

Answers (1)

Prune
Prune

Reputation: 77850

It's bitwise and because it operates on lists of Boolean values.

(sig[1:] >= 0)

returns a sequence of Booleans from the second element through the final: the first element is cut off, shifting the values left one position.

(sig[:-1] < 0)

returns a similar sequence, but below the x axis, and not shifted, but with the final element cut off.

This gives you a list of two sequences: (1) is the next value non-negative; (2) is the current value negative. A bit-wise and of the two gives you True at each location where the function rose above the axis.

Does that explain it well enough?

I FORGOT THE INTERPOLATION:

SicPy has a lovely interpolation support; I expect that's what this code is using. Without the import context (not included in the page you cited), I can't be certain, but SciPy and NumPy are the way to bet for these capabilities. The idea is to find a "fractional index" at which the signal crosses 0. It sort of assumes that the indices are equally-spaced x-coodinates, and interpolates the proper crossing point.

Upvotes: 1

Related Questions