diff --git a/docs/conf.py b/docs/conf.py index 3ff6426c..9c5cfa3a 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -92,6 +92,7 @@ def __getattr__(cls, name): numpydoc_show_class_members = False + # Custom function to define some 'noisy' class members to skip def skip_member(app, what, name, obj, skip, options): exclusions = ( diff --git a/docs/make_materials_table.py b/docs/make_materials_table.py index ea3053a6..6a36efc7 100755 --- a/docs/make_materials_table.py +++ b/docs/make_materials_table.py @@ -27,20 +27,17 @@ def format_freq(f): def print_section(title, data, headers, file): - print(title, file=file) print("-" * len(title), file=file) print(file=file) for subtitle, materials in data.items(): - print(subtitle, file=file) print("^" * len(subtitle), file=file) print(file=file) table = [] for keyword, p in materials.items(): - # fill the table row = [keyword, p["description"]] for c in p["coeffs"]: @@ -57,7 +54,6 @@ def print_section(title, data, headers, file): if __name__ == "__main__": - with open(datafile, "r") as f: data = json.load(f) @@ -66,7 +62,6 @@ def print_section(title, data, headers, file): ] with open(docfile, "w") as f: - print("Materials Database", file=f) print("==================", file=f) print(file=f) @@ -77,7 +72,6 @@ def print_section(title, data, headers, file): } for key, sectitle in sections.items(): - print_section( title=sectitle, data=data[key], diff --git a/examples/adaptive_filter_stft_domain.py b/examples/adaptive_filter_stft_domain.py index 42b8d1e3..28990923 100644 --- a/examples/adaptive_filter_stft_domain.py +++ b/examples/adaptive_filter_stft_domain.py @@ -41,12 +41,7 @@ num_blocks = 0 X_concat = np.zeros((num_bands, n_samples // hop), dtype=np.complex64) while n_samples - n > hop: - - stft_in.analysis( - x[ - n : n + hop, - ] - ) + stft_in.analysis(x[n : n + hop,]) X_concat[:, num_blocks] = stft_in.X n += hop @@ -73,7 +68,6 @@ error_per_band = np.zeros((num_bands, num_blocks), dtype=np.complex64) time_idx = 0 for n in range(num_blocks): - # update filter with new samples adaptive_filters.update(X_concat[:, n], D_concat[:, n]) error_per_band[:, n] = np.linalg.norm(adaptive_filters.W.conj() - W, axis=0) diff --git a/examples/bss_example.py b/examples/bss_example.py index 5f9ceadc..7ed6b532 100755 --- a/examples/bss_example.py +++ b/examples/bss_example.py @@ -75,7 +75,6 @@ ] if __name__ == "__main__": - choices = ["ilrma", "auxiva", "sparseauxiva", "fastmnmf", "fastmnmf2"] import argparse @@ -153,7 +152,6 @@ # Record each source separately separate_recordings = [] for source, signal in zip(room.sources, signals): - source.signal[:] = signal room.simulate() @@ -293,7 +291,6 @@ def convergence_callback(Y): ) if args.gui: - # Make a simple GUI to listen to the separated samples from tkinter import Tk, Button, Label import sounddevice as sd diff --git a/examples/bss_live.py b/examples/bss_live.py index 225e8bf3..2cffc743 100644 --- a/examples/bss_live.py +++ b/examples/bss_live.py @@ -67,7 +67,6 @@ if __name__ == "__main__": - choices = ["ilrma", "auxiva", "sparseauxiva", "fastmnmf", "fastmnmf2"] import argparse diff --git a/examples/cmu_arctic_corpus.py b/examples/cmu_arctic_corpus.py index ac948b80..66703180 100644 --- a/examples/cmu_arctic_corpus.py +++ b/examples/cmu_arctic_corpus.py @@ -18,7 +18,6 @@ import os if __name__ == "__main__": - parser = argparse.ArgumentParser( description="Example of using the CMUArcticCorpus wrapper" ) diff --git a/examples/directivities/plot_directivity_2D.py b/examples/directivities/plot_directivity_2D.py index 7657fe20..b6aa955d 100644 --- a/examples/directivities/plot_directivity_2D.py +++ b/examples/directivities/plot_directivity_2D.py @@ -19,7 +19,6 @@ fig = plt.figure() ax = plt.subplot(111, projection="polar") for pattern in DirectivityPattern: - dir_obj = CardioidFamily(orientation=orientation, pattern_enum=pattern) resp = dir_obj.get_response(azimuth=angles, magnitude=True, degrees=False) resp_db = dB(np.array(resp)) diff --git a/examples/doa_anechoic_room.py b/examples/doa_anechoic_room.py index 1c866db5..98b43534 100644 --- a/examples/doa_anechoic_room.py +++ b/examples/doa_anechoic_room.py @@ -11,7 +11,6 @@ methods = ["MUSIC", "FRIDA", "WAVES", "TOPS", "CSSM", "SRP", "NormMUSIC"] if __name__ == "__main__": - parser = argparse.ArgumentParser( description="Estimates the direction of arrival of a sound source." ) diff --git a/examples/google_speech_commands_corpus.py b/examples/google_speech_commands_corpus.py index 68c9f4ab..b1e2cd53 100644 --- a/examples/google_speech_commands_corpus.py +++ b/examples/google_speech_commands_corpus.py @@ -13,7 +13,6 @@ import pyroomacoustics as pra if __name__ == "__main__": - parser = argparse.ArgumentParser( description="Example of using the GoogleSpeechCommands wrapper" ) diff --git a/examples/hmm_training.py b/examples/hmm_training.py index d9a45496..ab25fbc8 100644 --- a/examples/hmm_training.py +++ b/examples/hmm_training.py @@ -12,7 +12,6 @@ from pyroomacoustics import HMM, CircularGaussianEmission, GaussianEmission if __name__ == "__main__": - K = 4 # number of states O = 6 # dimension of the emission vector model = "left-right" # transition matrix model diff --git a/examples/noise_reduction_spectral_subtraction.py b/examples/noise_reduction_spectral_subtraction.py index a87cec55..c9d08b99 100644 --- a/examples/noise_reduction_spectral_subtraction.py +++ b/examples/noise_reduction_spectral_subtraction.py @@ -80,7 +80,6 @@ processed_audio = np.zeros(signal.shape) n = 0 while noisy_signal.shape[0] - n >= hop: - # SCNR in frequency domain stft.analysis(noisy_signal[n : (n + hop)]) gain_filt = scnr.compute_gain_filter(stft.X) diff --git a/examples/noise_reduction_subspace.py b/examples/noise_reduction_subspace.py index bc30dc91..0b3d5b50 100644 --- a/examples/noise_reduction_subspace.py +++ b/examples/noise_reduction_subspace.py @@ -63,10 +63,7 @@ start_time = time.time() hop = frame_len // 2 while noisy_signal.shape[0] - n >= hop: - - processed_audio[ - n : n + hop, - ] = scnr.apply(noisy_signal[n : n + hop]) + processed_audio[n : n + hop,] = scnr.apply(noisy_signal[n : n + hop]) # update step n += hop diff --git a/examples/noise_reduction_wiener_filtering.py b/examples/noise_reduction_wiener_filtering.py index 5065ae3b..3fcd7639 100644 --- a/examples/noise_reduction_wiener_filtering.py +++ b/examples/noise_reduction_wiener_filtering.py @@ -69,7 +69,6 @@ processed_audio = np.zeros(noisy_signal.shape) n = 0 while noisy_signal.shape[0] - n >= hop: - # to frequency domain, 50% overlap stft.analysis(noisy_signal[n : (n + hop)]) diff --git a/examples/randomized_image_method.py b/examples/randomized_image_method.py index 198679c2..19d716ca 100644 --- a/examples/randomized_image_method.py +++ b/examples/randomized_image_method.py @@ -79,7 +79,6 @@ print("Sweeping echo measure for ISM is :") for n in range(M): - if n == 0: S = stft.analysis( room.rir[n][0], fft_size, fft_hop, win=analysis_window, zp_back=fft_zp @@ -133,7 +132,6 @@ print("Sweeping echo measure for randomized ISM is:") for n in range(M): - if n == 0: S = stft.analysis( room.rir[n][0], fft_size, fft_hop, win=analysis_window, zp_back=fft_zp diff --git a/examples/raytracing.py b/examples/raytracing.py index 2748ce35..f29410bb 100644 --- a/examples/raytracing.py +++ b/examples/raytracing.py @@ -32,7 +32,6 @@ def get_rir(size, reverb): - # We construct a non-shoebox room pol = size_opts[size]["mult"] * np.array([[0, 0], [0, 4], [3, 2], [3, 0]]).T mat = pra.Material(reverb_opts[reverb]["e_abs"]) @@ -66,7 +65,6 @@ def get_rir(size, reverb): if __name__ == "__main__": - parser = argparse.ArgumentParser( description=( "Demonstrates the use of ray tracing for rooms of " diff --git a/examples/room_from_rt60.py b/examples/room_from_rt60.py index 35c9cd30..8cc291db 100644 --- a/examples/room_from_rt60.py +++ b/examples/room_from_rt60.py @@ -14,7 +14,6 @@ methods = ["ism", "hybrid"] if __name__ == "__main__": - parser = argparse.ArgumentParser( description="Simulates and adds reverberation to a dry sound sample. Saves it into `./examples/samples`." ) diff --git a/examples/room_from_stl.py b/examples/room_from_stl.py index a42a0648..12d49086 100644 --- a/examples/room_from_stl.py +++ b/examples/room_from_stl.py @@ -27,7 +27,6 @@ default_stl_path = Path(__file__).parent / "data/INRIA_MUSIS.stl" if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Basic room from STL file example") parser.add_argument( "--file", type=str, default=default_stl_path, help="Path to STL file" diff --git a/examples/room_shoebox_3d_rt.py b/examples/room_shoebox_3d_rt.py index de599aca..665d4da8 100644 --- a/examples/room_shoebox_3d_rt.py +++ b/examples/room_shoebox_3d_rt.py @@ -79,11 +79,9 @@ def chrono(f, *args, **kwargs): if __name__ == "__main__": - rirs = {} for name, config in params.items(): - print("Simulate: ", name) shoebox = make_room(config) diff --git a/examples/stft_block_processing.py b/examples/stft_block_processing.py index 27759262..c5b554bd 100644 --- a/examples/stft_block_processing.py +++ b/examples/stft_block_processing.py @@ -51,7 +51,6 @@ # process the signals while full blocks are available n = 0 while audio.shape[0] - n > hop: - # go to frequency domain stft.analysis(audio[n : n + hop]) diff --git a/pyroomacoustics/acoustics.py b/pyroomacoustics/acoustics.py index fc69cf31..7d6f1864 100644 --- a/pyroomacoustics/acoustics.py +++ b/pyroomacoustics/acoustics.py @@ -82,7 +82,6 @@ def bandpass_filterbank(bands, fs=1.0, order=8, output="sos"): nyquist = fs / 2.0 for band in bands: - # remove bands above nyquist frequency if band[0] >= nyquist: raise ValueError("Bands should be below Nyquist frequency") @@ -161,7 +160,6 @@ class OctaveBandsFactory(object): """ def __init__(self, base_frequency=125.0, fs=16000, n_fft=512): - self.base_freq = base_frequency self.fs = fs self.n_fft = n_fft diff --git a/pyroomacoustics/adaptive/adaptive_filter.py b/pyroomacoustics/adaptive/adaptive_filter.py index 02c1e12c..6034d233 100644 --- a/pyroomacoustics/adaptive/adaptive_filter.py +++ b/pyroomacoustics/adaptive/adaptive_filter.py @@ -11,7 +11,6 @@ class AdaptiveFilter: """ def __init__(self, length): - # filter length self.length = length @@ -54,5 +53,4 @@ def update(self, x_n, d_n): self.d = d_n def name(self): - return self.__class__.__name__ diff --git a/pyroomacoustics/adaptive/data_structures.py b/pyroomacoustics/adaptive/data_structures.py index 64478ea2..88c74a89 100644 --- a/pyroomacoustics/adaptive/data_structures.py +++ b/pyroomacoustics/adaptive/data_structures.py @@ -16,7 +16,6 @@ class Buffer: """ def __init__(self, length=20, dtype=np.float64): - self.buf = np.zeros(length, dtype=dtype) self.len = length self.head = self.len @@ -71,7 +70,6 @@ def __getitem__(self, r): return ptr[r] def __repr__(self): - if self.head == self.len: return "[]" else: @@ -103,12 +101,10 @@ class Powers: """ def __init__(self, a, length=20, dtype=np.float64): - self.a = dtype(a) self.pwr = self.a ** np.arange(length) def __getitem__(self, r): - # find maximum power requested if isinstance(r, int): high = r + 1 @@ -148,7 +144,6 @@ class CoinFlipper: """ def __init__(self, p, length=10000): - self.p = p self.length = length self.buffer = np.random.random(length) < p diff --git a/pyroomacoustics/adaptive/lms.py b/pyroomacoustics/adaptive/lms.py index 99041332..646b9ff1 100644 --- a/pyroomacoustics/adaptive/lms.py +++ b/pyroomacoustics/adaptive/lms.py @@ -26,7 +26,6 @@ class NLMS(AdaptiveFilter): """ def __init__(self, length, mu=0.5): - self.mu = mu AdaptiveFilter.__init__(self, length) @@ -65,7 +64,6 @@ class BlockLMS(NLMS): """ def __init__(self, length, mu=0.01, L=1, nlms=False): - self.nlms = nlms # sketching parameters @@ -103,7 +101,6 @@ def update(self, x_n, d_n): # Block update if self.n % self.L == 0: - # block-update parameters X = la.hankel(self.x[: self.L], r=self.x[self.L - 1 :]) diff --git a/pyroomacoustics/adaptive/rls.py b/pyroomacoustics/adaptive/rls.py index 90c9b4c2..dc48c82e 100644 --- a/pyroomacoustics/adaptive/rls.py +++ b/pyroomacoustics/adaptive/rls.py @@ -12,6 +12,7 @@ from .adaptive_filter import AdaptiveFilter from .util import hankel_stride_trick + # First the classic RLS (for real numbered signals) class RLS(AdaptiveFilter): """ @@ -32,7 +33,6 @@ class RLS(AdaptiveFilter): """ def __init__(self, length, lmbd=0.999, delta=10, dtype=np.float32): - self.lmbd = lmbd self.lmbd_inv = 1 / lmbd self.delta = delta @@ -129,7 +129,6 @@ class BlockRLS(RLS): """ def __init__(self, length, lmbd=0.999, delta=10, dtype=np.float32, L=None): - # block size if L is None: self.block = length @@ -178,7 +177,6 @@ def update(self, x_n, d_n): # Block update if self.n % self.block == 0: - x_vec = self.x.top(self.block + self.length - 1) d_vec = self.d.top(self.block) diff --git a/pyroomacoustics/adaptive/subband_lms.py b/pyroomacoustics/adaptive/subband_lms.py index 15ac8fb1..d9c0479c 100644 --- a/pyroomacoustics/adaptive/subband_lms.py +++ b/pyroomacoustics/adaptive/subband_lms.py @@ -44,7 +44,6 @@ class SubbandLMS: """ def __init__(self, num_taps, num_bands, mu=0.5, nlms=True): - self.num_taps = num_taps self.num_bands = num_bands self.mu = mu @@ -53,7 +52,6 @@ def __init__(self, num_taps, num_bands, mu=0.5, nlms=True): self.reset() def reset(self): - # filter bank self.W = np.zeros((self.num_taps, self.num_bands), dtype=np.complex64) diff --git a/pyroomacoustics/adaptive/tests/test_adaptive.py b/pyroomacoustics/adaptive/tests/test_adaptive.py index 6c2cf1ad..4bf3102a 100644 --- a/pyroomacoustics/adaptive/tests/test_adaptive.py +++ b/pyroomacoustics/adaptive/tests/test_adaptive.py @@ -23,6 +23,7 @@ # convolve with the unknown filter d_clean = fftconvolve(x, w)[:n_samples] + # a function to the adaptive filter on all the samples def run_filter(algorithm, x, d): for i in range(x.shape[0]): diff --git a/pyroomacoustics/adaptive/tests/test_adaptive_frequency.py b/pyroomacoustics/adaptive/tests/test_adaptive_frequency.py index 9e8816df..d298dc23 100644 --- a/pyroomacoustics/adaptive/tests/test_adaptive_frequency.py +++ b/pyroomacoustics/adaptive/tests/test_adaptive_frequency.py @@ -31,12 +31,7 @@ num_blocks = 0 X_concat = np.zeros((num_bands, n_samples // hop), dtype=np.complex64) while n_samples - n > hop: - - stft_in.analysis( - x[ - n : n + hop, - ] - ) + stft_in.analysis(x[n : n + hop,]) X_concat[:, num_blocks] = stft_in.X n += hop @@ -47,6 +42,7 @@ for k in range(num_bands): Y_concat[k, :] = fftconvolve(X_concat[k, :], W[:, k])[:num_blocks] + # run filters on each block def run_filters(algorithm, X_concat, Y_concat): num_blocks = X_concat.shape[1] @@ -56,7 +52,6 @@ def run_filters(algorithm, X_concat, Y_concat): class TestAdaptiveFilterFrequencyDomain(TestCase): def test_subband_nlms(self): - subband_nlms = pra.adaptive.SubbandLMS( num_taps=num_taps, num_bands=num_bands, mu=0.5, nlms=True ) diff --git a/pyroomacoustics/adaptive/util.py b/pyroomacoustics/adaptive/util.py index fd5eaaff..cea93005 100644 --- a/pyroomacoustics/adaptive/util.py +++ b/pyroomacoustics/adaptive/util.py @@ -51,9 +51,7 @@ def toeplitz_multiplication(c, r, A, **kwargs): Af = np.fft.rfft(A, n=fft_len, axis=0) - return np.fft.irfft((Af.T * xf).T, n=fft_len, axis=0)[ - :m, - ] + return np.fft.irfft((Af.T * xf).T, n=fft_len, axis=0)[:m,] def hankel_multiplication(c, r, A, mkl=True, **kwargs): @@ -78,9 +76,7 @@ def hankel_multiplication(c, r, A, mkl=True, **kwargs): fmul = toeplitz_multiplication A = A[: r.shape[0], :] - return fmul(c[::-1], r, A, **kwargs)[ - ::-1, - ] + return fmul(c[::-1], r, A, **kwargs)[::-1,] def mkl_toeplitz_multiplication(c, r, A, A_padded=False, out=None, fft_len=None): @@ -134,9 +130,7 @@ def mkl_toeplitz_multiplication(c, r, A, A_padded=False, out=None, fft_len=None) else: A = fft.irfft(out, n=fft_len, axis=0) - return A[ - :m, - ] + return A[:m,] def naive_toeplitz_multiplication(c, r, A): @@ -232,7 +226,6 @@ def toeplitz_opt_circ_approx(r, matrix=False): if __name__ == "__main__": - import time try: diff --git a/pyroomacoustics/beamforming.py b/pyroomacoustics/beamforming.py index d922b2e8..2cf0846b 100644 --- a/pyroomacoustics/beamforming.py +++ b/pyroomacoustics/beamforming.py @@ -251,7 +251,6 @@ def spiral_2D_array(center, M, radius=1.0, divi=3, angle=None): def fir_approximation_ls(weights, T, n1, n2): - freqs_plus = np.array(weights.keys())[:, np.newaxis] freqs = np.vstack([freqs_plus, -freqs_plus]) omega = 2 * np.pi * freqs @@ -325,7 +324,6 @@ def circular_microphone_array_xyplane( azimuth_list = np.arange(M) * 360 / M + phi0 directivity_list = [] for i in range(M): - orientation = DirectionVector( azimuth=azimuth_list[i], colatitude=colatitude, degrees=True ) @@ -354,7 +352,6 @@ class MicrophoneArray(object): """Microphone array class.""" def __init__(self, R, fs, directivity=None): - R = np.array(R) self.dim = R.shape[0] # are we in 2D or in 3D self.nmic = R.shape[1] # number of microphones @@ -386,7 +383,6 @@ def __init__(self, R, fs, directivity=None): self.center = np.mean(R, axis=1, keepdims=True) def set_directivity(self, directivities): - """ This functions sets self.directivity as a list of directivities with `n_mics` entries, where `n_mics` is the number of microphones @@ -616,7 +612,6 @@ def filters_from_weights(self, non_causal=0.0): self.filters = np.zeros((self.M, self.Lg)) if self.N <= self.Lg: - # go back to time domain and shift DC to center tw = np.fft.irfft(np.conj(self.weights), axis=1, n=self.N) self.filters[:, : self.N] = np.concatenate( @@ -624,7 +619,6 @@ def filters_from_weights(self, non_causal=0.0): ) elif self.N > self.Lg: - # Least-square projection for i in np.arange(self.M): Lgp = np.floor((1 - non_causal) * self.Lg) @@ -641,7 +635,6 @@ def filters_from_weights(self, non_causal=0.0): self.filters[i] = np.real(np.linalg.lstsq(F, w, rcond=None)[0]) def weights_from_filters(self): - if self.filters is None: raise NameError("Filters must be defined.") @@ -654,7 +647,6 @@ def weights_from_filters(self): self.weights[m] = np.conj(np.fft.rfft(self.filters[m], n=self.N)) def steering_vector_2D(self, frequency, phi, dist, attn=False): - phi = np.array([phi]).reshape(phi.size) # Assume phi and dist are measured from the array's center @@ -701,7 +693,6 @@ def steering_vector_2D_from_point(self, frequency, source, attn=True, ff=False): D -= np.min(D) else: - D = distance(self.R, X) phase = np.exp(-1j * omega * D / constants.get("c")) @@ -715,7 +706,6 @@ def steering_vector_2D_from_point(self, frequency, source, attn=True, ff=False): return phase def response(self, phi_list, frequency): - i_freq = np.argmin(np.abs(self.frequencies - frequency)) if self.weights is None and self.filters is not None: @@ -736,7 +726,6 @@ def response(self, phi_list, frequency): return self.frequencies[i_freq], bfresp def response_from_point(self, x, frequency): - i_freq = np.argmin(np.abs(self.frequencies - frequency)) if self.weights is None and self.filters is not None: @@ -757,7 +746,6 @@ def response_from_point(self, x, frequency): return self.frequencies[i_freq], bfresp def plot_response_from_point(self, x, legend=None): - if self.weights is None and self.filters is not None: self.weights_from_filters() elif self.weights is None and self.filters is None: @@ -802,7 +790,6 @@ def plot_response_from_point(self, x, legend=None): plt.legend(legend) def plot_beam_response(self): - if self.weights is None and self.filters is not None: self.weights_from_filters() elif self.weights is None and self.filters is None: @@ -863,7 +850,6 @@ def plot_beam_response(self): plt.setp(plt.gca(), "yticklabels", np.arange(1, 5) * f_0) def snr(self, source, interferer, f, R_n=None, dB=False): - i_f = np.argmin(np.abs(self.frequencies - f)) if self.weights is None and self.filters is not None: @@ -905,7 +891,6 @@ def snr(self, source, interferer, f, R_n=None, dB=False): return SNR def udr(self, source, interferer, f, R_n=None, dB=False): - i_f = np.argmin(np.abs(self.frequencies - f)) if self.weights is None and self.filters is not None: @@ -939,12 +924,10 @@ def udr(self, source, interferer, f, R_n=None, dB=False): return UDR def process(self, FD=False): - if self.signals is None or len(self.signals) == 0: raise NameError("No signal to beamform.") if FD is True: - # STFT processing if self.weights is None and self.filters is not None: self.weights_from_filters() @@ -981,7 +964,6 @@ def process(self, FD=False): output = output[self.zpf : -self.zpb] else: - # TD processing if self.weights is not None and self.filters is None: @@ -1001,7 +983,6 @@ def process(self, FD=False): return output def plot(self, sum_ir=False, FD=True): - if self.weights is None and self.filters is not None: self.weights_from_filters() elif self.weights is not None and self.filters is None: @@ -1061,7 +1042,6 @@ def far_field_weights(self, phi): def rake_delay_and_sum_weights( self, source, interferer=None, R_n=None, attn=True, ff=False ): - self.weights = np.zeros((self.M, self.frequencies.shape[0]), dtype=complex) K = source.images.shape[1] - 1 @@ -1073,7 +1053,6 @@ def rake_delay_and_sum_weights( def rake_one_forcing_weights( self, source, interferer=None, R_n=None, ff=False, attn=True ): - if R_n is None: R_n = np.zeros((self.M, self.M)) @@ -1116,7 +1095,6 @@ def rake_max_sinr_weights( self.weights = np.zeros((self.M, self.frequencies.shape[0]), dtype=complex) for i, f in enumerate(self.frequencies): - A_good = self.steering_vector_2D_from_point( f, source.images, attn=attn, ff=ff ) @@ -1143,7 +1121,6 @@ def rake_max_sinr_weights( def rake_max_udr_weights( self, source, interferer=None, R_n=None, ff=False, attn=True ): - if source.images.shape[1] == 1: self.rake_max_sinr_weights( source.images, interferer.images, R_n=R_n, ff=ff, attn=attn @@ -1468,7 +1445,6 @@ def rake_one_forcing_filters(self, sources, interferers, R_n, epsilon=5e-3): As = np.zeros((Lg * self.M, K)) for r in np.arange(self.M): - # build constraint matrix hs = u.low_pass_dirac( s_time[r, :, np.newaxis], s_dmp[r, :, np.newaxis], self.fs, Lh diff --git a/pyroomacoustics/bss/auxiva.py b/pyroomacoustics/bss/auxiva.py index 0c5dd248..8825e6dc 100644 --- a/pyroomacoustics/bss/auxiva.py +++ b/pyroomacoustics/bss/auxiva.py @@ -84,7 +84,6 @@ def auxiva( return_filters=False, callback=None, ): - """ This is an implementation of AuxIVA/OverIVA that separates the input signal into statistically independent sources. The separation is done @@ -159,7 +158,6 @@ def update_J_from_orth_const(): # initialize A and W if W0 is None: - if init_eig: # Initialize the demixing matrices with the principal # eigenvectors of the input covariance @@ -198,7 +196,6 @@ def demix(Y, X, W): Y[:, :, :] = np.matmul(W, X) for epoch in range(n_iter): - demix(Y, X, W) if callback is not None and epoch % 10 == 0: diff --git a/pyroomacoustics/bss/sparseauxiva.py b/pyroomacoustics/bss/sparseauxiva.py index bfd26308..5d843712 100644 --- a/pyroomacoustics/bss/sparseauxiva.py +++ b/pyroomacoustics/bss/sparseauxiva.py @@ -39,7 +39,6 @@ def sparseauxiva( return_filters=False, callback=None, ): - """ Implementation of sparse AuxIVA algorithm for BSS presented in diff --git a/pyroomacoustics/bss/tests/test_bss.py b/pyroomacoustics/bss/tests/test_bss.py index 8cac85e4..cd2c28d7 100644 --- a/pyroomacoustics/bss/tests/test_bss.py +++ b/pyroomacoustics/bss/tests/test_bss.py @@ -22,9 +22,9 @@ # List of frame lengths to test L = [256, 512, 1024, 2048, 4096] + # Frequency Blind Source Separation def freq_bss(algo="auxiva", L=256, **kwargs): - # Room dimensions in meters room_dim = [8, 9] @@ -58,7 +58,6 @@ def freq_bss(algo="auxiva", L=256, **kwargs): # Record each source separately separate_recordings = [] for source, signal in zip(room.sources, signals): - source.signal[:] = signal room.simulate() diff --git a/pyroomacoustics/bss/tests/test_trinicon.py b/pyroomacoustics/bss/tests/test_trinicon.py index a00acd36..49440f0c 100644 --- a/pyroomacoustics/bss/tests/test_trinicon.py +++ b/pyroomacoustics/bss/tests/test_trinicon.py @@ -59,7 +59,6 @@ def test_trinicon(): # Record each source separately separate_recordings = [] for source, signal in zip(room.sources, signals): - source.signal[:] = signal room.simulate() @@ -112,7 +111,6 @@ def test_trinicon(): # Record each source separately separate_recordings = [] for source, signal in zip(room.sources, signals): - source.signal[:] = signal room.simulate() diff --git a/pyroomacoustics/bss/trinicon.py b/pyroomacoustics/bss/trinicon.py index e4528362..57d98188 100644 --- a/pyroomacoustics/bss/trinicon.py +++ b/pyroomacoustics/bss/trinicon.py @@ -101,7 +101,6 @@ def trinicon( m = 1 # online block index while m <= M: # online loop - # new chunk of input signal x = np.zeros((P, K * L + N)) if m * hop > S: @@ -118,7 +117,6 @@ def trinicon( w_new = w.copy() for j in range(j_max): # offline update loop - y_c = np.zeros((Q, K * L + N - L)) # c stands for chunk y_blocks = np.zeros((Q, K, N)) diff --git a/pyroomacoustics/datasets/base.py b/pyroomacoustics/datasets/base.py index 33ab2aa1..0dfb4d2d 100644 --- a/pyroomacoustics/datasets/base.py +++ b/pyroomacoustics/datasets/base.py @@ -252,7 +252,6 @@ def __str__(self): r = "The dataset contains {} samples.\n".format(len(self)) r += "Metadata attributes are:\n" for field, values in self.info.items(): - r += " {} ({}) :\n".format(field, len(values)) # for attributes with lots of values, we just print a few diff --git a/pyroomacoustics/datasets/cmu_arctic.py b/pyroomacoustics/datasets/cmu_arctic.py index a0f82cfe..a3e42e96 100644 --- a/pyroomacoustics/datasets/cmu_arctic.py +++ b/pyroomacoustics/datasets/cmu_arctic.py @@ -111,7 +111,6 @@ class CMUArcticCorpus(Dataset): """ def __init__(self, basedir=None, download=False, build=True, **kwargs): - # initialize Dataset.__init__(self) @@ -203,10 +202,8 @@ def build_corpus(self, **kwargs): # Check all the sentences for tag, info in cmu_arctic_sentences.items(): - # And all speakers for each sentence for speaker, path in info["paths"].items(): - # This is the metadata for this sample meta = Meta( speaker=speaker, diff --git a/pyroomacoustics/datasets/google_speech_commands.py b/pyroomacoustics/datasets/google_speech_commands.py index 2a7fb299..ddc71ab2 100644 --- a/pyroomacoustics/datasets/google_speech_commands.py +++ b/pyroomacoustics/datasets/google_speech_commands.py @@ -69,7 +69,6 @@ class GoogleSpeechCommands(Dataset): def __init__( self, basedir=None, download=False, build=True, subset=None, seed=0, **kwargs ): - # initialize Dataset.__init__(self) self.size_by_samples = {} @@ -108,7 +107,6 @@ def build_corpus(self, subset=None, **kwargs): # go through all subdirectories / soundtypes for idx, word in enumerate(self.classes): - if word == "_background_noise_": speech = False else: @@ -129,7 +127,6 @@ def build_corpus(self, subset=None, **kwargs): # add each file to the corpus for filename in files: - file_loc = os.path.join(self.basedir, word, os.path.basename(filename)) # could also add score of original model for each word? diff --git a/pyroomacoustics/datasets/timit.py b/pyroomacoustics/datasets/timit.py index 4d3f1ed4..0a501fd9 100644 --- a/pyroomacoustics/datasets/timit.py +++ b/pyroomacoustics/datasets/timit.py @@ -129,7 +129,6 @@ class Word: """ def __init__(self, word, boundaries, data, fs, phonems=None): - self.word = word self.phonems = phonems self.boundaries = boundaries @@ -257,14 +256,12 @@ def __init__(self, path): # just a sanity check if len(t) == 3: - # the word boundary w_bnd = np.array([int(t[0]), int(t[1])]) # recover the phonems making up the word w_ph_list = [] while ph_l_index < len(ph_lines): - ph_line = ph_lines[ph_l_index] u = ph_line.split() @@ -319,7 +316,6 @@ def play(self): print("Warning: sounddevice package is required to play audiofiles.") def plot(self, L=512, hop=128, zpb=0, phonems=False, **kwargs): - try: import matplotlib.pyplot as plt import seaborn as sns diff --git a/pyroomacoustics/denoise/iterative_wiener.py b/pyroomacoustics/denoise/iterative_wiener.py index c947a268..318ab275 100644 --- a/pyroomacoustics/denoise/iterative_wiener.py +++ b/pyroomacoustics/denoise/iterative_wiener.py @@ -171,7 +171,6 @@ class IterativeWiener(object): """ def __init__(self, frame_len, lpc_order, iterations, alpha=0.8, thresh=0.01): - if frame_len % 2: raise ValueError( "Frame length should be even as this method " "relies on 50% overlap." @@ -219,7 +218,6 @@ def compute_filtered_output(self, current_frame, frame_dft=None): # simple VAD if frame_energy < self.thresh: # noise frame - # update noise power spectral density # assuming white noise, i.e. flat spectrum self.noise_psd = ( @@ -229,7 +227,6 @@ def compute_filtered_output(self, current_frame, frame_dft=None): # update wiener filter self.wiener_filt[:] = compute_wiener_filter(self.speech_psd, self.noise_psd) else: # speech frame - s_i = current_frame # iteratively update speech power spectral density / wiener filter @@ -412,19 +409,13 @@ def apply_iterative_wiener( n = 0 while noisy_signal.shape[0] - n >= hop: # SCNR in frequency domain - stft.analysis( - noisy_signal[ - n : (n + hop), - ] - ) + stft.analysis(noisy_signal[n : (n + hop),]) X = scnr.compute_filtered_output( current_frame=stft.fft_in_buffer, frame_dft=stft.X ) # back to time domain - processed_audio[ - n : n + hop, - ] = stft.synthesis(X) + processed_audio[n : n + hop,] = stft.synthesis(X) # update step n += hop diff --git a/pyroomacoustics/denoise/spectral_subtraction.py b/pyroomacoustics/denoise/spectral_subtraction.py index c4b3bfd1..35331d6a 100644 --- a/pyroomacoustics/denoise/spectral_subtraction.py +++ b/pyroomacoustics/denoise/spectral_subtraction.py @@ -121,7 +121,6 @@ class SpectralSub(object): """ def __init__(self, nfft, db_reduc, lookback, beta, alpha=1): - self.beta = beta self.alpha = alpha @@ -210,17 +209,11 @@ def apply_spectral_sub( n = 0 while noisy_signal.shape[0] - n >= hop: # SCNR in frequency domain - stft.analysis( - noisy_signal[ - n : (n + hop), - ] - ) + stft.analysis(noisy_signal[n : (n + hop),]) gain_filt = scnr.compute_gain_filter(stft.X) # back to time domain - processed_audio[ - n : n + hop, - ] = stft.synthesis(gain_filt * stft.X) + processed_audio[n : n + hop,] = stft.synthesis(gain_filt * stft.X) # update step n += hop diff --git a/pyroomacoustics/denoise/subspace.py b/pyroomacoustics/denoise/subspace.py index f732ce21..ddd1b51e 100644 --- a/pyroomacoustics/denoise/subspace.py +++ b/pyroomacoustics/denoise/subspace.py @@ -124,7 +124,6 @@ def __init__( thresh=0.01, data_type="float32", ): - if frame_len % 2: raise ValueError( "Frame length should be even as this method " "performs 50% overlap." @@ -199,7 +198,6 @@ def apply(self, new_samples): return self.current_out def compute_signal_projection(self): - sigma = np.linalg.lstsq(self.cov_n, self.cov_sn, rcond=None)[0] - np.eye( self.frame_len ) @@ -217,7 +215,6 @@ def compute_signal_projection(self): # self.h_opt = np.dot(np.linalg.lstsq(v_t, q1, rcond=None)[0], v_t) def update_cov_matrices(self, new_samples): - # remove cov of old samples self.cov_sn *= self.n_frames self.cov_sn -= self._cov_sn[0] @@ -309,10 +306,7 @@ def apply_subspace( n = 0 hop = frame_len // 2 while noisy_signal.shape[0] - n >= hop: - - processed_audio[ - n : n + hop, - ] = scnr.apply(noisy_signal[n : n + hop]) + processed_audio[n : n + hop,] = scnr.apply(noisy_signal[n : n + hop]) # update step n += hop diff --git a/pyroomacoustics/directivities.py b/pyroomacoustics/directivities.py index 07e9db68..61289cad 100644 --- a/pyroomacoustics/directivities.py +++ b/pyroomacoustics/directivities.py @@ -215,7 +215,6 @@ def plot_response( azimuth = np.radians(azimuth) if colatitude is not None: - if degrees: colatitude = np.radians(colatitude) @@ -262,7 +261,6 @@ def plot_response( ax.set_zlabel("z") else: - if ax is None: fig = plt.figure() ax = plt.subplot(111) diff --git a/pyroomacoustics/doa/cssm.py b/pyroomacoustics/doa/cssm.py index 7399b8ff..c40adcdb 100644 --- a/pyroomacoustics/doa/cssm.py +++ b/pyroomacoustics/doa/cssm.py @@ -61,7 +61,6 @@ def __init__( num_iter=5, **kwargs ): - MUSIC.__init__( self, L=L, @@ -95,7 +94,6 @@ def _process(self, X): # If there are less peaks than expected sources, leave the band out # Otherwise, store the location of the peaks. for k in range(self.num_freq): - self.grid.set_values( 1 / self._compute_spatial_spectrum(C_hat[k, :, :], self.freq_bins[k]) ) @@ -119,7 +117,6 @@ def _process(self, X): # while(i < self.iter or (len(self.src_idx) < self.num_src and i < 20)): while i < self.iter: - # coherent sum R = self._coherent_sum(C_hat, f0, beta) @@ -137,7 +134,6 @@ def _process(self, X): i += 1 def _coherent_sum(self, C_hat, f0, beta): - R = np.zeros((self.M, self.M)) # coherently sum frequencies diff --git a/pyroomacoustics/doa/detect_peaks.py b/pyroomacoustics/doa/detect_peaks.py index df71b2f1..d32d23b2 100644 --- a/pyroomacoustics/doa/detect_peaks.py +++ b/pyroomacoustics/doa/detect_peaks.py @@ -25,7 +25,6 @@ def detect_peaks( show=False, ax=None, ): - """ Detect peaks in data based on their amplitude and other features. diff --git a/pyroomacoustics/doa/doa.py b/pyroomacoustics/doa/doa.py index 79d01a7e..59e7d380 100644 --- a/pyroomacoustics/doa/doa.py +++ b/pyroomacoustics/doa/doa.py @@ -95,7 +95,6 @@ def __init__(self, L, fs, nfft, c, grid, mode="far", precompute=False): self.mode_vec = None def __getitem__(self, ref): - # If the look up table was precomputed if self.precompute: return self.mode_vec[ref] @@ -192,7 +191,6 @@ def __init__( *args, **kwargs ): - if dim > L.shape[0]: raise ValueError("Microphones locations missing dimensions.") @@ -236,37 +234,30 @@ def __init__( # Some logic to create a grid for search self.grid = None if azimuth is None and colatitude is None: - # Use a default grid size if dim == 2: - if n_grid is None: n_grid = 360 self.grid = GridCircle(n_points=n_grid) elif dim == 3: - if n_grid is None: n_grid = 180 * 90 self.grid = GridSphere(n_points=n_grid) elif azimuth is None and colatitude is not None: - raise ValueError("Azimuth should always be specified.") else: - if dim == 2: - if colatitude is not None: warnings.warn("Colatitude is ignored for 2D problems.") self.grid = GridCircle(azimuth=azimuth) elif dim == 3: - if azimuth.ndim != 1: raise ValueError("Azimuth should be a 1D ndarray.") @@ -281,7 +272,6 @@ def __init__( self.grid = GridSphere(spherical_points=grid_points) else: - # when both azimuth and theta are specified, # we assume we want the cartesian product A, C = np.meshgrid(np.unique(azimuth), np.unique(colatitude)) @@ -366,7 +356,6 @@ def locate_sources( from .frida import FRIDA if not isinstance(self, FRIDA): - self.src_idx = self.grid.find_peaks(k=self.num_src) self.num_src = len(self.src_idx) @@ -423,13 +412,11 @@ def polar_plt_dirac( from .frida import FRIDA if not isinstance(self, FRIDA): # use spatial spectrum - dirty_img = self.grid.values alpha_recon = self.grid.values[self.src_idx] alpha_ref = alpha_recon else: # create dirty image - dirty_img = self._gen_dirty_img() alpha_recon = np.mean(np.abs(self.alpha_recon), axis=1) alpha_recon /= alpha_recon.max() diff --git a/pyroomacoustics/doa/frida.py b/pyroomacoustics/doa/frida.py index eea01932..cb6752a8 100644 --- a/pyroomacoustics/doa/frida.py +++ b/pyroomacoustics/doa/frida.py @@ -94,7 +94,6 @@ def __init__( use_cache=False, **kwargs ): - DOA.__init__(self, L, fs, nfft, c=c, num_src=num_src, mode="far", **kwargs) # intialize some attributes @@ -155,7 +154,6 @@ def _process(self, X): self.num_freq = self.freq_bins.shape[0] if self.dim == 2: - # build the G matrix if necessary if self.G is None: self.G = make_G( @@ -190,7 +188,6 @@ def _process(self, X): ) elif self.dim == 3: - raise ValueError("3D reconstruction is not yet available with FRIDA.") def _raw_average(self, X): @@ -208,7 +205,6 @@ def _raw_average(self, X): return np.mean(X[:, self.freq_bins, :] * phaser, axis=2) def _visibilities(self, X): - visi_noisy_all = [] for band_count in range(self.num_freq): # Estimate the covariance matrix and extract off-diagonal entries @@ -245,14 +241,12 @@ def _gen_dirty_img(self): num_mic = self.M if self.dim == 2: - x_plt, y_plt = polar2cart(1, self.grid.azimuth) img = np.zeros(self.grid.n_points, dtype=complex) pos_mic_x = self.L[0, :] pos_mic_y = self.L[1, :] for i in range(self.num_freq): - visi = self.visi_noisy_all[:, i] omega_band = 2 * np.pi * self.freq_hz[i] @@ -276,7 +270,6 @@ def _gen_dirty_img(self): return img / (num_mic * (num_mic - 1)) elif self.dim == 3: - raise ValueError("3D reconstruction is not yet available with FRIDA.") diff --git a/pyroomacoustics/doa/grid.py b/pyroomacoustics/doa/grid.py index b34b0c2e..07e1e691 100644 --- a/pyroomacoustics/doa/grid.py +++ b/pyroomacoustics/doa/grid.py @@ -25,7 +25,6 @@ class Grid: __metaclass__ = ABCMeta def __init__(self, n_points): - self.n_points = n_points self.values = None self.cartesian = np.zeros((3, n_points)) @@ -47,7 +46,6 @@ def find_peaks(self, k=1): return NotImplemented def set_values(self, vals): - vals = np.array(vals) if vals.ndim == 0: @@ -76,7 +74,6 @@ class GridCircle(Grid): def __init__(self, n_points=360, azimuth=None): if azimuth is not None: - if azimuth.ndim != 1: raise ValueError("Azimuth must be a 1D ndarray.") @@ -100,14 +97,12 @@ def __init__(self, n_points=360, azimuth=None): self.y[:] = np.sin(azimuth) def apply(self, func, spherical=False): - if spherical: self.values = func(self.azimuth) else: self.values = func(self.x, self.y) def find_peaks(self, k=1): - # make circular val_ext = np.append(self.values, self.values[:10]) @@ -123,7 +118,6 @@ def find_peaks(self, k=1): return candidates[max_idx] def plot(self, mark_peaks=0): - try: import matplotlib.pyplot as plt except ImportError: @@ -141,7 +135,6 @@ def plot(self, mark_peaks=0): ax.plot(pts, vals, "-") if mark_peaks > 0: - idx = self.find_peaks(k=mark_peaks) ax.plot(pts[idx], vals[idx], "ro") @@ -168,7 +161,6 @@ class GridSphere(Grid): def __init__(self, n_points=1000, spherical_points=None): if spherical_points is not None: - if spherical_points.ndim != 2 or spherical_points.shape[0] != 2: raise ValueError("spherical_points must be a 2D array with two rows.") @@ -254,11 +246,9 @@ def min_max_distance(self): dist = [] for u in range(self.n_points): - phi1, theta1 = self.spherical[:, u] for v in self.neighbors[u]: - phi2, theta2 = self.spherical[:, v] d = great_circ_dist(1, theta1, phi1, theta2, phi2) @@ -287,7 +277,6 @@ def find_peaks(self, k=1): # We start by looking at points whose neighbors all have lower values # than themselves for v in range(self.n_points): - is_local_max = True for u in self.neighbors[v]: @@ -340,7 +329,6 @@ def plot( projection=True, points_only=False, ): - if points_only: dirty_img = None dirty_grid_x = None @@ -397,7 +385,6 @@ def plot_old(self, plot_points=False, mark_peaks=0): ax.scatter(self.x, self.y, self.z, c="b", marker="o") if mark_peaks > 0: - id = self.find_peaks(k=mark_peaks) s = 1.05 ax.scatter( @@ -408,7 +395,6 @@ def plot_old(self, plot_points=False, mark_peaks=0): voronoi.sort_vertices_of_regions() if self.values is not None: - col_max = self.values.max() col_min = self.values.min() @@ -418,7 +404,6 @@ def plot_old(self, plot_points=False, mark_peaks=0): col_map = self.values / col_max else: - col_map = np.zeros(self.n_points) cmap = plt.get_cmap("coolwarm") diff --git a/pyroomacoustics/doa/music.py b/pyroomacoustics/doa/music.py index 51cdcd33..8bb85760 100644 --- a/pyroomacoustics/doa/music.py +++ b/pyroomacoustics/doa/music.py @@ -55,7 +55,6 @@ def __init__( frequency_normalization=False, **kwargs ): - DOA.__init__( self, L=L, @@ -123,7 +122,6 @@ def plot_individual_spectrum(self): # plot for k in range(self.num_freq): - freq = float(self.freq_bins[k]) / self.nfft * self.fs azimuth = self.grid.azimuth * 180 / np.pi @@ -146,7 +144,6 @@ def _compute_spatial_spectrumvec(self, cross): return 1.0 / abs(denom[..., 0, 0]) def _compute_spatial_spectrum(self, cross, k): - P = np.zeros(self.grid.n_points) for n in range(self.grid.n_points): diff --git a/pyroomacoustics/doa/plotters.py b/pyroomacoustics/doa/plotters.py index ba80e65a..38f9430c 100644 --- a/pyroomacoustics/doa/plotters.py +++ b/pyroomacoustics/doa/plotters.py @@ -50,13 +50,11 @@ def polar_plt_dirac( from fri import FRI if not isinstance(self, FRI): # use spatial spectrum - dirty_img = self.grid.values alpha_recon = self.grid.values[self.src_idx] alpha_ref = alpha_recon else: # create dirty image - dirty_img = self._gen_dirty_img() alpha_recon = np.mean(np.abs(self.alpha_recon), axis=1) alpha_recon /= alpha_recon.max() @@ -260,7 +258,6 @@ def sph_plot_diracs_plotly( and azimuth_grid is not None and colatitude_grid is not None ): - surfacecolor = np.abs(dirty_img) # for plotting purposes base = surface_base @@ -296,7 +293,6 @@ def sph_plot_diracs_plotly( traces.append(trace1) if colatitude_ref is not None and azimuth_ref is not None: - x_ref = np.sin(colatitude_ref) * np.cos(azimuth_ref) y_ref = np.sin(colatitude_ref) * np.sin(azimuth_ref) z_ref = np.cos(colatitude_ref) @@ -335,7 +331,6 @@ def sph_plot_diracs_plotly( traces.append(trace2) if colatitude is not None and azimuth is not None: - x_recon = np.sin(colatitude) * np.cos(azimuth) y_recon = np.sin(colatitude) * np.sin(azimuth) z_recon = np.cos(colatitude) @@ -441,7 +436,6 @@ def sph_plot_diracs( and colatitude_grid is not None and azimuth_grid is not None ): - azimuth_plt_internal = azimuth_grid.copy() azimuth_plt_internal[azimuth_grid > np.pi] -= np.pi * 2 p_hd = ax.pcolormesh( @@ -469,7 +463,6 @@ def sph_plot_diracs( p_hdc.update_ticks() if colatitude_ref is not None and azimuth_ref is not None: - if hasattr(colatitude_ref, "__iter__"): K = colatitude_ref.size x_ref = azimuth_ref.copy() @@ -501,7 +494,6 @@ def sph_plot_diracs( ) if colatitude is not None and azimuth is not None: - if hasattr(colatitude, "__iter__"): K_est = colatitude.size x = azimuth.copy() diff --git a/pyroomacoustics/doa/srp.py b/pyroomacoustics/doa/srp.py index aa000502..7bc8438e 100644 --- a/pyroomacoustics/doa/srp.py +++ b/pyroomacoustics/doa/srp.py @@ -51,7 +51,6 @@ def __init__( colatitude=None, **kwargs ): - DOA.__init__( self, L=L, @@ -109,7 +108,6 @@ def _process(self, X): DC_offset = pX.shape[-1] * self.L.shape[1] * len(self.freq_bins) for n in range(self.grid.n_points): - # In the loop, this is just a fancy way of computing # the quadratic form: # mode_vec^H @ CC @ mode_vec diff --git a/pyroomacoustics/doa/tests/test_doa.py b/pyroomacoustics/doa/tests/test_doa.py index 32e35084..85800040 100644 --- a/pyroomacoustics/doa/tests/test_doa.py +++ b/pyroomacoustics/doa/tests/test_doa.py @@ -96,7 +96,6 @@ def test_frida(self): if __name__ == "__main__": - """ algo_names = sorted(pra.doa.algorithms.keys()) diff --git a/pyroomacoustics/doa/tools_fri_doa_plane.py b/pyroomacoustics/doa/tools_fri_doa_plane.py index 322d6d9f..c82bc875 100644 --- a/pyroomacoustics/doa/tools_fri_doa_plane.py +++ b/pyroomacoustics/doa/tools_fri_doa_plane.py @@ -1627,7 +1627,6 @@ def dirac_recon_ri_inner( mtx_brecon[:sz_Rc1, :sz_Rc1] = GtG for inner in range(max_iter): - # update the mtx_loop matrix mtx_loop[row_s1:row_e1, col_s1:col_e1] = -R_loop mtx_loop[row_s2:row_e2, col_s2:col_e2] = -R_loop.T @@ -1709,7 +1708,6 @@ def make_G(p_mic_x, p_mic_y, omega_bands, sound_speed, M, signal_type="visibilit def make_GtG_and_inv(G_lst): - GtG_lst = [] GtG_inv_lst = [] for loop in range(len(G_lst)): diff --git a/pyroomacoustics/doa/tops.py b/pyroomacoustics/doa/tops.py index 78063b5b..a1ce30d7 100644 --- a/pyroomacoustics/doa/tops.py +++ b/pyroomacoustics/doa/tops.py @@ -61,7 +61,6 @@ def __init__( colatitude=None, **kwargs ): - MUSIC.__init__( self, L=L, diff --git a/pyroomacoustics/doa/waves.py b/pyroomacoustics/doa/waves.py index ec51aca2..e0510262 100644 --- a/pyroomacoustics/doa/waves.py +++ b/pyroomacoustics/doa/waves.py @@ -60,7 +60,6 @@ def __init__( num_iter=5, **kwargs ): - MUSIC.__init__( self, L=L, @@ -92,7 +91,6 @@ def _process(self, X): invalid = [] for k in range(self.num_freq): - self.grid.set_values( 1 / self._compute_spatial_spectrum(C_hat[k, :, :], self.freq_bins[k]) ) @@ -118,7 +116,6 @@ def _process(self, X): # while(i < self.iter or (len(self.src_idx) < self.num_src and i < 20)): while i < self.iter: - # construct waves matrix self._construct_waves_matrix(C_hat, f0, beta) diff --git a/pyroomacoustics/experimental/delay_calibration.py b/pyroomacoustics/experimental/delay_calibration.py index 54afd538..839637ad 100644 --- a/pyroomacoustics/experimental/delay_calibration.py +++ b/pyroomacoustics/experimental/delay_calibration.py @@ -109,7 +109,6 @@ def run(self, distance=0.0, ch_in=None, ch_out=None, oversampling=1): if __name__ == "__main__": - try: import sounddevice as sd diff --git a/pyroomacoustics/experimental/measure_ir.py b/pyroomacoustics/experimental/measure_ir.py index d3ec803f..d1488004 100644 --- a/pyroomacoustics/experimental/measure_ir.py +++ b/pyroomacoustics/experimental/measure_ir.py @@ -177,7 +177,6 @@ def measure_ir( if __name__ == "__main__": - """ This is just an interface to measure impulse responses easily """ diff --git a/pyroomacoustics/experimental/point_cloud.py b/pyroomacoustics/experimental/point_cloud.py index f734c04b..ae77daeb 100644 --- a/pyroomacoustics/experimental/point_cloud.py +++ b/pyroomacoustics/experimental/point_cloud.py @@ -60,7 +60,6 @@ def __init__(self, m=1, dim=3, diameter=0.0, X=None, labels=None, EDM=None): self.labels = [str(i) for i in range(self.m)] def __getitem__(self, ref): - if isinstance(ref, (str, unicode)): if self.labels is None: raise ValueError("Labels not set for this marker set") @@ -337,7 +336,6 @@ def doa(self, receiver, source): return np.array([azimuth, elevation]) def plot(self, axes=None, show_labels=True, **kwargs): - try: from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt @@ -348,7 +346,6 @@ def plot(self, axes=None, show_labels=True, **kwargs): return if self.dim == 2: - # Create a figure if needed if axes is None: axes = plt.subplot(111) @@ -386,7 +383,6 @@ def plot(self, axes=None, show_labels=True, **kwargs): if __name__ == "__main__": - import matplotlib.pyplot as plt # number of markers diff --git a/pyroomacoustics/experimental/tests/test_deconvolution.py b/pyroomacoustics/experimental/tests/test_deconvolution.py index 0f567a60..276475d9 100644 --- a/pyroomacoustics/experimental/tests/test_deconvolution.py +++ b/pyroomacoustics/experimental/tests/test_deconvolution.py @@ -33,7 +33,6 @@ def generate_signals(SNR, x, h, noise): class TestDeconvolution(TestCase): def test_deconvolve_hann_noiseless(self): - h = h_hann h_len = h_hann.shape[0] SNR = 1000.0 @@ -49,7 +48,6 @@ def test_deconvolve_hann_noiseless(self): self.assertTrue(rmse < tol) def test_wiener_deconvolve_hann_noiseless(self): - h = h_hann h_len = h_hann.shape[0] SNR = 1000.0 @@ -68,7 +66,6 @@ def test_wiener_deconvolve_hann_noiseless(self): if __name__ == "__main__": - import matplotlib.pyplot as plt h = h_hann diff --git a/pyroomacoustics/experimental/tests/test_measure_rt60.py b/pyroomacoustics/experimental/tests/test_measure_rt60.py index fe4474d7..648d898d 100644 --- a/pyroomacoustics/experimental/tests/test_measure_rt60.py +++ b/pyroomacoustics/experimental/tests/test_measure_rt60.py @@ -67,6 +67,5 @@ def test_rt60_plot(): if __name__ == "__main__": - test_rt60() test_rt60_plot() diff --git a/pyroomacoustics/metrics.py b/pyroomacoustics/metrics.py index 89a91805..04965894 100644 --- a/pyroomacoustics/metrics.py +++ b/pyroomacoustics/metrics.py @@ -38,26 +38,15 @@ def median(x, alpha=None, axis=-1, keepdims=False): if n % 2 == 1: # if n is odd, take central element - m = xsw[ - n // 2, - ] + m = xsw[n // 2,] else: # if n is even, average the two central elements - m = 0.5 * ( - xsw[ - n // 2 - 1, - ] - + xsw[ - n // 2, - ] - ) + m = 0.5 * (xsw[n // 2 - 1,] + xsw[n // 2,]) if alpha is None: if keepdims: m = np.moveaxis( - m[ - np.newaxis, - ], + m[np.newaxis,], 0, axis, ) @@ -85,14 +74,8 @@ def median(x, alpha=None, axis=-1, keepdims=False): else: ci = np.array( [ - xsw[ - j, - ] - - m, - xsw[ - k, - ] - - m, + xsw[j,] - m, + xsw[k,] - m, ] ) @@ -104,22 +87,14 @@ def median(x, alpha=None, axis=-1, keepdims=False): k = int(np.ceil(0.5 * n + 0.5 * eta * np.sqrt(n))) ci = np.array( [ - xsw[ - j, - ] - - m, - xsw[ - k, - ] - - m, + xsw[j,] - m, + xsw[k,] - m, ] ) if keepdims: m = np.moveaxis( - m[ - np.newaxis, - ], + m[np.newaxis,], 0, axis, ) @@ -164,7 +139,6 @@ def mse(x1, x2): # Itakura-Saito distance function def itakura_saito(x1, x2, sigma2_n, stft_L=128, stft_hop=128): - P1 = np.abs(stft.analysis(x1, stft_L, stft_hop)) ** 2 P2 = np.abs(stft(x2, stft_L, stft_hop)) ** 2 @@ -183,7 +157,6 @@ def itakura_saito(x1, x2, sigma2_n, stft_L=128, stft_hop=128): def snr(ref, deg): - return np.sum(ref**2) / np.sum((ref - deg) ** 2) @@ -244,7 +217,6 @@ def pesq(ref_file, deg_files, Fs=8000, swap=False, wb=False, bin="./bin/pesq"): # Recover output as the processes finish while states.any(): - for i, p in enumerate(pipes): if states[i] == True and p.poll() is not None: states[i] = False @@ -334,7 +306,6 @@ def sweeping_echo_measure(rir, fs, t_min=0, t_max=0.5, fb=400): # loop through different slope values for k in range(nCoeffs): - # get masks a = coeffs[k] diff --git a/pyroomacoustics/multirate.py b/pyroomacoustics/multirate.py index 57db9755..62470a7d 100644 --- a/pyroomacoustics/multirate.py +++ b/pyroomacoustics/multirate.py @@ -70,7 +70,6 @@ def frac_delay(delta, N, w_max=0.9, C=4): def low_pass(numtaps, B, epsilon=0.1): - bands = [0, (1 - epsilon) * B, B, 0.5] desired = [1, 0] @@ -96,7 +95,6 @@ def low_pass(numtaps, B, epsilon=0.1): def resample(x, p, q): - import fractions gcd = fractions.gcd(p, q) diff --git a/pyroomacoustics/parameters.py b/pyroomacoustics/parameters.py index 4a363d8c..677f48bf 100644 --- a/pyroomacoustics/parameters.py +++ b/pyroomacoustics/parameters.py @@ -63,7 +63,6 @@ def set(self, name, val): _constants[name] = val def get(self, name): - try: v = _constants[name] except KeyError: @@ -78,6 +77,7 @@ def get(self, name): # the instanciation of the class constants = Constants() + # Compute the speed of sound as a function # of temperature, humidity, and pressure def calculate_speed_of_sound(t, h, p): @@ -151,7 +151,6 @@ class Physics(object): """ def __init__(self, temperature=None, humidity=None): - self.p = 100.0 # pressure in kilo-Pascal (kPa), not used if humidity is None: self.H = 0.0 @@ -289,7 +288,6 @@ class Material(object): """ def __init__(self, energy_absorption, scattering=None): - # Handle the energy absorption input based on its type if isinstance(energy_absorption, (float, np.float32, np.float64)): # This material is flat over frequencies diff --git a/pyroomacoustics/phase/gl.py b/pyroomacoustics/phase/gl.py index 498a9849..b4375ce1 100644 --- a/pyroomacoustics/phase/gl.py +++ b/pyroomacoustics/phase/gl.py @@ -168,12 +168,9 @@ def griffin_lim( # the successive application of analysis/synthesis introduces # a shift of ``fft_size - hop`` that we must correct the_shift = fft_size - hop - y[:-the_shift,] = y[ - the_shift:, - ] + y[:-the_shift,] = y[the_shift:,] for epoch in range(n_iter): - # possibly monitor the reconstruction if callback is not None: callback(epoch, Y, y) @@ -185,9 +182,7 @@ def griffin_lim( Y *= X / np.abs(Y) # back to time domain - y[:-the_shift,] = engine.synthesis(Y)[ - the_shift:, - ] + y[:-the_shift,] = engine.synthesis(Y)[the_shift:,] # last callback if callback is not None: diff --git a/pyroomacoustics/phase/tests/test_gl.py b/pyroomacoustics/phase/tests/test_gl.py index 862ee7b6..3766c690 100644 --- a/pyroomacoustics/phase/tests/test_gl.py +++ b/pyroomacoustics/phase/tests/test_gl.py @@ -40,6 +40,7 @@ def compute_error(X_mag, y): np.random.seed(0) ini = [None, "random", X] + # The actual test case # We use deterministic phase initialization (to zero) class TestGL(unittest.TestCase): @@ -61,7 +62,6 @@ def test_griffin_lim_true(self): if __name__ == "__main__": - import matplotlib.pyplot as plt # monitor convergence diff --git a/pyroomacoustics/recognition.py b/pyroomacoustics/recognition.py index 62bcc8b6..c391d899 100644 --- a/pyroomacoustics/recognition.py +++ b/pyroomacoustics/recognition.py @@ -24,7 +24,6 @@ def __init__(self, nstates, odim=1, examples=None): self.K = nstates if examples is None: - # Initialize to random components self.O = odim self.mu = np.random.normal(size=(self.K, self.O)) @@ -41,7 +40,6 @@ def __init__(self, nstates, odim=1, examples=None): self.Sigma = np.array([np.mean(centered**2, axis=0)] * self.K) def update_parameters(self, examples, gamma): - g = np.concatenate(gamma, axis=0) X = np.concatenate(examples, axis=0) Z = g.sum(axis=0) @@ -103,7 +101,6 @@ def __init__(self, nstates, odim=1, examples=None): self.Sigma = np.array([np.diag(np.mean(centered**2, axis=0))] * self.K) def update_parameters(self, examples, gamma): - g = np.concatenate(gamma, axis=0) X = np.concatenate(examples, axis=0) Z = g.sum(axis=0) @@ -230,7 +227,6 @@ def fit(self, examples, tol=0.1, max_iter=10, verbose=False): loglikelihood_old = -np.inf # log-likelihood n_iter = 0 while True: - # Initialize new parameters value for accumulation loglikelihood = 0.0 @@ -244,7 +240,6 @@ def fit(self, examples, tol=0.1, max_iter=10, verbose=False): # ----------------- for X, pxz in zip(examples, p_x_given_z): - # check dimension of emission if X.shape[1] != self.emission.O: raise ValueError( diff --git a/pyroomacoustics/room.py b/pyroomacoustics/room.py index 037556dd..11930056 100644 --- a/pyroomacoustics/room.py +++ b/pyroomacoustics/room.py @@ -685,7 +685,6 @@ def wall_factory(corners, absorption, scattering, name=""): def sequence_generation(volume, duration, c, fs, max_rate=10000): - # repeated constant fpcv = 4 * np.pi * c**3 / volume @@ -694,7 +693,6 @@ def sequence_generation(volume, duration, c, fs, max_rate=10000): times = [t0] while times[-1] < t0 + duration: - # uniform random variable z = np.random.rand() # rate of the point process at this time @@ -850,7 +848,6 @@ def __init__( use_rand_ism=False, max_rand_disp=0.08, ): - self.walls = walls # Get the room dimension from that of the walls @@ -901,7 +898,6 @@ def _var_init( use_rand_ism, max_rand_disp, ): - self.fs = fs if t0 != 0.0: @@ -952,7 +948,6 @@ def _var_init( self.rir = None def _init_room_engine(self, *args): - args = list(args) if len(args) == 0: @@ -983,7 +978,6 @@ def _init_room_engine(self, *args): self.room_engine = libroom.Room(*args) def _update_room_engine_params(self): - # Now, if it exists, set the parameters of room engine if self.room_engine is not None: self.room_engine.set_params( @@ -1152,7 +1146,6 @@ def set_sound_speed(self, c): self._update_room_engine_params() def _wall_mapping(self): - # mapping between wall names and indices self.wallsId = {} for i in range(len(self.walls)): @@ -1242,7 +1235,6 @@ def from_corners( ############################ if materials is not None: - if absorption_compatibility_request: import warnings @@ -1394,7 +1386,6 @@ def extrude(self, height, v_vec=None, absorption=None, materials=None): ########################## if materials is not None: - if absorption_compatibility_request: import warnings @@ -1413,7 +1404,6 @@ def extrude(self, height, v_vec=None, absorption=None, materials=None): ), "Material not specified using correct class" elif absorption_compatibility_request: - import warnings warnings.warn( @@ -1514,7 +1504,6 @@ def plot( ax.add_collection(p) if self.mic_array is not None: - for i in range(self.mic_array.nmic): ax.scatter( self.mic_array.R[0][i], @@ -1545,7 +1534,6 @@ def plot( or self.mic_array.filters is not None ) ): - freq = np.array(freq) if freq.ndim == 0: freq = np.array([freq]) @@ -1647,7 +1635,6 @@ def plot( return fig, ax if self.dim == 3: - import matplotlib.colors as colors import matplotlib.pyplot as plt import mpl_toolkits.mplot3d as a3 @@ -1729,7 +1716,6 @@ def plot( # draw the microphones if self.mic_array is not None: - for i in range(self.mic_array.nmic): ax.scatter( self.mic_array.R[0][i], @@ -1929,7 +1915,6 @@ def add(self, obj): """ if isinstance(obj, SoundSource): - if obj.dim != self.dim: raise ValueError( ( @@ -1945,7 +1930,6 @@ def add(self, obj): self.sources.append(obj) elif isinstance(obj, MicrophoneArray): - if obj.dim != self.dim: raise ValueError( ( @@ -2103,18 +2087,15 @@ def add_soundsource(self, sndsrc, directivity=None): return self.add(sndsrc) def image_source_model(self): - if not self.simulator_state["ism_needed"]: return self.visibility = [] for source in self.sources: - n_sources = self.room_engine.image_source_model(source.position) if n_sources > 0: - # Copy to python managed memory source.images = self.room_engine.sources.copy() source.orders = self.room_engine.orders.copy() @@ -2126,7 +2107,6 @@ def image_source_model(self): # if randomized image method is selected, add a small random # displacement to the image sources if self.simulator_state["random_ism_needed"]: - n_images = np.shape(source.images)[1] # maximum allowed displacement is 8cm @@ -2148,7 +2128,6 @@ def image_source_model(self): self.simulator_state["ism_done"] = True def ray_tracing(self): - if not self.simulator_state["rt_needed"]: return @@ -2188,7 +2167,6 @@ def compute_rir(self): for m, mic in enumerate(self.mic_array.R.T): self.rir.append([]) for s, src in enumerate(self.sources): - """ Compute the room impulse response between the source and the microphone whose position is given as an @@ -2202,7 +2180,6 @@ def compute_rir(self): N = fdl if self.simulator_state["ism_needed"]: - # compute azimuth and colatitude angles for receiver if self.mic_array.directivity is not None: angle_function_array = angle_function(src.images, mic) @@ -2227,7 +2204,6 @@ def compute_rir(self): t_max = 0.0 if self.simulator_state["rt_needed"]: - # get the maximum length from the histograms nz_bins_loc = np.nonzero(self.rt_histograms[m][s][0].sum(axis=0))[0] if len(nz_bins_loc) == 0: @@ -2259,16 +2235,13 @@ def compute_rir(self): rir_bands = [] for b, bw in enumerate(bws): - ir_loc = np.zeros_like(ir) # IS method if self.simulator_state["ism_needed"]: - alpha = src.damping[b, :] / dist if self.mic_array.directivity is not None: - alpha *= self.mic_array.directivity[m].get_response( azimuth=azimuth, colatitude=colatitude, @@ -2302,7 +2275,6 @@ def compute_rir(self): # Ray Tracing if self.simulator_state["rt_needed"]: - if is_multi_band: seq_bp = self.octave_bands.analysis(seq, band=b) else: @@ -2330,7 +2302,6 @@ def compute_rir(self): # Do Air absorption if self.simulator_state["air_abs_needed"]: - # In case this was not multi-band, do the band pass filtering if len(rir_bands) == 1: rir_bands = self.octave_bands.analysis(rir_bands[0]).T @@ -2563,7 +2534,6 @@ def is_inside(self, p, include_borders=True): # re-run until we get a non-ambiguous result it = 0 while it < constants.get("room_isinside_max_iter"): - # Get random point outside the bounding box random_vec = np.random.randn(self.dim) random_vec /= np.linalg.norm(random_vec) @@ -2619,7 +2589,6 @@ def is_inside(self, p, include_borders=True): ) def wall_area(self, wall): - """Computes the area of a 3D planar wall. Parameters @@ -2701,7 +2670,6 @@ def rt60_theory(self, formula="sabine"): c = self.c for i, bw in enumerate(bandwidths): - # average absorption coefficients a = 0.0 for w in self.walls: @@ -2831,7 +2799,6 @@ def __init__( use_rand_ism=False, max_rand_disp=0.08, ): - p = np.array(p, dtype=np.float32) if len(p.shape) > 1 and (len(p) != 2 or len(p) != 3): @@ -2884,7 +2851,6 @@ def __init__( ########################## if materials is not None: - if absorption_compatibility_request: warnings.warn( "Because `materials` were specified, deprecated " @@ -2908,7 +2874,6 @@ def __init__( ), "Material not specified using correct class" elif absorption_compatibility_request: - warnings.warn( "Using absorption parameter is deprecated. Use `materials` with " "`Material` object instead.", @@ -2938,7 +2903,6 @@ def __init__( "'north', 'south', 'ceiling' (3d), 'floor' (3d)." ) else: - # In this case, no material is provided, use totally reflective # walls, no scattering materials = dict( @@ -3097,7 +3061,6 @@ def __init__( ) def __str__(self): - return "AnechoicRoom instance in {}D.".format(self.dim) def is_inside(self, p): diff --git a/pyroomacoustics/soundsource.py b/pyroomacoustics/soundsource.py index 5cc46280..89e94c2a 100644 --- a/pyroomacoustics/soundsource.py +++ b/pyroomacoustics/soundsource.py @@ -31,7 +31,6 @@ def __init__( delay=0, directivity=None, ): - position = np.array(position) self.dim = position.shape[0] @@ -119,7 +118,6 @@ def add_signal(self, signal): self.signal = signal def distance(self, ref_point): - return np.sqrt(np.sum((self.images - ref_point[:, np.newaxis]) ** 2, axis=0)) def set_ordering(self, ordering, ref_point=None): @@ -135,14 +133,12 @@ def set_ordering(self, ordering, ref_point=None): ref_point = ref_point[:, 0] if ordering == "nearest": - if ref_point is None: raise NameError("For nearest ordering, a reference point is needed.") self.I = self.distance(ref_point).argsort() elif ordering == "strongest": - if ref_point is None: raise NameError("For strongest ordering, a reference point is needed.") @@ -150,7 +146,6 @@ def set_ordering(self, ordering, ref_point=None): self.I = strength.argsort() elif ordering == "order": - self.ordering = "order" else: @@ -389,7 +384,6 @@ def build_rir_matrix(mics, sources, Lg, Fs, epsilon=5e-3, unit_damping=False): for s in range(len(sources)): for r in np.arange(mics.shape[1]): - dist = sources[s].distance(mics[:, r]) time = dist / constants.get("c") - t_min + offset if unit_damping == True: diff --git a/pyroomacoustics/tests/test_anechoic_room.py b/pyroomacoustics/tests/test_anechoic_room.py index 548c8dae..63edbd45 100644 --- a/pyroomacoustics/tests/test_anechoic_room.py +++ b/pyroomacoustics/tests/test_anechoic_room.py @@ -3,7 +3,6 @@ def test_anechoic_room(debug=False): - # sound signal fs = 40000 freq = 440 @@ -11,7 +10,6 @@ def test_anechoic_room(debug=False): signal = np.sin(2 * np.pi * freq * times) for dim in [2, 3]: - # create Anechoic room using the correct class room_infinite = pra.AnechoicRoom(fs=fs, dim=dim) diff --git a/pyroomacoustics/tests/test_angle_function.py b/pyroomacoustics/tests/test_angle_function.py index 93be79b3..8b7d679c 100644 --- a/pyroomacoustics/tests/test_angle_function.py +++ b/pyroomacoustics/tests/test_angle_function.py @@ -78,7 +78,6 @@ def find_error(type_coordinates): a_b_index = 0 for a in a_range: for b in b_range: - error_azimuth = (angle_function(a, b) - a_b_range[a_b_index])[0] error_colatitude = (angle_function(a, b) - a_b_range[a_b_index])[1] @@ -108,7 +107,6 @@ def find_error(type_coordinates): c_d_index = 0 for c in c_range: for d in d_range: - error_azimuth = (angle_function(c, d) - c_d_range[c_d_index])[0] error_colatitude = (angle_function(c, d) - c_d_range[c_d_index])[1] diff --git a/pyroomacoustics/tests/test_autocorr.py b/pyroomacoustics/tests/test_autocorr.py index 64a1a631..6e8221ee 100644 --- a/pyroomacoustics/tests/test_autocorr.py +++ b/pyroomacoustics/tests/test_autocorr.py @@ -10,7 +10,6 @@ def consistent_results(p, biased=True): - r_time = autocorr(x, p, method="time", biased=biased) r_fft = autocorr(x, p, method="fft", biased=biased) r_np = autocorr(x, p, method="numpy", biased=biased) diff --git a/pyroomacoustics/tests/test_bandpass_filterbank.py b/pyroomacoustics/tests/test_bandpass_filterbank.py index 8e5ca7e5..71b0d14e 100644 --- a/pyroomacoustics/tests/test_bandpass_filterbank.py +++ b/pyroomacoustics/tests/test_bandpass_filterbank.py @@ -39,7 +39,6 @@ def test_bandpass_filterbank(): if __name__ == "__main__": - import matplotlib.pyplot as plt f0 = 125.0 / 2.0 diff --git a/pyroomacoustics/tests/test_build_rir.py b/pyroomacoustics/tests/test_build_rir.py index f3cf0514..117c467b 100644 --- a/pyroomacoustics/tests/test_build_rir.py +++ b/pyroomacoustics/tests/test_build_rir.py @@ -71,7 +71,6 @@ def build_rir_wrap(time, alpha, visibility, fs, fdl): - # fractional delay length fdl = pra.constants.get("frac_delay_length") fdl2 = (fdl - 1) // 2 @@ -98,7 +97,6 @@ def build_rir_wrap(time, alpha, visibility, fs, fdl): def test_build_rir(): - if not build_rir_available: return @@ -191,7 +189,6 @@ def test_errors(): if __name__ == "__main__": - import matplotlib.pyplot as plt for t, a, v in zip(times, alphas, visibilities): diff --git a/pyroomacoustics/tests/test_issue_22.py b/pyroomacoustics/tests/test_issue_22.py index aa697cdf..1da75d23 100644 --- a/pyroomacoustics/tests/test_issue_22.py +++ b/pyroomacoustics/tests/test_issue_22.py @@ -19,7 +19,6 @@ def test_issue_22(): - np.random.seed(0) n_mics = 1 @@ -48,7 +47,6 @@ def test_issue_22(): shoebox.add_microphone_array(pyroomacoustics.MicrophoneArray(mic_pos, fs)) for i in range(n_times): - shoebox.image_source_model() if i != 0 and i % 1000 == 0: @@ -56,5 +54,4 @@ def test_issue_22(): if __name__ == "__main__": - test_issue_22() diff --git a/pyroomacoustics/tests/test_issue_235.py b/pyroomacoustics/tests/test_issue_235.py index d69dd4bd..da26a380 100644 --- a/pyroomacoustics/tests/test_issue_235.py +++ b/pyroomacoustics/tests/test_issue_235.py @@ -2,6 +2,5 @@ def test_set_rt_no_directivity(): - room = pra.ShoeBox([5, 4, 3]) room.set_ray_tracing() diff --git a/pyroomacoustics/tests/test_issue_236.py b/pyroomacoustics/tests/test_issue_236.py index 452512cc..3f57a185 100644 --- a/pyroomacoustics/tests/test_issue_236.py +++ b/pyroomacoustics/tests/test_issue_236.py @@ -54,7 +54,6 @@ def random_room_ism(max_order=10, eps=1e-6, verbose=False): def test_ism_shoebox_vs_general(verbose=False): - np.random.seed(0) n_repeat = 100 max_order = 10 diff --git a/pyroomacoustics/tests/test_issue_69.py b/pyroomacoustics/tests/test_issue_69.py index 8a916ff6..83af8ca0 100644 --- a/pyroomacoustics/tests/test_issue_69.py +++ b/pyroomacoustics/tests/test_issue_69.py @@ -11,6 +11,7 @@ fs = 16000 max_order = 5 + # scenario A def get_room_constructor_args(): """ @@ -49,7 +50,6 @@ def get_room_add_method(): class RoomConstructorSources(unittest.TestCase): def test_room_constructor(self): - room_1 = get_room_constructor_args() self.assertTrue(isinstance(room_1.sources[0], pra.SoundSource)) @@ -64,5 +64,4 @@ def test_rir_equal(self): if __name__ == "__main__": - unittest.main() diff --git a/pyroomacoustics/tests/test_materials.py b/pyroomacoustics/tests/test_materials.py index fc4ca0d2..e6157fe4 100644 --- a/pyroomacoustics/tests/test_materials.py +++ b/pyroomacoustics/tests/test_materials.py @@ -112,7 +112,6 @@ def test_empty(): if __name__ == "__main__": - test_material_e_float() test_material_es_float() test_material_es_dict diff --git a/pyroomacoustics/tests/test_metrics.py b/pyroomacoustics/tests/test_metrics.py index 1602ed2c..d54ce172 100644 --- a/pyroomacoustics/tests/test_metrics.py +++ b/pyroomacoustics/tests/test_metrics.py @@ -4,7 +4,6 @@ def test_median(): - # simple tests x = np.arange(1, 11) m = pra.median(x) @@ -42,7 +41,6 @@ def test_median(): for n in N: for a in alpha: - failures = np.zeros(R, dtype=bool) for r in range(R): @@ -56,5 +54,4 @@ def test_median(): if __name__ == "__main__": - test_median() diff --git a/pyroomacoustics/tests/test_rake_filters.py b/pyroomacoustics/tests/test_rake_filters.py index 43814101..f187500b 100644 --- a/pyroomacoustics/tests/test_rake_filters.py +++ b/pyroomacoustics/tests/test_rake_filters.py @@ -44,7 +44,6 @@ def test_perceptual_filters(): if __name__ == "__main__": - import matplotlib.pyplot as plt bf.rake_perceptual_filters( diff --git a/pyroomacoustics/tests/test_room_add.py b/pyroomacoustics/tests/test_room_add.py index 9973cf11..f6a87d46 100644 --- a/pyroomacoustics/tests/test_room_add.py +++ b/pyroomacoustics/tests/test_room_add.py @@ -10,7 +10,6 @@ def test_add_source_mic(): - room = pra.ShoeBox(room_size).add_source(source_loc0).add_microphone(mic0) assert len(room.sources) == 1 @@ -30,7 +29,6 @@ def test_add_source_mic(): def test_add_source_mic_obj(): - room = pra.ShoeBox(room_size) source0 = pra.SoundSource(source_loc0, signal=sig) @@ -58,7 +56,6 @@ def test_add_source_mic_obj(): def test_add_source_mic_obj_2(): - room = pra.ShoeBox(room_size) source0 = pra.SoundSource(source_loc0, signal=sig) @@ -77,7 +74,6 @@ def test_add_source_mic_obj_2(): def test_add_source_mic_ndarray(): - source0 = pra.SoundSource(source_loc0, signal=sig) source1 = pra.SoundSource(source_loc1, signal=sig) mic_array = np.c_[mic0, mic1] @@ -96,7 +92,6 @@ def test_add_source_mic_ndarray(): def test_add_source_mic_ndarray_2(): - source0 = pra.SoundSource(source_loc0, signal=sig) source1 = pra.SoundSource(source_loc1, signal=sig) mic_array = np.c_[mic0, mic1] diff --git a/pyroomacoustics/tests/test_room_is_insided.py b/pyroomacoustics/tests/test_room_is_insided.py index 2ca0b920..b4d8cac2 100644 --- a/pyroomacoustics/tests/test_room_is_insided.py +++ b/pyroomacoustics/tests/test_room_is_insided.py @@ -66,5 +66,4 @@ def test_room_is_inside(): if __name__ == "__main__": - test_room_is_inside() diff --git a/pyroomacoustics/tests/test_room_mix.py b/pyroomacoustics/tests/test_room_mix.py index d65f6de1..ee10a6a1 100644 --- a/pyroomacoustics/tests/test_room_mix.py +++ b/pyroomacoustics/tests/test_room_mix.py @@ -36,7 +36,6 @@ def callback_mix(premix, snr=0, sir=0, ref_mic=0, n_src=None, n_tgt=None): - # first normalize all separate recording to have unit power at microphone one p_mic_ref = np.std(premix[:, ref_mic, :], axis=1) premix /= p_mic_ref[:, None, None] @@ -58,7 +57,6 @@ def callback_mix(premix, snr=0, sir=0, ref_mic=0, n_src=None, n_tgt=None): class TestRoomMix(unittest.TestCase): def test_mix(self): - # Run the simulation premix = room.simulate( callback_mix=callback_mix, diff --git a/pyroomacoustics/tests/test_rt60.py b/pyroomacoustics/tests/test_rt60.py index 47e4fde1..56d698fd 100644 --- a/pyroomacoustics/tests/test_rt60.py +++ b/pyroomacoustics/tests/test_rt60.py @@ -13,7 +13,6 @@ def test_rt60_theory_single_band(): - # The desired reverberation time and dimensions of the room rt60_tgt = 0.3 # seconds @@ -33,7 +32,6 @@ def test_rt60_theory_single_band(): def test_rt60_theory_multi_band(): - # Create the room room = pra.ShoeBox( room_dim, @@ -47,7 +45,6 @@ def test_rt60_theory_multi_band(): def test_rt60_measure(): - # Create the room room = pra.ShoeBox( room_dim, @@ -68,7 +65,6 @@ def test_rt60_measure(): if __name__ == "__main__": - test_rt60_theory_single_band() test_rt60_theory_multi_band() test_rt60_measure() diff --git a/pyroomacoustics/tests/test_soundsource.py b/pyroomacoustics/tests/test_soundsource.py index 49d5738d..9df72cbf 100644 --- a/pyroomacoustics/tests/test_soundsource.py +++ b/pyroomacoustics/tests/test_soundsource.py @@ -3,7 +3,6 @@ def test_soundsource_basic(): - the_signal = np.ones(10) source = pra.SoundSource([1.0, 1.0], signal=the_signal) @@ -12,5 +11,4 @@ def test_soundsource_basic(): if __name__ == "__main__": - test_soundsource_basic() diff --git a/pyroomacoustics/tests/test_sync.py b/pyroomacoustics/tests/test_sync.py index 34b124de..a95da9e1 100644 --- a/pyroomacoustics/tests/test_sync.py +++ b/pyroomacoustics/tests/test_sync.py @@ -4,12 +4,10 @@ def test_correlate(): - N = [100, 200, 50, 37] M = [47, 82, 151, 893] for n, m in zip(N, M): - x = np.random.randn(n) y = np.random.randn(m) @@ -17,13 +15,11 @@ def test_correlate(): def test_tdoa_delay_int(): - N = [100, 200, 50, 1000] M = [47, 37, 12, 128] delays = [27, 4, 10, 347] for n, m, tau in zip(N, M, delays): - pulse = np.random.randn(m) x1 = np.zeros(n) x1[:m] = pulse @@ -38,7 +34,6 @@ def test_tdoa_delay_int(): def test_tdoa_delay_frac_phat(): - N = [14, 200, 70, 40, 28] M = [3, 78, 12, 10, 12] @@ -52,7 +47,6 @@ def test_tdoa_delay_frac_phat(): # test without explicit sampling frequency for n, m, tau, fil in zip(N, M, delays, frac_filters): - pulse = np.random.randn(m) signal = np.zeros(n) signal[:m] = pulse @@ -74,7 +68,6 @@ def test_tdoa_delay_frac_phat(): if __name__ == "__main__": - test_correlate() test_tdoa_delay_int() test_tdoa_delay_frac_phat() diff --git a/pyroomacoustics/tests/test_volume_area.py b/pyroomacoustics/tests/test_volume_area.py index 9fac463e..09c6418e 100644 --- a/pyroomacoustics/tests/test_volume_area.py +++ b/pyroomacoustics/tests/test_volume_area.py @@ -3,7 +3,6 @@ def test_room_volume(): - eps = 0.00001 # Create the 2D L-shaped room from the floor polygon diff --git a/pyroomacoustics/tests/tests_libroom/test_ccw3p.py b/pyroomacoustics/tests/tests_libroom/test_ccw3p.py index a95c8adb..dda2557d 100644 --- a/pyroomacoustics/tests/tests_libroom/test_ccw3p.py +++ b/pyroomacoustics/tests/tests_libroom/test_ccw3p.py @@ -45,7 +45,6 @@ def ccw3p(case): - p1, p2, p3 = case["points"] r = pra.libroom.ccw3p(p1, p2, p3) @@ -68,9 +67,7 @@ def test_ccw3p_colinear(): if __name__ == "__main__": - for lbl, case in cases.items(): - try: ccw3p(case) except: diff --git a/pyroomacoustics/tests/tests_libroom/test_geometry_routines.py b/pyroomacoustics/tests/tests_libroom/test_geometry_routines.py index d33cf482..ab9a3abd 100644 --- a/pyroomacoustics/tests/tests_libroom/test_geometry_routines.py +++ b/pyroomacoustics/tests/tests_libroom/test_geometry_routines.py @@ -226,7 +226,6 @@ def test_cosangleBetween3D_special(self): self.assertTrue(np.allclose(result, 0.956345613, atol=eps)) def test_dist_line_point2D(self): - start = [3, 3] end = [6, 9] point = [11, 4] @@ -236,7 +235,6 @@ def test_dist_line_point2D(self): self.assertTrue(abs(res - np.sqrt(6 * 6 + 3 * 3)) < eps) def test_dist_line_point2D_vert(self): - start = [-4, 12] end = [-4, 27] point = [7, 10] @@ -246,7 +244,6 @@ def test_dist_line_point2D_vert(self): self.assertTrue(abs(res - 11) < eps) def test_dist_line_point3D(self): - start = [0, 0, 0] end = [1, 2, 3] point = [4, 5, 6] @@ -256,7 +253,6 @@ def test_dist_line_point3D(self): self.assertTrue(abs(res - 1.963961012) < eps) def test_dist_line_point3D_online(self): - start = [0, 0, 0] end = [0, 0, 3] point = [0, 0, 6] diff --git a/pyroomacoustics/tests/tests_libroom/test_is_inside_2d_polygon.py b/pyroomacoustics/tests/tests_libroom/test_is_inside_2d_polygon.py index 24c2c257..98c72033 100644 --- a/pyroomacoustics/tests/tests_libroom/test_is_inside_2d_polygon.py +++ b/pyroomacoustics/tests/tests_libroom/test_is_inside_2d_polygon.py @@ -138,7 +138,6 @@ def test_top_outside(): if __name__ == "__main__": - test_inside() test_on_border() test_on_corner() diff --git a/pyroomacoustics/tests/tests_libroom/test_ray_energy.py b/pyroomacoustics/tests/tests_libroom/test_ray_energy.py index 4ef58c22..ac3efaeb 100644 --- a/pyroomacoustics/tests/tests_libroom/test_ray_energy.py +++ b/pyroomacoustics/tests/tests_libroom/test_ray_energy.py @@ -52,7 +52,6 @@ def add(self, delay, val): class TestRayEnergy(unittest.TestCase): def test_square_room(self): - """ This is a cubic room of 2x2x2 meters. The source is placed at [0.5,0.5, 1] and the receiver at [1.5, 1.5, 1]. A ray is launched towards [1, 0, 1] so that diff --git a/pyroomacoustics/tests/tests_libroom/test_room_construct.py b/pyroomacoustics/tests/tests_libroom/test_room_construct.py index dc97bffe..386c79a6 100644 --- a/pyroomacoustics/tests/tests_libroom/test_room_construct.py +++ b/pyroomacoustics/tests/tests_libroom/test_room_construct.py @@ -70,5 +70,4 @@ def test_room_construct(): if __name__ == "__main__": - room = test_room_construct() diff --git a/pyroomacoustics/tests/tests_libroom/test_room_walls.py b/pyroomacoustics/tests/tests_libroom/test_room_walls.py index a78c15b4..9252adee 100644 --- a/pyroomacoustics/tests/tests_libroom/test_room_walls.py +++ b/pyroomacoustics/tests/tests_libroom/test_room_walls.py @@ -241,7 +241,6 @@ def room_factory(walls, obstructing_walls, microphones): - args = [ walls, obstructing_walls, @@ -268,7 +267,6 @@ def room_factory(walls, obstructing_walls, microphones): class TestRoomWalls(unittest.TestCase): def test_max_dist_3D(self): - walls = [ pra.wall_factory(c, [a], [s]) for c, a, s in zip(wall_corners_3D, absorptions_3D, scatterings_2D) @@ -296,7 +294,6 @@ def test_max_dist_3D(self): self.assertTrue(abs(result - correct) < eps) def test_max_dist_2D(self): - walls = [ pra.wall_factory(c, [a], [s]) for c, a, s in zip(wall_corners_2D, absorptions_2D, scatterings_2D) @@ -347,7 +344,6 @@ def test_same_wall_false3D(self): self.assertTrue(not w1.same_as(w2)) def test_same_wall_false3D_more_corners(self): - # Modification of wall_corners_3D[0]: adding a corner => 5 corners wall c1 = np.array([[0, 3, 3, 1.5, 0], [0, 0, 0, 0, 0], [0, 0, 2, 1.5, 2]]) @@ -358,7 +354,6 @@ def test_same_wall_false3D_more_corners(self): self.assertTrue(not w1.same_as(w2)) def test_next_wall_hit(self): - walls = [ pra.wall_factory(c, [a], [s]) for c, a, s in zip(wall_corners_3D, absorptions_3D, scatterings_3D) @@ -400,7 +395,6 @@ def test_next_wall_hit(self): self.assertTrue(correct_next_wall and correct_result and correct_distance) def test_next_wall_nohit(self): - walls = [ pra.wall_factory(c, [a], [s]) for c, a, s in zip(wall_corners_3D, absorptions_3D, scatterings_3D) @@ -435,7 +429,6 @@ def test_next_wall_nohit(self): self.assertTrue(ttuple[1] == -1) def test_next_wall_hit2D(self): - walls = [ pra.wall_factory(c, [a], [s]) for c, a, s in zip(wall_corners_2D, absorptions_2D, scatterings_2D) @@ -511,7 +504,6 @@ def test_scat_ray_blocked(self): ) def test_scat_ray_ok(self): - walls = [ pra.wall_factory(c, [a], [s]) for c, a, s in zip( @@ -589,7 +581,6 @@ def test_scat_ray_energy(self): """ def test_contains_2D(self): - walls = [ pra.wall_factory(c, [a], [s]) for c, a, s in zip( @@ -604,7 +595,6 @@ def test_contains_2D(self): self.assertTrue(room.contains(microphones[:, 0])) def test_notcontains_2D(self): - walls = [ pra.wall_factory(c, [a], [s]) for c, a, s in zip( @@ -619,7 +609,6 @@ def test_notcontains_2D(self): self.assertTrue(not room.contains(microphones[:, 0])) def test_contains_3D(self): - walls = [ pra.wall_factory(c, [a], [s]) for c, a, s in zip(wall_corners_3D, absorptions_3D, scatterings_3D) @@ -632,7 +621,6 @@ def test_contains_3D(self): self.assertTrue(room.contains(microphones[:, 0])) def test_notcontains_3D(self): - walls = [ pra.wall_factory(c, [a], [s]) for c, a, s in zip(wall_corners_3D, absorptions_3D, scatterings_3D) diff --git a/pyroomacoustics/tests/tests_libroom/test_wall_construct.py b/pyroomacoustics/tests/tests_libroom/test_wall_construct.py index 5b5fc33c..5191327b 100644 --- a/pyroomacoustics/tests/tests_libroom/test_wall_construct.py +++ b/pyroomacoustics/tests/tests_libroom/test_wall_construct.py @@ -115,7 +115,6 @@ def test_wall_3d_normal_1(): if __name__ == "__main__": - test_wall_3d_construct_0() test_wall_3d_normal_0() test_wall_3d_area_0() diff --git a/pyroomacoustics/tests/tests_libroom/test_wall_intersection.py b/pyroomacoustics/tests/tests_libroom/test_wall_intersection.py index 1b33d0a1..31ffc796 100644 --- a/pyroomacoustics/tests/tests_libroom/test_wall_intersection.py +++ b/pyroomacoustics/tests/tests_libroom/test_wall_intersection.py @@ -304,7 +304,6 @@ def run_intersect(lbl): - case = cases[lbl] wall = pra.wall_factory(case["corners"], case["absorption"], case["scattering"]) p1, p2 = case["seg"] @@ -404,7 +403,6 @@ def test_2d_none_2(): if __name__ == "__main__": - test_3d_valid() test_3d_endpt_1() test_3d_endpt_2() diff --git a/pyroomacoustics/tests/tests_libroom/test_wall_side_reflect.py b/pyroomacoustics/tests/tests_libroom/test_wall_side_reflect.py index c23bb7a7..180c1055 100644 --- a/pyroomacoustics/tests/tests_libroom/test_wall_side_reflect.py +++ b/pyroomacoustics/tests/tests_libroom/test_wall_side_reflect.py @@ -98,7 +98,6 @@ def run_side(label): def run_reflect(label): - p = points[label]["p"] p_refl = np.array(points[label]["reflect"]) r_exp = points[label]["expect"] @@ -165,7 +164,6 @@ def test_reflect_2d_on(self): self.assertTrue(ret) def test_reflected_end2D(self): - eps = 0.001 start = [1, 3] @@ -184,7 +182,6 @@ def test_reflected_end2D(self): self.assertTrue(np.allclose(res, [5.0, -1.0], atol=eps)) def test_reflected_end3D(self): - eps = 0.001 start = [1, 1, 1] hit = [-1, 1, 3] diff --git a/pyroomacoustics/transform/dft.py b/pyroomacoustics/transform/dft.py index b87b0560..8d0690b1 100644 --- a/pyroomacoustics/transform/dft.py +++ b/pyroomacoustics/transform/dft.py @@ -94,7 +94,6 @@ def __init__( precision="double", bits=None, ): - self.nfft = nfft self.D = D self.axis = axis @@ -227,20 +226,12 @@ def analysis(self, x): # apply DFT if self.transform == "fftw": - self.a[ - :, - ] = x - self.X[ - :, - ] = self._forward() + self.a[:,] = x + self.X[:,] = self._forward() elif self.transform == "mkl": - self.X[ - :, - ] = mkl_fft.rfft_numpy(x, self.nfft, axis=self.axis) + self.X[:,] = mkl_fft.rfft_numpy(x, self.nfft, axis=self.axis) else: - self.X[ - :, - ] = rfft(x, self.nfft, axis=self.axis) + self.X[:,] = rfft(x, self.nfft, axis=self.axis) return self.X @@ -269,24 +260,16 @@ def synthesis(self, X=None): % (X.shape[0], X.shape[1], self.X.shape[0], self.X.shape[1]) ) - self.X[ - :, - ] = X + self.X[:,] = X # inverse DFT if self.transform == "fftw": self.b[:] = self.X - self.x[ - :, - ] = self._backward() + self.x[:,] = self._backward() elif self.transform == "mkl": - self.x[ - :, - ] = mkl_fft.irfft_numpy(self.X, self.nfft, axis=self.axis) + self.x[:,] = mkl_fft.irfft_numpy(self.X, self.nfft, axis=self.axis) else: - self.x[ - :, - ] = irfft(self.X, self.nfft, axis=self.axis) + self.x[:,] = irfft(self.X, self.nfft, axis=self.axis) # apply window if needed if self.synthesis_window is not None: diff --git a/pyroomacoustics/transform/stft.py b/pyroomacoustics/transform/stft.py index f4ef5a9e..27f6e71a 100644 --- a/pyroomacoustics/transform/stft.py +++ b/pyroomacoustics/transform/stft.py @@ -84,7 +84,6 @@ def __init__( precision="double", **kwargs ): - # initialize parameters self.num_samples = N # number of samples per frame self.num_channels = channels # number of channels @@ -183,9 +182,7 @@ def _make_buffers(self): self.out = np.zeros((self.hop, self.num_channels), dtype=self.time_dtype) # useful views on the input buffer - self.fft_in_state = self.fft_in_buffer[ - self.zf : self.zf + self.n_state, - ] + self.fft_in_state = self.fft_in_buffer[self.zf : self.zf + self.n_state,] self.fresh_samples = self.fft_in_buffer[ self.zf + self.n_state : self.zf + self.n_state + self.hop, ] @@ -350,7 +347,6 @@ def analysis(self, x): # ----check number of frames if self.streaming: # need integer multiple of hops - if self.fixed_input: if x_shape[0] != self.num_frames * self.hop: raise ValueError( @@ -372,7 +368,6 @@ def analysis(self, x): # need at least num_samples for last frame # e.g.[hop|hop|...|hop|num_samples] else: - if self.fixed_input: if x_shape[0] != (self.hop * (self.num_frames - 1) + self.num_samples): raise ValueError( @@ -396,7 +391,6 @@ def analysis(self, x): ) self.num_frames = 1 else: - # calculate num_frames and append zeros if necessary self.num_frames = int( np.ceil((x_shape[0] - self.num_samples) / self.hop) + 1 @@ -448,20 +442,14 @@ def _analysis_single(self, x_n): """ # correct input size check in: dft.analysis() - self.fresh_samples[:,] = x_n[ - :, - ] # introduce new samples - self.x_p[ - :, - ] = self.old_samples # save next state + self.fresh_samples[:,] = x_n[:,] # introduce new samples + self.x_p[:,] = self.old_samples # save next state # apply DFT to current frame self.X[:] = self.dft.analysis(self.fft_in_buffer) # shift backwards in the buffer the state - self.fft_in_state[:,] = self.x_p[ - :, - ] + self.fft_in_state[:,] = self.x_p[:,] def _analysis_streaming(self, x): """ @@ -475,23 +463,15 @@ def _analysis_streaming(self, x): n = 0 for k in range(self.num_frames): # introduce new samples - self.fresh_samples[:,] = x[ - n : n + self.hop, - ] + self.fresh_samples[:,] = x[n : n + self.hop,] # save next state - self.x_p[ - :, - ] = self.old_samples + self.x_p[:,] = self.old_samples # apply DFT to current frame - self.X[ - k, - ] = self.dft.analysis(self.fft_in_buffer) + self.X[k,] = self.dft.analysis(self.fft_in_buffer) # shift backwards in the buffer the state - self.fft_in_state[:,] = self.x_p[ - :, - ] + self.fft_in_state[:,] = self.x_p[:,] n += self.hop @@ -507,7 +487,6 @@ def _analysis_non_streaming(self, x): if not self.mono: for c in range(self.num_channels): - y = _as_strided(x[:, c], shape=new_shape, strides=new_strides) y = np.concatenate( ( @@ -522,7 +501,6 @@ def _analysis_non_streaming(self, x): else: self.X[:, :, c] = self.dft_frames.analysis(y).T else: - y = _as_strided(x, shape=new_shape, strides=new_strides) y = np.concatenate( ( @@ -587,7 +565,6 @@ def _check_input_frequency_dimensions(self, X): return self.X def process(self, X=None): - """ Parameters ----------- @@ -621,11 +598,9 @@ def process(self, X=None): return self.X def _process_single(self): - np.multiply(self.X, self.H, self.X) def _process_multiple(self): - if not self.fixed_input: if self.mono: self.H_multi = np.tile(self.H, (self.num_frames, 1)) @@ -694,22 +669,19 @@ def _synthesis_multiple(self): # synthesis + overlap and add if not self.mono: - x_r = np.zeros( (self.num_frames * self.hop, self.num_channels), dtype=self.time_dtype ) n = 0 for f in range(self.num_frames): - # apply IDFT to current frame and reconstruct output - x_r[ - n : n + self.hop, - ] = self._overlap_and_add(self.dft.synthesis(self.X[f, :, :])) + x_r[n : n + self.hop,] = self._overlap_and_add( + self.dft.synthesis(self.X[f, :, :]) + ) n += self.hop else: - x_r = np.zeros(self.num_frames * self.hop, dtype=self.time_dtype) # treat number of frames as the multiple channels for DFT @@ -728,38 +700,25 @@ def _synthesis_multiple(self): # overlap and add n = 0 for f in range(self.num_frames): - x_r[ - n : n + self.hop, - ] = self._overlap_and_add(mx[:, f]) + x_r[n : n + self.hop,] = self._overlap_and_add(mx[:, f]) n += self.hop return x_r def _overlap_and_add(self, x=None): - if x is None: x = self.dft.x - self.out[:,] = x[ - 0 : self.hop, - ] # fresh output samples + self.out[:,] = x[0 : self.hop,] # fresh output samples # add state from previous frames when overlap is used if self.n_state_out > 0: m = np.minimum(self.hop, self.n_state_out) - self.out[:m,] += self.y_p[ - :m, - ] + self.out[:m,] += self.y_p[:m,] # update state variables - self.y_p[: -self.hop,] = self.y_p[ - self.hop :, - ] # shift out left - self.y_p[ - -self.hop :, - ] = 0.0 - self.y_p[:,] += x[ - -self.n_state_out :, - ] + self.y_p[: -self.hop,] = self.y_p[self.hop :,] # shift out left + self.y_p[-self.hop :,] = 0.0 + self.y_p[:,] += x[-self.n_state_out :,] return self.out diff --git a/pyroomacoustics/transform/tests/test_dft.py b/pyroomacoustics/transform/tests/test_dft.py index 9f059614..8511245b 100644 --- a/pyroomacoustics/transform/tests/test_dft.py +++ b/pyroomacoustics/transform/tests/test_dft.py @@ -22,7 +22,6 @@ def no_window(nfft, D, transform, axis=0): - if D == 1: x_local = x[:, 0] X_local = X_numpy[:, 0] @@ -49,7 +48,6 @@ def no_window(nfft, D, transform, axis=0): def window(nfft, D, analysis_window, synthesis_window, axis=0): - if D == 1: x_local = x[:, 0] X_local = X_numpy[:, 0] @@ -127,7 +125,6 @@ def test_window(self): if __name__ == "__main__": - print() print("1D") res = no_window(nfft, D=1, transform="numpy") diff --git a/pyroomacoustics/transform/tests/test_dft_timing.py b/pyroomacoustics/transform/tests/test_dft_timing.py index 6280c296..8da539cd 100644 --- a/pyroomacoustics/transform/tests/test_dft_timing.py +++ b/pyroomacoustics/transform/tests/test_dft_timing.py @@ -25,7 +25,6 @@ def timing(transform, n_trials): - dft = pra.transform.DFT(nfft, D, transform=transform) start_time = time.time() for k in range(n_trials): @@ -66,7 +65,6 @@ def timing(transform, n_trials): ) if pyfftw_available: - # prepare a = pyfftw.empty_aligned([nfft, D], dtype="float32") b = pyfftw.empty_aligned([nfft // 2 + 1, D], dtype="complex64") diff --git a/pyroomacoustics/transform/tests/test_stft.py b/pyroomacoustics/transform/tests/test_stft.py index 0cabdf4d..f164f670 100644 --- a/pyroomacoustics/transform/tests/test_stft.py +++ b/pyroomacoustics/transform/tests/test_stft.py @@ -36,7 +36,6 @@ def incorrect_input_size(D, num_frames): - if D == 1: x_local = x[:, 0] else: @@ -79,9 +78,7 @@ def no_overlap_no_filter(D, num_frames=1, fixed_memory=False, streaming=True): hop = block_size # no overlap if not streaming: num_samples = (num_frames - 1) * hop + block_size - x_local = x_local[ - :num_samples, - ] + x_local = x_local[:num_samples,] # Create the STFT object if fixed_memory: @@ -102,37 +99,20 @@ def no_overlap_no_filter(D, num_frames=1, fixed_memory=False, streaming=True): processed_x = np.zeros(x_local.shape) if streaming: - n = 0 hop_frames = hop * num_frames # process the signals while full blocks are available while x_local.shape[0] - n > hop_frames: - stft.analysis( - x_local[ - n : n + hop_frames, - ] - ) - processed_x[ - n : n + hop_frames, - ] = stft.synthesis() + stft.analysis(x_local[n : n + hop_frames,]) + processed_x[n : n + hop_frames,] = stft.synthesis() n += hop_frames else: - stft.analysis(x_local) processed_x = stft.synthesis() n = processed_x.shape[0] - error = np.max( - np.abs( - x_local[ - :n, - ] - - processed_x[ - :n, - ] - ) - ) + error = np.max(np.abs(x_local[:n,] - processed_x[:n,])) return error @@ -158,9 +138,7 @@ def with_arbitrary_overlap_synthesis_window( hop = int((1 - overlap) * block_size) # quarter overlap if not streaming: num_samples = (num_frames - 1) * hop + block_size - x_local = x_local[ - :num_samples, - ] + x_local = x_local[:num_samples,] analysis_window = pra.hann(block_size) synthesis_window = pra.transform.stft.compute_synthesis_window(analysis_window, hop) @@ -192,29 +170,17 @@ def with_arbitrary_overlap_synthesis_window( processed_x = np.zeros(x_local.shape) if streaming: - n = 0 hop_frames = hop * num_frames # process the signals while full blocks are available while x_local.shape[0] - n > hop_frames: - stft.analysis( - x_local[ - n : n + hop_frames, - ] - ) - processed_x[ - n : n + hop_frames, - ] = stft.synthesis() + stft.analysis(x_local[n : n + hop_frames,]) + processed_x[n : n + hop_frames,] = stft.synthesis() n += hop_frames error = np.max( np.abs( - x_local[ - : n - block_size + hop, - ] - - processed_x[ - block_size - hop : n, - ] + x_local[: n - block_size + hop,] - processed_x[block_size - hop : n,] ) ) @@ -230,22 +196,12 @@ def with_arbitrary_overlap_synthesis_window( plt.show() else: - stft.analysis(x_local) processed_x = stft.synthesis() n = processed_x.shape[0] L = block_size - hop - error = np.max( - np.abs( - x_local[ - L:-L, - ] - - processed_x[ - L:, - ] - ) - ) + error = np.max(np.abs(x_local[L:-L,] - processed_x[L:,])) if 20 * np.log10(error) > -10: import matplotlib.pyplot as plt @@ -284,9 +240,7 @@ def no_overlap_with_filter(D, num_frames=1, fixed_memory=False, streaming=True): hop = block_size # no overlap if not streaming: num_samples = (num_frames - 1) * hop + block_size - x_local = x_local[ - :num_samples, - ] + x_local = x_local[:num_samples,] # Create the STFT object if fixed_memory: @@ -310,39 +264,22 @@ def no_overlap_with_filter(D, num_frames=1, fixed_memory=False, streaming=True): processed_x = np.zeros(x_local.shape) if not streaming: - stft.analysis(x_local) stft.process() processed_x = stft.synthesis() n = processed_x.shape[0] else: - n = 0 hop_frames = hop * num_frames # process the signals while full blocks are available while x_local.shape[0] - n > hop_frames: - stft.analysis( - x_local[ - n : n + hop_frames, - ] - ) + stft.analysis(x_local[n : n + hop_frames,]) stft.process() # apply the filter - processed_x[ - n : n + hop_frames, - ] = stft.synthesis() + processed_x[n : n + hop_frames,] = stft.synthesis() n += hop_frames - error = np.max( - np.abs( - y_local[ - :n, - ] - - processed_x[ - :n, - ] - ) - ) + error = np.max(np.abs(y_local[:n,] - processed_x[:n,])) return error @@ -367,9 +304,7 @@ def with_half_overlap_no_filter(D, num_frames=1, fixed_memory=False, streaming=T window = pra.hann(block_size) # the analysis window if not streaming: num_samples = (num_frames - 1) * hop + block_size - x_local = x_local[ - :num_samples, - ] + x_local = x_local[:num_samples,] # Create the STFT object if fixed_memory: @@ -396,48 +331,27 @@ def with_half_overlap_no_filter(D, num_frames=1, fixed_memory=False, streaming=T processed_x = np.zeros(x_local.shape) if not streaming: - stft.analysis(x_local) processed_x = stft.synthesis() n = processed_x.shape[0] error = np.max( np.abs( - x_local[ - block_size - hop : n - hop, - ] - - processed_x[ - block_size - hop : n - hop, - ] + x_local[block_size - hop : n - hop,] + - processed_x[block_size - hop : n - hop,] ) ) else: - n = 0 hop_frames = hop * num_frames # process the signals while full blocks are available while x_local.shape[0] - n > hop_frames: - stft.analysis( - x_local[ - n : n + hop_frames, - ] - ) - processed_x[ - n : n + hop_frames, - ] = stft.synthesis() + stft.analysis(x_local[n : n + hop_frames,]) + processed_x[n : n + hop_frames,] = stft.synthesis() n += hop_frames - error = np.max( - np.abs( - x_local[ - : n - hop, - ] - - processed_x[ - hop:n, - ] - ) - ) + error = np.max(np.abs(x_local[: n - hop,] - processed_x[hop:n,])) return error @@ -466,9 +380,7 @@ def with_half_overlap_with_filter(D, num_frames=1, fixed_memory=False, streaming window = pra.hann(block_size) # the analysis window if not streaming: num_samples = (num_frames - 1) * hop + block_size - x_local = x_local[ - :num_samples, - ] + x_local = x_local[:num_samples,] # Create the STFT object if fixed_memory: @@ -498,7 +410,6 @@ def with_half_overlap_with_filter(D, num_frames=1, fixed_memory=False, streaming processed_x = np.zeros(x_local.shape) if not streaming: - stft.analysis(x_local) stft.process() processed_x = stft.synthesis() @@ -506,42 +417,22 @@ def with_half_overlap_with_filter(D, num_frames=1, fixed_memory=False, streaming error = np.max( np.abs( - y_local[ - block_size : n - block_size, - ] - - processed_x[ - block_size : n - block_size, - ] + y_local[block_size : n - block_size,] + - processed_x[block_size : n - block_size,] ) ) else: - n = 0 hop_frames = hop * num_frames # process the signals while full blocks are available while x_local.shape[0] - n > hop_frames: - stft.analysis( - x_local[ - n : n + hop_frames, - ] - ) + stft.analysis(x_local[n : n + hop_frames,]) stft.process() # apply the filter - processed_x[ - n : n + hop_frames, - ] = stft.synthesis() + processed_x[n : n + hop_frames,] = stft.synthesis() n += hop_frames - error = np.max( - np.abs( - y_local[ - : n - hop, - ] - - processed_x[ - hop:n, - ] - ) - ) + error = np.max(np.abs(y_local[: n - hop,] - processed_x[hop:n,])) # if D==1: # import matplotlib.pyplot as plt @@ -554,7 +445,6 @@ def with_half_overlap_with_filter(D, num_frames=1, fixed_memory=False, streaming def call_all_stft_tests(num_frames=1, fixed_memory=False, streaming=True, overlap=True): - error = no_overlap_no_filter(1, num_frames, fixed_memory, streaming) print("no overlap, no filter, mono : %0.0f dB" % (20 * np.log10(error))) @@ -1001,7 +891,6 @@ def test_with_arbitrary_overlap_synthesis_window_mono(self): if __name__ == "__main__": - print() print("TEST INFO") print("-------------------------------------------------------------") diff --git a/pyroomacoustics/transform/tests/test_stft_oneshot.py b/pyroomacoustics/transform/tests/test_stft_oneshot.py index 49b1de10..071f5f53 100644 --- a/pyroomacoustics/transform/tests/test_stft_oneshot.py +++ b/pyroomacoustics/transform/tests/test_stft_oneshot.py @@ -16,7 +16,6 @@ def no_overlap(D): - if D == 1: x_local = x[:, 0] else: @@ -34,7 +33,6 @@ def no_overlap(D): def half_overlap(D): - if D == 1: x_local = x[:, 0] else: @@ -50,16 +48,7 @@ def half_overlap(D): x_r = stft.synthesis(X, L=block_size, hop=hop) return pra.dB( - np.max( - np.abs( - x_local[ - : -block_size + hop, - ] - - x_r[ - block_size - hop :, - ] - ) - ) + np.max(np.abs(x_local[: -block_size + hop,] - x_r[block_size - hop :,])) ) @@ -82,21 +71,11 @@ def append_one_sample(D): x_r = stft.synthesis(X, L=block_size, hop=hop) return pra.dB( - np.max( - np.abs( - x_local[ - : -block_size + hop, - ] - - x_r[ - block_size - hop : -1, - ] - ) - ) + np.max(np.abs(x_local[: -block_size + hop,] - x_r[block_size - hop : -1,])) ) def hop_one_sample(D): - if D == 1: x_local = x[:, 0] else: @@ -113,16 +92,7 @@ def hop_one_sample(D): x_r = stft.synthesis(X, L=block_size, hop=hop, win=synthesis_win) return pra.dB( - np.max( - np.abs( - x_local[ - : -block_size + hop, - ] - - x_r[ - block_size - hop :, - ] - ) - ) + np.max(np.abs(x_local[: -block_size + hop,] - x_r[block_size - hop :,])) ) @@ -145,7 +115,6 @@ def test_hop_one_sample(self): if __name__ == "__main__": - print() print("TEST INFO") print("-------------------------------------------------------------") diff --git a/pyroomacoustics/transform/tests/test_stft_timing.py b/pyroomacoustics/transform/tests/test_stft_timing.py index 38170462..7957d256 100644 --- a/pyroomacoustics/transform/tests/test_stft_timing.py +++ b/pyroomacoustics/transform/tests/test_stft_timing.py @@ -34,33 +34,15 @@ stft = STFT(block_size, hop=hop, channels=num_mic, streaming=True, analysis_window=win) start = time.time() for k in range(num_times): - x_r = np.zeros(signals.shape) n = 0 while signals.shape[0] - n > hop: - stft.analysis( - signals[ - n : n + hop, - ] - ) - x_r[ - n : n + hop, - ] = stft.synthesis() + stft.analysis(signals[n : n + hop,]) + x_r[n : n + hop,] = stft.synthesis() n += hop avg_time = (time.time() - start) / num_times print("%0.3f sec" % avg_time) -err_dB = 20 * np.log10( - np.max( - np.abs( - signals[ - : n - hop, - ] - - x_r[ - hop:n, - ] - ) - ) -) +err_dB = 20 * np.log10(np.max(np.abs(signals[: n - hop,] - x_r[hop:n,]))) print("Error [dB] : %0.3f" % err_dB) @@ -75,33 +57,15 @@ ) start = time.time() for k in range(num_times): - x_r = np.zeros(signals.shape) n = 0 while signals.shape[0] - n > hop: - stft.analysis( - signals[ - n : n + hop, - ] - ) - x_r[ - n : n + hop, - ] = stft.synthesis() + stft.analysis(signals[n : n + hop,]) + x_r[n : n + hop,] = stft.synthesis() n += hop avg_time = (time.time() - start) / num_times print("%0.3f sec" % avg_time) -err_dB = 20 * np.log10( - np.max( - np.abs( - signals[ - : n - hop, - ] - - x_r[ - hop:n, - ] - ) - ) -) +err_dB = 20 * np.log10(np.max(np.abs(signals[: n - hop,] - x_r[hop:n,]))) print("Error [dB] : %0.3f" % err_dB) @@ -116,7 +80,6 @@ stft = STFT(block_size, hop=hop, channels=num_mic, analysis_window=win, streaming=False) start = time.time() for k in range(num_times): - stft.analysis(signals) x_r = stft.synthesis() @@ -141,7 +104,6 @@ ) start = time.time() for k in range(num_times): - stft.analysis(signals[: (num_frames - 1) * hop + block_size, :]) x_r = stft.synthesis() avg_time = (time.time() - start) / num_times diff --git a/pyroomacoustics/utilities.py b/pyroomacoustics/utilities.py index ce47b6c0..a96444ed 100644 --- a/pyroomacoustics/utilities.py +++ b/pyroomacoustics/utilities.py @@ -310,7 +310,6 @@ def time_dB(signal, Fs, bits=16): def spectrum(signal, Fs, N): - from .stft import spectroplot, stft from .windows import hann @@ -335,7 +334,6 @@ def compare_plot( title1=None, title2=None, ): - try: import matplotlib.pyplot as plt except ImportError: @@ -411,7 +409,6 @@ def compare_plot( def real_spectrum(signal, axis=-1, **kwargs): - try: import matplotlib.pyplot as plt except ImportError: @@ -651,7 +648,6 @@ def levinson(r, b): epsilon = r[0] for j in np.arange(1, p): - g = np.sum(np.conj(r[1 : j + 1]) * a[::-1]) gamma = -g / epsilon a = np.concatenate((a, np.zeros(1))) + gamma * np.concatenate( @@ -659,12 +655,7 @@ def levinson(r, b): ) epsilon = epsilon * (1 - np.abs(gamma) ** 2) delta = np.dot(np.conj(r[1 : j + 1]), np.flipud(x)) - q = ( - b[ - j, - ] - - delta - ) / epsilon + q = (b[j,] - delta) / epsilon if len(b.shape) == 1: x = np.concatenate((x, np.zeros(1))) + q * np.conj(a[::-1]) else: @@ -810,7 +801,6 @@ def angle_function(s1, v2): # colatitude calculation for 3-D coordinates if s1.shape[0] == 3 and v2.shape[0] == 3: - z2 = v2[2] z_vals = s1[2] @@ -820,7 +810,6 @@ def angle_function(s1, v2): # colatitude calculation for 2-D coordinates elif s1.shape[0] == 2 and v2.shape[0] == 2: - num_points = s1.shape[1] colatitude = np.ones(num_points) * np.pi / 2 diff --git a/setup.py b/setup.py index 88c70ca4..31eb9e2f 100644 --- a/setup.py +++ b/setup.py @@ -86,6 +86,7 @@ def __str__(self): ### Build Tools (taken from pybind11 example) ### + # As of Python 3.6, CCompiler has a `has_flag` method. # cf http://bugs.python.org/issue26689 def has_flag(compiler, flagname):