基于触发值检测NumPy向量的上升/下降沿(类示波器触发)
Great question! Traversing arrays with Python loops is definitely slow for large datasets, but NumPy's vectorized operations are perfect for this edge-detection task—they’re implemented in optimized C under the hood, so you’ll get way better performance than manual iteration.
Implementing Rising Edge Detection
A rising edge is defined as a position where the current value crosses the threshold from below or equal to above. Here's how to implement this efficiently with pure NumPy:
import numpy as np def rising_edge(data, threshold): # Create a mask: current element > threshold AND previous element <= threshold edge_mask = (data[1:] > threshold) & (data[:-1] <= threshold) # The mask corresponds to gaps between data[0]&data[1], data[1]&data[2], etc. # Add 1 to get the index of the rising edge in the original array return np.where(edge_mask)[0] + 1
Testing this with your sample data:
data = np.array([-1, -0.5, 0, 0.5, 1, 1.5, 2]) trigger = rising_edge(data, 0.3) print(trigger) # Output: [3]
This matches your expected result perfectly.
Implementing Falling Edge Detection
For falling edges (crossing from above or equal to below the threshold), the logic is nearly identical—just flip the comparisons:
def falling_edge(data, threshold): edge_mask = (data[1:] < threshold) & (data[:-1] >= threshold) return np.where(edge_mask)[0] + 1
Why This Is Way Faster Than Looping
NumPy’s vectorized operations avoid the overhead of Python’s loop iteration by processing entire arrays at once in optimized C code. For large datasets (think thousands or millions of points), this will be orders of magnitude faster than a manual loop.
Bonus: Handling Edge Cases & Complex Triggers
- If you need to ignore tiny "glitches" (short-lived threshold crossings), you can smooth the data first with
np.convolveor use morphological filtering fromscipy.ndimageto filter out small edges. - If the first element of your array is already above/below the threshold, it won’t be flagged as an edge—this matches standard oscilloscope trigger behavior, which requires a valid transition.
内容的提问来源于stack exchange,提问作者Cris

