Esempio n. 1
0
def main():
    # loop over all experiments
    for expt in session.query(models.Experiment):

        print("In experiment '{}'".format(expt.id))

        dt = 1 / expt.sampling_frequency

        for traj in session.query(
                models.Trajectory).filter_by(experiment=expt):

            positions = traj.positions(session)
            velocities = traj.velocities(session)

            # calculate kinematic quantities
            velocities_a = kinematics.norm(velocities)

            accelerations = kinematics.acceleration(velocities, dt)
            accelerations_a = kinematics.norm(accelerations)

            headings = kinematics.heading(velocities)

            angular_velocities = kinematics.angular_velocity(velocities, dt)
            angular_velocities_a = kinematics.norm(angular_velocities)

            angular_accelerations = kinematics.acceleration(
                angular_velocities, dt)
            angular_accelerations_a = kinematics.norm(angular_accelerations)

            distance_from_wall = kinematics.distance_from_wall(
                positions, WALL_BOUNDS)

            # store kinematic quantities in timepoints
            for ctr, tp in enumerate(traj.timepoints(session)):

                tp.velocity_a = velocities_a[ctr]
                tp.acceleration_x, tp.acceleration_y, tp.acceleration_z = accelerations[
                    ctr]
                tp.acceleration_a = accelerations_a[ctr]

                tp.heading_xy, tp.heading_xz, tp.heading_xyz = headings[ctr]

                tp.angular_velocity_x, tp.angular_velocity_y, tp.angular_velocity_z = angular_velocities[
                    ctr]
                tp.angular_velocity_a = angular_velocities_a[ctr]

                tp.angular_acceleration_x, tp.angular_acceleration_y, tp.angular_acceleration_z = angular_accelerations[
                    ctr]
                tp.angular_acceleration_a = angular_accelerations_a[ctr]

                tp.distance_from_wall = distance_from_wall[ctr]

                session.add(tp)

            commit(session)
def main():
    # loop over all experiments
    for expt in session.query(models.Experiment):

        print("In experiment '{}'".format(expt.id))

        dt = 1 / expt.sampling_frequency

        for traj in session.query(models.Trajectory).filter_by(experiment=expt):

            positions = traj.positions(session)
            velocities = traj.velocities(session)

            # calculate kinematic quantities
            velocities_a = kinematics.norm(velocities)

            accelerations = kinematics.acceleration(velocities, dt)
            accelerations_a = kinematics.norm(accelerations)

            headings = kinematics.heading(velocities)

            angular_velocities = kinematics.angular_velocity(velocities, dt)
            angular_velocities_a = kinematics.norm(angular_velocities)

            angular_accelerations = kinematics.acceleration(angular_velocities, dt)
            angular_accelerations_a = kinematics.norm(angular_accelerations)

            distance_from_wall = kinematics.distance_from_wall(positions, WALL_BOUNDS)

            # store kinematic quantities in timepoints
            for ctr, tp in enumerate(traj.timepoints(session)):

                tp.velocity_a = velocities_a[ctr]
                tp.acceleration_x, tp.acceleration_y, tp.acceleration_z = accelerations[ctr]
                tp.acceleration_a = accelerations_a[ctr]

                tp.heading_xy, tp.heading_xz, tp.heading_xyz = headings[ctr]

                tp.angular_velocity_x, tp.angular_velocity_y, tp.angular_velocity_z = angular_velocities[ctr]
                tp.angular_velocity_a = angular_velocities_a[ctr]

                tp.angular_acceleration_x, tp.angular_acceleration_y, tp.angular_acceleration_z = angular_accelerations[ctr]
                tp.angular_acceleration_a = angular_accelerations_a[ctr]

                tp.distance_from_wall = distance_from_wall[ctr]

                session.add(tp)

            commit(session)
    def optim_fun(p):

        np.random.seed(SEED)

        start_pos = np.array([
            np.random.uniform(*BOUNDS[0]),
            np.random.uniform(*BOUNDS[1]),
            np.random.uniform(*BOUNDS[2]),
        ])

        # make agent and trajectory

        ag = CenterlineInferringAgent(
            tau=p[0], noise=p[1], bias=p[2], threshold=np.inf,
            hit_trigger='peak', hit_influence=0,
            k_0=np.eye(2), k_s=np.eye(2), tau_memory=1, bounds=BOUNDS)

        traj = ag.track(pl, start_pos, DURATION, DT)

        speeds = np.linalg.norm(traj['vs'], axis=1)
        ws = np.linalg.norm(angular_velocity(traj['vs'], DT), axis=1)
        ws = ws[~np.isnan(ws)]
        ys = traj['xs'][:, 1]

        ks_speeds = stats.ks_2samp(speeds, empirical['speeds'])[0]
        ks_ws = stats.ks_2samp(ws, empirical['ws'])[0]
        ks_ys = stats.ks_2samp(ys, empirical['ys'])[0]

        val = ks_speeds + ks_ws + ks_ys

        # punish unallowable values

        if np.any(p < 0):

            val += 10000

        return val
