Skip to content
This repository has been archived by the owner on Feb 14, 2019. It is now read-only.

Commit

Permalink
using stride tricks instead of for loops.
Browse files Browse the repository at this point in the history
This should significantly speed up energy computation, though I havn't
tested.

Changed the function to return an array is length N-windowSize,
instead of zero padding to N. Is this ok?

Added a simple doctest.
  • Loading branch information
schmidtc committed Mar 11, 2012
1 parent 6388b58 commit 2710697
Showing 1 changed file with 28 additions and 7 deletions.
35 changes: 28 additions & 7 deletions pymir/audio/energy.py
Expand Up @@ -3,17 +3,38 @@

import numpy
import scipy
from numpy.lib import stride_tricks

def energy(signal):
"""
This function does something.
Example:
>>> from test import chirp
>>> s = chirp()
>>> e = energy(s)
Below is for testing that I don't break things
>>> import hashlib
>>> hashlib.md5(e).hexdigest()
'615c65bb9e9055a75c32ceb5d309e597'
>>> hashlib.sha1(e).hexdigest()
'531b9ba53419bec6d4f679adc918e7449e17e452'
"""
N = len(signal)

windowSize = 256
window = numpy.hamming(windowSize)

e = scipy.zeros(N)

for i in range(0, N - windowSize):
e[i] = numpy.sum(window * numpy.power(signal[i:i + windowSize], 2) ) / windowSize


return e
n = N - windowSize #number of windowed samples.

# Create a view of signal who's shape is (n, windowSize). Use stride_tricks such that each stide jumps only one item.
s = stride_tricks.as_strided(signal,shape=(n,windowSize), strides=(signal.itemsize,signal.itemsize))
e = (window * numpy.power(s, 2)).sum(1) / windowSize
return e

def _test():
import doctest
doctest.testmod(verbose=True)
if __name__ == '__main__':
_test()

0 comments on commit 2710697

Please sign in to comment.