I want to do exactly what this guy did:
However I need to optimize it to run super fast. In brief I want to take a time series and tell every time it crosses crosses zero (changes sign). I want to record the time in between zero crossings. Since this is real data (32 bit float) I doubt I’ll every have a number which is exactly zero, so that is not important. I currently have a timing program in place so I’ll time your results to see who wins.
My solution gives (micro seconds):
JavaScript
x
4
1
open data 8384
2
sign data 8123
3
zcd data 415466
4
As you can see the zero-crossing detector is the slow part. Here’s my code.
JavaScript
1
34
34
1
import numpy, datetime
2
3
class timer():
4
def __init__(self):
5
self.t0 = datetime.datetime.now()
6
self.t = datetime.datetime.now()
7
def __call__(self,text='unknown'):
8
print text,'t',(datetime.datetime.now()-self.t).microseconds
9
self.t=datetime.datetime.now()
10
11
def zcd(data,t):
12
sign_array=numpy.sign(data)
13
t('sign data')
14
out=[]
15
current = sign_array[0]
16
count=0
17
for i in sign_array[1:]:
18
if i!=current:
19
out.append(count)
20
current=i
21
count=0
22
else: count+=1
23
t('zcd data')
24
return out
25
26
def main():
27
t = timer()
28
data = numpy.fromfile('deci.dat',dtype=numpy.float32)
29
t('open data')
30
zcd(data,t)
31
32
if __name__=='__main__':
33
main()
34
Advertisement
Answer
What about:
JavaScript
1
4
1
import numpy
2
a = [1, 2, 1, 1, -3, -4, 7, 8, 9, 10, -2, 1, -3, 5, 6, 7, -10]
3
zero_crossings = numpy.where(numpy.diff(numpy.sign(a)))[0]
4
Output:
JavaScript
1
3
1
> zero_crossings
2
array([ 3, 5, 9, 10, 11, 12, 15])
3
I.e., zero_crossings will contain the indices of elements before which a zero crossing occurs. If you want the elements after, just add 1 to that array.