def example_trajectory_centerline_with_plume(SEED, DURATION, DT, TAU, NOISE,
                                             BIAS, THRESHOLD, HIT_INFLUENCE,
                                             TAU_MEMORY, K_0, K_S, BOUNDS,
                                             PL_CONC, PL_MEAN, PL_STD):
    """
    Create an example trajectory and plot some of the resulting covariates.
    """

    # build plume and agent

    pl = GaussianLaminarPlume(PL_CONC, PL_MEAN, PL_STD)

    k_0 = K_0 * np.eye(2)
    k_s = K_S * np.eye(2)

    ag = CenterlineInferringAgent(tau=TAU,
                                  noise=NOISE,
                                  bias=BIAS,
                                  threshold=THRESHOLD,
                                  hit_trigger='peak',
                                  hit_influence=HIT_INFLUENCE,
                                  k_0=k_0,
                                  k_s=k_s,
                                  tau_memory=TAU_MEMORY,
                                  bounds=BOUNDS)

    # generate the trajectory

    np.random.seed(SEED)

    start_pos = np.array([
        np.random.uniform(*BOUNDS[0]),
        np.random.uniform(*BOUNDS[1]),
        np.random.uniform(*BOUNDS[2]),
    ])

    traj = ag.track(pl, start_pos, DURATION, DT)

    # plot trajectory

    fig = plt.figure(figsize=(15, 10), tight_layout=True)
    axs = [fig.add_subplot(4, 1, 1)]

    axs[-1].plot(traj['xs'][:, 0], traj['xs'][:, 1], lw=2, color='k', zorder=0)
    axs[-1].scatter(traj['xs'][0, 0],
                    traj['xs'][0, 1],
                    lw=0,
                    c='r',
                    zorder=1,
                    s=100)

    axs[-1].set_xlim(*BOUNDS[0])
    axs[-1].set_ylim(*BOUNDS[1])

    axs[-1].set_xlabel('x (m)')
    axs[-1].set_ylabel('y (m)')

    axs[-1].set_title('example trajectory')

    # plot some histograms

    speeds = np.linalg.norm(traj['vs'], axis=1)
    ws = np.linalg.norm(angular_velocity(traj['vs'], DT), axis=1)
    ws = ws[~np.isnan(ws)]

    axs.append(fig.add_subplot(4, 2, 3))
    axs.append(fig.add_subplot(4, 2, 4))

    axs[-2].hist(speeds, bins=30, lw=0, normed=True)
    axs[-1].hist(ws, bins=30, lw=0, normed=True)

    axs[-2].set_xlabel('speed (m/s)')
    axs[-1].set_xlabel('ang. vel (rad/s)')

    axs[-2].set_ylabel('relative counts')

    axs.append(fig.add_subplot(4, 1, 3))
    axs.append(axs[-1].twinx())

    ts = traj['ts']
    odors = traj['odors']
    cl_vars = np.trace(traj['centerline_ks'], axis1=1, axis2=2)

    axs[-2].plot(ts, odors, color='r', lw=2)
    axs[-1].plot(ts, cl_vars, color='k', lw=2)

    axs[-2].set_xlabel('time (s)')
    axs[-2].set_ylabel('odor')
    axs[-1].set_ylabel('centerline var')

    axs.append(fig.add_subplot(4, 1, 4))
    axs.append(axs[-1].twinx())

    bs = traj['bs']

    axs[-2].plot(ts, odors, color='r', lw=2)
    axs[-1].plot(ts, bs[:, 0], color='k', lw=2)

    axs[-2].set_xlabel('time (s)')
    axs[-2].set_ylabel('odor')
    axs[-1].set_ylabel('upwind bias')

    for ax in axs:

        set_font_size(ax, 16)

    return fig
