Пример #1
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)
Пример #2
0
from compoundeye.geometry import angles_distribution
from comp_model_plots import evaluate

import matplotlib.pyplot as plt
import numpy as np

if __name__ == "__main__":
    tilt = False
    samples = 1000
    nb_noise = 1
    max_noise = 1

    theta, phi, fit = angles_distribution(60, 60)
    alpha = (phi - np.pi / 2) % (2 * np.pi) - np.pi
    noises = np.linspace(0, max_noise, int(max_noise * 2) + 1, endpoint=True)

    costs, d_effs, eles = [], [], []
    x = []
    for noise in noises:
        costs.append([])
        d_effs.append([])
        eles.append([])
        x.append([])
        for _ in xrange(nb_noise):
            n = np.absolute(np.random.randn(*theta.shape)) < noise
            cloud = 100. * n.sum() / np.float32(n.size)
            x[-1].append(cloud)
            d_err, d_eff, tau = evaluate(noise=noise, tilting=False)
            costs[-1].append(d_err)
            d_effs[-1].append(d_eff)
            eles[-1].append(tau.flatten())
Пример #3
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)
Пример #4
0
    _, _, vh = np.linalg.svd(points - points.mean(axis=0))
    # unitary normal vector
    u = vh.conj().transpose()[:, -1]
    p = sph2vec(np.pi / 2, yaw, zenith=True)
    pp = p - p.dot(u) / np.square(np.linalg.norm(u)) * u
    theta_p, phi_p, _ = vec2sph(pp, zenith=True)
    return theta_p - np.pi / 2, phi_p - yaw


if __name__ == "__main__":
    from notebooks.plots import plot_sky

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

    # sun position
    seville = ephem.Observer()
    seville.lat = '37.392509'
    seville.lon = '-5.983877'
    seville.date = datetime(2018, 6, 21, 9, 0, 0)
    sun = ephem.Sun()
    sun.compute(seville)
    theta_s = np.array([np.pi / 2 - sun.alt])
    phi_s = np.array([(sun.az + np.pi) % (2 * np.pi) - np.pi])

    theta_sky, phi_sky = fibonacci_sphere(1000, 180)

    # ant-world
Пример #5
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
Пример #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
def noise_test(save=None, mode=0, repeats=10, **kwargs):
    from sphere.transform import sph2vec

    print "Running noise test:", kwargs
    modes = ['normal', 'corridor', 'side']
    print "Mode:", modes[mode]

    plt.figure("noise-%s" % modes[mode], figsize=(5, 5))
    n, omega = 60, 56
    etas = np.linspace(0, 1, 21)
    taus = np.zeros_like(etas)
    means = np.zeros_like(etas)
    ses = np.zeros_like(etas)
    for i in xrange(10):
        noise = np.ones(n, int)
        if mode > 0:
            theta, phi, fit = angles_distribution(n, float(omega))
            x, _, _ = sph2vec(theta, phi)
        else:
            x = np.argsort(np.absolute(np.random.randn(n)))
        for ii, eta in enumerate(etas):
            if mode == 0:
                noise[:] = 0
                noise[x[:int(eta * float(n))]] = 1
            else:
                noise[:] = 0
                if mode > 1:
                    noise[x > (1 - 2 * eta)] = 1
                else:
                    noise[np.abs(x) > (1 - eta)] = 1
            d_err, d_eff, tau, _, _ = evaluate(n=n,
                                               omega=omega,
                                               noise=noise,
                                               verbose=False,
                                               tilting=True,
                                               **kwargs)
            means[ii] = (means[ii] * i + d_err.mean()) / (i + 1)
            ses[ii] = (ses[ii] * i + d_err.std() / np.sqrt(d_err.size)) / (i +
                                                                           1)
            taus[ii] = (taus[ii] * i + tau.mean()) / (i + 1)

            print "Noise level: %.2f (%03d) | Mean cost: %.2f +/- %.4f" % (
                eta, np.sum(noise), means[ii], ses[ii])

    plt.fill_between(etas * 100, means - ses, means + ses, facecolor="grey")
    plt.plot(etas * 100, means, color="red", linestyle="-", label="tilting")
    plt.plot(etas * 100,
             taus * 45,
             color="red",
             linestyle="--",
             label="tau-tilting")

    taus = np.zeros_like(etas)
    means = np.zeros_like(etas)
    ses = np.zeros_like(etas)
    for i in xrange(repeats):
        noise = np.ones(n, int)
        if mode > 0:
            theta, phi, fit = angles_distribution(n, float(omega))
            x, _, _ = sph2vec(theta, phi)
        else:
            x = np.argsort(np.absolute(np.random.randn(n)))
        for ii, eta in enumerate(etas):
            if mode == 0:
                noise[:] = 0
                noise[x[:int(eta * float(n))]] = 1
            else:
                noise[:] = 0
                if mode > 1:
                    noise[x > (1 - 2 * eta)] = 1
                else:
                    noise[np.abs(x) > (1 - eta)] = 1
            d_err, d_eff, tau, _, _ = evaluate(n=n,
                                               omega=omega,
                                               noise=noise,
                                               verbose=False,
                                               tilting=False,
                                               **kwargs)
            means[ii] = (means[ii] * i + d_err.mean()) / (i + 1)
            ses[ii] = (ses[ii] * i + d_err.std() / np.sqrt(d_err.size)) / (i +
                                                                           1)
            taus[ii] = (taus[ii] * i + tau.mean()) / (i + 1)
            print "Noise level: %.2f (%03d) | Mean cost: %.2f +/- %.4f" % (
                eta, np.sum(noise), means[ii], ses[ii])

    plt.fill_between(etas * 100,
                     means - ses,
                     means + ses,
                     facecolor="grey",
                     alpha=.5)
    plt.plot(etas * 100, means, color="black", linestyle="-", label="plane")
    plt.plot(etas * 100,
             taus * 45,
             color="black",
             linestyle="--",
             label="tau-plane")

    plt.ylim([0, 90])
    plt.yticks([0, 30, 60, 90], [r'%d$^\circ$' % o for o in [0, 30, 60, 90]])
    plt.xlim([0, 100])
    plt.xlabel(r'noise ($\eta$)')
    plt.ylabel("MAE ($^\circ$)")
    # plt.legend()

    if save:
        plt.savefig(save)

    plt.show()
