Ejemplo n.º 1
0
def main():
    # define room
    room_material = pra.Material(energy_absorption=0.1, scattering=None)
    room_dim = [17, 6, 6]
    room = pra.ShoeBox(room_dim, fs=16000, materials=room_material)

    # define pipe
    pipe_center = np.array(room_dim) / 2
    pipe_faces = pra_utils.make_polygon(pipe_center, 1, 15, 4, [0, 1.57, 0])
    pipe_material = pra.Material(energy_absorption=0.2, scattering=0.1)

    pra_utils.add_obstacle(room, pipe_faces, pipe_material)

    # define mics and sources
    room.add_source([5, 3, 3])
    room.add_microphone([5.05, 3, 3.])

    room.image_source_model()

    room.plot(img_order=1)
    plt.gca().set_xlim3d(left=-1, right=18)
    plt.gca().set_ylim3d(bottom=-1, top=18)
    plt.gca().set_zlim3d(bottom=-1, top=18)
    plt.show()

    room.compute_rir()
    room.plot_rir()
    plt.show()
Ejemplo n.º 2
0
def main():
    # define room
    room_material = pra.Material(energy_absorption=0.96, scattering=None)
    room_dim = [10, 10, 5]
    room = pra.ShoeBox(room_dim,
                       fs=16000,
                       materials=room_material,
                       max_order=4,
                       ray_tracing=True,
                       air_absorption=True)

    # define obstacle
    obstacle_faces = make_polygon([3, 3, 2.5], 1, 4, 4, [0, 0, 0.78])
    obstacle_material = pra.Material(energy_absorption=0.2, scattering=0.1)

    add_obstacle(room, obstacle_faces, obstacle_material)

    obstacle_faces = make_cylinder([6, 4, 2.5], 1.4, 5, [1.57, 0, 0])
    add_obstacle(room, obstacle_faces, obstacle_material)
    # define mics and sources
    room.add_source([1.7, 3, 1.])
    room.add_microphone([1.7, 3, 1.1])

    room.image_source_model()

    room.plot(img_order=1)
    plt.gca().set_xlim3d(left=-2, right=11)
    plt.gca().set_ylim3d(bottom=-2, top=11)
    plt.gca().set_zlim3d(bottom=-2, top=11)
    plt.show()

    room.compute_rir()
    room.plot_rir()
    plt.show()
Ejemplo n.º 3
0
def empty_diff_walls():
    """Returns empty room with walls of different materials"""
    # 4 side walls are absorptive
    room_materials = [pra.Material(energy_absorption=0.1, scattering=None)] * 4
    # floor and ceiling are reflective
    room_materials.extend(
        [pra.Material(energy_absorption=0.98, scattering=None)] * 2)

    room_faces = make_polygon(centre=[0, 0, 2.5],
                              radius=10,
                              height=5,
                              N=4,
                              rpy=[0, 0, np.pi / 4])

    # create room
    walls = []
    walls.extend(create_walls(room_faces, room_materials))

    room = pra.Room(walls,
                    fs=fs,
                    max_order=3,
                    ray_tracing=False,
                    air_absorption=False)

    room.add_source([-5, 2, 2.])
    room.add_microphone([1, 0, 2.])

    # compute rir
    room.image_source_model()
    room.compute_rir()

    return room
