Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/Eomys/MoSQITo into master
Browse files Browse the repository at this point in the history
  • Loading branch information
wantysal committed Apr 13, 2021
2 parents ebdfd88 + 16bf3a3 commit 04c726d
Show file tree
Hide file tree
Showing 52 changed files with 6,964 additions and 1,700 deletions.
3 changes: 1 addition & 2 deletions mosqito/classes/Audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,7 @@ def __init__(self, file, is_stationary=False, calib=1, mat_signal="", mat_fs="")

# Init physical metrics attributes
self.third_spec = None
self.level_db = None
self.level_dba = None
self.level = None
self.welch = None

# Init physiological metrics attributes
Expand Down
Empty file added mosqito/classes/__init__.py
Empty file.
Empty file added mosqito/functions/__init__.py
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
85 changes: 67 additions & 18 deletions mosqito/functions/shared/level.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,82 @@
"""

# Standard library import
import numpy as np
from numpy import mean, sqrt, log10, linspace

# Local import
from mosqito.functions.shared.conversion import spectrum2dBA


def comp_level(is_stationary, spec_third, fs, unit):
"""Overall Sound Pressure Level calculation in the chosen unit
from the signal's third-octave spectrum
def comp_level(signal, fs, nb_points=[], start=[], stop=[]):
"""Overall Sound Pressure Level calculation from the time signal
The SPL can be computed according to a specified number of points or
during a given time frame
Parameter:
----------
spec_third_dB: numpy.array
third octave spectrum of the signal
signal : numpy.array
time signal value
fs: integer
sampling frequency
unit : string
'dB' or 'dBA'
Output:
-------
level : numpy.array
SPL in dB
"""
# Check the inputs
if nb_points != []:
if type(nb_points) != int:
raise TypeError("ERROR : Number of points should be an integer")

if nb_points < 1 or nb_points > len(signal):
raise ValueError(
"ERROR : Number of points should be between 1 and the length of the given signal"
)

if start != [] and stop != []:
if type(start) != int and type(start) != float:
raise TypeError("ERROR : Start (in sec) should be an integer or a float ")

if type(stop) != int and type(stop) != float:
raise TypeError("ERROR : Stop (in sec) should be an integer or a float ")

if start < 0 or stop < 0 or start > len(signal) / fs or stop > len(signal) / fs:
raise ValueError(
"ERROR : Time frame should be between 0s and the duration of the signal"
)

if start == stop:
raise ValueError("ERROR : Start and stop values must be different")

# Initialization
level = []

# Case of a given time frame
if start != [] and stop != []:
frame = signal[int(start * fs) : int(stop * fs)]
else:
start = 0
stop = len(signal) / fs
frame = signal

# Case of a given number of points
if nb_points != []:

time_axis = linspace(start, stop, num=nb_points)

frame_size = int(len(frame) / nb_points)
for i in range(nb_points):
frame_i = frame[i * frame_size : i * frame_size + frame_size]
peff = sqrt(mean(frame_i ** 2))
level.append(10 * log10((peff ** 2 / (2e-05) ** 2)))

if unit == "dB":
level = 10 * np.log10(sum(np.power(10, spec_third["values"] / 10)))
else:
peff = sqrt(mean(frame ** 2))
level = 10 * log10((peff ** 2 / (2e-05) ** 2))

elif unit == "dBA":
# spectrum A-weighting
spec_third_dBA = spectrum2dBA(spec_third["values"], fs)
level = 10 * np.log10(sum(np.power(10, spec_third_dBA / 10)))
output = {
"name": "Sound Pressure Level",
"values": level,
"time": time_axis,
}

