Exemplo n.º 1
0
def build_a(values, rdir, c, kernel_size):
    """
    Build a kernel containing pixel intensities
    :param values:
    :type values: np.ndarray
    :param rdir:
    :type rdir: np.ndarray
    :param c:
    :type c: np.ndarray
    :param kernel_size:
    :type kernel_size: float
    """

    window = kernel_size / 2.
    vdir = sph2vec(rdir.T)
    vc = sph2vec(c)
    d = np.abs(np.arccos(vdir.T.dot(vc)))

    home_i = np.argmin(d)
    home = values[home_i]
    j = d <= window

    a = np.zeros((j.sum(), 2), dtype=float)
    dj = angle_between(rdir[j], rdir[home_i])
    di = np.array([home - values[j]] * 2).T
    zeros = dj == 0
    a[~zeros] = (di[~zeros] / dj[~zeros].T).T

    return a[:, ::-1]
Exemplo n.º 2
0
def build_b(n_val, o_val, rdir, c, kernel_size):
    window = kernel_size / 2.
    vdir = sph2vec(rdir.T)
    vc = sph2vec(c)
    d = np.arccos(vdir.T.dot(vc))

    j = d <= window
    return n_val[j] - o_val[j]
Exemplo n.º 3
0
def angular_deviation_3d(y_predict, y_target, theta=True, phi=True):
    if theta:
        thy = y_predict[:, 1]
        tht = y_target[:, 1]
    else:
        thy = np.zeros_like(y_predict[:, 1])
        tht = np.zeros_like(y_target[:, 1])
    if phi:
        phy = y_predict[:, 0]
        pht = y_target[:, 0]
    else:
        phy = np.zeros_like(y_predict[:, 0])
        pht = np.zeros_like(y_target[:, 0])
    v1 = sph2vec(thy, phy)
    v2 = sph2vec(tht, pht)
    return np.rad2deg(np.arccos((v1 * v2).sum(axis=0)).std())
Exemplo n.º 4
0
def gaussian_weight(size, rdir, c, even=False):

    window = size / 2.
    vdir = sph2vec(rdir.T)
    vc = sph2vec(c)
    d = np.arccos(vdir.T.dot(vc))
    j = d <= window
    d = d[j]

    if even:
        return np.diag(np.ones(j.sum()))

    sigma = 2 * np.pi / rdir.shape[
        1]  # the standard deviation of your normal curve
    correlation = 0.  # see wiki for multivariate normal distributions
    z = (2 * np.pi * sigma * sigma) * np.sqrt(1 - correlation * correlation)
    exp = -1 / (2 *
                (1 - correlation * correlation)) * (d * d) / (sigma * sigma)

    return np.diag(1. / z * np.exp(exp))
