Rickson
Rickson

Reputation: 1090

Postprocessing data after convolution in Python

Please assume that we have the following test signal:

import numpy as np
fs = 10000
f1 = 60
duration = 10
samples = int(fs*duration)
t = np.arange(samples) / fs
signal = 15 * t * np.sin(2.0*np.pi*f1*t)

from which the RMS value will be calculated using convolution as follows:

def calculate_rms(signal, N):
    sig2 = np.power(signal,2)
    window = np.ones(N)/float(N)
    return np.sqrt(np.convolve(sig2, window, 'valid'))

N = (1.0 / f1) * fs
RMS = calculate_rms(signal,N) 

However, after convolution, RMS of course has less data points than t and signal and I am not sure how to postprocess t and signal in order to be able to plot them together with RMS as signal=f(t) and RMS=f(t) in the same plot witout distorting the temporal dimension.

Upvotes: 0

Views: 109

Answers (1)

WhoIsJack
WhoIsJack

Reputation: 1498

Option 1

In np.convolve, use the mode 'same' instead of 'valid' (see the docs for more info). If you do so, RMS will have the same shape as t and signal. There may be boundary effects at the edges, but these will likely be very minor and probably won't affect your plot.

Option 2

If you're desperate to keep the result clean of possible boundary effects, you can crop t and signal to correspond to the region that RMS covers. Since the valid part of the convolution starts at half of the window size, this can be done as follows.

t_cropped = t[int(N)//2:-int(N)//2+1]
signal_cropped = signal[int(N)//2:-int(N)//2+1]

Upvotes: 2

Related Questions