def example_trajectory_surging_with_plume(SEED, DURATION, DT, TAU, NOISE, BIAS,
                                          THRESHOLD, SURGE_AMP, TAU_SURGE,
                                          BOUNDS, PL_CONC, PL_MEAN, PL_STD):
    """
    Create an example trajectory and plot some of the resulting covariates.
    """

    # build plume and agent

    pl = GaussianLaminarPlume(PL_CONC, PL_MEAN, PL_STD)

    ag = SurgingAgent(tau=TAU,
                      noise=NOISE,
                      bias=BIAS,
                      threshold=THRESHOLD,
                      hit_trigger='peak',
                      surge_amp=SURGE_AMP,
                      tau_surge=TAU_SURGE,
                      bounds=BOUNDS)

    # generate the trajectory

    np.random.seed(SEED)

    start_pos = np.array([
        np.random.uniform(*BOUNDS[0]),
        np.random.uniform(*BOUNDS[1]),
        np.random.uniform(*BOUNDS[2]),
    ])

    traj = ag.track(pl, start_pos, DURATION, DT)

    # plot trajectory

    fig = plt.figure(figsize=(15, 10), tight_layout=True)
    axs = [fig.add_subplot(3, 1, 1)]

    axs[-1].plot(traj['xs'][:, 0], traj['xs'][:, 1], lw=2, color='k', zorder=0)
    axs[-1].scatter(traj['xs'][0, 0],
                    traj['xs'][0, 1],
                    lw=0,
                    c='r',
                    zorder=1,
                    s=100)

    axs[-1].set_xlim(*BOUNDS[0])
    axs[-1].set_ylim(*BOUNDS[1])

    axs[-1].set_xlabel('x (m)')
    axs[-1].set_ylabel('y (m)')

    axs[-1].set_title('example trajectory')

    # plot some histograms

    speeds = np.linalg.norm(traj['vs'], axis=1)
    ws = np.linalg.norm(angular_velocity(traj['vs'], DT), axis=1)
    ws = ws[~np.isnan(ws)]

    axs.append(fig.add_subplot(3, 2, 3))
    axs.append(fig.add_subplot(3, 2, 4))

    axs[-2].hist(speeds, bins=30, lw=0, normed=True)
    axs[-1].hist(ws, bins=30, lw=0, normed=True)

    axs[-2].set_xlabel('speed (m/s)')
    axs[-1].set_xlabel('ang. vel (rad/s)')

    axs[-2].set_ylabel('relative counts')

    axs.append(fig.add_subplot(3, 1, 3))
    axs.append(axs[-1].twinx())

    ts = traj['ts']
    odors = traj['odors']
    surge_forces = traj['surges']

    axs[-2].plot(ts, odors, color='r', lw=2)
    axs[-1].plot(ts, surge_forces, color='k', lw=2)

    axs[-2].set_xlabel('time (s)')
    axs[-2].set_ylabel('odor', color='red')
    axs[-1].set_ylabel('surge forces')

    for ax in axs:

        set_font_size(ax, 16)

    return fig
def example_trajectory_surging_no_plume(SEED, DURATION, DT, TAU, NOISE, BIAS,
                                        BOUNDS):
    """
    Create an example trajectory and plot some of the resulting covariates.
    """

    # build plume and agent

    pl = GaussianLaminarPlume(0, np.array([0., 0]), [1., 1.])
    ag = SurgingAgent(tau=TAU,
                      noise=NOISE,
                      bias=BIAS,
                      threshold=np.inf,
                      hit_trigger='peak',
                      surge_strength=0,
                      tau_surge=0,
                      bounds=BOUNDS)

    # generate the trajectory

    np.random.seed(SEED)

    start_pos = np.array([
        np.random.uniform(*BOUNDS[0]),
        np.random.uniform(*BOUNDS[1]),
        np.random.uniform(*BOUNDS[2]),
    ])

    traj = ag.track(pl, start_pos, DURATION, DT)

    # plot trajectory

    fig = plt.figure(figsize=(15, 10), tight_layout=True)
    axs = []

    axs.append(fig.add_subplot(2, 1, 1))

    axs[0].plot(traj['xs'][:, 0], traj['xs'][:, 1], lw=2, color='k', zorder=0)
    axs[0].scatter(traj['xs'][0, 0],
                   traj['xs'][0, 1],
                   lw=0,
                   c='r',
                   zorder=1,
                   s=100)

    axs[0].set_xlim(*BOUNDS[0])
    axs[0].set_ylim(*BOUNDS[1])

    axs[0].set_xlabel('x (m)')
    axs[0].set_ylabel('y (m)')

    axs[0].set_title('example trajectory')

    # plot some histograms

    speeds = np.linalg.norm(traj['vs'], axis=1)
    ws = np.linalg.norm(angular_velocity(traj['vs'], DT), axis=1)
    ws = ws[~np.isnan(ws)]

    axs.append(fig.add_subplot(2, 2, 3))
    axs.append(fig.add_subplot(2, 2, 4))

    axs[1].hist(speeds, bins=30, lw=0, normed=True)
    axs[2].hist(ws, bins=30, lw=0, normed=True)

    axs[1].set_xlabel('speed (m/s)')
    axs[2].set_xlabel('ang. vel (rad/s)')

    axs[1].set_ylabel('relative counts')

    for ax in axs:

        set_font_size(ax, 16)

    return fig
