예제 #1
0
 def phi_t(self, value):
     theta_t, phi_t = tilt(self._theta_c,
                           self._phi_c - np.pi,
                           theta=self._theta_t,
                           phi=self._phi_t)
     theta_t, self._phi_t = tilt(self._theta_c,
                                 self._phi_c,
                                 theta=self.theta_t,
                                 phi=value)
예제 #2
0
 def theta_t(self, value):
     theta_t, phi_t = tilt(self._theta_c,
                           self._phi_c - np.pi,
                           theta=self._theta_t,
                           phi=self._phi_t)
     self._theta_t, phi_t = tilt(self._theta_c,
                                 self._phi_c,
                                 theta=value,
                                 phi=self.phi_t)
예제 #3
0
def visualise_angle_of_polarisation(sky):
    import matplotlib.pyplot as plt

    plt.figure("angle-of-polarisation", figsize=(4.5, 4.5))
    ax = plt.subplot(111, polar=True)
    ax.set_theta_zero_location("N")
    ax.set_theta_direction(-1)

    theta_s, phi_s = tilt(sky.theta_t,
                          sky.phi_t,
                          theta=sky.theta_s,
                          phi=sky.phi_s)
    print theta_s, phi_s
    ax.scatter(sky.phi,
               sky.theta,
               s=10,
               c=sky.AOP,
               marker='.',
               cmap='hsv',
               vmin=-np.pi,
               vmax=np.pi)
    ax.scatter(phi_s, theta_s, s=100, edgecolor='black', facecolor='yellow')
    # ax.scatter(sky.phi_t + np.pi, sky.theta_t, s=200, edgecolor='black', facecolor='greenyellow')
    ax.set_ylim([0, np.pi / 2])
    ax.set_yticks([])
    ax.set_xticks(np.linspace(0, 2 * np.pi, 8, endpoint=False))
    ax.set_xticklabels([
        r'$0^\circ$ (N)', r'$45^\circ$ (NE)', r'$90^\circ$ (E)',
        r'$135^\circ$ (SE)', r'$180^\circ$ (S)', r'$-135^\circ$ (SW)',
        r'$-90^\circ$ (W)', r'$-45^\circ$ (NW)'
    ])

    plt.show()
예제 #4
0
    def __call__(self, env, *args, **kwargs):
        """

        :param env: the environment where the photorectors can percieve light
        :type env: Environment
        :param args: unlabeled arguments
        :type args: list
        :param kwargs: labeled arguments
        :type kwargs: dict
        :return:
        """
        env.theta_t = self.theta_t
        env.phi_t = self.phi_t

        _, alpha = tilt(self.theta_t,
                        self.phi_t + np.pi,
                        theta=np.pi / 2,
                        phi=self.mic_a)
        y, p, a = env(self.theta, self.phi, *args, **kwargs)

        # influence of the acceptance angle on the luminance and DOP
        # y = y.dot(self._rho_gaussian)
        # p = p.dot(self._rho_gaussian)

        # influence of the wavelength on the perceived light
        ry = spectrum_influence(y, self.rhabdom)

        s = ry * ((np.square(np.sin(a - alpha + self.mic_l)) + np.square(
            np.cos(a - alpha + self.mic_l)) * np.square(1. - p)) * self.mic_p +
                  (1. - self.mic_p))
        self.__r = np.sqrt(s)

        self._is_called = True

        return self.__r
예제 #5
0
def visualise(my_sky, y):
    import matplotlib.pyplot as plt

    plt.figure("Luminance", figsize=(4.5, 4.5))
    ax = plt.subplot(111, polar=True)
    ax.set_theta_zero_location("N")
    ax.set_theta_direction(-1)

    theta_s, phi_s = tilt(my_sky.theta_t,
                          my_sky.phi_t,
                          theta=my_sky.theta_s,
                          phi=my_sky.phi_s)
    ax.scatter(my_sky.phi,
               my_sky.theta,
               s=100,
               c=y,
               marker='.',
               cmap='coolwarm',
               vmin=-1,
               vmax=1)
    ax.scatter(phi_s, theta_s, s=100, edgecolor='black', facecolor='yellow')
    ax.scatter(my_sky.phi_t,
               my_sky.theta_t,
               s=50,
               edgecolor='black',
               facecolor='greenyellow')
    ax.set_ylim([0, np.pi / 2])
    ax.set_yticks([])
    ax.set_xticks(np.linspace(0, 2 * np.pi, 8, endpoint=False))
    ax.set_xticklabels([
        r'$0^\circ$ (N)', r'$45^\circ$ (NE)', r'$90^\circ$ (E)',
        r'$135^\circ$ (SE)', r'$180^\circ$ (S)', r'$-135^\circ$ (SW)',
        r'$-90^\circ$ (W)', r'$-45^\circ$ (NW)'
    ])

    plt.show()
예제 #6
0
    def __call__(self,
                 theta=None,
                 phi=None,
                 noise=0.,
                 eta=None,
                 uniform_polariser=False):
        """
        Call the sky instance to generate the sky cues.

        :param theta: array of points' elevation
        :type theta: np.ndarray
        :param phi: array of points' azimuth
        :type phi: np.ndarray
        :param noise: the noise level (sigma)
        :type noise: float
        :param eta: array of noise level in each point of interest
        :type eta: np.ndarray
        :param uniform_polariser:
        :type uniform_polariser: bool
        :return: Y, P, A
        """

        # set default arguments
        theta = ((self.__theta if theta is None else theta) +
                 np.pi) % (2 * np.pi) - np.pi
        phi = (
            (self.__phi if phi is None else phi) + np.pi) % (2 * np.pi) - np.pi

        # save points of interest
        self.__theta = theta.copy()
        self.__phi = phi.copy()

        # transform points in the sky according to tilting parameters
        theta, phi = tilt(self.theta_t,
                          self.phi_t + np.pi,
                          theta=theta,
                          phi=phi)
        theta_s, phi_s = self.theta_s, self.phi_s

        # SKY INTEGRATION
        gamma = np.arccos(
            np.cos(theta) * np.cos(theta_s) +
            np.sin(theta) * np.sin(theta_s) * np.cos(phi - phi_s))

        # Intensity
        i_prez = self.L(gamma, theta)
        i_00 = self.L(0.,
                      theta_s)  # the luminance (Cd/m^2) at the zenith point
        i_90 = self.L(
            np.pi / 2,
            np.absolute(theta_s -
                        np.pi / 2))  # the luminance (Cd/m^2) on the horizon
        # influence of sky intensity
        i = (1. / (i_prez + eps) - 1. /
             (i_00 + eps)) * i_00 * i_90 / (i_00 - i_90 + eps)
        if uniform_polariser:
            y = np.maximum(np.full_like(i_prez, self.Y_z), 0.)
        else:
            y = np.maximum(self.Y_z * i_prez / (i_00 + eps),
                           0.)  # Illumination

        # Degree of Polarisation
        lp = np.square(np.sin(gamma)) / (1 + np.square(np.cos(gamma)))
        if uniform_polariser:
            p = np.ones_like(lp)
        else:
            p = np.clip(
                2. / np.pi * self.M_p * lp * (theta * np.cos(theta) +
                                              (np.pi / 2 - theta) * i), 0., 1.)

        # Angle of polarisation
        if uniform_polariser:
            a = np.full_like(p, phi_s + np.pi)
        else:
            _, a = tilt(theta_s, phi_s + np.pi, theta, phi)

        # create cloud disturbance
        if type(noise) is np.ndarray:
            if noise.size == p.size:
                # print "yeah!"
                eta = np.array(noise, dtype=bool)
                if self.verbose:
                    print "Noise level: %.4f (%.2f %%)" % (
                        noise, 100. * eta.sum() / float(eta.size))
            else:
                eta = np.zeros_like(theta, dtype=bool)
                eta[:noise.size] = noise
        elif noise > 0:
            eta = np.argsort(np.absolute(
                np.random.randn(*p.shape)))[:int(noise * p.shape[0])]
        elif eta is None:
            eta = np.zeros_like(theta, dtype=bool)
        p[eta] = 0.  # destroy the polarisation pattern
        y[eta] = 0.  # destroy the polarisation pattern

        self.__y = y
        self.__dop = p
        self.__aop = a
        self.__eta = eta

        self.__is_generated = True

        return y, p, a
