I acquire an analog waveform and I expect it to have some local flatness (post-filtering). The waveform's exact shape is unknown but some rough characteristics (peak amplitude, duration, rise time, etc.) can be assumed to be known. The rough shape of the waveform can be assumed to be known (excluding any information about a flat region). Below you can find a simulated waveform, without any noise, etc. Simulated Waveform

Ideally, I would like to measure the flatness of any set of points on the waveform. However, I am very new to DSP so I do not know if that is feasible at all. I need to know where the flat region is, and "how flat" it is. Ideally, I would like to have a library for python because I currently simulate and analyze everything in Python. But I can also implement something from scratch if need be, I just need to understand what would be the most feasible way to approach this problem.

Also, since it has been asked in related questions: I do know the expected length of this flat region, but I do not know where exactly it would surface or with what level of error/tolerance. Taking into account uncertainties such as component degradation, we can assume I will not have much information about the quality and location of the flat region.


1 Answer 1


If you know the length of the flat region you can try a a running variance. If the length is $N$ you could define a metric $M$ as

$$M[n] = 2\frac{\sum_{k=-N/2}^{N/2-1} x[k]^2}{\sum_{k=-N}^{N-1} x[k]^2}$$

This compares the variance in a segment of length $N$ to that of the a segment of length $2N$. A flat segment will have a variance of $0$ so you can set a threshold below which you count a segment as "flat" . The "ideal" position the flat segment would be the local minimum of $M[n]$.

If your flat parts can have a bit of a tilt to them you can instead use a line fit (first order polynomial fit). The segment would be detected if a) the slope is below a certain threshold (maximum allowable tilt) and b) the fit error is small as compared to the power of the signal.

Each method can be implemented very efficiently by just calculating running sums and sums of squares of the signal.

  • $\begingroup$ Thank you this gives me a really good starting point. I had a few attempts with derivatives but they are always difficult. Just a follow up: if there is also uncertainty of the length, namely the 'N', what would be a good way to deal it? $\endgroup$
    – Guarneer
    Commented Sep 16, 2022 at 12:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.