Quickstart

import numpy as np
from harm_analysis import harm_analysis

fs = 1000
t = np.arange(4096) / fs
x = np.cos(2 * np.pi * 100.3 * t) + 0.01 * np.cos(2 * np.pi * 200.6 * t)  # tone + 2nd harmonic
x += np.random.default_rng(0).normal(0, 1e-4, t.size)  # noise

results = harm_analysis(x, fs=fs)
print(f"{results.fund_freq:.2f} Hz, SNR {results.snr_db:.1f} dB, THD {results.thd_db:.1f} dB")
# 100.30 Hz, SNR 75.8 dB, THD -40.0 dB

There are two main functions:

  • harm_analysis: for simulations with an injected tone, returning SNR, THDN, Noise, etc.

  • spec_analysis: for cases without an injected tone, that auto-detects DC, tones, and noise from the spectrum.

Results

harm_analysis returns a HarmResult and spec_analysis returns a SpecResult (see the API). Each metric is an attribute, and to_dict() returns all of them as a dictionary:

results = harm_analysis(x, fs=fs)

results.snr_db  # signal-to-noise ratio in dB
results.thd_db  # total harmonic distortion in dB
results.harm_freq  # frequencies of the harmonics (empty array if none)

for name, value in results.to_dict().items():
    print(f"{name}: {value}")

Plotting

Pass plot=True and a Matplotlib ax to draw the power spectrum. The function draws on the ax you pass in, so you can keep customizing it afterwards:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
results = harm_analysis(x, fs=fs, plot=True, ax=ax)

ax.set_title("My measurement")
ax.set_xscale("log")
fig.savefig("spectrum.png")

Command line

The harm-analysis and spec-analysis commands run the same analyses on a text file of samples (see Command Line Interface). Add --json to get machine-readable output, e.g. for scripts or AI tools:

harm-analysis data.txt --fs 1e6 --json

Values that are not finite (NaN, or -inf dB for a power of zero) are written as null.

harm_analysis example usage

This example generates a tone with noise, harmonics and a DC value.

"""Example usage of the harm_analysis function."""

import matplotlib.pyplot as plt
import numpy as np

from harm_analysis import harm_analysis

# test signal
N = 4096
fs = 1000
t = np.arange(0, N / fs, 1 / fs)
F1 = 100.13

noise = np.random.normal(loc=0, scale=10 ** (-70 / 20), size=len(t))

# Test signal
# Tone with harmonics, DC and white gaussian noise
x = (
    noise
    + 0.1234
    + 2 * np.cos(2 * np.pi * F1 * t)  # Fundamental
    + 0.01 * np.cos(2 * np.pi * F1 * 2 * t)
    + 0.005 * np.cos(2 * np.pi * F1 * 3 * t)
)

# Use the harm_analysis function
fig, ax = plt.subplots()
results = harm_analysis(x, fs=fs, plot=True, ax=ax)

print("Parameters:")
for key, value in results.to_dict().items():
    print(f"{key}: {value}")

# Show plot
ax.set_title("Harmonic analysis example")
fig.savefig("./docs/images/example_usage.png")

outputs:

Parameters:
fund_db: 3.0102581512076476
fund_freq: 100.13000099796048
harm_freq: [200.25992094 300.38966102 399.69191637]
harm_db: [-43.02319863 -49.03958346 -96.91632087]
dc_db: -18.173402262439694
noise_db: -70.06725978382238
thd_db: -45.0634991329662
snr_db: 73.07751793503003
sinad_db: 45.05664362546099
thdn_db: -45.05664362546099
total_noise_db: -70.06725978382238

example_usage.py output plot

spec_analysis example usage

"""Example usage of the spec_analysis function."""

import matplotlib.pyplot as plt
import numpy as np

from harm_analysis import spec_analysis

# test signal
N = 4096
fs = 1000
t = np.arange(0, N / fs, 1 / fs)
F1 = 100.13

noise = np.random.normal(loc=0, scale=10 ** (-70 / 20), size=len(t))

# Test signal
# Tone with harmonics, DC and white gaussian noise
x = (
    noise
    + 0.1234
    + 2 * np.cos(2 * np.pi * F1 * t)
    + 0.01 * np.cos(2 * np.pi * F1 * 2 * t)
    + 0.005 * np.cos(2 * np.pi * F1 * 3 * t)
    + 0.01 * np.cos(2 * np.pi * F1 * 0.43 * t)
)

# Use the spec_analysis function
fig, ax = plt.subplots()
results = spec_analysis(x, fs=fs, plot=True, ax=ax)

print("Function results:")
for key, value in results.to_dict().items():
    print(f"{key}: {value}")

# Show plot
ax.set_title("Spectrum analysis example")
fig.savefig("./docs/images/example_spec_analysis.png")

outputs:

Function results:
dc: 0.12339484186693771
dc_db: -18.17405988475026
noise_db: -69.83418824960202
tones_db: [-42.99790788   3.01017539 -43.01559798 -49.04951617]
tones_freq: [ 43.05579084 100.12999825 200.25985241 300.38969635]

example_spec_analysis.py output plot