예제 #7
0
def create_ephem_paths():
    # sensor design
    n = 60
    omega = 56
    theta, phi, fit = angles_distribution(n, float(omega))
    theta_t, phi_t = 0., 0.

    # ant-world
    noise = 0.0
    ttau = .06
    dx = 1e-02  # meters
    dt = 2. / 60.  # min
    delta = timedelta(minutes=dt)
    routes = load_routes()
    flow = dx * np.ones(2) / np.sqrt(2)
    max_theta = 0.


    def encode(theta, phi, Y, P, A, theta_t=0., phi_t=0., d_phi=0., nb_tcl=8, sigma=np.deg2rad(13),
               shift=np.deg2rad(40)):
        alpha = (phi + np.pi / 2) % (2 * np.pi) - np.pi
        phi_tcl = np.linspace(0., 2 * np.pi, nb_tcl, endpoint=False)  # TB1 preference angles
        phi_tcl = (phi_tcl + d_phi) % (2 * np.pi)

        # Input (POL) layer -- Photo-receptors
        s_1 = Y * (np.square(np.sin(A - alpha)) + np.square(np.cos(A - alpha)) * np.square(1. - P))
        s_2 = Y * (np.square(np.cos(A - alpha)) + np.square(np.sin(A - alpha)) * np.square(1. - P))
        r_1, r_2 = np.sqrt(s_1), np.sqrt(s_2)
        r_pol = (r_1 - r_2) / (r_1 + r_2 + eps)

        # Tilting (CL1) layer
        d_cl1 = (np.sin(shift - theta) * np.cos(theta_t) +
                 np.cos(shift - theta) * np.sin(theta_t) *
                 np.cos(phi - phi_t))
        gate = np.power(np.exp(-np.square(d_cl1) / (2. * np.square(sigma))), 1)
        w = -float(nb_tcl) / (2. * float(n)) * np.sin(phi_tcl[np.newaxis] - alpha[:, np.newaxis]) * gate[:, np.newaxis]
        r_tcl = r_pol.dot(w)

        R = r_tcl.dot(np.exp(-np.arange(nb_tcl) * (0. + 1.j) * 2. * np.pi / float(nb_tcl)))
        res = np.clip(3.5 * (np.absolute(R) - .53), 0, 2)  # certainty of prediction
        ele_pred = 26 * (1 - 2 * np.arcsin(1 - res) / np.pi) + 15
        d_phi += np.deg2rad(9 + np.exp(.1 * (54 - ele_pred))) / (60. / float(dt))

        return r_tcl, d_phi

    stats = {
        "max_alt": [],
        "noise": [],
        "opath": [],
        "ipath": [],
        "d_x": [],
        "d_c": [],
        "tau": []
    }

    avg_time = timedelta(0.)
    terrain = z_terrain.copy()
    for enable_ephemeris in [False, True]:
        if enable_ephemeris:
            print "Foraging with the time compensation mechanism."
        else:
            print "Foraging without the time compensation mechanism."

        # stats
        d_x = []  # logarithmic distance
        d_c = []
        tau = []  # tortuosity
        ri = 0

        print "Routes: ",
        for route in routes[::2]:
            net = CX(noise=0., pontin=False)
            net.update = True

            # sun position
            cur = datetime(2018, 6, 21, 10, 0, 0)
            seville_obs.date = cur
            sun.compute(seville_obs)
            theta_s = np.array([np.pi / 2 - sun.alt])
            phi_s = np.array([(sun.az + np.pi) % (2 * np.pi) - np.pi])

            sun_azi = []
            sun_ele = []
            time = []

            # outward route
            route.condition = Hybrid(tau_x=dx)
            oroute = route.reverse()
            x, y, yaw = [(x0, y0, yaw0) for x0, y0, _, yaw0 in oroute][0]
            opath = [[x, y, yaw]]

            v = np.zeros(2)
            tb1 = []
            d_phi = 0.

            for _, _, _, yaw in oroute:
                theta_n, phi_n = tilt(theta_t, phi_t, theta, phi + yaw)

                sun_ele.append(theta_s[0])
                sun_azi.append(phi_s[0])
                time.append(cur)
                sky.theta_s, sky.phi_s = theta_s, phi_s
                Y, P, A = sky(theta_n, phi_n, noise=noise)

                if enable_ephemeris:
                    r_tb1, d_phi = encode(theta, phi, Y, P, A, d_phi=d_phi)
                else:
                    r_tb1, d_phi = encode(theta, phi, Y, P, A, d_phi=0.)
                yaw0 = yaw
                _, yaw = np.pi - decode_sph(r_tb1) + phi_s

                net(yaw, flow)
                yaw = (yaw + np.pi) % (2 * np.pi) - np.pi
                v = np.array([np.sin(yaw), np.cos(yaw)]) * route.dx
                opath.append([opath[-1][0] + v[0], opath[-1][1] + v[1], yaw])
                tb1.append(net.tb1)

                cur += delta
                seville_obs.date = cur
                sun.compute(seville_obs)
                theta_s = np.array([np.pi / 2 - sun.alt])
                phi_s = np.array([(sun.az + np.pi) % (2 * np.pi) - np.pi])
            opath = np.array(opath)

            yaw -= phi_s

            # inward route
            ipath = [[opath[-1][0], opath[-1][1], opath[-1][2]]]
            L = 0.  # straight distance to the nest
            C = 0.  # distance towards the nest that the agent has covered
            SL = 0.
            TC = 0.
            tb1 = []
            tau.append([])
            d_x.append([])
            d_c.append([])

            while C < 15:
                theta_n, phi_n = tilt(theta_t, phi_t, theta, phi + yaw)

                sun_ele.append(theta_s[0])
                sun_azi.append(phi_s[0])
                time.append(cur)
                sky.theta_s, sky.phi_s = theta_s, phi_s
                Y, P, A = sky(theta_n, phi_n, noise=noise)

                if enable_ephemeris:
                    r_tb1, d_phi = encode(theta, phi, Y, P, A, d_phi=d_phi)
                else:
                    r_tb1, d_phi = encode(theta, phi, Y, P, A, d_phi=0.)
                _, yaw = np.pi - decode_sph(r_tb1) + phi_s
                motor = net(yaw, flow)
                yaw = (ipath[-1][2] + motor + np.pi) % (2 * np.pi) - np.pi
                v = np.array([np.sin(yaw), np.cos(yaw)]) * route.dx
                ipath.append([ipath[-1][0] + v[0], ipath[-1][1] + v[1], yaw])
                tb1.append(net.tb1)
                L = np.sqrt(np.square(opath[0][0] - ipath[-1][0]) + np.square(opath[0][1] - ipath[-1][1]))
                C += route.dx
                d_x[-1].append(L)
                d_c[-1].append(C)
                tau[-1].append(L / C)
                if C <= route.dx:
                    SL = L
                if TC == 0. and len(d_x[-1]) > 50 and d_x[-1][-1] > d_x[-1][-2]:
                    TC = C

                cur += delta
                seville_obs.date = cur
                sun.compute(seville_obs)
                theta_s = np.array([np.pi / 2 - sun.alt])
                phi_s = np.array([(sun.az + np.pi) % (2 * np.pi) - np.pi])

            ipath = np.array(ipath)
            d_x[-1] = np.array(d_x[-1]) / SL * 100
            d_c[-1] = np.array(d_c[-1]) / TC * 100
            tau[-1] = np.array(tau[-1])

            ri += 1

            avg_time += cur - datetime(2018, 6, 21, 10, 0, 0)

            stats["max_alt"].append(0.)
            stats["noise"].append(noise)
            stats["opath"].append(opath)
            stats["ipath"].append(ipath)
            stats["d_x"].append(d_x[-1])
            stats["d_c"].append(d_c[-1])
            stats["tau"].append(tau[-1])
            print ".",
        print ""
        print "average time:", avg_time / ri  # 1:16:40

    np.savez_compressed("data/pi-stats-ephem.npz", **stats)