Esempio n. 7
0
    def test_angular_velocity_higher_during_turns(self):

        dt = 0.1

        # turn around in xy plane
        v = np.array([[-1., 0, 0], [-1, 0, 0], [-1, 0, 0], [-1, 1, 0],
                      [0, 1, 0], [1, 1, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]])
        av = kinematics.angular_velocity(v, dt)

        self.assertFalse(np.any(np.isnan(av)))
        # make sure angular velocity in x-direction is zero
        np.testing.assert_array_almost_equal(av[:, 0], np.zeros(av[:,
                                                                   0].shape))
        # make sure angular velocity in y-direction is zero
        np.testing.assert_array_almost_equal(av[:, 1], np.zeros(av[:,
                                                                   1].shape))
        # make sure angular velocity magnitude in z-direction is higher in middle
        self.assertGreater(np.abs(av[4, 2]), av[0, 2])
        self.assertGreater(np.abs(av[4, 2]), av[8, 2])
        # make sure angular velocity in middle is less than zero (right-hand rule)
        self.assertLess(av[4, 2], 0)

        # turn around in xy plane the other way
        v = np.array([[-1., 0, 0], [-1, 0, 0], [-1, 0, 0], [-1, -1, 0],
                      [0, -1, 0], [1, -1, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]])
        av = kinematics.angular_velocity(v, dt)

        self.assertFalse(np.any(np.isnan(av)))
        # make sure angular velocity in x-direction is zero
        np.testing.assert_array_almost_equal(av[:, 0], np.zeros(av[:,
                                                                   0].shape))
        # make sure angular velocity in y-direction is zero
        np.testing.assert_array_almost_equal(av[:, 1], np.zeros(av[:,
                                                                   1].shape))
        # make sure angular velocity in z-direction is higher in middle
        self.assertGreater(np.abs(av[4, 2]), av[0, 2])
        self.assertGreater(np.abs(av[4, 2]), av[8, 2])
        # make sure angular velocity in middle is greater than zero (right-hand rule)
        self.assertGreater(av[4, 2], 0)

        # turn around in xz plane
        v = np.array([[-1., 0, 0], [-1, 0, 0], [-1, 0, 0], [-1, 0, 1],
                      [0, 0, 1], [1, 0, 1], [1, 0, 0], [1, 0, 0], [1, 0, 0]])
        av = kinematics.angular_velocity(v, dt)

        self.assertFalse(np.any(np.isnan(av)))
        # make sure angular velocity in x-direction is zero
        np.testing.assert_array_almost_equal(av[:, 0], np.zeros(av[:,
                                                                   0].shape))
        # make sure angular velocity in z-direction is zero
        np.testing.assert_array_almost_equal(av[:, 2], np.zeros(av[:,
                                                                   2].shape))
        # make sure angular velocity in y-direction is higher in middle
        self.assertGreater(np.abs(av[4, 1]), av[0, 1])
        self.assertGreater(np.abs(av[4, 1]), av[8, 1])
        # make sure angular velocity in middle is greater than zero (right-hand rule)
        self.assertGreater(av[4, 1], 0)

        # turn around in xz plane the other way
        v = np.array([[-1., 0, 0], [-1, 0, 0], [-1, 0, 0], [-1, 0, -1],
                      [0, 0, -1], [1, 0, -1], [1, 0, 0], [1, 0, 0], [1, 0, 0]])
        av = kinematics.angular_velocity(v, dt)

        self.assertFalse(np.any(np.isnan(av)))
        # make sure angular velocity in x-direction is zero
        np.testing.assert_array_almost_equal(av[:, 0], np.zeros(av[:,
                                                                   0].shape))
        # make sure angular velocity in z-direction is zero
        np.testing.assert_array_almost_equal(av[:, 2], np.zeros(av[:,
                                                                   2].shape))
        # make sure angular velocity in y-direction is higher in middle
        self.assertGreater(np.abs(av[4, 1]), av[0, 1])
        self.assertGreater(np.abs(av[4, 1]), av[8, 1])
        # make sure angular velocity in middle is less than zero (right-hand rule)
        self.assertLess(av[4, 1], 0)
