How to use the spaudiopy.utils.cart2sph function in spaudiopy

To help you get started, we’ve selected a few spaudiopy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github chris-hld / spaudiopy / examples / Loudspeaker_decoder.py View on Github external
ls_setup = IO.load_layout("../data/ls_layouts/Graz.json",
                              listener_position=listener_position)
    ls_setup.pop_triangles(normal_limit, aperture_limit, opening_limit,
                           blacklist)

else:
    raise ValueError


# %% Show setup
ls_setup.show()
plots.hull_normals(ls_setup)

# Test source location
src = np.array([1, 0.5, 2.5])
src_azi, src_colat, _ = utils.cart2sph(*src.tolist())

# %% VBAP
gains_vbap = decoder.vbap(src, ls_setup)


# %% Ambisonic decoding
# Ambisonic setup
N_e = ls_setup.get_characteristic_order()
ls_setup.ambisonics_setup(update_hull=True, N_kernel=20)

# Show ALLRAP hulls
plots.hull(ls_setup.ambisonics_hull, title='Ambisonic hull')
plots.hull(ls_setup.kernel_hull, mark_invalid=False, title='Kernel hull')

# ALLRAP
gains_allrap = decoder.allrap(src, ls_setup, N_sph=N_e)
github chris-hld / spaudiopy / spaudiopy / decoder.py View on Github external
# virtual t-design loudspeakers
    J = len(kernel_hull.points)
    # virtual speakers expressed as VBAP phantom sources
    G = vbap(src=kernel_hull.points, hull=ambisonics_hull)

    # SH tapering coefficients
    a_n = sph.max_rE_weights(N_sph)
    # sqrt(E) normalization (eq.6)
    a_w = np.sqrt(np.sum((2 * (np.arange(N_sph + 1) + 1)) / (4 * np.pi) *
                         a_n**2))
    a_n /= a_w
    a_n = sph.repeat_order_coeffs(a_n)

    # virtual Ambisonic decoder
    _t_azi, _t_colat, _t_r = utils.cart2sph(kernel_hull.points[:, 0],
                                            kernel_hull.points[:, 1],
                                            kernel_hull.points[:, 2])
    Y_td = sph.sh_matrix(N_sph, _t_azi, _t_colat, SH_type='real')

    # tapered dirac
    Y_k = Y_td @ np.diag(a_n) @ F_nm
    # ALLRAD2 Decoder
    ls_sig = np.sqrt(4 * np.pi / J * np.square(G.T) @ np.square(Y_k))

    # remove imaginary loudspeakers
    ls_sig = np.delete(ls_sig, ambisonics_hull.imaginary_speaker, axis=0)
    return ls_sig
github chris-hld / spaudiopy / spaudiopy / IO.py View on Github external
"""Save loudspeaker layout to json configuration file."""
    if not ls_layout.ambisonics_hull:
        raise ValueError("No ambisonics_hull.")
    out_data = {}
    out_data['Name'] = name
    out_data['Description'] = 'This configuration file was created with ' +\
                              'spaudiopy (v-' + str(__version__) + '), ' + \
                              str(datetime.now())

    out_data['LoudspeakerLayout'] = {}
    out_data['LoudspeakerLayout']['Name'] = name
    out_data['LoudspeakerLayout']['Description'] = description
    out_data['LoudspeakerLayout']['Loudspeakers'] = []

    for ls_idx in range(ls_layout.ambisonics_hull.npoints):
        ls_dirs = utils.cart2sph(ls_layout.ambisonics_hull.x[ls_idx],
                                 ls_layout.ambisonics_hull.y[ls_idx],
                                 ls_layout.ambisonics_hull.z[ls_idx])
        ls_dict = {}
        ls_dict['Azimuth'] = round(float(utils.rad2deg(ls_dirs[0])), 2)
        ls_dict['Elevation'] = round(float(90 - utils.rad2deg(ls_dirs[1])), 2)
        ls_dict['Radius'] = round(float(ls_dirs[2]), 2)
        ls_dict['IsImaginary'] = ls_idx in np.asarray(
                                    ls_layout.ambisonics_hull.imaginary_ls_idx)
        ls_dict['Channel'] = ls_idx + 1
        ls_dict['Gain'] = 0. if ls_idx in np.asarray(
                            ls_layout.ambisonics_hull.imaginary_ls_idx) else 1.
        out_data['LoudspeakerLayout']['Loudspeakers'].append(ls_dict)

    with open(filename, 'w') as outfile:
        json.dump(out_data, outfile, indent=4)