예제 #8
0
def create_paths(noise_type="uniform"):
    global seville_obs, sun, dx

    # sensor design
    n = 60
    omega = 56
    theta, phi, fit = angles_distribution(n, float(omega))
    theta_t, phi_t = 0., 0.

    # sun position
    seville_obs.date = datetime(2018, 6, 21, 9, 0, 0)
    sun.compute(seville_obs)
    theta_s = np.array([np.pi / 2 - sun.alt])
    phi_s = np.array([(sun.az + np.pi) % (2 * np.pi) - np.pi])

    # ant-world
    noise = 0.0
    ttau = .06
    dx = 1e-02
    routes = load_routes()
    flow = dx * np.ones(2) / np.sqrt(2)
    max_theta = 0.

    stats = {
        "max_alt": [],
        "noise": [],
        "opath": [],
        "ipath": [],
        "d_x": [],
        "d_c": [],
        "tau": []
    }

    for max_altitude in [.0, .1, .2, .3, .4, .5]:
        for ni, noise in enumerate([0.0, 0.2, 0.4, 0.6, 0.8, .97]):

            # stats
            d_x = []  # logarithmic distance
            d_c = []
            tau = []  # tortuosity
            ri = 0

            for route in routes[::2]:
                dx = route.dx

                net = CX(noise=0., pontin=False)
                net.update = True

                # outward route
                route.condition = Hybrid(tau_x=dx)
                oroute = route.reverse()
                x, y, yaw = [(x0, y0, yaw0) for x0, y0, _, yaw0 in oroute][0]
                opath = [[x, y, yaw]]

                v = np.zeros(2)
                tb1 = []

                for _, _, _, yaw in oroute:
                    theta_t, phi_t = get_3d_direction(opath[-1][0], opath[-1][1], yaw, tau=ttau)
                    max_theta = max_theta if max_theta > np.absolute(theta_t) else np.absolute(theta_t)
                    theta_n, phi_n = tilt(theta_t, phi_t, theta, phi + yaw)

                    sky.theta_s, sky.phi_s = theta_s, phi_s
                    Y, P, A = sky(theta_n, phi_n, noise=get_noise(theta_n, phi_n, noise, mode=noise_type))

                    r_tb1 = encode(theta, phi, Y, P, A)
                    yaw0 = yaw
                    _, yaw = np.pi - decode_sph(r_tb1) + phi_s

                    net(yaw, flow)
                    yaw = (yaw + np.pi) % (2 * np.pi) - np.pi
                    v = np.array([np.sin(yaw), np.cos(yaw)]) * route.dx
                    opath.append([opath[-1][0] + v[0], opath[-1][1] + v[1], yaw])
                    tb1.append(net.tb1)
                opath = np.array(opath)

                yaw -= phi_s

                # inward route
                ipath = [[opath[-1][0], opath[-1][1], opath[-1][2]]]
                L = 0.  # straight distance to the nest
                C = 0.  # distance towards the nest that the agent has covered
                SL = 0.
                TC = 0.
                tb1 = []
                tau.append([])
                d_x.append([])
                d_c.append([])

                while C < 15:
                    theta_t, phi_t = get_3d_direction(ipath[-1][0], ipath[-1][1], yaw, tau=ttau)
                    theta_n, phi_n = tilt(theta_t, phi_t, theta, phi + yaw)

                    sky.theta_s, sky.phi_s = theta_s, phi_s
                    Y, P, A = sky(theta_n, phi_n, noise=noise)

                    r_tb1 = encode(theta, phi, Y, P, A)
                    _, yaw = np.pi - decode_sph(r_tb1) + phi_s
                    motor = net(yaw, flow)
                    yaw = (ipath[-1][2] + motor + np.pi) % (2 * np.pi) - np.pi
                    v = np.array([np.sin(yaw), np.cos(yaw)]) * route.dx
                    ipath.append([ipath[-1][0] + v[0], ipath[-1][1] + v[1], yaw])
                    tb1.append(net.tb1)
                    L = np.sqrt(np.square(opath[0][0] - ipath[-1][0]) + np.square(opath[0][1] - ipath[-1][1]))
                    C += route.dx
                    d_x[-1].append(L)
                    d_c[-1].append(C)
                    tau[-1].append(L / C)
                    if C <= route.dx:
                        SL = L
                    if TC == 0. and len(d_x[-1]) > 50 and d_x[-1][-1] > d_x[-1][-2]:
                        TC = C

                ipath = np.array(ipath)
                d_x[-1] = np.array(d_x[-1]) / SL * 100
                d_c[-1] = np.array(d_c[-1]) / TC * 100
                tau[-1] = np.array(tau[-1])

                ri += 1

                stats["max_alt"].append(max_altitude)
                stats["noise"].append(noise)
                stats["opath"].append(opath)
                stats["ipath"].append(ipath)
                stats["d_x"].append(d_x[-1])
                stats["d_c"].append(d_c[-1])
                stats["tau"].append(tau[-1])

    np.savez_compressed("../data/pi-stats-%s.npz" % noise_type, **stats)
예제 #9
0
            opath = [[x, y, yaw]]

            v = np.zeros(2)
            tb1 = []
            # print np.rad2deg(phi_s)

            # plt.figure("yaws")
            for _, _, _, yaw in oroute:
                if mode == "uneven":
                    theta_t, phi_t = get_3d_direction(opath[-1][0],
                                                      opath[-1][1],
                                                      yaw,
                                                      tau=ttau)
                    max_theta = max_theta if max_theta > np.absolute(
                        theta_t) else np.absolute(theta_t)
                theta_n, phi_n = tilt(theta_t, phi_t, theta, phi + yaw)

                sky.theta_s, sky.phi_s = theta_s, phi_s
                eta = get_noise(theta, phi, noise, noise_type)

                Y, P, A = sky(theta_n, phi_n, noise=eta)

                r_tb1 = encode(theta, phi, Y, P, A)
                yaw0 = yaw
                _, yaw = np.pi - decode_sph(r_tb1) + phi_s
                # plt.plot(yaw0 % (2*np.pi), yaw % (2*np.pi), 'k.')

                # motor = net(r_tb1, flow)
                net(yaw, flow)
                yaw = (yaw + np.pi) % (2 * np.pi) - np.pi
                v = np.array([np.sin(yaw), np.cos(yaw)]) * route.dx