Пример #8
0
def noise_test(save=None, mode=0, repeats=10, **kwargs):
    from sphere.transform import sph2vec

    print "Running noise test:", kwargs
    modes = ['uniform', 'corridor', 'canopy']
    print "Mode:", modes[mode]

    plt.figure("noise-%s" % modes[mode], figsize=(4, 3))
    n, omega = 60, 56
    etas = np.linspace(0, 1, 21)
    taus = np.zeros_like(etas)
    means = np.zeros_like(etas)
    ses = np.zeros_like(etas)
    data = []
    theta, phi, fit = angles_distribution(n, float(omega))
    for i in xrange(repeats):
        for ii, eta in enumerate(etas):
            noise = get_noise(theta, phi, eta, mode=modes[mode])
            d_err, d_eff, tau, _, _ = evaluate(n=n,
                                               omega=omega,
                                               noise=noise,
                                               verbose=False,
                                               tilting=True,
                                               **kwargs)
            data.append([tau, d_err])
            means[ii] = (means[ii] * i + d_err.mean()) / (i + 1)
            ses[ii] = (ses[ii] * i + d_err.std() / np.sqrt(d_err.size)) / (i +
                                                                           1)
            taus[ii] = (taus[ii] * i + tau.mean()) / (i + 1)

            print "Noise level: %.2f (%03d) | Mean cost: %.2f +/- %.4f | tau: %.2f --> sigma: %2f" % (
                eta, np.sum(noise), means[ii], ses[ii], taus[ii],
                6. / taus[ii] + 6)

        np.savez_compressed("../data/noise-%s.npz" % modes[mode],
                            x=np.array(data)[:, 0],
                            y=np.array(data)[:, 1])

    sigmas = 6. / taus + 6.
    plt.fill_between(etas * 100, means - ses, means + ses, facecolor="grey")
    plt.plot(etas * 100, means, color="red", linestyle="-", label="tilting")
    plt.plot(etas * 100,
             taus * 45,
             color="red",
             linestyle="--",
             label="tau-tilting")
    plt.plot(etas * 100,
             sigmas,
             color="red",
             linestyle="--",
             label="sigma-tilting")

    taus = np.zeros_like(etas)
    means = np.zeros_like(etas)
    ses = np.zeros_like(etas)
    for i in xrange(repeats):
        for ii, eta in enumerate(etas):
            noise = get_noise(theta, phi, eta, mode=modes[mode])
            d_err, d_eff, tau, _, _ = evaluate(n=n,
                                               omega=omega,
                                               noise=noise,
                                               verbose=False,
                                               tilting=False,
                                               **kwargs)
            data.append([tau, d_err])
            means[ii] = (means[ii] * i + d_err.mean()) / (i + 1)
            ses[ii] = (ses[ii] * i + d_err.std() / np.sqrt(d_err.size)) / (i +
                                                                           1)
            taus[ii] = (taus[ii] * i + tau.mean()) / (i + 1)
            print "Noise level: %.2f (%03d) | Mean cost: %.2f +/- %.4f | tau: %.2f --> sigma: %2f" % (
                eta, np.sum(noise), means[ii], ses[ii], taus[ii],
                4. / taus[ii] + 2)

        np.savez_compressed("../data/noise-%s.npz" % modes[mode],
                            x=np.array(data)[:, 0],
                            y=np.array(data)[:, 1])

    sigmas = 4. / taus - 2.
    plt.fill_between(etas * 100,
                     means - ses,
                     means + ses,
                     facecolor="grey",
                     alpha=.5)
    plt.plot(etas * 100, means, color="black", linestyle="-", label="plane")
    plt.plot(etas * 100,
             taus * 45,
             color="black",
             linestyle="--",
             label="tau-plane")
    plt.plot(etas * 100,
             sigmas,
             color="black",
             linestyle="--",
             label="sigma-plane")

    plt.ylim([0, 90])
    plt.yticks([0, 30, 60, 90], [r'%d$^\circ$' % o for o in [0, 30, 60, 90]])
    plt.xlim([0, 100])
    plt.xlabel(r'noise ($\eta$)')
    plt.ylabel("MAE ($^\circ$)")
    # plt.legend()

    if save:
        plt.savefig(save)

    plt.show()