github chris-hld / spaudiopy / spaudiopy / sdm.py View on Github external
repeat(win))
        # execute
        with multiprocessing.Pool(processes=jobs_count,
                                  initializer=_init_shared_array,
                                  initargs=(_arr_base,
                                            shared_array_shape,)) as pool:
            pool.starmap(_intensity_sample, _arg_itr)
        # reshape
        I_vec = np.frombuffer(_arr_base.get_obj()).reshape(
            shared_array_shape)

    if smoothing_order > 0:
        assert(smoothing_order % 2)
        I_vec = np.apply_along_axis(signal.convolve, 0, I_vec,
                                    np.hanning(smoothing_order), 'same')
    I_azi, I_colat, I_r = utils.cart2sph(I_vec[:, 0], I_vec[:, 1],
                                         I_vec[:, 2], steady_colat=True)
    return I_azi, I_colat, I_r
github chris-hld / spaudiopy / spaudiopy / decoder.py View on Github external
else:
        raise ValueError('Run hull.setup_for_ambisonic() first!')
    if N_sph is None:
        N_sph = hull.characteristic_order

    # virtual t-design loudspeakers
    J = len(kernel_hull.points)
    # virtual speakers expressed as VBAP phantom sources
    G = vbap(src=kernel_hull.points, hull=ambisonics_hull)

    # SH tapering coefficients
    a_n = sph.max_rE_weights(N_sph)
    a_n = sph.repeat_order_coeffs(a_n)

    # virtual Ambisonic decoder
    _t_azi, _t_colat, _t_r = utils.cart2sph(kernel_hull.points[:, 0],
                                            kernel_hull.points[:, 1],
                                            kernel_hull.points[:, 2])
    Y_td = sph.sh_matrix(N_sph, _t_azi, _t_colat, SH_type='real')
    # ALLRAD Decoder
    D = 4 * np.pi / J * G.T @ Y_td
    # apply tapering to decoder matrix
    D = D @ np.diag(a_n)
    # loudspeaker output signals
    ls_sig = D @ F_nm
    # remove imaginary loudspeakers
    ls_sig = np.delete(ls_sig, ambisonics_hull.imaginary_speaker, axis=0)
    return ls_sig
github chris-hld / spaudiopy / spaudiopy / plots.py View on Github external
# Show them
    fig, axes = plt.subplots(1, 3, sharex='all', sharey='all',
                             figsize=(10, 2.2))  # works for nb
    for ip, _data in enumerate([E, spread, ang_error]):
        _data = _data.reshape(phi_plot.shape)
        ax = axes[ip]
        ax.set_aspect('equal')
        # draw mesh, value corresponds to center of mesh
        p = ax.pcolormesh(phi_plot-azi_steps/2, theta_plot-ele_steps/2,
                          _data, vmin=0, vmax=90 if ip == 1 or ip == 2
                          else np.max([1.0, np.max(_data)]))
        # draw loudspeakers
        if show_ls:
            for s, co in enumerate(ls_points):
                # map to pixels grid
                _azi_ls, _colat_ls, _ = utils.cart2sph(*co)
                ax.plot(_azi_ls, _colat_ls, marker='2', color='grey')
                # ax.text(_x_plot, _y_plot, s)  # LS Number
        # Labeling etc
        ax.grid(True)
        ax.set_xlim([-np.pi - azi_steps/2, np.pi + azi_steps/2])
        ax.set_ylim([0 - ele_steps/2, np.pi + ele_steps/2])
        ax.invert_yaxis()
        ax.set_xticks(np.linspace(-np.pi, np.pi, 5))
        ax.set_xticklabels([r'$-\pi$', r'$-\pi/2$', r'$0$',
                            r'$\pi/2$', r'$\pi$'])
        ax.set_yticks(np.linspace(0, np.pi, 3))
        ax.set_yticklabels([r'$0$', r'$\pi/2$', r'$\pi$'])
        cbar = fig.colorbar(p, ax=ax, fraction=0.024, pad=0.04)
        cbar.outline.set_linewidth(0.5)
        if ip == 0:
            ax.set_xlabel('Azimuth')
github chris-hld / spaudiopy / spaudiopy / sph.py View on Github external
def project_on_sphere(x, y, z):
    """Little helper that projects x, y, z onto unit sphere."""
    phi, theta, r = utils.cart2sph(x, y, z)
    r = np.ones_like(r)
    return utils.sph2cart(phi, theta, r)