예제 #10
0
def skyfeatures(noise=0., simple_pol=False, samples=1000, verbose=False):

    # default parameters
    tau_L = 2.
    c1 = .6
    c2 = 4.
    eps = np.finfo(float).eps
    AA, BB, CC, DD, EE = SensorObjective.T_L.dot(np.array(
        [tau_L, 1.]))  # sky parameters
    T_T = np.linalg.pinv(SensorObjective.T_L)
    tau_L, c = T_T.dot(np.array([AA, BB, CC, DD, EE]))
    tau_L /= c  # turbidity correction

    # Prez. et. al. Luminance function
    def L(cchi, zz):
        ii = zz < (np.pi / 2)
        ff = np.zeros_like(zz)
        if zz.ndim > 0:
            ff[ii] = (1. + AA * np.exp(BB / (np.cos(zz[ii]) + eps)))
        elif ii:
            ff = (1. + AA * np.exp(BB / (np.cos(zz) + eps)))
        pphi = (1. + CC * np.exp(DD * cchi) + EE * np.square(np.cos(cchi)))
        return ff * pphi

    theta_s, phi_s = np.array([np.pi / 6]), np.array([np.pi])

    theta, phi = fibonacci_sphere(samples, 180)
    phi = phi[theta <= np.pi / 2]
    theta = theta[theta <= np.pi / 2]
    samples = theta.size

    theta = (theta - np.pi) % (2 * np.pi) - np.pi
    phi = (phi + np.pi) % (2 * np.pi) - np.pi
    alpha = (phi + np.pi / 2) % (2 * np.pi) - np.pi

    # SKY INTEGRATION
    gamma = np.arccos(
        np.cos(theta) * np.cos(theta_s) +
        np.sin(theta) * np.sin(theta_s) * np.cos(phi - phi_s))
    # Intensity
    I_prez, I_00, I_90 = L(gamma, theta), L(0., theta_s), L(
        np.pi / 2, np.absolute(theta_s - np.pi / 2))
    # influence of sky intensity
    I = (1. / (I_prez + eps) - 1. /
         (I_00 + eps)) * I_00 * I_90 / (I_00 - I_90 + eps)
    chi = (4. / 9. - tau_L / 120.) * (np.pi - 2 * theta_s)
    Y_z = (4.0453 * tau_L - 4.9710) * np.tan(chi) - 0.2155 * tau_L + 2.4192
    Y = np.maximum(Y_z * I_prez / (I_00 + eps), 0.)  # Illumination

    # Degree of Polarisation
    M_p = np.exp(-(tau_L - c1) / (c2 + eps))
    LP = np.square(np.sin(gamma)) / (1 + np.square(np.cos(gamma)))
    if simple_pol:
        P = np.clip(2. / np.pi * M_p * LP, 0., 1.)
    else:
        P = np.clip(
            2. / np.pi * M_p * LP * (theta * np.cos(theta) +
                                     (np.pi / 2 - theta) * I), 0., 1.)

    # Angle of polarisation
    _, A = tilt(theta_s, phi_s + np.pi, theta, phi)

    # create cloud disturbance
    if type(noise) is np.ndarray:
        if noise.size == P.size:
            # print "yeah!"
            eta = np.array(noise, dtype=bool)
        else:
            eta = np.zeros_like(theta, dtype=bool)
            eta[:noise.size] = noise
    elif noise > 0:
        eta = np.argsort(np.absolute(
            np.random.randn(*P.shape)))[:int(noise * P.shape[0])]
        # eta = np.array(np.absolute(np.random.randn(*P.shape)) < noise, dtype=bool)
        if verbose:
            print "Noise level: %.4f (%.2f %%)" % (noise, 100. * eta.sum() /
                                                   float(eta.size))
    else:
        eta = np.zeros_like(theta, dtype=bool)
    P[eta] = 0.  # destroy the polarisation pattern
    Y[eta] = 10.

    return Y, P, A, theta, phi
