### Full Room Simulation Example Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.room.md A comprehensive example demonstrating the setup and simulation of a room with a source and microphone array. It includes room creation using inverse Sabine's formula, source and microphone placement, simulation, saving the output to WAV, measuring RT60, and plotting RIR and microphone signals. ```python import numpy as np import matplotlib.pyplot as plt import pyroomacoustics as pra from scipy.io import wavfile # The desired reverberation time and dimensions of the room rt60_tgt = 0.3 # seconds room_dim = [10, 7.5, 3.5] # meters # import a mono wavfile as the source signal # the sampling frequency should match that of the room fs, audio = wavfile.read("examples/samples/guitar_16k.wav") # We invert Sabine's formula to obtain the parameters for the ISM simulator e_absorption, max_order = pra.inverse_sabine(rt60_tgt, room_dim) # Create the room room = pra.ShoeBox( room_dim, fs=fs, materials=pra.Material(e_absorption), max_order=max_order ) # place the source in the room room.add_source([2.5, 3.73, 1.76], signal=audio, delay=0.5) # define the locations of the microphones mic_locs = np.c_[ [6.3, 4.87, 1.2], [6.3, 4.93, 1.2], # mic 1 # mic 2 ] # finally place the array in the room room.add_microphone_array(mic_locs) # Run the simulation (this will also build the RIR automatically) room.simulate() room.mic_array.to_wav( f"examples/samples/guitar_16k_reverb_{args.method}.wav", norm=True, bitdepth=np.int16, ) # measure the reverberation time rt60 = room.measure_rt60() print("The desired RT60 was {}".format(rt60_tgt)) print("The measured RT60 is {}".format(rt60[1, 0])) # Create a plot plt.figure() # plot one of the RIR. both can also be plotted using room.plot_rir() rir_1_0 = room.rir[1][0] plt.subplot(2, 1, 1) plt.plot(np.arange(len(rir_1_0)) / room.fs, rir_1_0) plt.title("The RIR from source 0 to mic 1") plt.xlabel("Time [s]") # plot signal at microphone 1 plt.subplot(2, 1, 2) plt.plot(room.mic_array.signals[1, :]) plt.title("Microphone 1 signal") plt.xlabel("Time [s]") plt.tight_layout() plt.show() ``` -------------------------------- ### Create and Visualize Beamformer Response Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/index.md This example shows how to set up a room, add a source, create a linear array beamformer, compute delay-and-sum weights, and plot the room with the beamformer response at different frequencies. Ensure pyroomacoustics, numpy, and matplotlib are installed. ```python import numpy as np import matplotlib.pyplot as plt import pyroomacoustics as pra # Create a 4 by 6 metres shoe box room room = pra.ShoeBox([4,6]) # Add a source somewhere in the room room.add_source([2.5, 4.5]) # Create a linear array beamformer with 4 microphones # with angle 0 degrees and inter mic distance 10 cm R = pra.linear_2D_array([2, 1.5], 4, 0, 0.1) room.add_microphone_array(pra.Beamformer(R, room.fs)) # Now compute the delay and sum weights for the beamformer room.mic_array.rake_delay_and_sum_weights(room.sources[0][:1]) # plot the room and resulting beamformer room.plot(freq=[1000, 2000, 4000, 8000], img_order=0) plt.show() ``` -------------------------------- ### Install Cookiecutter Source: https://github.com/lcav/pyroomacoustics/blob/master/README.rst Install the cookiecutter tool if necessary for generating simulation scripts. ```bash pip install cookiecutter ``` -------------------------------- ### Basic Python Example Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.md A simple demonstration of variable assignment and arithmetic operations in Python, as shown in the documentation's introductory examples. ```python x = 42 x = x + 1 ``` -------------------------------- ### Install and Configure Pre-commit Hooks Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/contributing.md Install pre-commit to manage code quality hooks like Black and isort. These hooks run automatically on commit and can be run manually on all files. ```shell pip install pre-commit pre-commit install ``` ```shell pre-commit run --all-files ``` -------------------------------- ### Install pyroomacoustics with pip Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/index.md Use this command to install the pyroomacoustics package. Ensure pip is up-to-date. ```default pip install pyroomacoustics ``` -------------------------------- ### Set up simulation script with cookiecutter Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/index.md Install cookiecutter and use it to generate a simulation script for 2D/3D scenarios. Then, run the generated script. ```default pip install cookiecutter cookiecutter gh:fakufaku/cookiecutter-pyroomacoustics-sim python .py ``` -------------------------------- ### Setup Room and Beamformer Source: https://github.com/lcav/pyroomacoustics/blob/master/notebooks/pyroomacoustics_demo.ipynb Configures a 2D shoebox room, adds signal and noise sources, and initializes a circular microphone array for beamforming. ```python Lg_t = 0.100 # filter size in seconds Lg = np.ceil(Lg_t*fs) # in samples # specify signal and noise source fs, signal = wavfile.read("arctic_a0010.wav") fs, noise = wavfile.read("exercise_bike.wav") # may spit out a warning when reading but it's alright! # Create 4x6 shoebox room with source and interferer and simulate room_bf = pra.ShoeBox([4,6], fs=fs, max_order=12) source = np.array([1, 4.5]) interferer = np.array([3.5, 3.]) room_bf.add_source(source, delay=0., signal=signal) room_bf.add_source(interferer, delay=0., signal=noise[:len(signal)]) # Create geometry equivalent to Amazon Echo center = [2, 1.5]; radius = 37.5e-3 fft_len = 512 echo = pra.circular_2D_array(center=center, M=6, phi0=0, radius=radius) echo = np.concatenate((echo, np.array(center, ndmin=2).T), axis=1) mics = pra.Beamformer(echo, room_bf.fs, N=fft_len, Lg=Lg) room_bf.add_microphone_array(mics) # Compute DAS weights mics.rake_delay_and_sum_weights(room_bf.sources[0][:1]) # plot the room and resulting beamformer before simulation fig, ax = room_bf.plot(freq=[500, 1000, 2000, 4000], img_order=0) ax.legend(['500', '1000', '2000', '4000']) fig.set_size_inches(20, 8) ``` -------------------------------- ### Verify pyroomacoustics Installation Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/contributing.md Confirm that the pyroomacoustics package is installed correctly by importing it and printing its version number. ```python python -c "import pyroomacoustics as pra; print(pra.__version__)" ``` -------------------------------- ### Create Room, Microphone Array, and Sound Source Source: https://github.com/lcav/pyroomacoustics/blob/master/README.rst This snippet demonstrates the initial setup for a room acoustics simulation by creating a Room object, adding a microphone array, and a sound source. This is a foundational step for simulating sound propagation and processing. ```python import pyroomacoustics as pa import numpy as np # Room dimensions in meters L = [10, 5, 3] # Length, Width, Height # Microphone array position mic_pos = np.array([[2, 3, 1.5]]) # Sound source position source_pos = np.array([[1, 1, 1]]) # Create a Room object room = pa.Room(L, fs=16000, sources=source_pos.T, mics=mic_pos.T) ``` -------------------------------- ### Griffin-Lim Phase Reconstruction Example Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.phase.gl.md Demonstrates how to use the Griffin-Lim algorithm to reconstruct a signal's phase from its STFT magnitude. It includes setting up STFT parameters, performing analysis, and monitoring convergence with a callback function. ```python import numpy as np from scipy.io import wavfile import pyroomacoustics as pra # We open a speech sample filename = "examples/input_samples/cmu_arctic_us_axb_a0004.wav" fs, audio = wavfile.read(filename) # These are the parameters of the STFT fft_size = 512 hop = fft_size // 4 win_a = np.hamming(fft_size) win_s = pra.transform.stft.compute_synthesis_window(win_a, hop) n_iter = 200 engine = pra.transform.STFT( fft_size, hop=hop, analysis_window=win_a, synthesis_window=win_s ) X = engine.analysis(audio) X_mag = np.abs(X) X_mag_norm = np.linalg.norm(X_mag) ** 2 # monitor convergence errors = [] # the callback to track the spectral distance convergence def cb(epoch, Y, y): # we measure convergence via spectral distance Y_2 = engine.analysis(y) sd = np.linalg.norm(X_mag - np.abs(Y_2)) ** 2 / X_mag_norm # save in the list every 10 iterations if epoch % 10 == 0: errors.append(sd) pra.phase.griffin_lim(X_mag, hop, win_a, n_iter=n_iter, callback=cb) plt.semilogy(np.arange(len(errors)) * 10, errors) plt.show() ``` -------------------------------- ### Example Usage of Powers Class Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.adaptive.data_structures.md Demonstrates how to instantiate and use the Powers class to retrieve powers of a given number. ```python >>> an = Powers(0.5) >>> print(an[4]) 0.0625 ``` -------------------------------- ### AuxIVA Separation Example Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.bss.auxiva.md Demonstrates how to perform blind source separation using AuxIVA. Reads a multichannel WAV file, performs STFT, separates sources, and then reconstructs the time-domain signals. ```python from scipy.io import wavfile import pyroomacoustics as pra # read multichannel wav file # audio.shape == (nsamples, nchannels) fs, audio = wavfile.read("my_multichannel_audio.wav") # STFT analysis parameters fft_size = 4096 # `fft_size / fs` should be ~RT60 hop == fft_size // 2 # half-overlap win_a = pra.hann(fft_size) # analysis window # optimal synthesis window win_s = pra.transform.compute_synthesis_window(win_a, hop) # STFT # X.shape == (nframes, nfrequencies, nchannels) X = pra.transform.analysis(audio, fft_size, hop, win=win_a) # Separation Y = pra.bss.auxiva(X, n_iter=20) # iSTFT (introduces an offset of `hop` samples) # y contains the time domain separated signals # y.shape == (new_nsamples, nchannels) y = pra.transform.synthesis(Y, fft_size, hop, win=win_s) ``` -------------------------------- ### Import pyroomacoustics Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.md This is the standard way to import the pyroomacoustics library for use in your code. It is assumed in docstring examples. ```python import pyroomacoustics as pra ``` -------------------------------- ### Install pyroomacoustics in Editable Mode Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/contributing.md Install the package in editable mode for local development. This links source files and compiled extensions, and ensures the latest version is used. Re-run after C++ code changes. ```shell pip install -U -e . ``` -------------------------------- ### Install pyroomacoustics in editable mode Source: https://github.com/lcav/pyroomacoustics/blob/master/CONTRIBUTING.rst Install the package in editable mode for local development. This links source files and compiled extensions. Re-run this command if C++ code changes. On macOS, set the deployment target if necessary. ```shell pip install -U -e . ``` ```shell MACOSX_DEPLOYMENT_TARGET=11.0 pip install -U -e . ``` -------------------------------- ### Using Google Speech Commands Dataset Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.datasets.md Demonstrates loading, filtering, and visualizing samples from Google's Speech Commands Dataset. The dataset is downloaded automatically if not available. Samples can be filtered by word and played if 'sounddevice' is installed. ```python # This example involves Google's Speech Commands Dataset available at # https://research.googleblog.com/2017/08/launching-speech-commands-dataset.html import matplotlib.pyplot as plt import pyroomacoustics as pra # The dataset is automatically downloaded if not available and 10 of each word is selected dataset = pra.datasets.GoogleSpeechCommands(download=True, subset=10, seed=0) # print dataset info, first 10 entries, and all sounds print(dataset) dataset.head(n=10) print("All sounds in the dataset:") print(dataset.classes) # filter by specific word selected_word = 'yes' matches = dataset.filter(word=selected_word) print("Number of '%s' samples : %d" % (selected_word, len(matches))) # if the sounddevice package is available, we can play the sample matches[0].play() # show the spectrogram plt.figure() matches[0].plot() plt.show() ``` -------------------------------- ### Plot room with microphone directivity Source: https://github.com/lcav/pyroomacoustics/blob/master/notebooks/rir_directivities_demo.ipynb Visualizes the shoebox room setup, including the source and the microphone with its defined directivity. ```python fig, ax = room.plot() ax.set_xlim([-1, 6]) ax.set_ylim([-1, 4]) ax.set_zlim([-1, 4]) ax.set_title("") fig.set_size_inches(10, 5); ``` -------------------------------- ### Initialize Hybrid ISM/Ray Tracing Simulator Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.room.md Configures the pyroomacoustics simulator to use a hybrid approach combining Image Source Model (ISM) for early reflections and Ray Tracing for the diffuse tail. This setup includes enabling air absorption and setting a maximum reflection order. ```python # Create the room room = pra.ShoeBox( room_dim, fs=16000, materials=pra.Material(e_absorption), max_order=3, ray_tracing=True, air_absorption=True, ) # Activate the ray tracing room.set_ray_tracing() ``` -------------------------------- ### STFT and Spectral Subtraction Setup Source: https://github.com/lcav/pyroomacoustics/blob/master/notebooks/stft.ipynb Initializes the STFT transform and SpectralSub object for noise suppression. Parameters like FFT length, overlap, and suppression levels can be tuned. ```python # STFT and SpectralSub parameters nfft = 512 # STFT frame length will be nfft/2 as we will use an STFT with 50% overlap. db_reduc = 10 # Maximum suppression per frequency bin. Large suppresion can result in more musical noise. lookback = 5 # How many frames to look back for the noise floor estimate. beta = 10 # An overestimation factor to "push" the suppression towards db_reduc. alpha = 3 # An exponential factor to tune the suppresion (see documentation of 'SpectralSub'). window = pra.hann(nfft, flag='asymmetric', length='full') # create objects stft = pra.transform.STFT(nfft, hop=nfft // 2, analysis_window=window) scnr = pra.denoise.SpectralSub(nfft, db_reduc, lookback, beta, alpha) ``` -------------------------------- ### STFT Object Creation and Filter Setup Source: https://github.com/lcav/pyroomacoustics/blob/master/notebooks/pyroomacoustics_demo.ipynb Configures STFT parameters, creates an STFT object, and sets a moving average filter for processing. Ensure FFT size is a power of 2 and adjust block size accordingly. ```python # filter to apply (moving average / low pass) h_len = 50 h = np.ones(h_len) h /= np.linalg.norm(h) # stft parameters fft_len = 512 block_size = fft_len - h_len + 1 # make sure the FFT size is a power of 2 hop = block_size // 2 # half overlap window = pra.hann(block_size, flag='asymmetric', length='full') # Create the STFT object + set filter and appropriate zero-padding stft = pra.transform.STFT(block_size, hop=hop, analysis_window=window, channels=1) stft.set_filter(h, zb=h.shape[0] - 1) ``` -------------------------------- ### Configuration Constants Source: https://github.com/lcav/pyroomacoustics/blob/master/notebooks/norm_music_demo.ipynb Defines constants and configuration parameters for the simulation, including sampling frequency, FFT size, simulation length, and microphone array setup. ```python # constants / config fs = 16000 nfft = 1024 n = 5*fs # simulation length of source signal (3 seconds) n_frames = 30 max_order = 10 doas_deg = np.linspace(start=0, stop=359, num=360, endpoint=True) rs = [0.5, 1, 1.5] mic_center = np.c_[[2,2,1]] mic_locs = mic_center + np.c_[[ 0.04, 0.0, 0.0], [ 0.0, 0.04, 0.0], [-0.04, 0.0, 0.0], [ 0.0, -0.04, 0.0], ) snr_lb, snr_ub = 0, 30 ``` -------------------------------- ### Initialize STFT and SpectralSub for Block-by-Block Processing Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.denoise.spectral_subtraction.md Initialize STFT and SpectralSub objects for processing audio in blocks. This setup is used for applying noise reduction incrementally. ```python # initialize STFT and SpectralSub objects nfft = 512 stft = pra.transform.STFT(nfft, hop=nfft//2, analysis_window=pra.hann(nfft)) scnr = pra.denoise.SpectralSub(nfft, db_reduc=10, lookback=5, beta=20, alpha=3) # apply block-by-block for n in range(num_blocks): # go to frequency domain for noise reduction stft.analysis(mono_noisy) gain_filt = scnr.compute_gain_filter(stft.X) # estimating input convolved with unknown response mono_denoised = stft.synthesis(gain_filt*stft.X) ``` -------------------------------- ### Initialize and Use SubbandLMS for Frequency Domain Filtering Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.adaptive.md Shows the setup for using SubbandLMS for frequency domain adaptive filtering. This involves initializing STFT blocks for signal transformation and the SubbandLMS filter itself. The update loop processes blocks of audio, transforms them to the frequency domain, updates the filter, and estimates the output. ```python # initialize STFT and SubbandLMS blocks block_size = 128 stft_x = pra.transform.STFT(N=block_size, hop=block_size//2, analysis_window=pra.hann(block_size)) stft_d = pra.transform.STFT(N=block_size, hop=block_size//2, analysis_window=pra.hann(block_size)) nlms = pra.adaptive.SubbandLMS(num_taps=6, num_bands=block_size//2+1, mu=0.5, nlms=True) # preparing input and reference signals ... # apply block-by-block for n in range(num_blocks): # obtain block ... # to frequency domain stft_x.analysis(x_block) stft_d.analysis(d_block) nlms.update(stft_x.X, stft_d.X) # estimating input convolved with unknown response y_hat = stft_d.synthesis(np.diag(np.dot(nlms.W.conj().T,stft_x.X))) # AEC output E = stft_d.X - np.diag(np.dot(nlms.W.conj().T,stft_x.X)) out = stft_d.synthesis(E) ``` -------------------------------- ### Clone the pyroomacoustics Repository Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/contributing.md Clone the project repository to start contributing. External dependencies like Eigen, nanoflann, and pybind11 are fetched automatically during the build process. ```shell git clone git@github.com:LCAV/pyroomacoustics.git ``` -------------------------------- ### Setting up Room Environment for BSS Source: https://github.com/lcav/pyroomacoustics/blob/master/notebooks/pyroomacoustics_demo.ipynb Defines room dimensions, source locations, and microphone array positions. It then creates a ShoeBox room object and adds sources and microphones to it, simulating an acoustic environment. ```python # Room 4m by 6m room_dim = [8, 9] # source locations and delays locations = [[2.5,3], [2.5, 6]] delays = [1., 0.] # create an anechoic room with sources and mics room = pra.ShoeBox(room_dim, fs=16000, max_order=15, absorption=0.35, sigma2_awgn=1e-8) # add mic and good source to room # Add silent signals to all sources for sig, d, loc in zip(signals, delays, locations): room.add_source(loc, signal=sig, delay=d) # add microphone array room.add_microphone_array(pra.MicrophoneArray(np.c_[[6.5, 4.49], [6.5, 4.51]], room.fs)) ``` -------------------------------- ### Set macOS Deployment Target for Installation Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/contributing.md If necessary on macOS, set the MACOSX_DEPLOYMENT_TARGET environment variable before installing in editable mode to ensure compatibility. ```shell MACOSX_DEPLOYMENT_TARGET=11.0 pip install -U -e . ``` -------------------------------- ### Get SOFA Database Helper Function Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.datasets.sofa.md A helper function to quickly load the SOFA database. This is a convenient way to get an instance of the SOFADatabase object. ```python from pyroomacoustics.datasets import get_sofa_db db = get_sofa_db() ``` -------------------------------- ### Load and List Available SOFA Files Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.datasets.sofa.md Instantiate the SOFADatabase and display a list of all available SOFA files and the devices they contain. This is useful for exploring the dataset. ```python from pyroomacoustics.datasets import SOFADatabase db = SOFADatabase() db.list() ``` -------------------------------- ### nmic Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.beamforming.md Gets the number of microphones in the array. ```APIDOC ## nmic ### Description The number of microphones of the array. ### Property `nmic` ``` -------------------------------- ### Creating and Filtering Artificial Samples Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.datasets.md Demonstrates how to create artificial audio samples with metadata, add them to a Dataset object, and filter them based on metadata attributes using exact matches, list containment, or callable functions. ```python # Prepare a few artificial samples samples = [ { 'data' : 0.99, 'metadata' : { 'speaker' : 'alice', 'sex' : 'female', 'age' : 37, 'number' : 'one' }, }, { 'data' : 2.1, 'metadata' : { 'speaker' : 'alice', 'sex' : 'female', 'age' : 37, 'number' : 'two' }, }, { 'data' : 1.02, 'metadata' : { 'speaker' : 'bob', 'sex' : 'male', 'age' : 48, 'number' : 'one' }, }, { 'data' : 2.07, 'metadata' : { 'speaker' : 'bob', 'sex' : 'male', 'age' : 48, 'number' : 'two' }, }, ] corpus = Dataset() for s in samples: new_sample = Sample(s['data'], **s['metadata']) corpus.add_sample(new_sample) # Then, it possible to display summary info about the corpus print(corpus) # The number of samples in the corpus is given by ``len`` print('Number of samples:', len(corpus)) # And we can access samples with the slice operator print('Sample #2:') print(corpus[2]) # (shortcut for `corpus.samples[2]`) # We can obtain a new corpus with only male subject corpus_male_only = corpus.filter(sex='male') print(corpus_male_only) # Only retain speakers above 40 years old corpus_older = corpus.filter(age=lambda a : a > 40) print(corpus_older) ``` -------------------------------- ### dim Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.beamforming.md Gets the dimension of the microphone array. ```APIDOC ## dim ### Description Gets the dimension of the microphone array. ### Property `dim` ``` -------------------------------- ### MicrophoneArray.M property Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.beamforming.md Gets the number of microphones in the array. ```APIDOC ## MicrophoneArray.M ### Description This property returns the total number of microphones in the array. ### Returns * **int** – The number of microphones. ``` -------------------------------- ### Initialize and Use DOA Algorithm Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.doa.md Initialize a DOA finding object with microphone locations, sampling frequency, and FFT parameters. Then, use the locate_sources method with STFT data and optional frequency bins to perform DOA finding. ```python >>> doa = pyroomacoustics.doa.MUSIC(R, fs, nfft) >>> doa.locate_sources(X, freq_bins=np.arange(20, 40)) ``` -------------------------------- ### Enter the pyroomacoustics Docker container Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/index.md Run an interactive terminal session inside the 'pyroom_container' Docker image. ```default docker run -it pyroom_container:latest /bin/bash ``` -------------------------------- ### CardioidFamily Methods Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.md Provides methods for calculating and visualizing cardioid-based directivities. Users can get the response, set orientation, and sample rays. ```APIDOC ## CardioidFamily.get_response() ### Description Calculates the directivity response for the cardioid family. ### Method Not specified (assumed to be a method call within a Python class). ### Endpoint N/A ### Parameters None explicitly documented. ### Request Example N/A ### Response Returns the directivity response. ## CardioidFamily.get_response_cartesian() ### Description Calculates the directivity response in Cartesian coordinates. ### Method Not specified (assumed to be a method call within a Python class). ### Endpoint N/A ### Parameters None explicitly documented. ### Request Example N/A ### Response Returns the directivity response in Cartesian coordinates. ## CardioidFamily.is_impulse_response ### Description Checks if the directivity is an impulse response. ### Method Not specified (assumed to be a property or method call within a Python class). ### Endpoint N/A ### Parameters None explicitly documented. ### Request Example N/A ### Response Boolean indicating if it's an impulse response. ## CardioidFamily.plot_response() ### Description Plots the directivity response. ### Method Not specified (assumed to be a method call within a Python class). ### Endpoint N/A ### Parameters None explicitly documented. ### Request Example N/A ### Response Generates a plot of the directivity response. ## CardioidFamily.sample_rays() ### Description Samples rays based on the directivity pattern. ### Method Not specified (assumed to be a method call within a Python class). ### Endpoint N/A ### Parameters None explicitly documented. ### Request Example N/A ### Response Returns sampled ray information. ## CardioidFamily.set_orientation() ### Description Sets the orientation of the directivity. ### Method Not specified (assumed to be a method call within a Python class). ### Endpoint N/A ### Parameters None explicitly documented. ### Request Example N/A ### Response Updates the orientation of the directivity. ``` -------------------------------- ### Import Libraries for Pyroomacoustics Source: https://github.com/lcav/pyroomacoustics/blob/master/notebooks/pyroomacoustics_demo.ipynb Imports necessary libraries for pyroomacoustics, including numpy, matplotlib, scipy, and IPython. Ensure these are installed via pip. ```python import numpy as np import matplotlib.pyplot as plt from scipy.io import wavfile from scipy.signal import fftconvolve import IPython import pyroomacoustics as pra ``` -------------------------------- ### MUSIC Class Initialization Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.doa.music.md Initializes the MUSIC DOA algorithm. The `locate_source()` method should be called to apply the algorithm. ```APIDOC ## class pyroomacoustics.doa.music.MUSIC ### Description Class to apply MUltiple SIgnal Classication (MUSIC) direction-of-arrival (DoA) for a microphone array. ### Parameters * **L** (*numpy array*) – Microphone array positions. Each column should correspond to the cartesian coordinates of a single microphone. * **fs** (*float*) – Sampling frequency. * **nfft** (*int*) – FFT length. * **c** (*float*) – Speed of sound. Default: 343 m/s * **num_src** (*int*) – Number of sources to detect. Default: 1 * **mode** (*str*) – ‘far’ or ‘near’ for far-field or near-field detection respectively. Default: ‘far’ * **r** (*numpy array*) – Candidate distances from the origin. Default: np.ones(1) * **azimuth** (*numpy array*) – Candidate azimuth angles (in radians) with respect to x-axis. Default: np.linspace(-180.,180.,30)*np.pi/180 * **colatitude** (*numpy array*) – Candidate elevation angles (in radians) with respect to z-axis. Default is x-y plane search: np.pi/2*np.ones(1) * **frequency_normalization** (*bool*) – If True, the MUSIC pseudo-spectra are normalized before averaging across the frequency axis, default:False ``` -------------------------------- ### Initialize DOA Algorithms Source: https://github.com/lcav/pyroomacoustics/blob/master/notebooks/norm_music_demo.ipynb Initializes the MUSIC and NormMUSIC Direction of Arrival (DOA) algorithms with specified parameters. ```python kwargs = {'L': mic_locs, 'fs': fs, 'nfft': nfft, 'azimuth': np.deg2rad(np.arange(360)) } algorithms = { 'MUSIC': doa.music.MUSIC(**kwargs), 'NormMUSIC': doa.normmusic.NormMUSIC(**kwargs), } columns = ["r", "DOA"] + list(algorithms.keys()) ``` -------------------------------- ### Create Directivity Object Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.room.md Creates a frequency-independent directivity object using the CardioidFamily. This example demonstrates setting a hypercardioid pattern with a specific orientation. ```python # create directivity object from pyroomacoustics.directivities import ( DirectivityPattern, DirectionVector, CardioidFamily, ) dir_obj = CardioidFamily( orientation=DirectionVector(azimuth=90, colatitude=15, degrees=True), pattern_enum=DirectivityPattern.HYPERCARDIOID, ) ``` -------------------------------- ### MeasuredDirectivity Methods Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.md Methods for handling measured directivities, including filtering impulse responses, getting direction vectors, calculating responses, and plotting. ```APIDOC ## MeasuredDirectivity.filter_len_ir() ### Description Filters the impulse response for the measured directivity. ### Method Not specified (assumed to be a method call within a Python class). ### Endpoint N/A ### Parameters None explicitly documented. ### Request Example N/A ### Response Returns the filtered impulse response. ## MeasuredDirectivity.get_direction_vectors() ### Description Retrieves the direction vectors associated with the measured directivity. ### Method Not specified (assumed to be a method call within a Python class). ### Endpoint N/A ### Parameters None explicitly documented. ### Request Example N/A ### Response Returns the direction vectors. ## MeasuredDirectivity.get_response() ### Description Calculates the directivity response from measured data. ### Method Not specified (assumed to be a method call within a Python class). ### Endpoint N/A ### Parameters None explicitly documented. ### Request Example N/A ### Response Returns the directivity response. ## MeasuredDirectivity.get_response_cartesian() ### Description Calculates the directivity response in Cartesian coordinates from measured data. ### Method Not specified (assumed to be a method call within a Python class). ### Endpoint N/A ### Parameters None explicitly documented. ### Request Example N/A ### Response Returns the directivity response in Cartesian coordinates. ## MeasuredDirectivity.is_impulse_response ### Description Checks if the measured directivity is an impulse response. ### Method Not specified (assumed to be a property or method call within a Python class). ### Endpoint N/A ### Parameters None explicitly documented. ### Request Example N/A ### Response Boolean indicating if it's an impulse response. ## MeasuredDirectivity.plot() ### Description Plots the measured directivity. ### Method Not specified (assumed to be a method call within a Python class). ### Endpoint N/A ### Parameters None explicitly documented. ### Request Example N/A ### Response Generates a plot of the measured directivity. ## MeasuredDirectivity.sample_rays() ### Description Samples rays based on the measured directivity pattern. ### Method Not specified (assumed to be a method call within a Python class). ### Endpoint N/A ### Parameters None explicitly documented. ### Request Example N/A ### Response Returns sampled ray information. ## MeasuredDirectivity.set_orientation() ### Description Sets the orientation of the measured directivity. ### Method Not specified (assumed to be a method call within a Python class). ### Endpoint N/A ### Parameters None explicitly documented. ### Request Example N/A ### Response Updates the orientation of the measured directivity. ``` -------------------------------- ### Load and Access SOFA Database Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.directivities.md Instantiate the SOFA database and access its properties like device type and labels. The database is downloaded if not present. ```python db = SOFADatabase() # type of device: 'sources' or 'microphones' db["Soundfield_ST450_CUBE"].type # list of the labels of the sources/microphones db["Soundfield_ST450_CUBE"].contains ``` -------------------------------- ### TOPS Class Initialization Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.doa.tops.md Initializes the TOPS class with microphone array positions, sampling frequency, FFT length, and optional parameters for speed of sound, number of sources, mode, candidate distances, azimuth angles, and colatitude angles. ```APIDOC ## TOPS(L, fs, nfft, c=343.0, num_src=1, mode='far', r=None, azimuth=None, colatitude=None, **kwargs) ### Description Class to apply Test of Orthogonality of Projected Subspaces [[TOPS]](#id2) for Direction of Arrival (DoA) estimation. ### Parameters * **L** (*numpy array*) – Microphone array positions. Each column should correspond to the cartesian coordinates of a single microphone. * **fs** (*float*) – Sampling frequency. * **nfft** (*int*) – FFT length. * **c** (*float*) – Speed of sound. Default: 343 m/s * **num_src** (*int*) – Number of sources to detect. Default: 1 * **mode** (*str*) – ‘far’ or ‘near’ for far-field or near-field detection respectively. Default: ‘far’ * **r** (*numpy array*) – Candidate distances from the origin. Default: np.ones(1) * **azimuth** (*numpy array*) – Candidate azimuth angles (in radians) with respect to x-axis. Default: np.linspace(-180.,180.,30)*np.pi/180 * **colatitude** (*numpy array*) – Candidate elevation angles (in radians) with respect to z-axis. Default is x-y plane search: np.pi/2*np.ones(1) ``` -------------------------------- ### Get Global Delay in RIR Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.room.md Retrieves the global delay introduced by the fractional delay filter used in the simulator. This delay is important for accurate RIR calculations. ```python global_delay = pra.constants.get("frac_delay_length") // 2 ``` -------------------------------- ### Configure and Plot 3D Room with ISM Source: https://github.com/lcav/pyroomacoustics/blob/master/notebooks/pyroomacoustics_demo.ipynb Sets up a 3D room with specific materials and maximum ISM order. It configures ray tracing parameters and adds a source and microphone before computing and visualizing image sources. ```python # specify signal source fs, signal = wavfile.read("arctic_a0010.wav") # set max_order to a low value for a quick (but less accurate) RIR room = pra.Room.from_corners(corners, fs=fs, max_order=3, materials=pra.Material(0.2, 0.15), ray_tracing=True, air_absorption=True) room.extrude(2., materials=pra.Material(0.2, 0.15)) # Set the ray tracing parameters room.set_ray_tracing(receiver_radius=0.5, n_rays=10000, energy_thres=1e-5) # add source and set the signal to WAV file content room.add_source([1., 1., 0.5], signal=signal) # add two-microphone array R = np.array([[3.5, 3.6], [2., 2.], [0.5, 0.5]]) # [[x], [y], [z]] room.add_microphone(R) # compute image sources room.image_source_model() # visualize 3D polyhedron room and image sources fig, ax = room.plot(img_order=3) fig.set_size_inches(18.5, 10.5); ``` -------------------------------- ### pyroomacoustics.adaptive.data_structures.Powers Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.adaptive.data_structures.md This class allows to store all powers of a small number and get them ‘a la numpy’ with the bracket operator, with automatic increase when new values are requested. ```APIDOC ## Class: Powers ### Description This class allows to store all powers of a small number and get them ‘a la numpy’ with the bracket operator. There is automatic increase when new values are requested. ### Parameters * **a** (float) - the number * **length** (int) - the number of integer powers * **dtype** (numpy.type, optional) - the data type (typically np.float32 or np.float64) ### Example ```python >>> an = Powers(0.5) >>> print(an[4]) 0.0625 ``` ``` -------------------------------- ### pyroomacoustics.room.Room Constructor Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.room.md Initializes a Room object, defining the acoustic environment. It takes parameters for walls, sampling frequency, maximum reflection order, and optional settings for noise, sources, microphones, and simulation behavior. ```APIDOC ## Class: pyroomacoustics.room.Room ### Description A Room object represents the acoustic environment, defined by walls, sound sources, and microphones. It can be configured for 2D or 3D simulations with various parameters affecting sound propagation and simulation methods. ### Parameters * **walls** (*list* *of* *Wall* *or* *Wall2D objects*) – The walls forming the room. * **fs** (*int* *,* *optional*) – The sampling frequency in Hz. Default is 8000. * **t0** (*float* *,* *optional*) – The global starting time of the simulation in seconds. Default is 0. * **max_order** (*int* *,* *optional*) – The maximum reflection order in the image source model. Default is 1. * **sigma2_awgn** (*float* *,* *optional*) – The variance of the additive white Gaussian noise added during simulation. By default, none is added. * **sources** (*list* *of* *SoundSource objects* *,* *optional*) – Sources to place in the room. * **mics** (*MicrophoneArray object* *,* *optional*) – The microphone array to place in the room. * **temperature** (*float* *,* *optional*) – The air temperature in the room in degree Celsius. Default is set so that speed of sound is 343 m/s. * **humidity** (*float* *,* *optional*) – The relative humidity of the air in the room (between 0 and 100). Default is 0. * **air_absorption** (*bool* *,* *optional*) – If True, absorption of sound energy by the air will be simulated. * **ray_tracing** (*bool* *,* *optional*) – If True, the ray tracing simulator will be used along with image source model. * **use_rand_ism** (*bool* *,* *optional*) – If True, image source positions will have a small random displacement. * **max_rand_disp** (*float* *,* *optional*) – If using randomized image source method, the maximum displacement of the image sources. * **min_phase** (*bool* *,* *optional*) – If True, generated RIRs will have a minimum phase response. Cannot be used with ray tracing model. ``` -------------------------------- ### pyroomacoustics.directivities.direction.DirectionVector Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.directivities.md Represents direction vectors in 3D space using azimuth and colatitude angles. It can store directions in degrees or radians and provides a property to get the direction as a unit vector in Cartesian coordinates. ```APIDOC ## Class: pyroomacoustics.directivities.direction.DirectionVector ### Description Object for representing direction vectors in 3D, parameterized by an azimuth and colatitude angle. ### Parameters * **azimuth** (*float*) - The azimuth angle. * **colatitude** (*float*, optional) - The colatitude angle. Defaults to PI / 2 (only XY plane). * **degrees** (*bool*, optional) - Whether provided values are in degrees (True) or radians (False). Defaults to True. ### Properties #### unit_vector * **Description**: Direction vector in cartesian coordinates. * **Returns**: Direction vector as a numpy array. ``` -------------------------------- ### Load and display an audio file Source: https://github.com/lcav/pyroomacoustics/blob/master/notebooks/rir_demo.ipynb Reads an audio file and displays it for playback. Ensure the audio file 'arctic_a0010.wav' is in the same directory. ```python fs, audio_anechoic = wavfile.read('arctic_a0010.wav') IPython.display.display(IPython.display.Audio(audio_anechoic, rate=fs)) ``` -------------------------------- ### Build Docker container for pyroomacoustics Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/index.md Build a Docker image tagged as 'pyroom_container' from the provided Dockerfile. Ensure your Docker daemon has at least 4GB of memory allocated for building C++ extensions. ```default docker build -t pyroom_container . ``` -------------------------------- ### CircularGaussianEmission Class Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.recognition.md Represents a Circular Gaussian emission model for HMMs. It includes methods to get probability density functions (PDFs), recompute probabilities given observations, and update model parameters. ```APIDOC ## Class: CircularGaussianEmission ### Description Represents a Circular Gaussian emission model for HMMs. ### Methods #### get_pdfs() Return the pdf of all the emission probabilities. #### prob_x_given_state(examples) Recompute the probability of the observation given the state of the latent variables. #### update_parameters(examples, gamma) Update the parameters of the emission model. ``` -------------------------------- ### Circular Microphone Array in 3D Source: https://github.com/lcav/pyroomacoustics/blob/master/notebooks/rir_directivities_demo.ipynb Utilizes `circular_microphone_array_xyplane` to create a circular microphone array in the XY plane. This function simplifies the setup for circular configurations and allows specifying directivity for all microphones in the array. ```python mic_rotation = 0 room_dim = [7, 7, 5] source_loc = [5, 2.5, 4] center = [3, 3, 2] colatitude = 90 # make a room room = pra.ShoeBox(p=room_dim) # add source room.add_source(source_loc) # add circular microphone array pattern = DirectivityPattern.CARDIOID orientation = DirectionVector(azimuth=mic_rotation, colatitude=colatitude, degrees=True) directivity = CardioidFamily(orientation=orientation, pattern_enum=pattern) mic_array = pra.beamforming.circular_microphone_array_xyplane( center=center, M=7, phi0=mic_rotation, radius=50e-2, fs=room.fs, directivity=directivity, ) room.add_microphone_array(mic_array) # plot everything fig, ax = room.plot() ax.set_xlim([-1, 8]) ax.set_ylim([-1, 8]) ax.set_zlim([-1, 6]); ``` -------------------------------- ### pyroomacoustics.acoustics.octave_bands Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.acoustics.md Generates a bank of octave bands, which can be used for frequency analysis. This function allows customization of the center frequency, whether to use third octave bands, the starting frequency, and the number of bands. ```APIDOC ## pyroomacoustics.acoustics.octave_bands(fc=1000, third=False, start=0.0, n=8) ### Description Create a bank of octave bands. ### Parameters - **fc** (float, optional) – The center frequency (default 1000) - **third** (bool, optional) – Use third octave bands (default False) - **start** (float, optional) – Starting frequency for octave bands in Hz (default 0.) - **n** (int, optional) – Number of frequency bands (default 8) ``` -------------------------------- ### Import necessary libraries and load audio Source: https://github.com/lcav/pyroomacoustics/blob/master/notebooks/rir_directivities_demo.ipynb Imports required libraries for pyroomacoustics, plotting, and audio handling. Loads an audio file and normalizes it. ```python import numpy as np import matplotlib.pyplot as plt import pyroomacoustics as pra from pyroomacoustics import dB from pyroomacoustics.directivities import ( DirectivityPattern, DirectionVector, CardioidFamily, ) from pyroomacoustics.doa import spher2cart from scipy.io import wavfile import IPython fs, signal = wavfile.read("arctic_a0010.wav") signal = signal / np.max(np.abs(signal)) # so that simulation is within [-1, 1] for normalize=False ``` -------------------------------- ### Capture RIR with Real Spherical Harmonics Directivities Source: https://github.com/lcav/pyroomacoustics/blob/master/docs/pyroomacoustics.directivities.md Example of capturing room impulse response using real spherical harmonics directivities, treating each harmonic as a separate microphone. Requires pyroomacoustics and numpy. ```python # Simple example recording the different Harmonics as different microphones. order = 2 azimuth = np.deg2rad(50) room = pra.AnechoicRoom(fs=16000) room.add_source([np.cos(azimuth), np.sin(azimuth), 1.0]) for m, n in zip(*get_mn_in_acn_order(order)): room.add_microphone( [0.0, 0.0, 1.0], directivity=pra.directivities.RealSphericalHarmonicsDirectivity( m, n), ) room.compute_rir() ```