def example_trajectory_with_plume(
        SEED, DURATION, DT, TAU, NOISE, BIAS, THRESHOLD, HIT_INFLUENCE,
        TAU_MEMORY, K_0, K_S, BOUNDS,
        PL_CONC, PL_MEAN, PL_STD):
    """
    Create an example trajectory and plot some of the resulting covariates.
    """

    # build plume and agent

    pl = GaussianLaminarPlume(PL_CONC, PL_MEAN, PL_STD)

    k_0 = K_0 * np.eye(2)
    k_s = K_S * np.eye(2)

    ag = CenterlineInferringAgent(
        tau=TAU, noise=NOISE, bias=BIAS, threshold=THRESHOLD,
        hit_trigger='peak', hit_influence=HIT_INFLUENCE,
        k_0=k_0, k_s=k_s, tau_memory=TAU_MEMORY, bounds=BOUNDS)

    # generate the trajectory

    np.random.seed(SEED)

    start_pos = np.array([
        np.random.uniform(*BOUNDS[0]),
        np.random.uniform(*BOUNDS[1]),
        np.random.uniform(*BOUNDS[2]),
    ])

    traj = ag.track(pl, start_pos, DURATION, DT)

    # plot trajectory

    fig = plt.figure(figsize=(15, 10), tight_layout=True)
    axs = [fig.add_subplot(4, 1, 1)]

    axs[-1].plot(traj['xs'][:, 0], traj['xs'][:, 1], lw=2, color='k', zorder=0)
    axs[-1].scatter(traj['xs'][0, 0], traj['xs'][0, 1], lw=0, c='r', zorder=1, s=100)

    axs[-1].set_xlim(*BOUNDS[0])
    axs[-1].set_ylim(*BOUNDS[1])

    axs[-1].set_xlabel('x (m)')
    axs[-1].set_ylabel('y (m)')

    axs[-1].set_title('example trajectory')

    # plot some histograms

    speeds = np.linalg.norm(traj['vs'], axis=1)
    ws = np.linalg.norm(angular_velocity(traj['vs'], DT), axis=1)
    ws = ws[~np.isnan(ws)]

    axs.append(fig.add_subplot(4, 2, 3))
    axs.append(fig.add_subplot(4, 2, 4))

    axs[-2].hist(speeds, bins=30, lw=0, normed=True)
    axs[-1].hist(ws, bins=30, lw=0, normed=True)

    axs[-2].set_xlabel('speed (m/s)')
    axs[-1].set_xlabel('ang. vel (rad/s)')

    axs[-2].set_ylabel('relative counts')

    axs.append(fig.add_subplot(4, 1, 3))
    axs.append(axs[-1].twinx())

    ts = traj['ts']
    odors = traj['odors']
    cl_vars = np.trace(traj['centerline_ks'], axis1=1, axis2=2)

    axs[-2].plot(ts, odors, color='r', lw=2)
    axs[-1].plot(ts, cl_vars, color='k', lw=2)

    axs[-2].set_xlabel('time (s)')
    axs[-2].set_ylabel('odor')
    axs[-1].set_ylabel('centerline var')

    axs.append(fig.add_subplot(4, 1, 4))
    axs.append(axs[-1].twinx())

    bs = traj['bs']

    axs[-2].plot(ts, odors, color='r', lw=2)
    axs[-1].plot(ts, bs[:, 0], color='k', lw=2)

    axs[-2].set_xlabel('time (s)')
    axs[-2].set_ylabel('odor')
    axs[-1].set_ylabel('upwind bias')

    for ax in axs:

        set_font_size(ax, 16)

    return fig
