0

I'm using the matplotlib function psd to generate the power spectral density of a bunch of radio signals I'm receiving. All I want are the returned values but the function plots the whole spectrum not matter what. Is there a way to prevent it from plotting? Is there another function that could do this without the plot? I'm trying to run this as rapidly as possible so anything to speed it up (aka preventing the plot entirely) would be very useful.

The code is pretty straightforward but I'm not sure how to suppress this plotting and ideally prevent it from doing it entirely because I want this code to run as fast as possible:

from pylab import *
power, psd_frequencies = psd(radio_samples, NFFT=256, Fs=samples_rate, Fc=center_frequency)

Alternatives to running psd() that would be faster are very welcome too.

clifgray
  • 4,313
  • 11
  • 67
  • 116
  • Just as a tip, I **strongly** recommend never using pylab in real code. Pylab is just a namespace clutter for matplotlib's pyplot and numpy smooshed together, see [this answer](https://stackoverflow.com/a/46761217/3100515). If what you want is simply a power spectral density, there are plenty of options in scipy or you can make your own with an fft. – Ajean Jul 05 '18 at 15:25
  • @Ajean thanks for the tip there, much appreciated. Do you have any suggested options in scipy? I found https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.welch.html#scipy.signal.welch which looks to do the same thing. – clifgray Jul 05 '18 at 17:21

1 Answers1

2

To reproduce exactly what matplotlib plots in the psd plot, you may use its own method:

from matplotlib.mlab import psd
power, psd_frequencies = psd(radio_samples, NFFT=256, Fs=samples_rate)
psd_frequencies += center_frequency

This gives you the data, but without the plot.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • That looks simple enough! My main remaining question is that this matplotlib.mlab.psd function doesn't actually have the Fc agrument and I'm not totally sure how to convert the frequencies it gives back into the frequencies in Hz. – clifgray Jul 05 '18 at 18:15
  • Oh, sorry, you are right, you would just add the center frequency afterwards, right? I updated the answer. – ImportanceOfBeingErnest Jul 05 '18 at 18:24
  • Okay that answers it pretty well. I see some discussion of this elsewhere but is there any reason to use scipy.signal.welch instead of this? Looks like they do pretty much the same thing? – clifgray Jul 05 '18 at 18:51
  • I did not look into the exact details, but the point is that `scipy` is not a dependency of matplotlib. So matplotlib needs its own implementation of Welch's algorithm instead of relying on the one from scipy. From a user's perspective the use of `scipy` may be totally fine. – ImportanceOfBeingErnest Jul 05 '18 at 19:00
  • what is the central frequency again? – chintan thakrar Jun 17 '21 at 03:43