Exemplo n.º 5
0
    def visualise(cls,
                  sensor,
                  sL=None,
                  show_sun=False,
                  sides=True,
                  interactive=False,
                  colormap=None,
                  scale=[0, 1],
                  title=None):
        """
        :param sensor:
        :type sensor: CompassSensor
        :return:
        """
        import matplotlib.pyplot as plt
        from matplotlib.patches import Ellipse, Rectangle
        from matplotlib.cm import get_cmap
        import matplotlib as mpl

        if interactive:
            plt.ion()

        if colormap is not None:
            get_colour = lambda x: get_cmap(colormap)(x)
        else:
            get_colour = lambda x: x * np.array([.5, .5, 1.])
        xyz = sph2vec(np.pi / 2 - sensor.theta_local, np.pi + sensor.phi_local,
                      sensor.R_c)
        xyz[0] *= -1

        lat, lon = hp.Rotator(rot=(np.rad2deg(-sensor.yaw),
                                   np.rad2deg(-sensor.pitch),
                                   np.rad2deg(-sensor.roll)))(
                                       sensor.sky.lat, np.pi - sensor.sky.lon)
        xyz_sun = sph2vec(np.pi / 2 - lat, np.pi + lon, sensor.R_c)
        xyz_sun[0] *= -1

        if sides:
            figsize = (10, 10)
        else:
            if colormap is None or scale is None:
                figsize = (5, 5)
            else:
                figsize = (5.05, 5.05)
        plt.figure("Sensor Design" if title is None else title,
                   figsize=figsize)

        # top view
        if sides:
            ax_t = plt.subplot2grid((4, 4), (1, 1),
                                    colspan=2,
                                    rowspan=2,
                                    aspect="equal",
                                    adjustable='box-forced')
        else:
            if colormap is not None and scale is not None:
                ax_t = plt.subplot2grid((10, 10), (0, 0),
                                        colspan=9,
                                        rowspan=9,
                                        aspect="equal",
                                        adjustable='box-forced')
            else:
                ax_t = plt.subplot(111)
        outline = Ellipse(xy=np.zeros(2),
                          width=2 * sensor.R_c,
                          height=2 * sensor.R_c)
        sensor_outline = Ellipse(xy=np.zeros(2),
                                 width=2 * sensor.alpha + 2 * sensor.R_l,
                                 height=2 * sensor.alpha + 2 * sensor.R_l)
        ax_t.add_artist(outline)
        outline.set_clip_box(ax_t.bbox)
        outline.set_alpha(.2)
        outline.set_facecolor("grey")
        ax_t.add_artist(sensor_outline)
        sensor_outline.set_clip_box(ax_t.bbox)
        sensor_outline.set_alpha(.5)
        sensor_outline.set_facecolor("grey")

        stheta, sphi = sensor.theta_local, np.pi + sensor.phi_local
        sL = sL if sL is not None else sensor.L
        if sensor.mode == "event":
            sL = np.clip(1. * sL + .5, 0., 1.)
        for (x, y, z), th, ph, L in zip(xyz.T, stheta, sphi, sL):

            lens = Ellipse(xy=[x, y],
                           width=1.5 * sensor.r_l,
                           height=1.5 * np.cos(th) * sensor.r_l,
                           angle=np.rad2deg(ph))
            ax_t.add_artist(lens)
            lens.set_clip_box(ax_t.bbox)
            lens.set_facecolor(get_colour(np.asscalar(L)))
        if show_sun:
            ax_t.plot(xyz_sun[0], xyz_sun[1], 'ro', markersize=22)

        ax_t.set_xlim(-sensor.R_c - 2, sensor.R_c + 2)
        ax_t.set_ylim(-sensor.R_c - 2, sensor.R_c + 2)
        ax_t.set_xticklabels([])
        ax_t.set_yticklabels([])

        if sides:
            # side view #1 (x, z)
            ax = plt.subplot2grid((4, 4), (0, 1),
                                  colspan=2,
                                  aspect="equal",
                                  adjustable='box-forced',
                                  sharex=ax_t)
            outline = Ellipse(xy=np.zeros(2),
                              width=2 * sensor.R_c,
                              height=2 * sensor.R_c)
            fade_one = Rectangle(xy=[-sensor.R_c, -sensor.R_c],
                                 width=2 * sensor.R_c,
                                 height=2 * sensor.R_c - sensor.height -
                                 sensor.R_l)
            ax.add_artist(outline)
            outline.set_clip_box(ax.bbox)
            outline.set_alpha(.5)
            outline.set_facecolor("grey")
            ax.add_artist(fade_one)
            fade_one.set_clip_box(ax.bbox)
            fade_one.set_alpha(.6)
            fade_one.set_facecolor("white")
            for (x, y, z), th, ph, L in zip(xyz.T, stheta, sphi, sL):
                if y > 0:
                    continue
                lens = Ellipse(xy=[x, z],
                               width=1.5 * sensor.r_l,
                               height=np.sin(-y / sensor.R_c) * 1.5 *
                               sensor.r_l,
                               angle=np.rad2deg(np.arcsin(-x / sensor.R_c)))
                ax.add_artist(lens)
                lens.set_clip_box(ax.bbox)
                lens.set_facecolor(get_colour(L))

            ax.set_xlim(-sensor.R_c - 2, sensor.R_c + 2)
            ax.set_ylim(0, sensor.R_c + 2)
            ax.set_xticks([])
            ax.set_yticks([])

            # side view #2 (-x, z)
            ax = plt.subplot2grid((4, 4), (3, 1),
                                  colspan=2,
                                  aspect="equal",
                                  adjustable='box-forced',
                                  sharex=ax_t)
            outline = Ellipse(xy=np.zeros(2),
                              width=2 * sensor.R_c,
                              height=2 * sensor.R_c)
            fade_one = Rectangle(
                xy=[-sensor.R_c, -sensor.R_c + sensor.height + sensor.R_l],
                width=2 * sensor.R_c,
                height=2 * sensor.R_c - sensor.height - sensor.R_l)
            ax.add_artist(outline)
            outline.set_clip_box(ax.bbox)
            outline.set_alpha(.5)
            outline.set_facecolor("grey")
            ax.add_artist(fade_one)
            fade_one.set_clip_box(ax.bbox)
            fade_one.set_alpha(.6)
            fade_one.set_facecolor("white")
            for (x, y, z), th, ph, L in zip(xyz.T, stheta, sphi, sL):
                if y < 0:
                    continue
                lens = Ellipse(xy=[x, -z],
                               width=1.5 * sensor.r_l,
                               height=np.sin(-y / sensor.R_c) * 1.5 *
                               sensor.r_l,
                               angle=np.rad2deg(np.arcsin(x / sensor.R_c)))
                ax.add_artist(lens)
                lens.set_clip_box(ax.bbox)
                lens.set_facecolor(get_colour(L))

            ax.set_xlim(-sensor.R_c - 2, sensor.R_c + 2)
            ax.set_ylim(-sensor.R_c - 2, 0)
            ax.set_yticks([])

            # side view #3 (y, z)
            ax = plt.subplot2grid((4, 4), (1, 3),
                                  rowspan=2,
                                  aspect="equal",
                                  adjustable='box-forced',
                                  sharey=ax_t)
            outline = Ellipse(xy=np.zeros(2),
                              width=2 * sensor.R_c,
                              height=2 * sensor.R_c)
            fade_one = Rectangle(xy=[-sensor.R_c, -sensor.R_c],
                                 width=2 * sensor.R_c - sensor.height -
                                 sensor.R_l,
                                 height=2 * sensor.R_c)
            ax.add_artist(outline)
            outline.set_clip_box(ax.bbox)
            outline.set_alpha(.5)
            outline.set_facecolor("grey")
            ax.add_artist(fade_one)
            fade_one.set_clip_box(ax.bbox)
            fade_one.set_alpha(.6)
            fade_one.set_facecolor("white")
            for (x, y, z), th, ph, L in zip(xyz.T, stheta, sphi, sL):
                if x > 0:
                    continue
                lens = Ellipse(
                    xy=[z, y],
                    width=1.5 * sensor.r_l,
                    height=np.sin(-x / sensor.R_c) * 1.5 * sensor.r_l,
                    angle=np.rad2deg(np.arcsin(y / sensor.R_c)) + 90)
                ax.add_artist(lens)
                lens.set_clip_box(ax.bbox)
                lens.set_facecolor(get_colour(L))

            ax.set_ylim(-sensor.R_c - 2, sensor.R_c + 2)
            ax.set_xlim(0, sensor.R_c + 2)
            ax.set_yticks([])
            ax.set_xticks([])

            # side view #4 (-y, z)
            ax = plt.subplot2grid((4, 4), (1, 0),
                                  rowspan=2,
                                  aspect="equal",
                                  adjustable='box-forced',
                                  sharey=ax_t)
            outline = Ellipse(xy=np.zeros(2),
                              width=2 * sensor.R_c,
                              height=2 * sensor.R_c)
            fade_one = Rectangle(
                xy=[-sensor.R_c + sensor.height + sensor.R_l, -sensor.R_c],
                width=2 * sensor.R_c - sensor.height - sensor.R_l,
                height=2 * sensor.R_c)
            ax.add_artist(outline)
            outline.set_clip_box(ax.bbox)
            outline.set_alpha(.5)
            outline.set_facecolor("grey")
            ax.add_artist(fade_one)
            fade_one.set_clip_box(ax.bbox)
            fade_one.set_alpha(.6)
            fade_one.set_facecolor("white")
            for (x, y, z), th, ph, L in zip(xyz.T, stheta, sphi, sL):
                if x < 0:
                    continue
                lens = Ellipse(
                    xy=[-z, y],
                    width=1.5 * sensor.r_l,
                    height=np.sin(-x / sensor.R_c) * 1.5 * sensor.r_l,
                    angle=np.rad2deg(np.arcsin(-y / sensor.R_c)) - 90)
                ax.add_artist(lens)
                lens.set_clip_box(ax.bbox)
                lens.set_facecolor(get_colour(L))

            ax.set_ylim(-sensor.R_c - 2, sensor.R_c + 2)
            ax.set_xlim(-sensor.R_c - 2, 0)
            ax.set_xticks([])
        else:
            plt.axis('off')

        if colormap is not None and not sides and scale is not None:
            ax = plt.subplot2grid((10, 10), (9, 9),
                                  aspect="equal",
                                  adjustable='box-forced',
                                  projection='polar')
            ax._direction = 2 * np.pi
            ax.set_theta_zero_location("N")

            # quant_steps = 360
            cb = mpl.colorbar.ColorbarBase(ax,
                                           cmap=get_cmap(colormap),
                                           norm=mpl.colors.Normalize(
                                               0.0, 2 * np.pi),
                                           orientation='horizontal',
                                           ticks=np.linspace(0,
                                                             2 * np.pi,
                                                             4,
                                                             endpoint=False))

            cb.outline.set_visible(False)
            # cb.ax.set_xticks([0, np.pi/6, np.pi/3, np.pi/2, 2*np.pi/3, 5*np.pi/6, np.pi])
            cb.ax.set_xticklabels(
                np.linspace(scale[0], scale[1], 4, endpoint=False))
            cb.ax.tick_params(pad=1, labelsize=8)

        plt.tight_layout(pad=0.)

        if interactive:
            plt.draw()
            plt.pause(.1)
        else:
            plt.show()