def optimize_model_params(
        SEED,
        DURATION, DT, BOUNDS,
        EXPERIMENT, ODOR_STATE,
        MAX_TRAJS_EMPIRICAL,
        N_TIME_POINTS_EMPIRICAL,
        SAVE_FILE_PREFIX,
        INITIAL_PARAMS, MAX_ITERS):
    """
    Find optimal model parameters by fitting speed and angular velocity distributions of empirical
    data.
    """

    # check to see if empirical time points have already been saved

    file_name = '{}_{}_odor_{}.npy'.format(SAVE_FILE_PREFIX, EXPERIMENT, ODOR_STATE)

    if os.path.isfile(file_name):

        empirical = np.load(file_name)[0]

    else:

        print('extracting time points from data')

        # get all trajectories

        trajs = session.query(models.Trajectory).filter_by(
            experiment_id=EXPERIMENT, odor_state=ODOR_STATE, clean=True).\
            limit(MAX_TRAJS_EMPIRICAL).all()

        # get all speeds and angular velocities

        cc = np.concatenate
        speeds_empirical = cc([traj.velocities_a(session) for traj in trajs])
        ws_empirical = cc([traj.angular_velocities_a(session) for traj in trajs])
        ys_empirical = cc([traj.timepoint_field(session, 'position_y') for traj in trajs])

        # sample a set of speeds and ws

        np.random.seed(SEED)

        speeds_empirical = np.random.choice(speeds_empirical, N_TIME_POINTS_EMPIRICAL, replace=False)
        ws_empirical = np.random.choice(ws_empirical, N_TIME_POINTS_EMPIRICAL, replace=False)
        ys_empirical = np.random.choice(ys_empirical, N_TIME_POINTS_EMPIRICAL, replace=False)

        empirical = {'speeds': speeds_empirical, 'ws': ws_empirical, 'ys': ys_empirical}

        # save them for easy access next time

        np.save(file_name, np.array([empirical]))

    print('performing optimization')

    # make a plume

    pl = GaussianLaminarPlume(0, np.zeros((2,)), np.ones((2,)))

    # define function to be optimized

    def optim_fun(p):

        np.random.seed(SEED)

        start_pos = np.array([
            np.random.uniform(*BOUNDS[0]),
            np.random.uniform(*BOUNDS[1]),
            np.random.uniform(*BOUNDS[2]),
        ])

        # make agent and trajectory

        ag = CenterlineInferringAgent(
            tau=p[0], noise=p[1], bias=p[2], threshold=np.inf,
            hit_trigger='peak', hit_influence=0,
            k_0=np.eye(2), k_s=np.eye(2), tau_memory=1, bounds=BOUNDS)

        traj = ag.track(pl, start_pos, DURATION, DT)

        speeds = np.linalg.norm(traj['vs'], axis=1)
        ws = np.linalg.norm(angular_velocity(traj['vs'], DT), axis=1)
        ws = ws[~np.isnan(ws)]
        ys = traj['xs'][:, 1]

        ks_speeds = stats.ks_2samp(speeds, empirical['speeds'])[0]
        ks_ws = stats.ks_2samp(ws, empirical['ws'])[0]
        ks_ys = stats.ks_2samp(ys, empirical['ys'])[0]

        val = ks_speeds + ks_ws + ks_ys

        # punish unallowable values

        if np.any(p < 0):

            val += 10000

        return val

    # optimize it

    p_best = optimize.fmin(optim_fun, np.array(INITIAL_PARAMS), maxiter=MAX_ITERS)

    # generate one final trajectory

    np.random.seed(SEED)

    start_pos = np.array([
        np.random.uniform(*BOUNDS[0]),
        np.random.uniform(*BOUNDS[1]),
        np.random.uniform(*BOUNDS[2]),
    ])

    ag = CenterlineInferringAgent(
        tau=p_best[0], noise=p_best[1], bias=p_best[2], threshold=np.inf,
        hit_trigger='peak', hit_influence=0,
        k_0=np.eye(2), k_s=np.eye(2), tau_memory=1, bounds=BOUNDS)

    traj = ag.track(pl, start_pos, DURATION, DT)

    speeds = np.linalg.norm(traj['vs'], axis=1)
    ws = np.linalg.norm(angular_velocity(traj['vs'], DT), axis=1)
    ws = ws[~np.isnan(ws)]
    ys = traj['xs'][:, 1]

    # make plots of things that have been optimized

    ## get bins

    speed_max = max(speeds.max(), empirical['speeds'].max())
    bins_speed = np.linspace(0, speed_max, 41, endpoint=True)
    bincs_speed = 0.5 * (bins_speed[:-1] + bins_speed[1:])

    w_max = max(ws.max(), empirical['ws'].max())
    bins_w = np.linspace(0, w_max, 41, endpoint=True)
    bincs_w = 0.5 * (bins_w[:-1] + bins_w[1:])

    bins_y = np.linspace(BOUNDS[1][0], BOUNDS[1][1], 41, endpoint=True)
    bincs_y = 0.5 * (bins_y[:-1] + bins_y[1:])

    cts_speed, _ = np.histogram(speeds, bins=bins_speed, normed=True)
    cts_speed_empirical, _ = np.histogram(empirical['speeds'], bins=bins_speed, normed=True)

    cts_w, _ = np.histogram(ws, bins=bins_w, normed=True)
    cts_w_empirical, _ = np.histogram(empirical['ws'], bins=bins_w, normed=True)

    cts_y, _ = np.histogram(ys, bins=bins_y, normed=True)
    cts_y_empirical, _ = np.histogram(empirical['ys'], bins=bins_y, normed=True)

    fig = plt.figure(figsize=(15, 8), tight_layout=True)
    axs = []

    axs.append(fig.add_subplot(2, 3, 1))
    axs.append(fig.add_subplot(2, 3, 2))
    axs.append(fig.add_subplot(2, 3, 3))

    axs[0].plot(bincs_speed, cts_speed_empirical, lw=2, color='k')
    axs[0].plot(bincs_speed, cts_speed, lw=2, color='r')

    axs[0].set_xlabel('speed (m/s)')
    axs[0].set_ylabel('rel. counts')

    axs[0].legend(['data', 'model'], fontsize=16)

    axs[1].plot(bincs_w, cts_w_empirical, lw=2, color='k')
    axs[1].plot(bincs_w, cts_w, lw=2, color='r')

    axs[1].set_xlabel('ang. vel. (rad/s)')

    axs[2].plot(bincs_y, cts_y_empirical, lw=2, color='k')
    axs[2].plot(bincs_y, cts_y, lw=2, color='r')

    axs[2].set_xlabel('y (m)')

    axs.append(fig.add_subplot(2, 1, 2))

    axs[3].plot(traj['xs'][:500, 0], traj['xs'][:500, 1], lw=2, color='k', zorder=0)
    axs[3].scatter(traj['xs'][0, 0], traj['xs'][0, 1], lw=0, c='r', zorder=1, s=100)

    axs[3].set_xlim(*BOUNDS[0])
    axs[3].set_ylim(*BOUNDS[1])

    axs[3].set_xlabel('x (m)')
    axs[3].set_ylabel('y (m)')

    axs[3].set_title('example trajectory')

    for ax in axs:

        set_font_size(ax, 16)

    # print out parameters

    print('best params:')
    print('tau = {}'.format(p_best[0]))
    print('noise = {}'.format(p_best[1]))
    print('bias = {}'.format(p_best[2]))

    return fig