예제 #11
0
def evaluate_old(
        n=60,
        omega=56,
        noise=0.,
        nb_cl1=16,
        sigma=np.deg2rad(13),
        shift=np.deg2rad(40),
        nb_tb1=8,
        use_default=False,
        weighted=True,
        fibonacci=False,
        simple_pol=False,
        uniform_poliriser=False,

        # single evaluation
        sun_azi=None,
        sun_ele=None,

        # data parameters
        tilting=True,
        samples=1000,
        show_plots=False,
        show_structure=False,
        verbose=False):

    # default parameters
    tau_L = 2.
    c1 = .6
    c2 = 4.
    eps = np.finfo(float).eps
    AA, BB, CC, DD, EE = T_L.dot(np.array([tau_L, 1.]))  # sky parameters
    T_T = np.linalg.pinv(T_L)
    tau_L, c = T_T.dot(np.array([AA, BB, CC, DD, EE]))
    tau_L /= c  # turbidity correction

    # Prez. et. al. Luminance function
    def L(cchi, zz):
        ii = zz < (np.pi / 2)
        ff = np.zeros_like(zz)
        if zz.ndim > 0:
            ff[ii] = (1. + AA * np.exp(BB / (np.cos(zz[ii]) + eps)))
        elif ii:
            ff = (1. + AA * np.exp(BB / (np.cos(zz) + eps)))
        pphi = (1. + CC * np.exp(DD * cchi) + EE * np.square(np.cos(cchi)))
        return ff * pphi

    if tilting:
        angles = np.array([[0., 0.], [np.pi / 6, 0.], [np.pi / 6, np.pi / 4],
                           [np.pi / 6, 2 * np.pi / 4],
                           [np.pi / 6, 3 * np.pi / 4],
                           [np.pi / 6, 4 * np.pi / 4],
                           [np.pi / 6, 5 * np.pi / 4],
                           [np.pi / 6, 6 * np.pi / 4],
                           [np.pi / 6, 7 * np.pi / 4], [np.pi / 3, 0.],
                           [np.pi / 3, np.pi / 4], [np.pi / 3, 2 * np.pi / 4],
                           [np.pi / 3, 3 * np.pi / 4],
                           [np.pi / 3, 4 * np.pi / 4],
                           [np.pi / 3, 5 * np.pi / 4],
                           [np.pi / 3, 6 * np.pi / 4],
                           [np.pi / 3, 7 * np.pi / 4]])  # 17
        if samples == 1000:
            samples /= 2
    else:
        angles = np.array([[0., 0.]])  # 1

    # generate the different sun positions
    if sun_azi is not None or sun_ele is not None:
        theta_s = sun_ele if type(sun_ele) is np.ndarray else np.array(
            [sun_ele])
        phi_s = sun_azi if type(sun_azi) is np.ndarray else np.array([sun_azi])
    else:
        theta_s, phi_s = fibonacci_sphere(samples=samples, fov=161)
        phi_s = phi_s[theta_s <= np.pi / 2]
        theta_s = theta_s[theta_s <= np.pi / 2]
    samples = theta_s.size

    # generate the properties of the sensor
    try:
        theta, phi, fit = angles_distribution(n, float(omega))
    except ValueError:
        theta = np.empty(0, dtype=np.float32)
        phi = np.empty(0, dtype=np.float32)
        fit = False

    if not fit or n > 100 or fibonacci:
        theta, phi = fibonacci_sphere(n, float(omega))
    # theta, phi, fit = angles_distribution(n, omega)
    # if not fit:
    #     print theta.shape, phi.shape
    theta = (theta - np.pi) % (2 * np.pi) - np.pi
    phi = (phi + np.pi) % (2 * np.pi) - np.pi
    alpha = (phi + np.pi / 2) % (2 * np.pi) - np.pi

    # computational model parameters
    phi_cl1 = np.linspace(0., 4 * np.pi, nb_cl1,
                          endpoint=False)  # CL1 preference angles
    phi_tb1 = np.linspace(0., 2 * np.pi, nb_tb1,
                          endpoint=False)  # TB1 preference angles

    # initialise lists for the statistical data
    d = np.zeros((samples, angles.shape[0]), dtype=np.float32)
    t = np.zeros_like(d)
    d_eff = np.zeros((samples, angles.shape[0]), dtype=np.float32)
    a_ret = np.zeros_like(t)
    tb1 = np.zeros((samples, angles.shape[0], nb_tb1), dtype=np.float32)

    # iterate through the different tilting angles
    for j, (theta_t, phi_t) in enumerate(angles):
        # transform relative coordinates
        theta_s_, phi_s_ = tilt(theta_t, phi_t, theta=theta_s, phi=phi_s)
        theta_, phi_ = tilt(theta_t, phi_t + np.pi, theta=theta, phi=phi)
        _, alpha_ = tilt(theta_t, phi_t + np.pi, theta=np.pi / 2, phi=alpha)

        for i, (e, a, e_org,
                a_org) in enumerate(zip(theta_s_, phi_s_, theta_s, phi_s)):

            # SKY INTEGRATION
            gamma = np.arccos(
                np.cos(theta_) * np.cos(e_org) +
                np.sin(theta_) * np.sin(e_org) * np.cos(phi_ - a_org))
            # Intensity
            I_prez, I_00, I_90 = L(gamma, theta_), L(0., e_org), L(
                np.pi / 2, np.absolute(e_org - np.pi / 2))
            # influence of sky intensity
            I = (1. / (I_prez + eps) - 1. /
                 (I_00 + eps)) * I_00 * I_90 / (I_00 - I_90 + eps)
            chi = (4. / 9. - tau_L / 120.) * (np.pi - 2 * e_org)
            Y_z = (4.0453 * tau_L -
                   4.9710) * np.tan(chi) - 0.2155 * tau_L + 2.4192
            if uniform_poliriser:
                Y = np.maximum(np.full_like(I_prez, Y_z), 0.)
            else:
                Y = np.maximum(Y_z * I_prez / (I_00 + eps), 0.)  # Illumination

            # Degree of Polarisation
            M_p = np.exp(-(tau_L - c1) / (c2 + eps))
            LP = np.square(np.sin(gamma)) / (1 + np.square(np.cos(gamma)))
            if uniform_poliriser:
                P = np.ones_like(LP)
            elif simple_pol:
                P = np.clip(2. / np.pi * M_p * LP, 0., 1.)
            else:
                P = np.clip(
                    2. / np.pi * M_p * LP * (theta_ * np.cos(theta_) +
                                             (np.pi / 2 - theta_) * I), 0., 1.)

            # Angle of polarisation
            if uniform_poliriser:
                A = np.full_like(P, a_org + np.pi)
            else:
                _, A = tilt(e_org, a_org + np.pi, theta_, phi_)

            # create cloud disturbance
            if noise > 0:
                eta = np.absolute(np.random.randn(*P.shape)) < noise
                if verbose:
                    print "Noise level: %.4f (%.2f %%)" % (
                        noise, 100. * eta.sum() / float(eta.size))
                P[eta] = 0.  # destroy the polarisation pattern
            else:
                eta = np.zeros(1)

            # COMPUTATIONAL MODEL

            # Input (POL) layer -- Photo-receptors
            s_1 = 15. * (np.square(np.sin(A - alpha_)) +
                         np.square(np.cos(A - alpha_)) * np.square(1. - P))
            s_2 = 15. * (np.square(np.cos(A - alpha_)) +
                         np.square(np.sin(A - alpha_)) * np.square(1. - P))
            r_1, r_2 = np.sqrt(s_1), np.sqrt(s_2)
            # r_1, r_2 = np.log(s_1 + 1.), np.log(s_2 + 1.)
            r_pol = (r_1 - r_2) / (r_1 + r_2 + eps)

            # Tilting (CL1) layer
            d_cl1 = (
                np.sin(shift - theta) * np.cos(theta_t) +
                np.cos(shift - theta) * np.sin(theta_t) * np.cos(phi - phi_t))
            gate = np.power(
                np.exp(-np.square(d_cl1) / (2. * np.square(sigma))), 1)
            w_cl1 = float(nb_cl1) / float(n) * np.sin(
                alpha[:, np.newaxis] - phi_cl1[np.newaxis]) * gate[:,
                                                                   np.newaxis]
            r_cl1 = r_pol.dot(w_cl1)

            # Output (TB1) layer
            w_tb1 = float(nb_tb1) / float(
                2 * nb_cl1) * np.cos(phi_tb1[np.newaxis] -
                                     phi_cl1[:, np.newaxis])

            r_tb1 = r_cl1.dot(w_tb1)

            if use_default:
                w = -float(nb_tb1) / (2. * float(n)) * np.sin(phi_tb1[
                    np.newaxis] - alpha[:, np.newaxis]) * gate[:, np.newaxis]
                r_tb1 = r_pol.dot(w)

            # decode response - FFT
            R = r_tb1.dot(
                np.exp(-np.arange(nb_tb1) * (0. + 1.j) * np.pi /
                       (float(nb_tb1) / 2.)))
            a_pred = (np.pi - np.arctan2(R.imag, R.real)) % (
                2. * np.pi) - np.pi  # sun azimuth (prediction)
            tau_pred = np.absolute(R)  # certainty of prediction

            d[i, j] = np.absolute(
                azidist(np.array([e, a]), np.array([0., a_pred])))
            t[i, j] = tau_pred if weighted else 1.
            a_ret[i, j] = a_pred
            tb1[i, j] = r_tb1

            # effective degree of polarisation
            M = r_cl1.max() - r_cl1.min()
            # M = t[i, j] * 2.
            p = np.power(10, M / 2.)
            d_eff[i, j] = np.mean((p - 1.) / (p + 1.))

            if show_plots:
                plt.figure("sensor-noise-%2d" %
                           (100. * eta.sum() / float(eta.size)),
                           figsize=(18, 4.5))

                ax = plt.subplot(1, 12, 10)
                plt.imshow(w_cl1, cmap="coolwarm", vmin=-1, vmax=1)
                plt.xlabel("CBL", fontsize=16)
                plt.xticks([0, 15], ["1", "16"])
                plt.yticks([0, 59], ["1", "60"])

                ax.tick_params(axis='both', which='major', labelsize=16)
                ax.tick_params(axis='both', which='minor', labelsize=16)

                ax = plt.subplot(1, 6, 6)  # , sharey=ax)
                plt.imshow(w_tb1, cmap="coolwarm", vmin=-1, vmax=1)
                plt.xlabel("TB1", fontsize=16)
                plt.xticks([0, 7], ["1", "8"])
                plt.yticks([0, 15], ["1", "16"])
                cbar = plt.colorbar(ticks=[-1, 0, 1])
                cbar.ax.set_yticklabels([r'$\leq$ -1', r'0', r'$\geq$ 1'])

                ax.tick_params(axis='both', which='major', labelsize=16)
                ax.tick_params(axis='both', which='minor', labelsize=16)

                ax = plt.subplot(1, 4, 1, polar=True)
                ax.scatter(phi,
                           theta,
                           s=150,
                           c=r_pol,
                           marker='o',
                           cmap="coolwarm",
                           vmin=-1,
                           vmax=1)
                ax.scatter(a,
                           e,
                           s=100,
                           marker='o',
                           edgecolor='black',
                           facecolor='yellow')
                ax.scatter(phi_t + np.pi,
                           theta_t,
                           s=200,
                           marker='o',
                           edgecolor='black',
                           facecolor='yellowgreen')
                ax.set_theta_zero_location("N")
                ax.set_theta_direction(-1)
                ax.set_ylim([0, np.deg2rad(40)])
                ax.set_yticks([])
                ax.set_xticks(
                    np.linspace(-3 * np.pi / 4,
                                5 * np.pi / 4,
                                8,
                                endpoint=False))
                ax.set_title("POL Response", fontsize=16)

                ax.tick_params(axis='both', which='major', labelsize=16)
                ax.tick_params(axis='both', which='minor', labelsize=16)

                ax = plt.subplot(1, 4, 2, polar=True)
                ax.scatter(phi,
                           theta,
                           s=150,
                           c=r_pol * gate,
                           marker='o',
                           cmap="coolwarm",
                           vmin=-1,
                           vmax=1)
                ax.scatter(a,
                           e,
                           s=100,
                           marker='o',
                           edgecolor='black',
                           facecolor='yellow')
                ax.scatter(phi_t + np.pi,
                           theta_t,
                           s=200,
                           marker='o',
                           edgecolor='black',
                           facecolor='yellowgreen')
                ax.set_theta_zero_location("N")
                ax.set_theta_direction(-1)
                ax.set_ylim([0, np.deg2rad(40)])
                ax.set_yticks([])
                ax.set_xticks(
                    np.linspace(-3 * np.pi / 4,
                                5 * np.pi / 4,
                                8,
                                endpoint=False))
                ax.set_title("Gated Response", fontsize=16)

                ax.tick_params(axis='both', which='major', labelsize=16)
                ax.tick_params(axis='both', which='minor', labelsize=16)

                ax = plt.subplot(1, 4, 3, polar=True)
                x = np.linspace(0, 2 * np.pi, 721)

                # CBL
                ax.fill_between(x,
                                np.full_like(x, np.deg2rad(60)),
                                np.full_like(x, np.deg2rad(90)),
                                facecolor="C1",
                                alpha=.5,
                                label="CBL")
                ax.scatter(phi_cl1[:nb_cl1 / 2] - np.pi / 24,
                           np.full(nb_cl1 / 2, np.deg2rad(75)),
                           s=600,
                           c=r_cl1[:nb_cl1 / 2],
                           marker='o',
                           edgecolor='red',
                           cmap="coolwarm",
                           vmin=-1,
                           vmax=1)
                ax.scatter(phi_cl1[nb_cl1 / 2:] + np.pi / 24,
                           np.full(nb_cl1 / 2, np.deg2rad(75)),
                           s=600,
                           c=r_cl1[nb_cl1 / 2:],
                           marker='o',
                           edgecolor='green',
                           cmap="coolwarm",
                           vmin=-1,
                           vmax=1)

                for ii, pp in enumerate(phi_cl1[:nb_cl1 / 2] - np.pi / 24):
                    ax.text(pp - np.pi / 20,
                            np.deg2rad(75),
                            "%d" % (ii + 1),
                            ha="center",
                            va="center",
                            size=10,
                            bbox=dict(boxstyle="circle", fc="w", ec="k"))
                for ii, pp in enumerate(phi_cl1[nb_cl1 / 2:] + np.pi / 24):
                    ax.text(pp + np.pi / 20,
                            np.deg2rad(75),
                            "%d" % (ii + 9),
                            ha="center",
                            va="center",
                            size=10,
                            bbox=dict(boxstyle="circle", fc="w", ec="k"))
                # TB1
                ax.fill_between(x,
                                np.full_like(x, np.deg2rad(30)),
                                np.full_like(x, np.deg2rad(60)),
                                facecolor="C2",
                                alpha=.5,
                                label="TB1")
                ax.scatter(phi_tb1,
                           np.full_like(phi_tb1, np.deg2rad(45)),
                           s=600,
                           c=r_tb1,
                           marker='o',
                           edgecolor='blue',
                           cmap="coolwarm",
                           vmin=-1,
                           vmax=1)
                for ii, pp in enumerate(phi_tb1):
                    ax.text(pp,
                            np.deg2rad(35),
                            "%d" % (ii + 1),
                            ha="center",
                            va="center",
                            size=10,
                            bbox=dict(boxstyle="circle", fc="w", ec="k"))
                    ax.arrow(pp,
                             np.deg2rad(35),
                             0,
                             np.deg2rad(10),
                             fc='k',
                             ec='k',
                             head_width=.1,
                             overhang=.3)

                # Sun position
                ax.scatter(a,
                           e,
                           s=500,
                           marker='o',
                           edgecolor='black',
                           facecolor='yellow')

                # Decoded TB1
                # ax.plot([0, a_pred], [0, e_pred], 'k--', lw=1)
                ax.plot([0, a_pred], [0, np.pi / 2], 'k--', lw=1)
                ax.arrow(a_pred,
                         0,
                         0,
                         np.deg2rad(20),
                         fc='k',
                         ec='k',
                         head_width=.3,
                         head_length=.2,
                         overhang=.3)

                ax.legend(ncol=2, loc=(-.55, -.1), fontsize=16)
                ax.set_theta_zero_location("N")
                ax.set_theta_direction(-1)
                ax.set_ylim([0, np.pi / 2])
                ax.set_yticks([])
                ax.set_xticks([])
                ax.set_title("Sensor Response", fontsize=16)

                plt.subplots_adjust(left=.02, bottom=.12, right=.98, top=.88)

                ax.tick_params(axis='both', which='major', labelsize=16)
                ax.tick_params(axis='both', which='minor', labelsize=16)

                plt.show()

    d_deg = np.rad2deg(d)

    if show_structure:
        plt.figure("sensor-structure", figsize=(4.5, 4.5))
        ax = plt.subplot(111, polar=True)
        ax.scatter(phi, theta, s=150, c="black", marker='o')
        ax.set_theta_zero_location("N")
        ax.set_theta_direction(-1)
        ax.set_ylim([0, np.deg2rad(50)])
        ax.set_yticks([])
        ax.set_xticks(
            np.linspace(-3 * np.pi / 4, 5 * np.pi / 4, 8, endpoint=False))
        ax.set_title("POL Response")
        plt.show()

    return d_deg, d_eff, t, a_ret, tb1