Exemplo n.º 6
0
def visualise_compnet(sensor, sL=None, interactive=True, cmap="coolwarm", vmin=0, vmax=1, title=None):
    """

    :param sensor:
    :type sensor: CompassSensor
    :return:
    """

    if interactive and not plt.isinteractive():
        plt.ion()

    if isinstance(cmap, basestring):
        cmap = get_cmap(cmap)

    xyz = sph2vec(np.pi/2 - sensor.theta_local, np.pi + sensor.phi_local, sensor.R_c)
    xyz[0] *= -1

    lat, lon = hp.Rotator(rot=(
        np.rad2deg(-sensor.yaw), np.rad2deg(-sensor.pitch), np.rad2deg(-sensor.roll)
    ))(sensor.sky.lat, np.pi-sensor.sky.lon)
    xyz_sun = sph2vec(np.pi/2 - lat, np.pi + lon, sensor.R_c)
    xyz_sun[0] *= -1

    fig = plt.figure("Compass-CompModel" if title is None or interactive else title, figsize=(12, 7))
    fig.clear()
    ax_t = plt.subplot2grid((1, 12), (0, 0), colspan=10)

    outline = Ellipse(xy=np.zeros(2),
                      width=2 * sensor.R_c,
                      height=2 * sensor.R_c)
    sensor_outline = Ellipse(xy=np.zeros(2),
                             width=2 * sensor.alpha + 2 * sensor.R_l,
                             height=2 * sensor.alpha + 2 * sensor.R_l)
    ax_t.add_patch(outline)
    outline.set_clip_box(ax_t.bbox)
    outline.set_alpha(.2)
    outline.set_facecolor("grey")

    stheta, sphi = sensor.theta_local, np.pi + sensor.phi_local
    sL = np.clip(sL if sL is not None else sensor.L, 0., 1.)
    for k, ((x, y, z), th, ph, L) in enumerate(zip(xyz.T, stheta, sphi, sL)):
        for j, tl2 in enumerate(sensor.tl2):
            line = ConnectionPatch([x, y], [sensor.R_c + 5, j * sensor.R_c / 8. - sensor.R_c + 1],
                                   "data", "data", lw=.5, color=cmap(np.asscalar(L) * sensor.w_tl2[k, j] + .5))
            ax_t.add_patch(line)

    ax_t.add_patch(sensor_outline)
    sensor_outline.set_clip_box(ax_t.bbox)
    sensor_outline.set_alpha(.5)
    sensor_outline.set_facecolor("grey")

    for k, ((x, y, z), th, ph, L) in enumerate(zip(xyz.T, stheta, sphi, sL)):
        lens = Ellipse(xy=[x, y], width=1.5 * sensor.r_l, height=1.5 * np.cos(th) * sensor.r_l,
                       angle=np.rad2deg(ph))
        ax_t.add_patch(lens)
        lens.set_clip_box(ax_t.bbox)
        lens.set_facecolor(cmap(np.asscalar(L)))

    scale = 5.
    for j, tl2 in enumerate(sensor.tl2):
        x = sensor.R_c + 5
        y = j * sensor.R_c / 8. - sensor.R_c + 1
        for k, cl1 in enumerate(sensor.cl1):
            line = ConnectionPatch([x, y], [sensor.R_c + 10, k * sensor.R_c / 8. - sensor.R_c + 1],
                                   "data", "data", lw=.5, color=cmap(scale * tl2 * sensor.w_cl1[j, k] + .5))
            ax_t.add_patch(line)
        neuron = Ellipse(xy=[x, y], width=.1 * sensor.R_c, height=.1 * sensor.R_c)
        ax_t.add_artist(neuron)
        neuron.set_clip_box(ax_t.bbox)
        neuron.set_facecolor(cmap(scale * tl2 + .5))

    for j, cl1 in enumerate(sensor.cl1):
        x = sensor.R_c + 10
        y = j * sensor.R_c / 8. - sensor.R_c + 1
        for k, tb1 in enumerate(sensor.tb1):
            line = ConnectionPatch([x, y], [sensor.R_c + 15, k * sensor.R_c / 8. - sensor.R_c / 2. + 1],
                                   "data", "data", lw=.5, color=cmap(scale * cl1 * sensor.w_tb1[j, k] + .5))
            ax_t.add_patch(line)
        neuron = Ellipse(xy=[x, y], width=.1 * sensor.R_c, height=.1 * sensor.R_c)
        ax_t.add_artist(neuron)
        neuron.set_clip_box(ax_t.bbox)
        neuron.set_facecolor(cmap(scale * cl1 + .5))

    for j, tb1 in enumerate(sensor.tb1):
        x = sensor.R_c + 15
        y = j * sensor.R_c / 8. - sensor.R_c / 2 + 1
        neuron = Ellipse(xy=[x, y], width=.1 * sensor.R_c, height=.1 * sensor.R_c)
        ax_t.add_artist(neuron)
        neuron.set_clip_box(ax_t.bbox)
        neuron.set_facecolor(cmap(scale * tb1 + .5))

    ax_t.text(0, sensor.R_c - sensor.r_l, "0", fontsize=15, verticalalignment='center', horizontalalignment='center')
    ax_t.text(-sensor.R_c + sensor.r_l, 0, "90", fontsize=15, verticalalignment='center', horizontalalignment='center')
    ax_t.text(0, -sensor.R_c + sensor.r_l, "180", fontsize=15, verticalalignment='center', horizontalalignment='center')
    ax_t.text(sensor.R_c - sensor.r_l, 0, "-90", fontsize=15, verticalalignment='center', horizontalalignment='center')

    norm = np.sqrt(np.square(xyz_sun[0]) + np.square(xyz_sun[1])) / (sensor.R_c - 3 * sensor.r_l)
    ax_t.plot([-xyz_sun[0]/norm, xyz_sun[0]/norm], [-xyz_sun[1]/norm, xyz_sun[1]/norm], "k-")
    ax_t.plot(xyz_sun[0], xyz_sun[1],
              marker='o',
              fillstyle='full',
              markeredgecolor='black',
              markerfacecolor='yellow',
              markersize=15)

    ax_t.text(0, 0, "z", fontsize=15, verticalalignment='center', horizontalalignment='center',
              color='red', fontweight='bold')

    ax_t.set_xlim(-sensor.R_c - 2, sensor.R_c + 17)
    ax_t.set_ylim(-sensor.R_c - 2, sensor.R_c + 2)
    ax_t.set_xticklabels([])
    ax_t.set_yticklabels([])

    plt.axis('off')

    plt.subplot2grid((4, 12), (1, 10), colspan=2, rowspan=2)
    theta, phi = decode_sph(sensor.tb1)
    alpha = np.linspace(0, 2*np.pi, 100)
    plt.plot(theta * np.sin(phi + alpha + np.pi/2), alpha)
    plt.ylabel("phase (degrees)")
    plt.ylim([0, 2*np.pi])
    plt.xlim([theta+np.pi/360, -theta-np.pi/360])
    plt.xticks([-theta, 0, theta], ["%d" % np.rad2deg(-theta), "0", "%d" % np.rad2deg(theta)])
    plt.yticks([0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi], ["0", "90", "180", "270", "360"])

    plt.tight_layout(pad=0.)

    if interactive:
        plt.draw()
        plt.pause(.1)
    else:
        plt.show()