8000 Merge pull request #4326 from tacaswell/fix_mlab_psd · matplotlib/matplotlib@063e3f1 · GitHub
[go: up one dir, main page]

Skip to content

Commit 063e3f1

Browse files
committed
Merge pull request #4326 from tacaswell/fix_mlab_psd
BUG : fix scaling issue with mlab.psd and odd NFFT
2 parents f918227 + 01d2e6c commit 063e3f1

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

lib/matplotlib/mlab.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -782,7 +782,15 @@ def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None,
782782
# Also include scaling factors for one-sided densities and dividing by
783783
# the sampling frequency, if desired. Scale everything, except the DC
784784
# component and the NFFT/2 component:
785-
result[1:-1] *= scaling_factor
785+
786+
# if we have a even number of frequencies, don't scale NFFT/2
787+
if not NFFT % 2:
788+
slc = slice(1, -1, None)
789+
# if we have an odd number, just don't scale DC
790+
else:
791+
slc = slice(1, None, None)
792+
793+
result[slc] *= scaling_factor
786794

787795
# MATLAB divides by the sampling frequency so that density function
788796
# has units of dB/Hz and can be integrated by the plotted frequency

lib/matplotlib/tests/test_mlab.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2960,8 +2960,17 @@ def test_evaluate_equal_dim_and_num_lt(self):
29602960
np.testing.assert_array_almost_equal(y, y_expected, 7)
29612961

29622962

2963-
#*****************************************************************
2964-
#*****************************************************************
2963+
def test_psd_onesided_norm():
2964+
u = np.array([0, 1, 2, 3, 1, 2, 1])
2965+
dt = 1.0
2966+
Su = np.abs(np.fft.fft(u) * dt)**2 / float(dt * u.size)
2967+
P, f = mlab.psd(u, NFFT=u.size, Fs=1/dt, window=mlab.window_none,
2968+
detrend=mlab.detrend_none, noverlap=0, pad_to=None,
2969+
scale_by_freq=None,
2970+
sides='onesided')
2971+
Su_1side = np.append([Su[0]], Su[1:4] + Su[4:][::-1])
2972+
assert_allclose(P, Su_1side, atol=1e-06)
2973+
29652974

29662975
if __name__ == '__main__':
29672976
import nose

0 commit comments

Comments
 (0)
0