예제 #1
0
from environment import Sky
from compoundeye.geometry import angles_distribution, fibonacci_sphere
from code.compass import decode_sph
from sphere.transform import sph2vec, vec2sph, tilt
from net import CX
from notebooks.results import get_noise

from datetime import datetime
import ephem
import numpy as np
import matplotlib.pyplot as plt

eps = np.finfo(float).eps

# create sky
sky = Sky()

# create random terrain
x_terrain = np.linspace(0, 10, 1001, endpoint=True)
y_terrain = np.linspace(0, 10, 1001, endpoint=True)
x_terrain, y_terrain = np.meshgrid(x_terrain, y_terrain)
try:
    z_terrain = np.load("terrain-%.2f.npz" % 0.6)["terrain"] * 1000 * .5
except IOError:
    z_terrain = np.random.randn(*x_terrain.shape) / 50

print z_terrain.max(), z_terrain.min()


def encode(theta,
           phi,
예제 #2
0
from environment import Sun, Sky, eps, get_seville_observer
from world import load_routes, Hybrid
from sphere.transform import sph2vec, vec2sph, tilt
from code.compass import decode_sph
from net import CX

from datetime import datetime, timedelta
import numpy as np

x_terrain = np.linspace(0, 10, 1001, endpoint=True)
y_terrain = np.linspace(0, 10, 1001, endpoint=True)
x_terrain, y_terrain = np.meshgrid(x_terrain, y_terrain)
z_terrain = np.zeros_like(x_terrain)

seville_obs = get_seville_observer()
sky = Sky()
sun = Sun()
dx = .05


def get_terrain(max_altitude=.5, tau=.6, x=None, y=None):
    global z_terrain

    # create terrain
    if x is None or y is None:
        x, y = np.meshgrid(x_terrain, y_terrain)
    try:
        z = np.load("../data/terrain-%.2f.npz" % 0.6)["terrain"] * 1000 * max_altitude
    except IOError:
        z = np.random.randn(*x.shape) / 50
        terrain = np.zeros_like(z)
예제 #3
0
    P[eta] = 0.  # destroy the polarisation pattern
    Y[eta] = 10.

    return Y, P, A, theta, phi


if __name__ == "__main__":
    from compoundeye import POLCompassDRA
    from environment import Sky

    samples = 1000
    noise = .0
    # noise = .99

    theta, phi = fibonacci_sphere(samples, 180)
    sky = Sky(np.pi / 6, np.pi)
    y, p, a = sky(theta, phi)
    # y, p, a, theta, phi = skyfeatures(noise, samples=50000)
    # dra = POLCompassDRA()
    # r = dra(sky, noise=noise)
    #
    # print r.shape
    # print r
    #
    # plt.figure("pol-%02d" % (10 * noise), figsize=(3, 3))
    # ax = plt.subplot(111, polar=True)
    # ax.scatter(dra.phi, dra.theta, s=100, marker='.', c=r, cmap="coolwarm", vmin=-.1, vmax=.1)
    # ax.set_theta_zero_location("N")
    # ax.set_theta_direction(-1)
    # ax.set_ylim([0, np.deg2rad(30)])
    # plt.yticks([])
예제 #4
0
from model import DRA, spectrum

import numpy as np


class POLCompassDRA(DRA):
    def __init__(self, n=60, omega=56, rho=5.4, nb_pr=2):
        super(POLCompassDRA, self).__init__(n=n,
                                            omega=omega,
                                            rho=rho,
                                            nb_pr=nb_pr,
                                            name="pol")
        self.rhabdom = np.array([[spectrum["uv"], spectrum["uv"]]] * n).T
        self.mic_l = np.array([[0., np.pi / 2]] * n).T


if __name__ == "__main__":
    from environment import Sky
    from model import visualise

    sky = Sky(theta_s=np.pi / 3)
    dra = POLCompassDRA()
    dra.theta_t = np.pi / 6
    dra.phi_t = np.pi / 3
    # s = dra(sky)
    r_pol = dra(sky)
    r_po = dra.r_po
    # print s.shape

    visualise(sky, r_po)
예제 #5
0
 def add_sky(self):
     print "Here's the sky!"
     sky = Sky(base)
     return "Sky"
예제 #6
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
예제 #7
0
from world import load_routes, Hybrid
from environment import Sky
from compoundeye.geometry import angles_distribution
from code.compass import decode_sph
from sphere.transform import sph2vec, vec2sph, tilt
from net import CX

from datetime import datetime
import ephem
import numpy as np
import matplotlib.pyplot as plt

eps = np.finfo(float).eps

# create sky
sky = Sky()

# create random terrain
x_terrain = np.linspace(0, 10, 1001, endpoint=True)
y_terrain = np.linspace(0, 10, 1001, endpoint=True)
x_terrain, y_terrain = np.meshgrid(x_terrain, y_terrain)
try:
    z_terrain = np.load("terrain-%.2f.npz" % 0.6)["terrain"] * 100
except IOError:
    z_terrain = np.random.randn(*x_terrain.shape) / 50

print z_terrain.max(), z_terrain.min()


def encode(theta, phi, Y, P, A, theta_t=0., phi_t=0., nb_tb1=8, sigma=np.deg2rad(13), shift=np.deg2rad(40)):
    alpha = (phi + np.pi/2) % (2 * np.pi) - np.pi