Ejemplo n.º 4
0
def simulateSound(room_dim, R_loc, source_locations, source_audios, rt60, materials=None, max_order=None):
    # source_audios: array of numpy array
    # L: max of all audios. Zero padding at the end
    # return (all_channel_data (C, L), groundtruth_with_reverb (N, C, L), groundtruth_data (N, C, L), angles (N)

    if materials is not None:
        (ceiling, east, west, north, south, floor) = materials
        room = pra.ShoeBox(
            room_dim,
            fs=fs,
            materials=pra.make_materials(
                ceiling=ceiling,
                floor=floor,
                east=east,
                west=west,
                north=north,
                south=south,
            ), max_order=max_order
        )
    else:
        try:
            e_absorption, max_order_rt60 = pra.inverse_sabine(rt60, room_dim)
        except ValueError:
            e_absorption, max_order_rt60 = pra.inverse_sabine(1, room_dim)
        room = pra.ShoeBox(room_dim, fs=fs, materials=pra.Material(e_absorption), max_order=max_order_rt60)

    R = generate_mic_array(R_MIC, N_MIC, R_loc)
    room.add_microphone_array(pra.MicrophoneArray(R, room.fs))

    length = max([len(source_audios[i]) for i in range(len(source_audios))])
    for i in range(len(source_audios)):
        source_audios[i] = np.pad(source_audios[i], (0, length - len(source_audios[i])), 'constant')

    for i in range(len(source_locations)):
        room.add_source(source_locations[i], signal=source_audios[i], delay=0)

    room.image_source_model()
    premix_w_reverb = room.simulate(return_premix=True)
    mixed = room.mic_array.signals

    # groundtruth
    room_gt = pra.ShoeBox(room_dim, fs=fs, materials=pra.Material(1.0), max_order=0)
    # R_gt=generate_mic_array(R_MIC, N_MIC, R_loc)
    R_gt = generate_mic_array(0, 1, R_loc)
    room_gt.add_microphone_array(pra.MicrophoneArray(R_gt, room.fs))

    for i in range(len(source_locations)):
        room_gt.add_source(source_locations[i], signal=source_audios[i], delay=0)
    room_gt.compute_rir()

    room_gt.image_source_model()
    premix = room_gt.simulate(return_premix=True)

    return (mixed, premix_w_reverb, premix, R)
Ejemplo n.º 5
0
def test_issue_22():

    np.random.seed(0)

    n_mics = 1
    n_src = 1
    n_times = 25000
    dim = 3
    mic_pos = np.random.rand(dim, n_mics)
    abs_coeff = 0.1
    e_abs = 1.0 - (1.0 - abs_coeff) ** 2
    fs = 16000
    wall_max_len = 15

    room_dim = np.random.rand(dim) * wall_max_len

    shoebox = pyroomacoustics.ShoeBox(
        room_dim,
        materials=pyroomacoustics.Material(e_abs),
        fs=fs,
        max_order=0,
    )

    src_pos = np.random.rand(dim, n_src) * room_dim[:, None]
    for src in src_pos.T:
        shoebox.add_source(src)

    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:
            print(i)
Ejemplo n.º 6
0
def simulateBackground(background_audio):
    # diffused noise. simulate in a large room
    bg_radius = np.random.uniform(low=10.0, high=20.0)
    bg_theta = np.random.uniform(low=0, high=2 * np.pi)
    H = 10
    bg_loc = [bg_radius * np.cos(bg_theta), bg_radius * np.sin(bg_theta), H]

    # Bg should be further away to be diffuse
    left_wall = np.random.uniform(low=-40, high=-20)
    right_wall = np.random.uniform(low=20, high=40)
    top_wall = np.random.uniform(low=20, high=40)
    bottom_wall = np.random.uniform(low=-40, high=-20)
    height = np.random.uniform(low=20, high=40)
    corners = np.array([[left_wall, bottom_wall], [left_wall, top_wall],
                        [right_wall, top_wall], [right_wall, bottom_wall]]).T
    absorption = np.random.uniform(low=0.5, high=0.99)
    room = pra.Room.from_corners(corners,
                                 fs=fs,
                                 max_order=10,
                                 materials=pra.Material(absorption))
    room.extrude(height)
    mic_array = generate_mic_array(R_MIC, N_MIC, (0, 0, H))
    room.add_microphone_array(pra.MicrophoneArray(mic_array, fs))
    room.add_source(bg_loc, signal=background_audio)

    room.image_source_model()
    room.simulate()
    return room.mic_array.signals
Ejemplo n.º 7
0
def empty_room():
    """returns an empty cuboidal room with source and mic somewhat in center"""
    room_material = pra.Material(energy_absorption=0.6, scattering=None)
    room_faces = make_polygon(centre=[0, 0, 2.5],
                              radius=10,
                              height=5,
                              N=4,
                              rpy=[0, 0, np.pi / 4])

    # create room
    walls = []
    walls.extend(create_walls(room_faces, room_material))

    room = pra.Room(walls,
                    fs=fs,
                    max_order=3,
                    ray_tracing=True,
                    air_absorption=False)

    room.add_source([0, 0, 2.])
    room.add_microphone([0, 0.2, 2.1])

    # compute rir
    room.image_source_model()
    room.ray_tracing()
    room.compute_rir()

    return room
