In numpy, I would like to detect the points at which the signal crosses from (having been previously) below a certain threshold, to being above a certain other threshold. This is for things like debouncing, or accurate zero crossings in the presence of noise, etc.
Like this:
import numpy
# set up little test problem
N = 1000
values = numpy.sin(numpy.linspace(0, 20, N))
values += 0.4 * numpy.random.random(N) - 0.2
v_high = 0.3
v_low = -0.3
# find transitions from below v_low to above v_high
transitions = numpy.zeros_like(values, dtype=numpy.bool)
state = "high"
for i in range(N):
if values[i] > v_high:
# previous state was low, this is a low-to-high transition
if state == "low":
transitions[i] = True
state = "high"
if values[i] < v_low:
state = "low"
I would like a way to do this without looping over the array explicitly: but I can't think of any way, since each state value depends on the previous state. Is it possible to do without a loop?