Ejemplo n.º 1
0
def get_angle_leg(data, webots=True):
    # input data shape (frame,joint,xyz)
    if webots:
        datamat_j = jf.get_joint_angles(data,
                                        project_1DOF=True,
                                        interpolate=False)
        joint_names = jf.get_name_vector(joint_names=[
            'THORAX_COXA', 'COXA_FEMUR', 'FEMUR_TIBIA', 'TIBIA_TARSUS'
        ],
                                         coxa_names=['LD', 'T_1', 'T_2'],
                                         side_names=['L', 'R'],
                                         leg_names=['F', 'M', 'H'],
                                         last_point_name='CLAW')
        data_angle = np.asarray(datamat_j[joint_names[1]])

    else:
        data_angle = np.zeros(
            (data.shape[0], 30),
            dtype=np.float32)  # result is 5 angles per limb (6x5)
        # Defining forward reference of the fly
        mean_hind_bodycoxa = np.mean(
            (data[:, 10, :] + data[:, 25, :]) / 2,
            0)  #check skeleton.py to confirm the landmark IDs
        mean_mid_bodycoxa = np.mean((data[:, 5, :] + data[:, 20, :]) / 2, 0)
        v_forw = mean_mid_bodycoxa - mean_hind_bodycoxa
        for img_id in range(data.shape[0]):
            a_id = 0
            for p_id in range(1, data.shape[1] - 1, 5):
                data_angle[img_id, a_id] = angle_three_points(
                    data[img_id, p_id - 1, :], data[img_id, p_id, :],
                    data[img_id, p_id + 1, :])  # hinge COXA_FEMUR
                p_id += 1
                a_id += 1
                data_angle[img_id, a_id] = angle_three_points(
                    data[img_id, p_id - 1, :], data[img_id, p_id, :],
                    data[img_id, p_id + 1, :])  # hinge FEMUR_TIBIA
                p_id += 1
                a_id += 1
                data_angle[img_id, a_id] = angle_three_points(
                    data[img_id, p_id - 1, :], data[img_id, p_id, :],
                    data[img_id, p_id + 1, :])  # hinge TIBIA_TARSUS
                a_id += 1
                o_v = data[img_id, p_id -
                           2, :] - data[img_id, p_id -
                                        3, :]  # body-coxa shifted to origin
                r, data_angle[
                    img_id, a_id], data_angle[img_id, a_id + 1] = cs.cart2sp(
                        o_v[0], o_v[1], o_v[2]
                    )  # convert to cartesian | elipsiod joint (ass.) BODY_COXA T1 & T2
                a_id += 2
                #write this in a more compact, more efficient fashion later. For now, it works.

    print(
        f'Number of nan or inf after angles: {np.sum(np.logical_or(np.isnan(data_angle), np.isinf(data_angle)))}'
    )
    data_angle[np.logical_or(np.isnan(data_angle), np.isinf(data_angle))] = 0
    # output data shape (frame, angle)
    return data_angle
Ejemplo n.º 2
0
def mean_center(j_ang, nj_ang, o_ang, no_ang, exp):
    '''
    This function outputs a plot for each angle, where the meancentered time-sequence is compared to itself, prior to the mean centering step. The point was just to check how meaningfull the mean centering step was at this stage. Meancentering of the time series leaves the rest angle at zero.
    '''

    name_vector, extended_name_vector = jf.get_name_vector()
    extended_name_vector = np.append(extended_name_vector,
                                     ['L_STRIPES', 'R_STRIPES', 'ANTENNAE'])
    for i in range(np.shape(j_ang)[1]):
        fig = plt.figure()
        figsize = (24, 6)
        plt.plot(j_ang[:, i],
                 color='k',
                 linewidth=.7,
                 alpha=.5,
                 label='Not meancentered, subject {}'.format(exp))
        plt.plot(nj_ang[:, i],
                 color='b',
                 linewidth=.7,
                 alpha=.5,
                 label='Meancentered, subject {}'.format(exp))
        plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
        plt.title(extended_name_vector[i])
        plt.ylabel('Angle (rad)')
        plt.xlabel('time')
    for i in range(np.shape(o_ang)[1]):
        fig = plt.figure()
        figsize = (24, 6)
        plt.plot(o_ang[:, i],
                 color='r',
                 linewidth=.7,
                 alpha=.5,
                 label='Not meancentered, subject {}'.format(exp))
        plt.plot(no_ang[:, i],
                 color='g',
                 linewidth=.7,
                 alpha=.5,
                 label='Meancentered, subject {}'.format(exp))
        plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
        plt.title(extended_name_vector[i + 36])
        plt.ylabel('Angle (rad)')
        plt.xlabel('time')
