Skip to content

Commit

Permalink
Fix auglib.transform.PinkNoise for odd samples (#24)
Browse files Browse the repository at this point in the history
* Fix auglib.transform.PinkNoise for odd samples

* Add comment to code

* Fix linter

* Update test

* Add test for shape
  • Loading branch information
hagenw authored Jan 29, 2024
1 parent ef48643 commit e9fbcb9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
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
16 changes: 16 additions & 0 deletions tests/test_transform_pink_noise.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,19 @@ 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()
augmented_signal = transform(signal)
assert signal.shape == augmented_signal.shape

0 comments on commit e9fbcb9

Please sign in to comment.