Signals with NumPy
On a computer a signal is an array of samples taken at a fixed sampling rate (samples per second). The time of sample is . This lesson sets up the NumPy habits used in every later lesson: building time axes, generating tones and noise, measuring signals, and printing results readably.
A time axis and a tone
Two ways to build the time axis, and the difference matters:
import numpy as np
fs = 8 # 8 samples per second (tiny, to print everything)
t1 = np.arange(0, 1, 1 / fs) # 8 samples, endpoint excluded
t2 = np.linspace(0, 1, fs, endpoint=False) # the same 8 samples
t3 = np.linspace(0, 1, fs) # 8 samples INCLUDING t = 1: spacing is 1/7, not 1/8
print(t1.tolist())
print(np.allclose(t1, t2), " spacing of t3:", round(t3[1] - t3[0], 4))
x = np.cos(2 * np.pi * 1 * t1) # 1 Hz cosine, one full period
print((np.round(x, 3) + 0.0).tolist())[0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
True spacing of t3: 0.1429
[1.0, 0.707, 0.0, -0.707, -1.0, -0.707, 0.0, 0.707]
For periodic signals and the FFT you want the endpoint excluded: the sample at would repeat the one at .
Measuring a signal
The quantities used throughout the course:
- mean (DC component) ,
- energy and power ,
- RMS ; a sine of amplitude has RMS ,
- SNR in decibels, .
import numpy as np
fs = 1000
t = np.arange(0, 1, 1 / fs)
s = 2.0 * np.sin(2 * np.pi * 5 * t)
rng = np.random.default_rng(1)
noise = 0.5 * rng.normal(size=t.size)
x = s + noise
power = lambda v: np.mean(v ** 2)
print(f"mean of s: {abs(np.mean(s)):.4f} RMS of s: {np.sqrt(power(s)):.4f} (2/sqrt 2 = {2 / np.sqrt(2):.4f})")
print(f"noise power: {power(noise):.4f}")
print(f"SNR: {10 * np.log10(power(s) / power(noise)):.2f} dB")mean of s: 0.0000 RMS of s: 1.4142 (2/sqrt 2 = 1.4142)
noise power: 0.2439
SNR: 9.14 dB
The signal power is and the noise power about , so the SNR is about dB.
Printing complex results
Fourier transforms produce complex numbers. Rounding and converting with .tolist() keeps the output short; the + 0.0 turns a negative zero -0.0 into 0.0:
import numpy as np
x = np.array([1.0, 2.0, 0.0, -1.0])
X = np.fft.fft(x)
print(np.round(X, 3).tolist())
print("magnitudes:", (np.round(np.abs(X), 3) + 0.0).tolist())
print("phases (rad):", (np.round(np.angle(X), 3) + 0.0).tolist())[(2+0j), (1-3j), 0j, (1+3j)]
magnitudes: [2.0, 3.162, 0.0, 3.162]
phases (rad): [0.0, -1.249, 0.0, 1.249]
In software
- Audio files store samples at 44100 or 48000 Hz;
scipy.io.wavfile.readreturns exactly such arrays. ECG monitors sample around 250-1000 Hz, accelerometers in phones around 100-400 Hz. - The SciPy and NumPy FFT modules expect the time axis to be uniformly spaced; irregular samples need resampling or a Lomb-Scargle periodogram.
Exercises
Exercise 1: Number of samples
How many samples does 2.5 seconds of audio at 48 kHz contain, and what is the time between samples?
Answer
120000 samples, about 20.8 microseconds apart.
Solution
, and s.
Exercise 2: RMS of a square wave (code)
A square wave alternates between and . What is its RMS, and how does it compare with a sine of amplitude 1?
Answer
RMS 1.0 versus about 0.7071 for the sine.
Solution
import numpy as np
t = np.arange(0, 1, 1 / 1000)
sq = np.sign(np.sin(2 * np.pi * 4 * t + 0.1))
print(round(float(np.sqrt(np.mean(sq ** 2))), 4), round(float(np.sqrt(np.mean(np.sin(2 * np.pi * 4 * t) ** 2))), 4))1.0 0.7071
Every sample of the square wave has magnitude 1, so its RMS is 1; the sine spends time near 0, so its RMS is only . (The phase 0.1 avoids samples exactly at the zero crossings, where np.sign would return 0.)
Exercise 3: Decibels
If the noise power doubles, how many decibels does the SNR drop?
Answer
About 3 dB.
Solution
, so doubling the noise power lowers the SNR by about 3 dB; a factor of 10 in power is 10 dB.
Test yourself
Why use np.arange(0, 1, 1/fs) instead of np.linspace(0, 1, fs) for one period?
- it is faster
- it excludes the endpoint, so the period is not repeated and the spacing is exactly
- it gives more samples
- linspace cannot make floats
A sine wave of amplitude has RMS…
An SNR of 20 dB means the signal power is…
- 20 times the noise power
- 100 times the noise power
- 2 times
- equal