def example_trajectory_no_plume(SEED, DURATION, DT, TAU, NOISE, BIAS, BOUNDS):
    """
    Create an example trajectory and plot some of the resulting covariates.
    """

    # build plume and agent

    pl = GaussianLaminarPlume(0, np.array([0., 0]), np.eye(2))
    ag = CenterlineInferringAgent(
        tau=TAU, noise=NOISE, bias=BIAS, threshold=np.inf,
        hit_trigger='peak', hit_influence=0,
        k_0=np.eye(2), k_s=np.eye(2), tau_memory=1, bounds=BOUNDS)

    # generate the trajectory

    np.random.seed(SEED)

    start_pos = np.array([
        np.random.uniform(*BOUNDS[0]),
        np.random.uniform(*BOUNDS[1]),
        np.random.uniform(*BOUNDS[2]),
    ])

    traj = ag.track(pl, start_pos, DURATION, DT)

    # plot trajectory

    fig = plt.figure(figsize=(15, 10), tight_layout=True)
    axs = []

    axs.append(fig.add_subplot(2, 1, 1))

    axs[0].plot(traj['xs'][:, 0], traj['xs'][:, 1], lw=2, color='k', zorder=0)
    axs[0].scatter(traj['xs'][0, 0], traj['xs'][0, 1], lw=0, c='r', zorder=1, s=100)

    axs[0].set_xlim(*BOUNDS[0])
    axs[0].set_ylim(*BOUNDS[1])

    axs[0].set_xlabel('x (m)')
    axs[0].set_ylabel('y (m)')

    axs[0].set_title('example trajectory')

    # plot some histograms

    speeds = np.linalg.norm(traj['vs'], axis=1)
    ws = np.linalg.norm(angular_velocity(traj['vs'], DT), axis=1)
    ws = ws[~np.isnan(ws)]

    axs.append(fig.add_subplot(2, 2, 3))
    axs.append(fig.add_subplot(2, 2, 4))

    axs[1].hist(speeds, bins=30, lw=0, normed=True)
    axs[2].hist(ws, bins=30, lw=0, normed=True)

    axs[1].set_xlabel('speed (m/s)')
    axs[2].set_xlabel('ang. vel (rad/s)')

    axs[1].set_ylabel('relative counts')

    for ax in axs:

        set_font_size(ax, 16)

    return fig
