if __name__ == "__main__":

    #################
    n_dims = 3
    frame_rate = 500.
    #################

    # Import data from mapping experiment
    mapping_space_directory = os.path.join(mapping_experiment.subdirs['analysis'], 'behaviour_space')
    eigenfish = np.load(os.path.join(mapping_space_directory, 'eigenfish.npy'))
    mean_tail, std_tail = np.load(os.path.join(mapping_space_directory, 'tail_statistics.npy'))
    exemplar_info = pd.read_csv(os.path.join(mapping_experiment.subdirs['analysis'], 'exemplars.csv'),
                                index_col='bout_index',
                                dtype={'ID': str, 'video_code': str})
    exemplar_info = exemplar_info[exemplar_info['clean']]
    exemplars = BoutData.from_directory(exemplar_info, mapping_experiment.subdirs['kinematics'],
                                        check_tail_lengths=False, tail_columns_only=True)
    exemplars = exemplars.map(eigenfish, whiten=True, mean=mean_tail, std=std_tail)
    exemplars = exemplars.list_bouts(values=True, ndims=n_dims)

    # Set paths
    output_directory = create_folder(experiment.subdirs['analysis'], 'distance_matrices')

    # Import experiment bouts
    experiment_bouts = import_bouts(experiment.directory)
    experiment_bouts = experiment_bouts.map(eigenfish, whiten=True, mean=mean_tail, std=std_tail)

    # Compute distance matrices
    print_heading('CALCULATING DISTANCE MATRICES')
    distances = {}
    analysis_times = []
    timer = Timer()
import pandas as pd

if __name__ == "__main__":

    frame_rate = 500.
    n_dims = 3

    bout_indices = np.load(paths['bout_indices'])
    bouts_df = pd.read_csv(paths['bouts'],
                           dtype={
                               'ID': str,
                               'video_code': str
                           })
    bouts_df = bouts_df.loc[bout_indices]
    bouts = BoutData.from_directory(bouts_df,
                                    experiment.subdirs['kinematics'],
                                    tail_columns_only=True,
                                    check_tail_lengths=False)

    eigenfish = np.load(paths['eigenfish'])
    mean_tail, std_tail = np.load(paths['tail_statistics'])

    transformed = bouts.map(eigenfish,
                            whiten=True,
                            mean=mean_tail,
                            std=std_tail)
    transformed_bouts = transformed.list_bouts(values=True, ndims=n_dims)

    print_heading('CALCULATING DISTANCE MATRIX - NORMAL')
    distance_matrix = calculate_distance_matrix(transformed_bouts,
                                                fs=frame_rate,
                                                flip=False)
Пример #3
0
                     strike_frames['start']).values / 500.
    example_lengths = (strike_frames['end'] -
                       strike_frames['start']).values / 500.
    for key, label in cluster_labels.iteritems():
        strike_times = example_times[strike_frames['strike_cluster'] == label]
        kde = KernelDensity(0.01).fit(strike_times.reshape(-1, 1))
        density = np.exp(
            kde.score_samples(bins)) * 0.01 * len(strike_times) / float(
                len(example_times))
        strike_info[key]['capture_times'] = strike_times
        strike_info[key]['capture_times_kde'] = density

    # Import kinematic data for example strikes
    example_strike_frames = BoutData.from_directory(
        strike_frames,
        experiment.subdirs['kinematics'],
        check_tail_lengths=False,
        tail_columns_only=False)
    example_capture_frames = example_strike_frames.list_bouts()
    example_capture_frames = [
        bout.loc[:, 'tip'].values for bout in example_capture_frames
    ]

    # ================
    # COMPOSITE FIGURE
    # ================

    # Make axes
    fig = plt.figure(figsize=(1.854, 3))
    gs = gridspec.GridSpec(4, 1)
    ax1 = fig.add_subplot(gs[0])
if __name__ == "__main__":

    # =========
    # Open data
    # =========
    capture_strike_info = pd.read_csv(
        os.path.join(experiment.subdirs['analysis'], 'capture_strikes', 'capture_strikes.csv'),
        index_col=0, dtype={'ID': str, 'video_code': str})

    eigenfish = np.load(os.path.join(experiment.subdirs['analysis'], 'behaviour_space', 'eigenfish.npy'))
    mean, std = np.load(os.path.join(experiment.subdirs['analysis'], 'behaviour_space', 'tail_statistics.npy'))

    # =======================================================
    # Load bout data for capture strikes and project onto PCs
    # =======================================================
    capture_strikes = BoutData.from_directory(capture_strike_info, experiment.subdirs['kinematics'],
                                              check_tail_lengths=False, tail_columns_only=True)
    transformed_strikes = capture_strikes.map(eigenfish, whiten=True, mean=mean, std=std)
    transformed_strikes = transformed_strikes.list_bouts(values=True, ndims=3)

    # =========================================================
    # Split strikes by cluster and flip to be in same direction
    # =========================================================
    clustered = [[], []]
    for l, strike in zip(capture_strike_info['strike_cluster'].values, transformed_strikes):
        truncated = strike[12:37]
        truncated = truncated * np.sign(truncated[:10, 1][np.abs(truncated[:10, 1]).argmax()])
        clustered[l].append(truncated)
    cluster_mean_traces = [np.mean(traces, axis=0) for traces in clustered]

    # ==============================================================
    # Align all traces to cluster average and calculate new averages
Пример #5
0
if __name__ == "__main__":

    # Load the exemplar bout data
    exemplars = pd.read_csv(os.path.join(experiment.subdirs['analysis'],
                                         'exemplars.csv'),
                            index_col='bout_index',
                            dtype={
                                'ID': str,
                                'video_code': str
                            })
    exemplars = exemplars[exemplars['clean']]
    labels = exemplars['module'].values

    exemplar_data = BoutData.from_directory(exemplars,
                                            experiment.subdirs['kinematics'],
                                            check_tail_lengths=False,
                                            tail_columns_only=False)

    eigenfish = np.load(
        os.path.join(experiment.subdirs['analysis'], 'behaviour_space',
                     'eigenfish.npy'))
    tail_stats = np.load(
        os.path.join(experiment.subdirs['analysis'], 'behaviour_space',
                     'tail_statistics.npy'))

    exemplar_kinematics = BoutData(exemplar_data.data.loc[:, 'k0':'k49'],
                                   exemplar_data.metadata)
    exemplars_transformed = exemplar_kinematics.map(eigenfish, True,
                                                    tail_stats[0],
                                                    tail_stats[1])
Пример #6
0
    mapped_bouts = pd.read_csv(paths['mapped_bouts'],
                               index_col='bout_index',
                               dtype={
                                   'ID': str,
                                   'video_code': str
                               })
    n_states = len(mapped_bouts['state'].unique())
    cluster_indices = [
        np.where(mapped_bouts['state'].values == l)[0]
        for l in np.arange(n_states)
    ]

    mapped_bouts_data = BoutData.from_directory(
        mapped_bouts,
        experiment.subdirs['kinematics'],
        tail_columns_only=False,
        check_tail_lengths=False)
    all_bouts = mapped_bouts_data.list_bouts()

    # Turn angles
    turn_angles = np.array(
        [bout['angular_velocity'].sum() for bout in all_bouts])
    turn_angles = np.degrees(
        np.abs(turn_angles)
    ) / 500.  # ignore direction, convert to degrees, account for frame rate
    turn_angles = np.array([
        np.median(turn_angles[idxs]) for idxs in cluster_indices
    ])  # take cluster medians

    # Maximum angular velocity