Ejemplo n.º 8
0
def test_issue_115_rt_breaking():
    """
    As background, only ray tracing only starts to be active for rays that run
    longer than the maximum ISM order.
    The problem happen when the ISM order is very high (here 17),
    then, in some circumstances, it is possible that no ray travels longer
    than that. Then the histogram is empty and an error happen.
    """
    print("Test with high order ISM")
    shoebox = pra.ShoeBox(
        [4.232053263716528, 3.9244954007318853, 5.563810437305445],
        materials=pra.Material(energy_absorption=0.6965517438548237),
        fs=16000,
        max_order=17,
        ray_tracing=True,
    )
    source_loc = [1.2028020579854695, 2.2980760894630676, 2.0654520390433984]
    shoebox.add_source(source_loc)
    R = np.array([[1.8062807887952617], [2.7793113278109454], [1.42966428606882]])
    print(
        "mic - source distance : {} m".format(
            np.sqrt(sum((np.array(source_loc) - np.squeeze(R)) ** 2))
        )
    )
    shoebox.add_microphone_array(pra.MicrophoneArray(R, shoebox.fs))
    shoebox.compute_rir()
Ejemplo n.º 9
0
def get_rir(audio_signal,
            fs,
            rt60=0.2,
            room_dim=[60, 60, 10],
            room_source=[30, 30, 4.5],
            mic_pos=[30, 10, 7],
            T=19,
            D=0.01,
            S=35):
    import pyroomacoustics as pra
    import numpy as np
    c = 1449.2 + 4.6 * T - 0.055 * T**2 + 0.0029 * T**3 + (1.34 - 0.01 * T) * (
        S - 35) + 0.016 * D
    e_absorption, max_order = pra.inverse_sabine(rt60, room_dim, c=c)
    room = pra.ShoeBox(room_dim,
                       fs=fs,
                       materials=pra.Material(e_absorption),
                       ray_tracing=False,
                       max_order=3,
                       air_absorption=False)
    room.add_source(room_source, signal=audio_signal, delay=1.0)
    mic_locs = np.c_[mic_pos,  # mic 1
                     ]
    room.add_microphone_array(mic_locs)
    room.compute_rir()
    rir = room.rir[0][0]
    return rir
Ejemplo n.º 10
0
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"])
    room = pra.Room.from_corners(pol,
                                 fs=16000,
                                 max_order=2,
                                 materials=mat,
                                 ray_tracing=True)

    # Create the 3D room by extruding the 2D by a specific height
    room.extrude(size_opts[size]["mult"] * 2.5, materials=mat)

    # set the ray tracing parameters
    room.set_ray_tracing(
        receiver_radius=size_opts[size]["receiver_radius"])  # , n_rays=100000)

    # Adding the source
    room.add_source(size_opts[size]["mult"] * np.array([1.8, 0.4, 1.6]),
                    signal=audio_anechoic)

    # Adding the microphone
    R = size_opts[size]["mult"] * np.array([[0.5], [1.2], [0.5]])
    room.add_microphone_array(pra.MicrophoneArray(R, room.fs))

    # Compute the RIR using the hybrid method
    s = time.perf_counter()
    room.compute_rir()
    print("Computation time:", time.perf_counter() - s)

    return room.rir[0][0], room
Ejemplo n.º 11
0
def test_issue_115_ism_breaking():
    """
    When a source was too close to the microphone, the time-of-flight
    might be smaller than the delay due to the fractionnal delay filter
    used to create the impulse response.
    It is then necessary to add this delay to the rir filter to ensure
    no runtime error.
    """
    print("Test with source close to microphone.")
    shoebox = pra.ShoeBox(
        [9.29447785567344, 6.529510207957697, 4.4677460263160995],
        materials=pra.Material(energy_absorption=0.1675976883006225),
        fs=16000,
        max_order=17,
    )
    source_loc = [5.167674641605016, 4.379726875714017, 2.9190423403507504]
    shoebox.add_source(source_loc)
    noise_loc = [8.47420884677372, 5.675261722911696, 1.2040578622058364]
    shoebox.add_source(noise_loc)
    R = np.array([[8.571318246865648], [5.799718630723678], [1.3702254938278977]])
    print(
        "mic - source distance : {} m".format(
            np.sqrt(sum((np.array(source_loc) - np.squeeze(R)) ** 2))
        )
    )
    print(
        "mic - noise distance : {} m".format(
            np.sqrt(sum((np.array(noise_loc) - np.squeeze(R)) ** 2))
        )
    )
    shoebox.add_microphone_array(pra.MicrophoneArray(R, shoebox.fs))
    shoebox.compute_rir()