Ejemplo n.º 3
0
def see_joint_angles(j_ang, j_ang1, o_ang, o_ang1, exp1, exp2):
    '''
    This function outputs the full set of joint angles that are given by joint_functions. In BehavPreprocess, 2 of the experiments are kept as control for the joint angles function, in self.ctrl_list_angles. These experiments, at this point, consist in joint angles (and other angles) calculations from the 3D positions of the leg joints, abdominal stripes and antennae. The first 2 entries correspond to leg joint angles, and the ramining 2, to other angles (head tilt and abdominal tilt).
    '''

    name_vector, extended_name_vector = jf.get_name_vector()
    extended_name_vector = np.append(extended_name_vector,
                                     ['L_STRIPES', 'R_STRIPES', 'ANTENNAE'])
    for i in range(np.shape(j_ang)[1]):
        fig = plt.figure()
        plt.plot(j_ang[:, i],
                 color='k',
                 linewidth=.7,
                 alpha=.5,
                 label='Control subject {}'.format(exp1))
        plt.plot(j_ang1[:, i],
                 color='b',
                 linewidth=.7,
                 alpha=.5,
                 label='Control subject {}'.format(exp2))
        plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
        plt.title(extended_name_vector[i])
        plt.ylabel('Angle (rad)')
        plt.xlabel('time')
    for i in range(np.shape(o_ang)[1]):
        fig = plt.figure()
        plt.plot(o_ang[:, i],
                 color='r',
                 linewidth=.7,
                 alpha=.5,
                 label='Control subject {}'.format(exp1))
        plt.plot(o_ang1[:, i],
                 color='g',
                 linewidth=.7,
                 alpha=.5,
                 label='Control subject {}'.format(exp2))
        plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
        plt.title(extended_name_vector[i + 36])
        plt.ylabel('Angle (rad)')
        plt.xlabel('time')
Ejemplo n.º 4
0
def plt_wav(angl_exp_list,
            test_rest_mask,
            fly_tags,
            exp,
            j_ang=0,
            num_ang=1,
            fps=100,
            chan=25,
            fmin=1,
            fmax=50,
            x_size=9,
            y_size=3,
            show_rest=False,
            show_pose=True,
            H_angles=False):
    '''
    Simply plots the wavelet transformation of a chosen joint angle. The only purpose it serves here is to check how the wavelets would look for any given number of channels, minimum frequency and maximum frequency (DO NOT go beyond the Nyquist frequency (=fps/2) due to aliasing).
    '''
    # Joint names
    if H_angles:
        _, extended_name_vector = jf.get_name_vector()
        extended_name_vector = np.append(
            extended_name_vector, ['L_STRIPES', 'R_STRIPES', 'ANTENNAE'])
    else:
        extended_name_vector = np.append(
            get_name_3point_angles(), ['L_STRIPES', 'R_STRIPES', 'ANTENNAE'])

    # Pre frame normalization
    angles_ts = angl_exp_list[exp]
    spect, f = find_wav(angles_ts[:, j_ang:j_ang + num_ang].copy(),
                        chan=chan,
                        omega0=5,
                        fps=fps,
                        fmin=fmin,
                        fmax=fmax)
    r_mask = test_rest_mask[exp] * 1
    rest = ranges(np.where(r_mask)[0])
    colors = ['white', 'lavender', 'palegreen', 'beige', 'coral', 'pink']
    plt.figure(figsize=(x_size, y_size))
    ax1 = plt.subplot(2, 1, 1)
    nframes = spect.shape[0]
    nfeats = spect.shape[1]
    ax1.imshow(np.transpose(spect),
               extent=[1, nframes, nfeats, 0],
               aspect='auto')
    d = angles_ts[:, j_ang:j_ang + num_ang].copy()
    if show_pose:
        for i in range(num_ang):
            d[:, i] = ((-d[:, i] + np.mean(d[:, i])) * (chan / 2) /
                       (max(d[:, i]) - min(d[:, i]))) + (
                           (num_ang - i) - 1 / 2) * chan
        ax1.plot(np.arange(0, d.shape[0]),
                 d,
                 alpha=0.8,
                 c=colors[0 % len(colors)])
    if show_rest:
        for i in range(np.shape(rest)[0]):
            ax1.axvspan(rest[i][0], rest[i][1], facecolor='0.5', alpha=0.45)
    ax1.set(title=f'Wavelet transform, {fly_tags[exp]}',
            xlabel='time',
            ylabel='Wavelet data (background) & joint angles (white)')
    ax1.spines['top'].set_visible(False)
    ax1.spines['right'].set_visible(False)
    ax1.spines['bottom'].set_visible(False)
    ax1.spines['left'].set_visible(False)
    ax1.set_yticklabels([])
    for i in range(num_ang):
        ax1.annotate(extended_name_vector[j_ang + num_ang - i - 1],
                     xy=(-5, chan * (i - 1 / 2) + chan),
                     xycoords='data',
                     rotation=90,
                     size=5,
                     va='center',
                     horizontalalignment='right',
                     verticalalignment='top')
    ax1.tick_params(axis='both', which='both', length=0)

    # Post frame normalization
    nspect = normalize_ts(spect, ax=0)
    ax2 = plt.subplot(2, 1, 2)
    ax2.imshow(np.transpose(nspect),
               extent=[1, nspect.shape[0], nspect.shape[1], 0],
               aspect='auto')
    if show_rest:
        for i in range(np.shape(rest)[0]):
            ax2.axvspan(rest[i][0], rest[i][1], facecolor='0.5', alpha=0.35)
    ax2.plot(np.arange(0, d.shape[0]),
             d,
             alpha=0.01,
             c=colors[0 % len(colors)])
    ax2.set(title=f'Frame normalization, {fly_tags[exp]}',
            xlabel='time',
            ylabel='Normalied wavelet data')
    ax2.spines['top'].set_visible(False)
    ax2.spines['right'].set_visible(False)
    ax2.spines['bottom'].set_visible(False)
    ax2.spines['left'].set_visible(False)
    ax2.set_yticklabels([])
    for j in range(num_ang):
        ax2.annotate(extended_name_vector[j_ang + num_ang - j],
                     xy=(-5, chan * (j - 1 / 2) + chan),
                     xycoords='data',
                     rotation=90,
                     size=5,
                     va='center',
                     horizontalalignment='right',
                     verticalalignment='bottom')
    ax2.tick_params(axis='both', which='both', length=0)
    return