예제 #12
0
def evaluate_slow(
        n=60,
        omega=56,
        noise=0.,
        nb_cl1=8,
        sigma_pol=np.deg2rad(13),
        shift_pol=np.deg2rad(40),
        nb_tb1=8,
        sigma_sol=np.deg2rad(13),
        shift_sol=np.deg2rad(40),
        use_default=False,
        weighted=True,
        fibonacci=False,
        uniform_polariser=False,

        # single evaluation
        sun_azi=None,
        sun_ele=None,

        # data parameters
        tilting=True,
        samples=1000,
        show_plots=False,
        show_structure=False,
        verbose=False):

    if tilting:
        angles = np.array([[0., 0.], [np.pi / 6, 0.], [np.pi / 6, np.pi / 4],
                           [np.pi / 6, 2 * np.pi / 4],
                           [np.pi / 6, 3 * np.pi / 4],
                           [np.pi / 6, 4 * np.pi / 4],
                           [np.pi / 6, 5 * np.pi / 4],
                           [np.pi / 6, 6 * np.pi / 4],
                           [np.pi / 6, 7 * np.pi / 4], [np.pi / 3, 0.],
                           [np.pi / 3, np.pi / 4], [np.pi / 3, 2 * np.pi / 4],
                           [np.pi / 3, 3 * np.pi / 4],
                           [np.pi / 3, 4 * np.pi / 4],
                           [np.pi / 3, 5 * np.pi / 4],
                           [np.pi / 3, 6 * np.pi / 4],
                           [np.pi / 3, 7 * np.pi / 4]])  # 17
        if samples == 1000:
            samples /= 2
    else:
        angles = np.array([[0., 0.]])  # 1

    # generate the different sun positions
    if sun_azi is not None or sun_ele is not None:
        theta_s = sun_ele if type(sun_ele) is np.ndarray else np.array(
            [sun_ele])
        phi_s = sun_azi if type(sun_azi) is np.ndarray else np.array([sun_azi])
    else:
        theta_s, phi_s = fibonacci_sphere(samples=samples, fov=161)
        phi_s = phi_s[theta_s <= np.pi / 2]
        theta_s = theta_s[theta_s <= np.pi / 2]
    samples = theta_s.size

    # generate the properties of the sensor
    try:
        theta, phi, fit = angles_distribution(n, float(omega))
    except ValueError:
        theta = np.empty(0, dtype=np.float32)
        phi = np.empty(0, dtype=np.float32)
        fit = False

    if not fit or n > 100 or fibonacci:
        theta, phi = fibonacci_sphere(n, float(omega))
    # theta, phi, fit = angles_distribution(n, omega)
    # if not fit:
    #     print theta.shape, phi.shape
    theta = (theta - np.pi) % (2 * np.pi) - np.pi
    phi = (phi + np.pi) % (2 * np.pi) - np.pi
    alpha = (phi + np.pi / 2) % (2 * np.pi) - np.pi

    # computational model parameters
    phi_cl1 = np.linspace(0., 2 * np.pi, nb_cl1,
                          endpoint=False)  # CL1 preference angles
    phi_tb1 = np.linspace(0., 2 * np.pi, nb_tb1,
                          endpoint=False)  # TB1 preference angles

    # initialise lists for the statistical data
    d = np.zeros((samples, angles.shape[0]), dtype=np.float32)
    t = np.zeros_like(d)
    d_eff = np.zeros((samples, angles.shape[0]), dtype=np.float32)
    a_ret = np.zeros_like(t)
    tb1 = np.zeros((samples, angles.shape[0], nb_tb1), dtype=np.float32)

    # iterate through the different tilting angles
    for j, (theta_t, phi_t) in enumerate(angles):
        # transform relative coordinates
        theta_s_, phi_s_ = tilt(theta_t, phi_t, theta=theta_s, phi=phi_s)
        _, alpha_ = tilt(theta_t, phi_t + np.pi, theta=np.pi / 2, phi=alpha)

        for i, (e, a, e_org,
                a_org) in enumerate(zip(theta_s_, phi_s_, theta_s, phi_s)):

            sky = Sky(theta_s=e_org, phi_s=a_org, theta_t=theta_t, phi_t=phi_t)
            sky.verbose = verbose

            # COMPUTATIONAL MODEL

            # Input (POL) layer -- Photo-receptors

            dra = POLCompassDRA(n=n, omega=omega)
            dra.theta_t = theta_t
            dra.phi_t = phi_t
            r_pol = dra(sky, noise=noise, uniform_polariser=uniform_polariser)
            r_sol = dra.r_po

            # Tilting (SOL) layer
            d_pol = (np.sin(shift_pol - theta) * np.cos(theta_t) +
                     np.cos(shift_pol - theta) * np.sin(theta_t) *
                     np.cos(phi - phi_t))
            gate_pol = np.power(
                np.exp(-np.square(d_pol) / (2. * np.square(sigma_pol))), 1)
            z_pol = -float(nb_cl1) / float(n)
            w_cl1_pol = z_pol * np.sin(phi_cl1[
                np.newaxis] - alpha[:, np.newaxis]) * gate_pol[:, np.newaxis]

            d_sol = (np.sin(shift_sol - theta) * np.cos(theta_t) +
                     np.cos(shift_sol - theta) * np.sin(theta_t) *
                     np.cos(phi - phi_t))
            gate_sol = np.power(
                np.exp(-np.square(d_sol) / (2. * np.square(sigma_sol))), 1)
            z_sol = float(nb_cl1) / float(n)
            w_cl1_sol = z_sol * np.sin(phi_cl1[
                np.newaxis] - alpha[:, np.newaxis]) * gate_sol[:, np.newaxis]

            o = 1. / 64.
            f_pol, f_sol = .5 * np.power(2 * theta_t / np.pi, o), .5 * (
                1 - np.power(2 * theta_t / np.pi, o))
            r_cl1_pol = r_pol.dot(w_cl1_pol)
            r_cl1_sol = r_sol.dot(w_cl1_sol)
            r_cl1 = f_pol * r_cl1_pol + f_sol * r_cl1_sol
            # r_cl1 = r_cl1_sol

            # Output (TCL) layer
            # w_tb1 = np.eye(nb_tb1)
            w_tb1 = float(nb_tb1) / float(nb_cl1) * np.cos(
                phi_tb1[np.newaxis] - phi_cl1[:, np.newaxis])

            r_tb1 = r_cl1.dot(w_tb1)

            if use_default:
                w = -float(nb_tb1) / (2. * float(n)) * np.sin(
                    phi_tb1[np.newaxis] -
                    alpha[:, np.newaxis]) * gate_pol[:, np.newaxis]
                r_tb1 = r_pol.dot(w)

            # decode response - FFT
            R = r_tb1.dot(
                np.exp(-np.arange(nb_tb1) * (0. + 1.j) * np.pi /
                       (float(nb_tb1) / 2.)))
            a_pred = (np.pi - np.arctan2(R.imag, R.real)) % (
                2. * np.pi) - np.pi  # sun azimuth (prediction)
            tau_pred = np.maximum(np.absolute(R), 0)  # certainty of prediction

            d[i, j] = np.absolute(
                azidist(np.array([e, a]), np.array([0., a_pred])))
            t[i, j] = tau_pred if weighted else 1.
            a_ret[i, j] = a_pred
            tb1[i, j] = r_tb1

            # effective degree of polarisation
            M = r_cl1.max() - r_cl1.min()
            # M = t[i, j] * 2.
            p = np.power(10, M / 2.)
            d_eff[i, j] = np.mean((p - 1.) / (p + 1.))

            if show_plots:
                plt.figure("sensor-noise-%2d" %
                           (100. * sky.eta.sum() / float(sky.eta.size)),
                           figsize=(18, 4.5))

                ax = plt.subplot(1, 12, 10)
                plt.imshow(w_cl1_pol, cmap="coolwarm", vmin=-1, vmax=1)
                plt.xlabel("CBL", fontsize=16)
                plt.xticks([0, 15], ["1", "16"])
                plt.yticks([0, 59], ["1", "60"])

                ax.tick_params(axis='both', which='major', labelsize=16)
                ax.tick_params(axis='both', which='minor', labelsize=16)

                ax = plt.subplot(1, 6, 6)  # , sharey=ax)
                plt.imshow(w_tb1, cmap="coolwarm", vmin=-1, vmax=1)
                plt.xlabel("TB1", fontsize=16)
                plt.xticks([0, 7], ["1", "8"])
                plt.yticks([0, 15], ["1", "16"])
                cbar = plt.colorbar(ticks=[-1, 0, 1])
                cbar.ax.set_yticklabels([r'$\leq$ -1', r'0', r'$\geq$ 1'])

                ax.tick_params(axis='both', which='major', labelsize=16)
                ax.tick_params(axis='both', which='minor', labelsize=16)

                ax = plt.subplot(1, 4, 1, polar=True)
                ax.scatter(phi,
                           theta,
                           s=150,
                           c=r_pol,
                           marker='o',
                           cmap="coolwarm",
                           vmin=-1,
                           vmax=1)
                ax.scatter(a,
                           e,
                           s=100,
                           marker='o',
                           edgecolor='black',
                           facecolor='yellow')
                ax.scatter(phi_t + np.pi,
                           theta_t,
                           s=200,
                           marker='o',
                           edgecolor='black',
                           facecolor='yellowgreen')
                ax.set_theta_zero_location("N")
                ax.set_theta_direction(-1)
                ax.set_ylim([0, np.deg2rad(40)])
                ax.set_yticks([])
                ax.set_xticks(np.linspace(0, 2 * np.pi, 8, endpoint=False))
                ax.set_xticklabels([
                    r'$0^\circ$', r'$45^\circ$', r'$90^\circ$', r'$135^\circ$',
                    r'$180^\circ$', r'$-135^\circ$', r'$-90^\circ$',
                    r'$-45^\circ$'
                ])
                ax.set_title("POL Response", fontsize=16)

                ax.tick_params(axis='both', which='major', labelsize=16)
                ax.tick_params(axis='both', which='minor', labelsize=16)

                ax = plt.subplot(1, 4, 2, polar=True)
                ax.scatter(phi,
                           theta,
                           s=150,
                           c=r_pol * gate_pol,
                           marker='o',
                           cmap="coolwarm",
                           vmin=-1,
                           vmax=1)
                ax.scatter(a,
                           e,
                           s=100,
                           marker='o',
                           edgecolor='black',
                           facecolor='yellow')
                ax.scatter(phi_t + np.pi,
                           theta_t,
                           s=200,
                           marker='o',
                           edgecolor='black',
                           facecolor='yellowgreen')
                ax.set_theta_zero_location("N")
                ax.set_theta_direction(-1)
                ax.set_ylim([0, np.deg2rad(40)])
                ax.set_yticks([])
                ax.set_xticks(np.linspace(0, 2 * np.pi, 8, endpoint=False))
                ax.set_xticklabels([
                    r'$0^\circ$', r'$45^\circ$', r'$90^\circ$', r'$135^\circ$',
                    r'$180^\circ$', r'$-135^\circ$', r'$-90^\circ$',
                    r'$-45^\circ$'
                ])
                ax.set_title("Gated Response", fontsize=16)

                ax.tick_params(axis='both', which='major', labelsize=16)
                ax.tick_params(axis='both', which='minor', labelsize=16)

                ax = plt.subplot(1, 4, 3, polar=True)
                x = np.linspace(0, 2 * np.pi, 721)

                # CBL
                ax.fill_between(x,
                                np.full_like(x, np.deg2rad(60)),
                                np.full_like(x, np.deg2rad(90)),
                                facecolor="C1",
                                alpha=.5,
                                label="CBL")
                ax.scatter(phi_cl1[:nb_cl1 / 2] - np.pi / 24,
                           np.full(nb_cl1 / 2, np.deg2rad(75)),
                           s=600,
                           c=r_cl1[:nb_cl1 / 2],
                           marker='o',
                           edgecolor='red',
                           cmap="coolwarm",
                           vmin=-1,
                           vmax=1)
                ax.scatter(phi_cl1[nb_cl1 / 2:] + np.pi / 24,
                           np.full(nb_cl1 / 2, np.deg2rad(75)),
                           s=600,
                           c=r_cl1[nb_cl1 / 2:],
                           marker='o',
                           edgecolor='green',
                           cmap="coolwarm",
                           vmin=-1,
                           vmax=1)

                for ii, pp in enumerate(phi_cl1[:nb_cl1 / 2] - np.pi / 24):
                    ax.text(pp - np.pi / 20,
                            np.deg2rad(75),
                            "%d" % (ii + 1),
                            ha="center",
                            va="center",
                            size=10,
                            bbox=dict(boxstyle="circle", fc="w", ec="k"))
                for ii, pp in enumerate(phi_cl1[nb_cl1 / 2:] + np.pi / 24):
                    ax.text(pp + np.pi / 20,
                            np.deg2rad(75),
                            "%d" % (ii + 9),
                            ha="center",
                            va="center",
                            size=10,
                            bbox=dict(boxstyle="circle", fc="w", ec="k"))
                # TB1
                ax.fill_between(x,
                                np.full_like(x, np.deg2rad(30)),
                                np.full_like(x, np.deg2rad(60)),
                                facecolor="C2",
                                alpha=.5,
                                label="TB1")
                ax.scatter(phi_tb1,
                           np.full_like(phi_tb1, np.deg2rad(45)),
                           s=600,
                           c=r_tb1,
                           marker='o',
                           edgecolor='blue',
                           cmap="coolwarm",
                           vmin=-1,
                           vmax=1)
                for ii, pp in enumerate(phi_tb1):
                    ax.text(pp,
                            np.deg2rad(35),
                            "%d" % (ii + 1),
                            ha="center",
                            va="center",
                            size=10,
                            bbox=dict(boxstyle="circle", fc="w", ec="k"))
                    ax.arrow(pp,
                             np.deg2rad(35),
                             0,
                             np.deg2rad(10),
                             fc='k',
                             ec='k',
                             head_width=.1,
                             overhang=.3)

                # Sun position
                ax.scatter(a,
                           e,
                           s=500,
                           marker='o',
                           edgecolor='black',
                           facecolor='yellow')

                # Decoded TB1
                # ax.plot([0, a_pred], [0, e_pred], 'k--', lw=1)
                ax.plot([0, a_pred], [0, np.pi / 2], 'k--', lw=1)
                ax.arrow(a_pred,
                         0,
                         0,
                         np.deg2rad(20),
                         fc='k',
                         ec='k',
                         head_width=.3,
                         head_length=.2,
                         overhang=.3)

                ax.legend(ncol=2, loc=(-.55, -.1), fontsize=16)
                ax.set_theta_zero_location("N")
                ax.set_theta_direction(-1)
                ax.set_ylim([0, np.pi / 2])
                ax.set_yticks([])
                ax.set_xticks([])
                ax.set_title("Sensor Response", fontsize=16)

                plt.subplots_adjust(left=.02, bottom=.12, right=.98, top=.88)

                ax.tick_params(axis='both', which='major', labelsize=16)
                ax.tick_params(axis='both', which='minor', labelsize=16)

                plt.show()

    d_deg = np.rad2deg(d)

    if show_structure:
        plt.figure("sensor-structure", figsize=(4.5, 4.5))
        ax = plt.subplot(111, polar=True)
        ax.scatter(phi, theta, s=150, c="black", marker='o')
        ax.set_theta_zero_location("N")
        ax.set_theta_direction(-1)
        ax.set_ylim([0, np.deg2rad(50)])
        ax.set_yticks([])
        ax.set_xticks(
            np.linspace(-3 * np.pi / 4, 5 * np.pi / 4, 8, endpoint=False))
        ax.set_title("POL Response")
        plt.show()

    return d_deg, d_eff, t, a_ret, tb1