Esempio n. 11
0
    def test_angular_velocity_higher_during_turns(self):

        dt = 0.1

        # turn around in xy plane
        v = np.array([[-1., 0, 0], [-1, 0, 0], [-1, 0, 0],
                      [-1, 1, 0], [0, 1, 0], [1, 1, 0],
                      [1, 0, 0], [1, 0, 0], [1, 0, 0]])
        av = kinematics.angular_velocity(v, dt)

        self.assertFalse(np.any(np.isnan(av)))
        # make sure angular velocity in x-direction is zero
        np.testing.assert_array_almost_equal(av[:, 0], np.zeros(av[:, 0].shape))
        # make sure angular velocity in y-direction is zero
        np.testing.assert_array_almost_equal(av[:, 1], np.zeros(av[:, 1].shape))
        # make sure angular velocity magnitude in z-direction is higher in middle
        self.assertGreater(np.abs(av[4, 2]), av[0, 2])
        self.assertGreater(np.abs(av[4, 2]), av[8, 2])
        # make sure angular velocity in middle is less than zero (right-hand rule)
        self.assertLess(av[4, 2], 0)

        # turn around in xy plane the other way
        v = np.array([[-1., 0, 0], [-1, 0, 0], [-1, 0, 0],
                      [-1, -1, 0], [0, -1, 0], [1, -1, 0],
                      [1, 0, 0], [1, 0, 0], [1, 0, 0]])
        av = kinematics.angular_velocity(v, dt)

        self.assertFalse(np.any(np.isnan(av)))
        # make sure angular velocity in x-direction is zero
        np.testing.assert_array_almost_equal(av[:, 0], np.zeros(av[:, 0].shape))
        # make sure angular velocity in y-direction is zero
        np.testing.assert_array_almost_equal(av[:, 1], np.zeros(av[:, 1].shape))
        # make sure angular velocity in z-direction is higher in middle
        self.assertGreater(np.abs(av[4, 2]), av[0, 2])
        self.assertGreater(np.abs(av[4, 2]), av[8, 2])
        # make sure angular velocity in middle is greater than zero (right-hand rule)
        self.assertGreater(av[4, 2], 0)

        # turn around in xz plane
        v = np.array([[-1., 0, 0], [-1, 0, 0], [-1, 0, 0],
                      [-1, 0, 1], [0, 0, 1], [1, 0, 1],
                      [1, 0, 0], [1, 0, 0], [1, 0, 0]])
        av = kinematics.angular_velocity(v, dt)

        self.assertFalse(np.any(np.isnan(av)))
        # make sure angular velocity in x-direction is zero
        np.testing.assert_array_almost_equal(av[:, 0], np.zeros(av[:, 0].shape))
        # make sure angular velocity in z-direction is zero
        np.testing.assert_array_almost_equal(av[:, 2], np.zeros(av[:, 2].shape))
        # make sure angular velocity in y-direction is higher in middle
        self.assertGreater(np.abs(av[4, 1]), av[0, 1])
        self.assertGreater(np.abs(av[4, 1]), av[8, 1])
        # make sure angular velocity in middle is greater than zero (right-hand rule)
        self.assertGreater(av[4, 1], 0)

        # turn around in xz plane the other way
        v = np.array([[-1., 0, 0], [-1, 0, 0], [-1, 0, 0],
                      [-1, 0, -1], [0, 0, -1], [1, 0, -1],
                      [1, 0, 0], [1, 0, 0], [1, 0, 0]])
        av = kinematics.angular_velocity(v, dt)

        self.assertFalse(np.any(np.isnan(av)))
        # make sure angular velocity in x-direction is zero
        np.testing.assert_array_almost_equal(av[:, 0], np.zeros(av[:, 0].shape))
        # make sure angular velocity in z-direction is zero
        np.testing.assert_array_almost_equal(av[:, 2], np.zeros(av[:, 2].shape))
        # make sure angular velocity in y-direction is higher in middle
        self.assertGreater(np.abs(av[4, 1]), av[0, 1])
        self.assertGreater(np.abs(av[4, 1]), av[8, 1])
        # make sure angular velocity in middle is less than zero (right-hand rule)
        self.assertLess(av[4, 1], 0)