Ejemplo n.º 5
0
def see_postural_series(pose_data, fly_tags, exp, joint, limb, H_angle=True):
    '''
    Plots a postural time series from a given experiment at a given joint. If H_angle=True, it reflects joint angles 
    from Halla's function, otherwise default angle computing.
    '''

    fig = plt.figure()
    if H_angle:
        name_vector, extended_name_vector = jf.get_name_vector()
        extended_name_vector = np.append(
            extended_name_vector, ['L_STRIPES', 'R_STRIPES', 'ANTENNAE'])

        limb_data = np.transpose(
            np.stack(
                (pose_data[exp][:, limb * 6], pose_data[exp][:, limb * 6 + 1],
                 pose_data[exp][:, limb * 6 + 2], pose_data[exp][:,
                                                                 limb * 6 + 3],
                 pose_data[exp][:,
                                limb * 6 + 4], pose_data[exp][:,
                                                              limb * 6 + 5])))
        limb_df = pd.DataFrame(limb_data,
                               columns=extended_name_vector[limb *
                                                            6:(limb + 1) * 6])
        sns.lineplot(data=limb_df,
                     palette="Set2",
                     linewidth=1,
                     dashes=False,
                     alpha=.7)
        sns.despine(left=True, right=True, top=True, bottom=True)
        plt.legend(loc='upper left',
                   bbox_to_anchor=(-0.01, -.15),
                   fancybox=False,
                   shadow=False,
                   ncol=3,
                   prop={'size': 8})
        plt.title(f'Pose data from {fly_tags[exp]}')
        plt.ylabel('Angle (rad)')
        plt.xlabel('time')

    else:
        extended_name_vector = get_name_3point_angles()
        extended_name_vector = np.append(
            extended_name_vector, ['L_STRIPES', 'R_STRIPES', 'ANTENNAE'])
        limb_data = np.transpose(
            np.stack(
                (pose_data[exp][:, limb * 5], pose_data[exp][:, limb * 5 + 1],
                 pose_data[exp][:, limb * 5 + 2], pose_data[exp][:,
                                                                 limb * 5 + 3],
                 pose_data[exp][:, limb * 5 + 4])))
        limb_df = pd.DataFrame(limb_data,
                               columns=extended_name_vector[limb *
                                                            5:(limb + 1) * 5])
        sns.lineplot(data=limb_df,
                     palette="Set2",
                     linewidth=1,
                     dashes=False,
                     alpha=.7)
        sns.despine(left=True, right=True, top=True, bottom=True)
        plt.legend(loc='upper left',
                   bbox_to_anchor=(-0.01, -.25),
                   fancybox=False,
                   shadow=False,
                   ncol=3,
                   prop={'size': 8})
        #         plt.plot(pose_data[exp][:,joint], color='k', linewidth=.7, alpha=.5, label=f'Fly {exp}')
        #         # recreate extended_name_vector for this just by removing body-coxa T2 angle.
        plt.title(f'Pose data from {fly_tags[exp]}')
        plt.ylabel('Angle (rad)')
        plt.xlabel('time')
    return