Ejemplo n.º 12
0
def simroom(room_dim, src_loc, mic_locs):

    parser = argparse.ArgumentParser(
        description=
        "Simulates and adds reverberation to a dry sound sample. Saves it into `./examples/samples`."
    )
    parser.add_argument(
        "--method",
        "-m",
        choices=methods,
        default=methods[0],
        help="Simulation method to use",
    )
    args = parser.parse_args()

    # The desired reverberation time and dimensions of the room
    rt60_tgt = 0.3  # seconds
    # 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)

    room.add_source(src_loc, signal=audio, delay=0.5)

    # 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(
        "examples/samples/guitar_16k_reverb_{}.wav".format(args.method),
        norm=True,
        bitdepth=np.int16,
    )
    """
    detect_peaks(room.mic_array.signals[0, :], mph=0, mpd=1000, threshold=10, show=True)
    detect_peaks(room.mic_array.signals[1, :], mph=0, mpd=1000, threshold=10, show=True)
    detect_peaks(room.mic_array.signals[2, :], mph=0, mpd=1000, threshold=10, show=True)

    print(max(room.mic_array.signals[0, :]))
    print(max(room.mic_array.signals[1, :]))
    print(max(room.mic_array.signals[2, :]))
    """
    return np.array([
        max(room.mic_array.signals[0, :]),
        max(room.mic_array.signals[1, :]),
        max(room.mic_array.signals[2, :])
    ])
Ejemplo n.º 13
0
def test_room_volume():

    eps = 0.00001

    # Create the 2D L-shaped room from the floor polygon
    pol = 4 * np.array([[0, 0], [0, 1], [2, 1], [2, 0.5], [1, 0.5], [1, 0]]).T
    r_absor = 0.1
    e_abs = 1.0 - (1.0 - r_absor)**2
    room = pra.Room.from_corners(pol,
                                 fs=16000,
                                 max_order=6,
                                 materials=pra.Material(e_abs))

    # Create the 3D room by extruding the 2D by 3 meters
    room.extrude(3.0, materials=pra.Material(e_abs))

    assert np.allclose(room.get_volume(), 72, atol=eps)
Ejemplo n.º 14
0
def test_rt60_theory_multi_band():

    # Create the room
    room = pra.ShoeBox(room_dim, fs=fs, materials=pra.Material("curtains_cotton_0.5"),)

    # run the different rt60 functions
    room.rt60_theory(formula="sabine")
    room.rt60_theory(formula="eyring")
Ejemplo n.º 15
0
def augment_room(y, scale=1.0):
    corners = np.array([[0, 0], [0, 5 * scale], [3 * scale, 5 * scale],
                        [3 * scale, 0]]).T
    room = pra.Room.from_corners(
        corners,
        fs=sr,
        materials=pra.Material(0.2, 0.15),
        ray_tracing=True,
        air_absorption=True,
    )
    room.extrude(2.0, materials=pra.Material(0.2, 0.15))
    room.set_ray_tracing(receiver_radius=0.5, n_rays=10000, energy_thres=1e-5)
    room.add_source([1.5 * scale, 4 * scale, 0.5], signal=y)
    R = np.array([[1.5 * scale], [0.5 * scale], [0.5]])
    room.add_microphone(R)
    room.simulate()
    return room.mic_array.signals[0]
Ejemplo n.º 16
0
def empty_room(outpath):
    room = pra.ShoeBox([2.5, 3, 4],
                       materials=pra.Material(0.2, 0.34),
                       air_absorption=True)

    # pretty print room dict
    pprint(create_room_dict(room), sort_dicts=False)

    # dump room into a yaml
    dump_room(room, outpath)
Ejemplo n.º 17
0
def room_simulate(num_mic, mic_array, room_type):
    room_list = {
        'star_3': [8.3, 3.4, 2.5],
        'room_819': [7.9, 7.0, 2.7],
        'room_409': [7.0, 4.2, 2.7]
    }
    room = room_list[room_type]
    dim_x, dim_y, dim_z = room[0], room[1], room[2]
    sr = 16000
    rt60 = 0.3
    e_absorption, max_order = pra.inverse_sabine(rt60, [dim_x, dim_y, dim_z])
    print(e_absorption, max_order)
    num_direction = 12
    mic_radius = 0.04  #0.03231 testing
    #mic_radius =  np.random.uniform(low=0.025,high=0.035)
    mic_x_radius = 0.0637
    mic_y_radius = 0.0484
    mic_lin = 0.04

    room = pra.ShoeBox(room,
                       fs=sr,
                       materials=pra.Material(e_absorption),
                       max_order=max_order)

    mic_center = np.array([dim_x / 2, dim_y / 2, 0.69])
    thetas = np.arange(num_mic) / num_mic * 2 * np.pi
    theta_source = np.arange(num_direction) / num_direction * 2 * np.pi
    if mic_array == 'circle':
        center_to_mic = np.stack(
            [np.cos(thetas),
             np.sin(thetas),
             np.zeros_like(thetas)], 0) * mic_radius
    elif mic_array == 'ellipse':
        center_to_mic = np.stack([
            mic_x_radius * np.cos(thetas), mic_y_radius * np.sin(thetas),
            np.zeros_like(thetas)
        ], 0)
    elif mic_array == 'linear':
        linear = np.arange(num_mic) * mic_lin
        linear = linear - np.max(linear) / 2
        center_to_mic = np.stack(
            [linear, np.zeros_like(linear),
             np.zeros_like(linear)], 0)
    mic_positions = mic_center[:, None] + center_to_mic
    room.add_microphone_array(mic_positions)
    far_field_distance = 1
    thetas = np.arange(num_direction) / num_direction * 2 * np.pi
    center_to_source = np.stack([
        np.cos(theta_source),
        np.sin(theta_source),
        np.zeros_like(theta_source)
    ], -1) * far_field_distance
    source_positions = mic_center[None, :] + center_to_source

    return room, source_positions
Ejemplo n.º 18
0
def get_room_add_method():
    shoebox = pra.ShoeBox(
        room_dim, materials=pra.Material(e_abs), fs=fs, max_order=max_order
    )
    shoebox.add_source(source_position)
    mics = pra.MicrophoneArray(np.array([mic_position]).T, fs)
    shoebox.add_microphone_array(mics)

    shoebox.image_source_model()
    shoebox.compute_rir()
    return shoebox
Ejemplo n.º 19
0
def make_room(room_size,
              source_location,
              mic_array_location,
              rt60,
              sample_rate=16000):
    e_absorption, max_order = pra.inverse_sabine(rt60, room_size)
    r = pra.ShoeBox(room_size,
                    fs=sample_rate,
                    materials=pra.Material(e_absorption),
                    max_order=max_order)
    r.add_microphone_array(mic_array_location)
    r.add_source(source_location)
    return r
Ejemplo n.º 20
0
def compute_rir(order):
    fromPos = np.zeros((3))
    toPos = np.ones((3, 1))
    roomSize = np.array([3, 3, 3])
    e_abs = 1.0 - (1.0 - 0.95)**2
    room = pra.ShoeBox(roomSize,
                       fs=1000,
                       materials=pra.Material(e_abs),
                       max_order=order)
    room.add_source(fromPos)
    mics = pra.MicrophoneArray(toPos, room.fs)
    room.add_microphone_array(mics)
    room.compute_rir()
Ejemplo n.º 21
0
def test_walls_area():
    eps = 0.00001

    # Create the 2D L-shaped room from the floor polygon
    pol = 4 * np.array([[0, 0], [0, 1], [2, 1], [2, 0.5], [1, 0.5], [1, 0]]).T
    r_absor = 0.1
    e_abs = 1.0 - (1.0 - r_absor)**2
    room = pra.Room.from_corners(pol,
                                 fs=16000,
                                 max_order=6,
                                 materials=pra.Material(e_abs))

    # Create the 3D room by extruding the 2D by 3 meters
    room.extrude(3.0, materials=pra.Material(e_abs))

    assert np.allclose(room.wall_area(room.walls[0]), 6, atol=eps)
    assert np.allclose(room.wall_area(room.walls[1]), 12, atol=eps)
    assert np.allclose(room.wall_area(room.walls[2]), 6, atol=eps)
    assert np.allclose(room.wall_area(room.walls[3]), 24, atol=eps)
    assert np.allclose(room.wall_area(room.walls[4]), 12, atol=eps)
    assert np.allclose(room.wall_area(room.walls[5]), 12, atol=eps)
    assert np.allclose(room.wall_area(room.walls[6]), 24, atol=eps)
    assert np.allclose(room.wall_area(room.walls[7]), 24, atol=eps)
Ejemplo n.º 22
0
def room_with_box():
    """Returns cuboidal room with box"""
    room_material = pra.Material(energy_absorption=0.6, scattering=None)
    room_faces = make_polygon(centre=[0, 0, 2.5],
                              radius=10,
                              height=5,
                              N=4,
                              rpy=[0, 0, np.pi / 4])

    # define obstacle
    obstacle_faces = make_polygon(centre=[2.5, 0, 2.5],
                                  radius=1.8,
                                  height=3,
                                  N=4,
                                  rpy=[0, 0, np.pi / 4],
                                  reverse_normals=True)
    obstacle_material = pra.Material(energy_absorption=0.1, scattering=0.1)

    # create room
    walls = []
    walls.extend(create_walls(room_faces, room_material))
    walls.extend(create_walls(obstacle_faces, obstacle_material))

    room = pra.Room(walls,
                    fs=fs,
                    max_order=3,
                    ray_tracing=False,
                    air_absorption=False)

    room.add_source([0, 0, 2.])
    room.add_microphone([0, 0.2, 2.1])

    # compute rir
    room.image_source_model()
    room.compute_rir()

    return room
Ejemplo n.º 23
0
def test_ism():

    room = pra.ShoeBox(room_size, fs, materials=pra.Material(0.1), max_order=50)

    room.add_source(source_loc)

    room.add_microphone(mic_loc)

    room.compute_rir()

    ssf_ism = met.sweeping_echo_measure(room.rir[0][0], fs)

    assert 0 <= ssf_ism <= 1.0

    return ssf_ism
Ejemplo n.º 24
0
def test_rt60_measure():

    # Create the room
    room = pra.ShoeBox(
        room_dim, fs=fs, materials=pra.Material("curtains_cotton_0.5"), max_order=10,
    )

    # place the source in the room
    room.add_source([2.5, 3.73, 1.76])

    # place a microphone in the room
    room.add_microphone([6.3, 4.87, 1.2])

    room.compute_rir()

    room.measure_rt60()
Ejemplo n.º 25
0
def func(cat1, cat2, cat2fn):
    rt60_tgt = 0.3  # seconds
    room_dim = [10, 10, 3]  # meters

    # We invert Sabine's formula to obtain the parameters for the ISM simulator
    e_absorption, max_order = pra.inverse_sabine(rt60_tgt, room_dim)

    # microphone locations
    mic_locs = np.c_[[4.9, 4, 1], [5.1, 4.1, 1], [5.1, 3.9, 1], [5, 4, 1.2],
                     [5, 4, 0.8], [4.9, 3.9, 1.2], [5.1, 4.1, 0.8]]

    for i in range(100):
        rand1 = np.random.randint(0, len(cat2fn[cat1]))
        rand2 = np.random.randint(0, len(cat2fn[cat2]))
        fn1 = cat2fn[cat1][rand1]
        fn2 = cat2fn[cat2][rand2]

        fs, audio1 = wavfile.read("inputs/ESC-50-master/audio/" + fn1)
        fs, audio2 = wavfile.read("inputs/ESC-50-master/audio/" + fn2)

        min_len = min(audio1.shape[0], audio2.shape[0])

        audio1 = audio1[:min_len]
        audio2 = audio2[:min_len]

        for i in range(5):
            room = pra.ShoeBox(room_dim,
                               fs=fs,
                               materials=pra.Material(e_absorption),
                               max_order=max_order)
            values = np.random.random(6) * 2.0 - 1.0
            loc1 = [values[0] + 5, values[1] + 5, values[2] + 1.5]
            loc2 = [values[3] + 5, values[4] + 5, values[5] + 1.5]

            room.add_source(loc1, signal=audio1, delay=0.)
            room.add_source(loc2, signal=audio2, delay=0.)
            room.add_microphone_array(mic_locs)
            room.simulate()

            filename = fn1 + " " + fn2 + " " + str(loc1) + str(loc2) + ".wav"
            room.mic_array.to_wav(
                f"outputs/combined/" + filename,
                norm=True,
                bitdepth=np.int16,
            )
Ejemplo n.º 26
0
def test_rt60_theory_single_band():

    # The desired reverberation time and dimensions of the room
    rt60_tgt = 0.3  # seconds

    # 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
    )

    rt60_sabine = pra.rt60_sabine(S, V, e_absorption, 0.0, room.c)
    assert (rt60_sabine - room.rt60_theory(formula="sabine")) < eps

    rt60_eyring = pra.rt60_eyring(S, V, e_absorption, 0.0, room.c)
    assert (rt60_eyring - room.rt60_theory(formula="eyring")) < eps
Ejemplo n.º 27
0
def random_room_ism(max_order=10, eps=1e-6, verbose=False):
    """
    Create a random shoebox room and compute the difference
    """

    # locations of stuff
    room_dim = np.random.randint(1, 101, size=3)
    src_loc = np.random.rand(3) * room_dim
    mic_loc = np.random.rand(3) * room_dim
    # too close is not good
    while np.linalg.norm(mic_loc - src_loc) < 0.05:
        mic_loc = np.random.rand(3) * room_dim

    # random list of materials
    materials = dict(
        zip(
            ["north", "south", "west", "east", "ceiling", "floor"],
            [pra.Material(x) for x in np.random.rand(6)],
        ))

    # shoebox room: working correctly
    room = pra.ShoeBox(room_dim, max_order=max_order, materials=materials)
    # general room: not working
    room2 = pra.Room(room.walls, max_order=max_order)

    room.add_source(src_loc)
    room2.add_source(src_loc)

    room.add_microphone(mic_loc)
    room2.add_microphone(mic_loc)

    room.image_source_model()
    room2.image_source_model()

    trans_shoebox = np.sort(room.sources[0].damping)
    trans_general = np.sort(room2.sources[0].damping)

    error = np.linalg.norm(trans_general - trans_shoebox)

    if verbose:
        print("error", np.linalg.norm(trans_shoebox - trans_general))

    assert error < eps
Ejemplo n.º 28
0
def get_room_constructor_args():
    """
    When provided with sources and microphones, the constructor
    should try to compute the RIR immediately
    """
    source = pra.SoundSource(position=source_position)
    mics = pra.MicrophoneArray(np.array([mic_position]).T, fs)
    shoebox = pra.ShoeBox(
        room_dim,
        materials=pra.Material(e_abs),
        fs=fs,
        max_order=max_order,
        sources=[source],
        mics=mics,
    )

    shoebox.image_source_model()
    shoebox.compute_rir()
    return shoebox
Ejemplo n.º 29
0
def test_random_ism():

    room = pra.ShoeBox(
        room_size, fs, materials=pra.Material(0.1), max_order=50, use_rand_ism=True
    )

    room.add_source(source_loc)

    room.add_microphone(mic_loc)

    room.compute_rir()

    # measure of spectral flatness of sweeping echoes
    # higher value is desired
    ssf_rism = met.sweeping_echo_measure(room.rir[0][0], fs)

    assert 0 <= ssf_rism <= 1.0

    return ssf_rism
Ejemplo n.º 30
0
def main():
    # create anechoic room
    wall_material = pra.Material(energy_absorption=0.1, scattering=None)
    room_dim = [10, 10, 5]
    room = pra.ShoeBox(
        room_dim,
        fs=16000,
        materials=wall_material,
        max_order=3,
        ray_tracing=True,
        air_absorption=True,
    )
    print('Created room.')

    # TODO: add polygonal objects

    # prepare waveform
    num_cycles = 8
    sig_freq = 500
    waveform = square_wave(sig_freq,
                           amp=10000,
                           fs=16000,
                           len=num_cycles / sig_freq)
    # plt.plot(waveform)

    # add sources and mics
    zh = 2
    source_coord = [3, 3, zh]
    mic_locs = np.c_[[5.0, 5.0, zh], [5.3, 5.0, zh]]
    room.add_source(source_coord, signal=waveform)
    room.add_microphone_array(mic_locs)
    print('Added source and mics.')

    # visualise room
    room.plot()
    plt.show()

    # Simulated RIRs
    room.compute_rir()
    room.plot_rir()
    plt.show()

    print('Done, exiting...')