Bird
Raised Fist0
SciPydata~20 mins

Power spectral density in SciPy - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Power Spectral Density Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of PSD calculation with scipy.signal.welch
What is the shape of the frequency and power spectral density arrays returned by scipy.signal.welch for a signal of length 1024 with default parameters?
SciPy
import numpy as np
from scipy.signal import welch

fs = 1000  # Sampling frequency
x = np.random.randn(1024)  # Random signal
f, Pxx = welch(x, fs=fs)
print(f.shape, Pxx.shape)
A(1024,) (1024,)
B(512,) (512,)
C(129,) (129,)
D(256,) (256,)
Attempts:
2 left
💡 Hint
The default nperseg is 256, which affects the output length.
❓ data_output
intermediate
2:00remaining
Power spectral density peak frequency detection
Given a signal composed of two sine waves at 50 Hz and 120 Hz sampled at 500 Hz, which frequency corresponds to the highest peak in the PSD computed by scipy.signal.welch?
SciPy
import numpy as np
from scipy.signal import welch

fs = 500
T = 1.0
t = np.linspace(0, T, int(T*fs), endpoint=False)
x = 0.5*np.sin(2*np.pi*50*t) + 0.3*np.sin(2*np.pi*120*t)
f, Pxx = welch(x, fs=fs, nperseg=100)
peak_freq = f[np.argmax(Pxx)]
print(peak_freq)
A120.0
B50.0
C85.0
D0.0
Attempts:
2 left
💡 Hint
The sine wave with larger amplitude usually produces the higher peak in PSD.
❓ visualization
advanced
3:00remaining
Interpreting PSD plot of noisy signal
You compute the PSD of a noisy sine wave using scipy.signal.welch and plot it. Which feature in the plot indicates the sine wave frequency?
SciPy
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import welch

fs = 1000
T = 2.0
t = np.linspace(0, T, int(T*fs), endpoint=False)
x = np.sin(2*np.pi*60*t) + 0.5*np.random.randn(len(t))
f, Pxx = welch(x, fs=fs)
plt.semilogy(f, Pxx)
plt.xlabel('Frequency (Hz)')
plt.ylabel('PSD (V**2/Hz)')
plt.title('Power Spectral Density')
plt.show()
AA sharp peak near 60 Hz
BA peak near 0 Hz
CA flat line across all frequencies
DMultiple peaks at random frequencies
Attempts:
2 left
💡 Hint
A sine wave shows as a peak at its frequency in the PSD plot.
🧠 Conceptual
advanced
2:00remaining
Effect of segment length on PSD resolution
How does increasing the segment length (nperseg) in scipy.signal.welch affect the frequency resolution and variance of the PSD estimate?
ADecreases frequency resolution and decreases variance
BDecreases frequency resolution and increases variance
CIncreases frequency resolution and decreases variance
DIncreases frequency resolution but increases variance
Attempts:
2 left
💡 Hint
Longer segments give finer frequency bins but fewer averages leading to higher variance.
🔧 Debug
expert
3:00remaining
Identifying error in PSD computation code
What error does the following code raise when computing PSD with scipy.signal.welch? import numpy as np from scipy.signal import welch fs = 1000 x = np.random.randn(500) f, Pxx = welch(x, fs=fs, nperseg=1024) print(f.shape, Pxx.shape)
SciPy
import numpy as np
from scipy.signal import welch

fs = 1000
x = np.random.randn(500)
f, Pxx = welch(x, fs=fs, nperseg=1024)
print(f.shape, Pxx.shape)
AValueError: nperseg must not be greater than input length
BTypeError: unsupported operand type(s) for /: 'int' and 'str'
CIndexError: index out of range
DNo error, runs successfully
Attempts:
2 left
💡 Hint
nperseg cannot be larger than the signal length.

Practice

(1/5)
1. What does the power spectral density (PSD) represent in signal analysis?
easy
A. The phase shift of a signal at various points
B. The total energy of a signal over time
C. How the power of a signal is distributed over different frequencies
D. The amplitude of a signal at a single point in time

Solution

  1. Step 1: Understand the definition of PSD

    Power spectral density shows how the power of a signal is spread across frequencies, not just total energy or amplitude at one time.
  2. Step 2: Compare options with PSD meaning

    Only How the power of a signal is distributed over different frequencies correctly describes PSD as power distribution over frequencies.
  3. Final Answer:

    How the power of a signal is distributed over different frequencies -> Option C
  4. Quick Check:

    PSD = power distribution over frequency [OK]