return level
return output
Empty file.
2 changes: 1 addition & 1 deletion mosqito/functions/sharpness/sharpness_aures.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def comp_sharpness_aures(N, N_specific, is_stationary):
gA = np.zeros((z.size))
gA = 0.078 * (np.exp(0.171 * z) / z) * (N / np.log(N * 0.05 + 1))
S = 0.11 * sum(N_specific * gA * z * 0.1) / N
print("Aures sharpness:", str(S), "acum")
print("Aures sharpness:", "%.2f" % S, "acum")
else:
S = np.zeros((N.size))
gA = np.zeros((z.size, N.size))
Expand Down
2 changes: 1 addition & 1 deletion mosqito/functions/sharpness/sharpness_bismarck.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def comp_sharpness_bismarck(N, N_specific, is_stationary):
S = 0
else:
S = 0.11 * sum(N_specific * gB * z * 0.1) / N
print("Bismarck sharpness:", str(S), "acum")
print("Bismarck sharpness:", "%.2f" % S, "acum")
else:
S = np.zeros((N.size))
for t in range(N.size):
Expand Down
2 changes: 1 addition & 1 deletion mosqito/functions/sharpness/sharpness_din.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def comp_sharpness_din(N, N_specific, is_stationary):
S = 0
else:
S = 0.11 * sum(N_specific * gDIN * z * 0.1) / N
print("DIN sharpness:", str(S), "acum")
print("DIN sharpness:", "%.2f" % S, "acum")
else:
S = np.zeros((N.size))
for t in range(N.size):
Expand Down
2 changes: 1 addition & 1 deletion mosqito/functions/sharpness/sharpness_fastl.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def comp_sharpness_fastl(N, N_specific, is_stationary):
S = 0
else:
S = 0.11 * sum(N_specific * gZF * z * 0.1) / N
print("Fastl sharpness:", str(S), "acum")
print("Fastl sharpness:", "%.2f" % S, "acum")
else:
S = np.zeros((N.size))
for t in range(N.size):
Expand Down
Empty file.
Empty file.
132 changes: 70 additions & 62 deletions mosqito/methods/Audio/compute_level.py
Original file line number Diff line number Diff line change
@@ -1,82 +1,90 @@
# -*- coding: utf-8 -*-

from numpy import log10, power, linspace
from numpy import log10, linspace, mean, sqrt

from SciDataTool import Data1D, DataTime


def compute_level(self, unit):
"""Overall Sound Pressure Level calculation in the chosen unit
TODO: modify to use get_rms of SciDataTool or even remove
def compute_level(self, nb_points=[], start=[], stop=[]):
"""Overall Sound Pressure Level calculation from the time signal
The SPL can be computed according to a specified number of points or
during a given time frame
Parameter:
----------
unit : string
'dB' or 'dBA' to apply A-weighting
plot : boolean
if True, the overall level is plotted along time (non-steady signals)
"""
signal : numpy.array
time signal value
fs: integer
sampling frequency
if unit == "dB":
# Third octave spectrum calculation
if self.third_spec_db == None:
self.comp_3oct_spec()
Output:
-------
level : numpy.array
SPL in dB
L = 10 * log10(sum(power(10, self.third_spec_db.values / 10)))
"""
# Check the inputs
if nb_points != []:
if type(nb_points) != int:
raise TypeError("ERROR : Number of points should be an integer")

