Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix auglib.transform.PinkNoise for odd samples #24

Merged
merged 5 commits into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions auglib/core/transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -3261,16 +3261,20 @@ def _pink_noise(self, samples: int) -> np.ndarray:
def psd(f):
return 1 / np.where(f == 0, float("inf"), np.sqrt(f))

white_noise = np.fft.rfft(np.random.randn(samples))
# Add extra sample
# to ensure correct length for odd samples
length = samples + 1

white_noise = np.fft.rfft(np.random.randn(length))

# Normalized pink noise shape
pink_shape = psd(np.fft.rfftfreq(samples))
pink_shape = psd(np.fft.rfftfreq(length))
pink_shape = pink_shape / np.sqrt(np.mean(pink_shape**2))

white_noise_shaped = white_noise * pink_shape
pink_noise = np.fft.irfft(white_noise_shaped)

return np.atleast_2d(pink_noise)
return np.atleast_2d(pink_noise[:samples])


class Prepend(Base):
Expand Down
15 changes: 15 additions & 0 deletions tests/test_transform_pink_noise.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,18 @@ def test_pink_noise(duration, sampling_rate, gain_db, snr_db):
assert noise.shape == expected_noise.shape
assert noise.dtype == expected_noise.dtype
np.testing.assert_almost_equal(noise, expected_noise)


@pytest.mark.parametrize(
"signal",
[
# Odd,
# compare https://github.com/audeering/auglib/issues/23
np.ones((1, 30045)),
# Even
np.ones((1, 200)),
],
)
def test_pink_noise_odd_and_even_samples(signal):
transform = auglib.transform.PinkNoise()
transform(signal)
audeerington marked this conversation as resolved.
Show resolved Hide resolved
Loading