Skip to content

Commit

Permalink
Ensure correct float types with numpy 2.0 (#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
hagenw authored Jul 4, 2024
1 parent 4cf278e commit aa87c89
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 10 deletions.
24 changes: 19 additions & 5 deletions auglib/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def from_db(x_db: typing.Union[float, observe.Base]) -> float:
"""
x_db = observe.observe(x_db)
x = pow(10.0, x_db / 20.0)
return x
return float(x)


def get_peak(signal: np.ndarray) -> float:
Expand All @@ -34,28 +34,42 @@ def get_peak(signal: np.ndarray) -> float:
Returns:
peak as positive value
Examples:
>>> get_peak(np.array([1, 2, 3]))
3.0
"""
minimum = np.min(signal)
maximum = np.max(signal)
if abs(minimum) > maximum:
peak = abs(minimum)
else:
peak = maximum
return peak
return float(peak)


def rms_db(signal: np.ndarray):
def rms_db(signal: np.ndarray) -> float:
r"""Root mean square in dB.
Very soft signals are limited
to a value of -120 dB.
Args:
signal: input signal
Returns:
root mean square in decibel
Examples:
>>> rms_db(np.zeros((1, 4)))
-120.0
"""
# It is:
# 20 * log10(rms) = 10 * log10(power)
# which saves us from calculating sqrt()
power = np.mean(np.square(signal))
return 10 * np.log10(max(1e-12, power))
return float(10 * np.log10(max(1e-12, power)))


def to_db(x: typing.Union[float, observe.Base]) -> float:
Expand All @@ -75,7 +89,7 @@ def to_db(x: typing.Union[float, observe.Base]) -> float:
x = observe.observe(x)
assert x > 0, "cannot convert gain {} to decibels".format(x)
x_db = 20 * np.log10(x)
return x_db
return float(x_db)


def to_samples(
Expand Down
6 changes: 2 additions & 4 deletions tests/test_transform_babble_noise.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,8 @@ def test_babble_noise_1(
if snr_db is not None:
gain_db = -120 - snr_db
gain = audmath.inverse_db(gain_db)
expected_babble = gain * np.ones(
(1, int(duration * sampling_rate)),
dtype=auglib.core.transform.DTYPE,
)
expected_babble = gain * np.ones((1, int(duration * sampling_rate)))
expected_babble = expected_babble.astype(auglib.core.transform.DTYPE)

babble = transform(signal)
assert babble.dtype == expected_babble.dtype
Expand Down
2 changes: 1 addition & 1 deletion tests/test_transform_pink_noise.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ 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)
np.testing.assert_almost_equal(noise, expected_noise, decimal=6)


@pytest.mark.parametrize(
Expand Down

0 comments on commit aa87c89

Please sign in to comment.