Hint: PSD shows power spread by frequency, not time or phase [OK]
Common Mistakes:
  • Confusing PSD with total signal energy
  • Thinking PSD shows amplitude at one time
  • Mixing PSD with phase information
2. Which of the following is the correct way to import the Welch method for PSD calculation from scipy?
easy
A. from scipy.signal import welch
B. import scipy.welch
C. from scipy import welch
D. import scipy.signal.welch as welch

Solution

  1. Step 1: Recall scipy.signal module structure

    The Welch method is inside scipy.signal, so we import it from there.
  2. Step 2: Check import syntax correctness

    Only 'from scipy.signal import welch' is valid Python syntax for this function.
  3. Final Answer:

    from scipy.signal import welch -> Option A
  4. Quick Check:

    Correct import = from scipy.signal import welch [OK]
Hint: Welch is in scipy.signal, import directly from there [OK]
Common Mistakes:
  • Trying to import welch directly from scipy
  • Using incorrect import syntax
  • Assuming welch is a standalone module
3. What will be the output type of the following code snippet?
from scipy.signal import welch
import numpy as np
fs = 100
x = np.sin(2 * np.pi * 10 * np.arange(1000) / fs)
freqs, psd = welch(x, fs)
print(type(freqs), type(psd))
medium
A. (, )
B. (, )
C. (, )
D. (, )

Solution

  1. Step 1: Understand welch output types

    The welch function returns two numpy arrays: frequencies and power spectral density values.
  2. Step 2: Check printed types

    Printing type(freqs) and type(psd) will show numpy.ndarray for both.
  3. Final Answer:

    (<class 'numpy.ndarray'>, <class 'numpy.ndarray'>) -> Option D
  4. Quick Check:

    welch returns arrays = numpy.ndarray [OK]
Hint: Welch returns frequency and PSD as numpy arrays [OK]
Common Mistakes:
  • Expecting lists instead of numpy arrays
  • Thinking output is a tuple of floats
  • Confusing output with single float values
4. Identify the error in this code snippet that calculates PSD:
from scipy.signal import welch
import numpy as np
fs = 50
x = np.random.randn(500)
freqs, psd = welch(x)
print(freqs)
medium
A. The print statement should be print(psd) instead
B. Missing sampling frequency (fs) argument in welch call
C. Random data cannot be used with welch
D. Import statement for welch is incorrect

Solution

  1. Step 1: Check welch function call parameters

    The welch function needs the sampling frequency (fs) to correctly compute frequencies.
  2. Step 2: Identify missing argument

    Here, fs=50 is defined but not passed to welch, causing incorrect frequency calculation.
  3. Final Answer:

    Missing sampling frequency (fs) argument in welch call -> Option B
  4. Quick Check:

    Pass fs to welch to get correct frequencies [OK]
Hint: Always pass fs to welch for correct frequency output [OK]
Common Mistakes:
  • Forgetting to pass fs argument
  • Assuming random data is invalid input
  • Confusing print output with error
5. You have a noisy signal sampled at 200 Hz. You want to find the dominant frequency component using scipy's Welch method. Which parameter adjustment helps improve frequency resolution in the PSD estimate?
hard
A. Increase the segment length (nperseg) to use longer data chunks
B. Decrease the sampling frequency (fs) to reduce data size
C. Use a smaller window type to reduce computation
D. Set detrend to False to keep original signal shape

Solution

  1. Step 1: Understand frequency resolution in Welch method

    Frequency resolution improves with longer segments (nperseg) because it provides finer frequency bins.
  2. Step 2: Evaluate options for improving resolution

    Increasing nperseg increases segment length, improving resolution. Decreasing fs reduces max frequency but not resolution. Window type affects leakage, not resolution. Detrend affects baseline, not resolution.
  3. Final Answer:

    Increase the segment length (nperseg) to use longer data chunks -> Option A
  4. Quick Check:

    Longer nperseg = better frequency resolution [OK]
Hint: Longer segments (nperseg) give finer frequency detail [OK]
Common Mistakes:
  • Reducing sampling frequency to improve resolution
  • Confusing window type with resolution effect
  • Ignoring segment length impact on frequency bins
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard