Exemple #1
0
def compute_array(meshpath, src_coord, lis_coord, r, s, micarray):
    mesh = ps.loadobj(meshpath, os.path.join(os.path.dirname(meshpath), ''), r, s)
    ctx = ps.Context()
    ctx.diffuse_count = 20000
    ctx.specular_count = 2000
    ctx.channel_type = ps.ChannelLayoutType.mono
    scene = ps.Scene()
    scene.setMesh(mesh)

    src = ps.Source(src_coord)
    src.radius = 0.01

    res = {}
    res_buffer = []
    rate = 0
    abandon_flag = False
    for offset in micarray:
        lis = ps.Listener((offset + lis_coord).tolist())
        lis.radius = 0.01

        res_ch = scene.computeIR(src, lis, ctx)
        rate = res_ch['rate']
        sa = res_ch['samples']
        res['rate'] = rate
        res_buffer.append(sa)
    res['samples'] = np.zeros((len(res_buffer), np.max([len(ps) for ps in res_buffer])))
    for i, c in enumerate(res_buffer):
        res['samples'][i, :len(c)] = c
    return res
Exemple #2
0
def compute_scene_ir_absorb(roomdim, tasks, r):
    # Initialize scene mesh
    try:
        mesh = ps.createbox(roomdim[0], roomdim[1], roomdim[2], r, 0.5)
    except Exception as e:
        print(str(e))

    ctx = ps.Context()
    ctx.diffuse_count = 2000
    ctx.specular_count = 2000
    ctx.threads_count = min(multiprocessing.cpu_count(), 8)

    scene = ps.Scene()
    scene.setMesh(mesh)

    channel = ps.ChannelLayoutType.mono
    ctx.channel_type = channel
    ctx.sample_rate = 16000

    status = 0

    for task in tasks:
        src_coord = task[0]
        lis_coord = task[1]
        wavname = task[2]

        cnt = 0
        src = ps.Source(src_coord)
        src.radius = 0.01

        lis = ps.Listener(lis_coord)
        lis.radius = 0.01
        # lis.channel_layout_type = ps.ChannelLayoutType.mono

        a = np.array(src_coord)
        b = np.array(lis_coord)
        dist = np.linalg.norm(a - b)
        direct_idx = int(ctx.sample_rate * dist / 343)
        res = scene.computeIR(src, lis, ctx)
        res['samples'] = np.atleast_2d(res['samples'])
        if (np.argmax(np.fabs(res['samples'])) == 0):
            status = 1
            wavname += '_startzero.wav'
        elif (np.max(np.fabs(res['samples'])) == 0):
            status = 2
            wavname += '_zeromax.wav'
        elif (np.isnan(res['samples']).any()):
            status = 3
            wavname += '_nan.wav'

    return status
Exemple #3
0
def main():
    # Simulation using .obj file (and an optional .mtl file)
    ctx = ps.Context()
    ctx.diffuse_count = 20000
    ctx.specular_count = 2000
    ctx.channel_type = ps.ChannelLayoutType.stereo

    mesh1 = ps.loadobj(
        "cube.obj", ""
    )  # if the second argument is empty, the code will infer the .mtl name using .obj name
    scene = ps.Scene()
    scene.setMesh(mesh1)

    src_coord = [1, 1, 0.5]
    lis_coord = [5, 3, 0.5]

    src = ps.Source(src_coord)
    src.radius = 0.01

    lis = ps.Listener(lis_coord)
    lis.radius = 0.01

    res = scene.computeMultichannelIR(src, lis, ctx)

    w = WaveWriter('test1.wav',
                   channels=np.shape(res['samples'])[0],
                   samplerate=int(res['rate']))
    w.write(np.array(res['samples']))
    print("IR using .obj input written to test1.wav.")

    # Simulation using a shoebox definition
    ctx = ps.Context()
    ctx.diffuse_count = 20000
    ctx.specular_count = 2000
    ctx.channel_type = ps.ChannelLayoutType.stereo

    mesh2 = ps.createbox(10, 6, 2, 0.5, 0.5)
    scene = ps.Scene()
    scene.setMesh(mesh2)

    res = scene.computeMultichannelIR(src, lis, ctx)
    w2 = WaveWriter('test2.wav',
                    channels=np.shape(res['samples'])[0],
                    samplerate=int(res['rate']))
    w2.write(np.array(res['samples']))
    print("IR using shoebox input written to test2.wav.")
Exemple #4
0
def pygsound_compute_ir(
    scene, context, source_pos, mic_pos, src_radius=0.01, mic_radius=0.01
):

    assert mic_pos.shape[0] == 3
    assert len(source_pos) == 3

    # set source and receiver
    src = ps.Source(source_pos)
    src.radius = src_radius
    lis = ps.Listener((mic_pos[:, 0]).tolist())
    lis.radius = mic_radius

    # compute IR
    res_ch = scene.computeIR(src, lis, context)
    ir = np.array(res_ch["samples"])
    if np.linalg.norm(ir) == 0.0:
        raise ValueError("Either source or mic is outside of room.")
    return ir
Exemple #5
0
def main():
    l = 10
    w = 6
    h = 2
    absorb = 0.3
    reflec = np.sqrt(1.0 - absorb)

    ctx = ps.Context()
    ctx.diffuse_count = 20000
    ctx.specular_count = 2000
    ctx.channel_type = ps.ChannelLayoutType.mono
    scene = ps.Scene()

    mesh = ps.createbox(l, w, h, absorb, 0.5)
    scene.setMesh(mesh)

    src_coord = [1, 1, 0.5]
    lis_coord = [5, 3, 0.5]

    src = ps.Source(src_coord)
    src.radius = 0.01

    lis = ps.Listener(lis_coord)
    lis.radius = 0.01

    rir_gs = scene.computeIR(src, lis, ctx)
    rir_img = rg.rir_generator(343,
                               16000,
                               lis_coord,
                               src_coord, [l, w, h],
                               beta=[reflec] * 6)
    rir_img = rir_img / max(abs(rir_img[0]))

    max_cnt = min(len(rir_gs['samples']), len(rir_img[0])) * 2

    fig, axs = plt.subplots(4, 1, figsize=(10, 20))
    axs[0].set_title('Image Method (waveform)')
    axs[0].plot(rir_img[0], linewidth=0.5)
    axs[0].set_xlabel('Sample')
    axs[0].set_xlim(0, max_cnt)
    axs[0].set_ylim(-1, 1)
    axs[0].set_ylabel('Amplitude')

    axs[1].set_title('Geometric Sound Propagation (waveform)')
    axs[1].plot(rir_gs['samples'], linewidth=0.5)
    axs[1].set_xlabel('Sample')
    axs[1].set_xlim(0, max_cnt)
    axs[1].set_ylim(-1, 1)
    axs[1].set_ylabel('Amplitude')

    axs[2].set_title('Image Method (spectrogram)')
    axs[2].specgram(rir_img[0],
                    mode='magnitude',
                    NFFT=1024,
                    Fs=16000,
                    noverlap=512)
    axs[2].set_xlim(0, max_cnt / 16000)
    axs[2].set_xlabel('Times (s)')
    axs[2].set_ylabel('Frequency (Hz)')

    axs[3].set_title('Geometric Sound Propagation (spectrogram)')
    axs[3].specgram(rir_gs['samples'],
                    mode='magnitude',
                    NFFT=1024,
                    Fs=16000,
                    noverlap=512)
    axs[3].set_xlim(0, max_cnt / 16000)
    axs[3].set_xlabel('Times (s)')
    axs[3].set_ylabel('Frequency (Hz)')

    fig.tight_layout()
    plt.savefig('img_comparison.png')
    plt.show()