Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot the integral of a signal as time goes by?

I have a time-dependent signal.

I wish to plot its integration over time with time being x-axis and integration value being y-axis.

Is there any Python way of doing this?

To be more specific:

I have a time array, time, and a signal array, signal. They are of same dimension.

I need to integrate signal over time with scipy.integrate.trapz().

Instead of getting the final integral, I wish to see the integral varying as time passes.

like image 219
Sibbs Gambling Avatar asked Aug 15 '13 03:08

Sibbs Gambling


People also ask

What is the integral of a signal?

Integral: This means that the differentiated signals will have spectral components with amplitude increasing linearly with frequency. Instead, the integrated signal will have spectral components with amplitude decreasing proportionally with frequency.

Why do we integrate a signal?

One integrates a signal because one needs the integral of a signal. There are many reasons why. A common one may be to avoid steady state following error in a control loop. Indeed, a low pass filter can be thought of as a leaky integrator.


2 Answers

Try using scipy.integrate.cumtrapz() instead :

plt.plot(time[:-1], scipy.integrate.cumtrapz(signal, x=time))
plt.show()

It computes an array containing the cumulative integral values.

http://docs.scipy.org/doc/scipy-0.10.1/reference/generated/scipy.integrate.trapz.html

like image 51
lmjohns3 Avatar answered Sep 19 '22 22:09

lmjohns3


A slightly better answer uses the optional "initial" argument. Here is a complete example:

import scipy.integrate as it
import numpy as np 
import matplotlib.pyplot as plt
t=np.linspace(0,1, 100)
y=t**2
y_int = it.cumtrapz(  y  ,  t, initial=0.0)  # y_int is same size as t
plt.plot(t, y_int)
plt.show()

This avoids the strange indexing like time[:-1]

like image 45
wander95 Avatar answered Sep 17 '22 22:09

wander95