if self.is_stationary == True:
self.level_db = Data1D(
values=[L], name="Overall Sound Pressure Level", unit="dB"
if nb_points < 1 or nb_points > len(self.signal.values):
raise ValueError(
"ERROR : Number of points should be between 1 and the length of the given signal"
)

else:
time = Data1D(
symbol="T",
name="Time axis",
unit="s",
values=linspace(
0,
len(self.signal.values) / self.fs,
self.third_spec_db.values.shape[1],
),
)
if start != [] and stop != []:
if type(start) != int and type(start) != float:
raise TypeError("ERROR : Start (in sec) should be an integer or a float ")

if type(stop) != int and type(stop) != float:
raise TypeError("ERROR : Stop (in sec) should be an integer or a float ")

self.level_db = DataTime(
symbol="dB",
axes=[time],
values=L,
name="Overall Sound Pressure Level",
unit="dB",
if (
start < 0
or stop < 0
or start > len(self.signal.values) / self.fs
or stop > len(self.signal.values) / self.fs
):
raise ValueError(
"ERROR : Time frame should be between 0s and the duration of the signal"
)

elif unit == "dBA":
# Third octave spectrum calculation
if self.third_spec_dba == None:
self.comp_3oct_spec(unit="dBA")
if start == stop:
raise ValueError("ERROR : Start and stop values must be different")

L = 10 * log10(sum(power(10, self.third_spec_dba.values / 10)))
# Initialization
level = []

if self.is_stationary == True:
self.level_dba = Data1D(
values=[L], name="Overall Sound Pressure Level", unit="dBA"
)
else:
time = Data1D(
symbol="T",
name="Time axis",
unit="s",
values=linspace(
0,
len(self.signal.values) / self.fs,
self.third_spec_dba.values.shape[1],
),
)
# Case of a given time frame
if start != [] and stop != []:
frame = self.signal.values[int(start * self.fs) : int(stop * self.fs)]
else:
start = 0
stop = len(self.signal.values) / self.fs
frame = self.signal.values

self.level_dba = DataTime(
symbol="dBA",
axes=[time],
values=L,
name="Overall Sound Pressure Level",
unit="dBA",
)
# Case of a given number of points
if nb_points != []:

time = Data1D(
name="time", unit="s", values=linspace(start, stop, num=nb_points)
)

frame_size = int(len(frame) / nb_points)
for i in range(nb_points):
frame_i = frame[i * frame_size : i * frame_size + frame_size]
peff = sqrt(mean(frame_i ** 2))
level.append(10 * log10((peff ** 2 / (2e-05) ** 2)))

self.level = DataTime(
name="Sound Pressure Level",
symbol="SPL",
unit="dB",
axes=[time],
values=level,
)

else:
peff = sqrt(mean(frame ** 2))
self.level = 10 * log10((peff ** 2 / (2e-05) ** 2))
Empty file added mosqito/methods/__init__.py
Empty file.
Empty file added mosqito/tests/Audio/__init__.py
Empty file.
16 changes: 15 additions & 1 deletion mosqito/tests/Audio/test_Audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,9 @@ def test_comp_3oct_spec(fixture_import_signal):
audio.comp_3oct_spec()
audio.third_spec.plot_2D_Data(
"freqs",
is_logscale_x=True,
type_plot="curve",
is_logscale_x=True,
x_min=20,
y_min=0,
y_max=40,
unit="dB",
Expand All @@ -62,6 +63,19 @@ def test_comp_3oct_spec(fixture_import_signal):
)


@pytest.mark.audio
def test_level(fixture_import_signal_time):
audio = fixture_import_signal_time
audio.compute_level(nb_points=20, start=0.5, stop=4)
audio.level.plot_2D_Data(
"time",
type_plot="curve",
unit="dB",
is_show_fig=is_show_fig,
save_path=out_path + "test_level.png",
)


@pytest.mark.audio
def test_compute_loudness(fixture_import_signal):
audio = fixture_import_signal
Expand Down
Empty file added mosqito/tests/__init__.py
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
5 changes: 2 additions & 3 deletions mosqito/tests/tonality_tnr_pr/test_pr.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,14 @@ def test_pr():
signal.append(
{
"is_stationary": True,
"tones freq": [200, 2000],
"data_file": r"mosqito\tests\tonality_tnr_pr\white_noise_200_2000_Hz_stationary.wav",
"data_file": r"mosqito\tests\tonality_tnr_pr\white_noise_442_1768_Hz_stationary.wav",
}
)

signal.append(
{
"is_stationary": False,
"data_file": r"mosqito\tests\tonality_tnr_pr\white_noise_200_2000_Hz_varying.wav",
"data_file": r"mosqito\tests\tonality_tnr_pr\white_noise_442_1768_Hz_varying.wav",
}
)

Expand Down
4 changes: 2 additions & 2 deletions mosqito/tests/tonality_tnr_pr/test_tnr.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,14 @@ def test_tnr():
{
"is_stationary": True,
"tones freq": [200, 2000],
"data_file": r"mosqito\tests\tonality_tnr_pr\white_noise_200_2000_Hz_stationary.wav",
"data_file": r"mosqito\tests\tonality_tnr_pr\white_noise_442_1768_Hz_stationary.wav",
}
)

signal.append(
{
"is_stationary": False,
"data_file": r"mosqito\tests\tonality_tnr_pr\white_noise_200_2000_Hz_varying.wav",
"data_file": r"mosqito\tests\tonality_tnr_pr\white_noise_442_1768_Hz_varying.wav",
}
)

Expand Down
Binary file not shown.
6 changes: 5 additions & 1 deletion mosqito/validations/sharpness/validation_sharpness_din.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,11 @@ def check_compliance(sharpness, reference, noise_type):
plt.ylabel("Sharpness, [acum]")

plt.savefig(
"./mosqito/validations/sharpness/output/" + "validation_sharpness_" + noise_type + "_noise" + ".png",
"./mosqito/validations/sharpness/output/"
+ "validation_sharpness_"
+ noise_type
+ "_noise"
+ ".png",
format="png",
)
plt.clf()
Expand Down
Loading

0 comments on commit 04c726d

Please sign in to comment.