Spectral
Spectral analysis functions: FFT amplitude spectrum, power spectral density, cross-spectral density, coherence, autocorrelation, and cross-correlation.
Three estimators of the same quantity live here, and they fail differently.
psd averages periodograms and is the default. blackman_tukey_psd transforms
a tapered autocorrelation and trades resolution for variance through the lag
window, explicitly. ar_psd fits an all-pole model to the whole record and can
separate two close peaks on a record too short for either of the others — at
the cost of an order that decides what the answer says.
segment_advice answers the question the first of those poses. nperseg can be
wrong in two opposite directions, and only one of them is obvious.
All estimators use scipy.signal under the hood with engineering-friendly defaults (Hann window, density scaling, mean detrending).

dspkit.spectral.fft_spectrum(x, fs, window='hann', scaling='amplitude')
Single-sided FFT amplitude spectrum with window amplitude correction.
For a pure sine of amplitude A at frequency f, the returned spectrum will
show A at that frequency bin (with scaling='amplitude').
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
(array_like, shape(N))
|
Time-domain signal. |
required |
fs
|
float
|
Sampling frequency [Hz]. |
required |
window
|
str or None
|
Window function name accepted by |
'hann'
|
scaling
|
(amplitude, rms)
|
|
'amplitude'
|
Returns:
| Name | Type | Description |
|---|---|---|
freqs |
(ndarray, shape(N // 2 + 1))
|
Frequency vector [Hz]. |
amplitude |
(ndarray, shape(N // 2 + 1))
|
Amplitude spectrum in the same units as |
Source code in dspkit/spectral.py
dspkit.spectral.psd(x, fs, window='hann', nperseg=None, noverlap=None, scaling='density', detrend='constant')
Power spectral density (or power spectrum) via Welch's method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
(array_like, shape(N))
|
Time-domain signal. |
required |
fs
|
float
|
Sampling frequency [Hz]. |
required |
window
|
str
|
Window function (default |
'hann'
|
nperseg
|
int or None
|
Segment length. Defaults to |
None
|
noverlap
|
int or None
|
Number of overlapping samples between segments.
Defaults to |
None
|
scaling
|
(density, spectrum)
|
|
'density'
|
detrend
|
str or False
|
Detrending applied to each segment before windowing.
|
'constant'
|
Returns:
| Name | Type | Description |
|---|---|---|
freqs |
ndarray
|
Frequency vector [Hz]. |
Pxx |
ndarray
|
One-sided PSD or power spectrum (real, non-negative). |
Source code in dspkit/spectral.py
dspkit.spectral.ar_psd(x, fs, order=None, method='burg', n_freqs=2048, max_order=None, criterion='aic', detrend=True)
Power spectral density from an autoregressive model.
The third classical spectral estimator, alongside Welch (psd) and the
correlogram (blackman_tukey_psd). Instead of averaging periodograms it
fits an all-pole model to the record and evaluates its transfer function::
S(f) = e / | 1 + sum_k a_k exp(-2 pi i f k / fs) |^2 / fs
Reach for it when the record is too short for Welch. Welch's resolution is set by the segment length and its variance by the number of segments, and a short record cannot give both. An AR model is not segmented at all: it spends the whole record on one fit, so it can resolve two close modes where Welch would need more data than exists.
Measured on two tones at 10.0 and 10.8 Hz in noise, 2 s at 100 Hz -- 200 samples in total::
Welch, nperseg=200 (Be = 0.75 Hz) one peak at 10.50 Hz
Welch, nperseg=128 (Be = 1.17 Hz) one peak at 10.16 Hz
Welch, nperseg= 64 (Be = 2.34 Hz) one peak at 10.94 Hz
AR Burg, order 30 9.99 and 10.85 Hz
Welch merges them at every usable segment length; the AR fit separates them to within 0.05 Hz. Note the order needed, which is the next point.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
(array_like, shape(N))
|
The record. |
required |
fs
|
float
|
Sampling frequency [Hz]. |
required |
order
|
int or None
|
Model order. |
None
|
method
|
(burg, yule_walker)
|
Burg by default -- it does not window the data and always returns a stable model. Yule-Walker is offered because it is what most textbooks derive and is useful for comparison. |
'burg'
|
n_freqs
|
int
|
Frequencies at which to evaluate, from 0 to Nyquist. This is a drawing
resolution, not an information one: the model has |
2048
|
max_order
|
int or None
|
Ceiling for automatic selection. Defaults to |
None
|
criterion
|
(aic, bic)
|
Used only when |
'aic'
|
detrend
|
bool
|
Remove the mean first (default True). A DC offset is a pole at zero frequency and will otherwise dominate the fit. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
freqs |
ndarray
|
Frequency vector [Hz]. |
pxx |
ndarray
|
One-sided PSD [units^2/Hz]. |
info |
dict
|
|
Notes
The order is the estimate. Unlike Welch, where a bad nperseg gives a
blurred but honest picture, a bad AR order changes what the spectrum says.
Too low and close modes merge into one broad peak; too high and the model
spends poles on noise. Measured on the library's 2-DOF example, displacement
output (N = 20480, fs = 1024 Hz, true modes 8.613 Hz at 1.22% damping and
20.795 Hz at 2.94%)::
order 2 one peak, at 10.5 Hz — the two modes merged
order 4 one peak, at 10.5 Hz
order 22 8.504 and 21.761 Hz
order 100 8.504 and 20.760 Hz
AIC -> 83 8.504 and 20.760 Hz
BIC -> 46 8.504 and 21.010 Hz
An order of 4 is not enough for a 2-DOF system, which is the trap: the
rule of thumb "two poles per mode" describes a noiseless model, not a fit to
a finite noisy record. AIC and BIC both landed somewhere workable here, but
AIC will happily run to whatever max_order allows on a long record — it
chose the ceiling on the acceleration channel of the same fixture.
It is a model, not a measurement. An AR spectrum is smooth and confident
everywhere, including where the data says nothing, and it has no equivalent
of a confidence interval falling out of the segment count. Cross-check
against psd before believing a peak that only the AR estimate shows.
Peaks are also biased: an all-pole model represents a resonance exactly and
an antiresonance only by cancellation, so notches come out shallower than
they are. Use psd where the notch matters.
See Also
psd, blackman_tukey_psd, segment_advice, ar_order_selection
Examples:
>>> import numpy as np
>>> from dspkit.spectral import ar_psd
>>> from dspkit._testing import generate_2dof
>>> t, a1, a2 = generate_2dof(duration=20.0, fs=1024.0, seed=0)
>>> f, p, info = ar_psd(a1, 1024.0, order=40)
>>> info['order'], info['reflection_stable']
(40, True)
Source code in dspkit/spectral.py
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 | |
dspkit.spectral.ar_order_selection(x, max_order, method='burg', criterion='aic')
Choose an AR order by an information criterion.
Returns (best_order, scores) where scores[p] is the criterion at
order p. "aic" is the Akaike criterion N ln(e_p) + 2p,
"bic" swaps the penalty for p ln N and so picks lower orders.
Order selection on a spectrum is not the same problem as on a forecast, and no criterion settles it: too low and peaks merge, too high and the estimate grows spurious ones. Treat the answer as a starting point and look at the spectrum.
Source code in dspkit/spectral.py
dspkit.spectral.csd(x, y, fs, window='hann', nperseg=None, noverlap=None, detrend='constant')
Cross-spectral density via Welch's method.
Gxy(f) = E[X*(f) Y(f)] / Hz, where X, Y are the DFTs of x and y.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
(array_like, shape(N))
|
Input signals. They must have the same sampling frequency. |
required |
y
|
(array_like, shape(N))
|
Input signals. They must have the same sampling frequency. |
required |
fs
|
float
|
Sampling frequency [Hz]. |
required |
window
|
str
|
Window function (default |
'hann'
|
nperseg
|
int or None
|
Segment length. Defaults to |
None
|
noverlap
|
int or None
|
Overlapping samples. Defaults to |
None
|
detrend
|
str or False
|
Per-segment detrending (see |
'constant'
|
Returns:
| Name | Type | Description |
|---|---|---|
freqs |
ndarray
|
Frequency vector [Hz]. |
Pxy |
ndarray(complex)
|
One-sided cross-spectral density [units_x · units_y / Hz]. |
Source code in dspkit/spectral.py
dspkit.spectral.coherence(x, y, fs, window='hann', nperseg=None, noverlap=None, detrend='constant', min_segments=8)
Magnitude-squared coherence between x and y.
Cxy(f) = |Gxy(f)|² / (Gxx(f) · Gyy(f)), values in [0, 1].
A value near 1 means the two signals are linearly related at that frequency. A value near 0 indicates noise or nonlinearity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
(array_like, shape(N))
|
|
required |
y
|
(array_like, shape(N))
|
|
required |
fs
|
float
|
Sampling frequency [Hz]. |
required |
window
|
str
|
Window function (default |
'hann'
|
nperseg
|
int or None
|
Segment length. Defaults to |
None
|
noverlap
|
int or None
|
Overlapping samples. Defaults to |
None
|
detrend
|
str or False
|
Per-segment detrending. |
'constant'
|
min_segments
|
int
|
Warn below this many Welch segments (default 8). Fewer than two segments raises instead — see Notes. |
8
|
Returns:
| Name | Type | Description |
|---|---|---|
freqs |
ndarray
|
|
Cxy |
ndarray
|
Magnitude-squared coherence, values in [0, 1]. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the parameters give fewer than two Welch segments. |
Notes
Coherence is made by the averaging, not by the formula. Within a
single segment |Gxy|² = Gxx·Gyy identically, so a one-segment estimate is
exactly 1.0 at every frequency whatever the two signals are.
nperseg = len(x) is precisely that case, and it is rejected rather
than returned. Measured on the library's 2-DOF example (N = 20480,
fs = 1024 Hz): mean coherence 0.0675 at nperseg=1024 (39 segments),
and exactly 1.0000 everywhere at nperseg=N.
The bias does not stop at one segment, it only becomes finite. For two
independent signals averaged over n_d segments the expected coherence
is about 1 / n_d, so a value of 0.2 from 5 segments is what
independence looks like, not evidence of a relationship. min_segments
warns while that floor is still large; it does not correct for it.
What this will not tell you: whether the relationship is causal, which
channel leads (use the cross-spectrum phase), whether a low value means
noise or nonlinearity, or whether a high value at one frequency survives
conditioning on the other channels in an array — for that see
dspkit.multisensor.partial_coherence.
Source code in dspkit/spectral.py
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 | |
dspkit.spectral.resolution_bandwidth(fs, nperseg, window='hann')
Effective resolution bandwidth of a Welch estimate [Hz].
The equivalent noise bandwidth of the window, N sum(w^2) / (sum w)^2
bins, converted to Hz. It is the width of the rectangle that would pass the
same noise power, and it is what decides whether a sharp peak is resolved
or smeared -- not the bin spacing fs / nperseg, which is finer and
flatters the estimate.
Measured: Hann gives exactly 1.5 bins, Hamming 1.363, rectangular 1.0, Blackman 1.727 and flat-top 3.770, independent of length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fs
|
float
|
Sampling frequency [Hz]. |
required |
nperseg
|
int
|
Welch segment length in samples. |
required |
window
|
str
|
Window name, as passed to the estimators. |
'hann'
|
Source code in dspkit/spectral.py
dspkit.spectral.segment_advice(x, fs, nperseg=None, noverlap=None, window='hann', n_inputs=1, target_segments=20, peak_prominence_db=6.0, dynamic_range_db=20.0, max_peaks=8)
Whether nperseg is long enough to resolve the peaks and short enough to
average.
The two failure modes pull in opposite directions and only one of them is
obvious. Too few averages is the familiar one: coherence is biased up by
about q / n_d and spectra are noisy, and the cure is a shorter segment.
The other is that a segment too short to resolve the narrowest peak lets
leakage smear peaks and notches, which biases coherence down and
manufactures a residual where none exists -- an error that grows as the
square of the resolution bandwidth and is worst exactly where the signal is
strongest. Shortening nperseg to win averages walks straight into it.
This returns both numbers together so the trade can be made deliberately rather than one side at a time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
(array_like, shape(N))
|
The record. Used to find the sharpest peak; pass the channel whose resonances matter. |
required |
fs
|
float
|
Sampling frequency [Hz]. |
required |
nperseg
|
int or None
|
Segment length to assess. Defaults to |
None
|
noverlap
|
int or None
|
Overlap in samples, default |
None
|
window
|
str
|
Window name. |
'hann'
|
n_inputs
|
int
|
Number of predictors, for the coherence bias floor |
1
|
target_segments
|
int
|
Averages considered adequate, used only to size the record this would need. 20 puts the bias floor at 0.05. |
20
|
peak_prominence_db
|
float
|
How far a peak must stand above its surroundings, in dB, to count as a resonance worth resolving (default 6, a factor of four in power). Lower it on a record whose modes barely clear the noise. |
6.0
|
dynamic_range_db
|
float
|
Ignore peaks more than this far below the tallest (default 20 dB). Widens the net on a flat spectrum; narrow it on one with a huge dynamic range where only the top mode is of interest. |
20.0
|
max_peaks
|
int
|
Consider only the tallest this many peaks. "The sharpest peak" means the sharpest one that matters, not the narrowest wiggle on the floor. |
8
|
Returns:
| Type | Description |
|---|---|
dict with keys
|
|
Notes
An unresolved peak cannot report its own width. The bandwidth measured
off a smeared peak is roughly the resolution bandwidth itself, whatever the
true width is, so ratio saturates near 1 rather than growing. That is
why the verdict for ratio above about 0.9 is "unresolved" rather than a
number: the honest answer is that the record cannot yet say how narrow the
peak is, and the test is to lengthen nperseg until the measured width
stops shrinking.
"squeezed" means both cannot be satisfied on this record: resolving the
peak leaves too few segments. That is a statement about the record, not
about the parameters, and the fix is more data. duration_for_both says
how much.
See Also
resolution_bandwidth, coherence, dspkit.frf.error_spectrum, dspkit.peaks.peak_bandwidth
Source code in dspkit/spectral.py
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 | |
dspkit.spectral.autocorrelation(x, fs=None, normalize=True, max_lag=None)
Biased autocorrelation function (ACF) via FFT.
Uses the biased estimator (divides by N, not N-k) for better variance behaviour at large lags.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
(array_like, shape(N))
|
Input signal (zero-mean recommended; detrend first if needed). |
required |
fs
|
float or None
|
Sampling frequency [Hz]. If provided, the lag axis is in seconds; otherwise it is in samples. |
None
|
normalize
|
bool
|
If |
True
|
max_lag
|
float or None
|
Maximum lag to return. Interpreted in seconds if |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
lags |
ndarray
|
Lag axis (seconds if |
acf |
ndarray
|
Autocorrelation values. |
Source code in dspkit/spectral.py
dspkit.spectral.cross_correlation(x, y, fs=None, normalize=True, max_lag=None)
Biased cross-correlation function (CCF) via FFT.
Computes the full two-sided CCF with lags from -(N-1) to +(N-1):
CCF[k] = (1/N) Σ_n x[n] · y[n + k]
A positive peak at lag k > 0 means y is the delayed copy: the pairing
is x[n] with y[n+k], so if y[n] = x[n-d] the peak sits at k = +d and x
leads y by d samples. (This docstring said the opposite until 2026-09-02;
the formula above was always right. test_cross_correlation_lag_sign
pins the direction.)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
(array_like, shape(N))
|
Input signals. Must have the same length. |
required |
y
|
(array_like, shape(N))
|
Input signals. Must have the same length. |
required |
fs
|
float or None
|
Sampling frequency [Hz]. If provided, the lag axis is in seconds; otherwise it is in samples. |
None
|
normalize
|
bool
|
If |
True
|
max_lag
|
float or None
|
Maximum absolute lag to return. Interpreted in seconds if |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
lags |
ndarray
|
Symmetric lag axis, running from |
ccf |
ndarray
|
Cross-correlation values. |