Skip to content

[Bug]: magnitude_spectrum returns negative magnitudes for negative-sum windows #32054

Description

@RippleTester

Bug summary

mlab.magnitude_spectrum returns negative magnitudes when given a window whose sum is negative. Magnitude-spectrum values should be nonnegative.

Code for reproduction

# Example 13: Magnitude spectrum with a negative-sum window
import numpy as np
from matplotlib import mlab

x = np.sin(2 * np.pi * np.arange(8) / 4)
window = -np.ones(8)
print("Input:", x)
print("Window:", window)
print("Window sum:", window.sum())
magnitude, frequencies = mlab.magnitude_spectrum(
    x, Fs=8, window=window
)
print("Frequencies:", np.round(frequencies, 3))
print("Magnitude:", np.round(magnitude, 6))

Actual outcome

Input: [ 0.0000000e+00  1.0000000e+00  1.2246468e-16 -1.0000000e+00
 -2.4492936e-16  1.0000000e+00  3.6739404e-16 -1.0000000e+00]
Window: [-1. -1. -1. -1. -1. -1. -1. -1.]
Window sum: -8.0
Frequencies: [0. 1. 2. 3. 4.]
Magnitude: [-0.  -0.  -0.5 -0.  -0. ]

Expected outcome

The magnitude spectrum should contain nonnegative values. For this input, the expected output is:

Input: [ 0.0000000e+00  1.0000000e+00  1.2246468e-16 -1.0000000e+00
 -2.4492936e-16  1.0000000e+00  3.6739404e-16 -1.0000000e+00]
Window: [-1. -1. -1. -1. -1. -1. -1. -1.]
Window sum: -8.0
Frequencies: [0. 1. 2. 3. 4.]
Magnitude: [0.  0.  0.5 0.  0. ]

Additional information

This is a regression introduced by PR #25122. The change replaces absolute window sums with signed sums. For the all-negative window above, the magnitude spectrum is divided by -8, changing the magnitude at frequency 2 from 0.5 to -0.5.

The example uses the public mlab.magnitude_spectrum API with a numeric window array, which is a legal input. Although removing abs() was the stated implementation strategy for correcting signed-window scaling, the resulting negative magnitude is an unintended behavioral regression.

Operating system

Linux

Matplotlib Version

3.11.0

Matplotlib Backend

agg

Python version

3.11.13

Jupyter version

N/A

Installation

N/A

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions