def plot_C_hist(self, param_fns=[lambda C_hist: C_hist[:,:,3], lambda C_hist: C_hist[:,:,5], lambda C_hist: C_hist[:,:,6], lambda C_hist: np.sqrt(C_hist[:, :, 3]**2 + C_hist[:,:,5]**2)],
            labels=['Change in x-vel tuning', 'Change in z-vel tuning', 'Change in baseline', 'Change in mod. depth']):
        '''
        Plot parameter trajectories for C
        '''
        C_hist = self.hdf.root.task[1:]['filt_C']
        n_units = C_hist.shape[1]
        n_blocks = int(np.ceil(float(n_units)/7))

        fig = plt.figure(facecolor='w', figsize=(8./3*len(param_fns), 2*n_blocks))
        axes = plotutil.subplots(n_blocks, len(param_fns), y=0.01)
        #, bottom_offset=0.01)
        #fig = plt.figure(figsize=(8, 2*n_units), facecolor='w')
        #axes = plotutil.subplots(n_units, len(param_fns), y=0.01) #, bottom_offset=0.01)

        for m, fn in enumerate(param_fns):
            for k in range(n_blocks):
                sl = slice(k*7, (k+1)*7, None)
                param_hist = fn(C_hist)[:,sl]
                param_hist_diff = param_hist - param_hist[0,:]
                axes[k,m].plot(param_hist_diff)
                axes[k,m].set_xticklabels([])
                if m == 0:
                    plotutil.ylabel(axes[k,m], 'Units %d-%d' % (sl.start, sl.stop-1))
                if k == n_blocks - 1:
                    plotutil.xlabel(axes[k,m], labels[m])

            lims = np.vstack(map(lambda ax: ax.get_ylim(), axes[:,m]))
            ylim = min(lims[:,0]), max(lims[:,1])
            plotutil.set_axlim(axes[:,m], ylim, axis='y')

        self.save_plot('clda_param_hist')
Beispiel #2
0
def plot_dist_to_targ(task_entry,
                      reach_trajectories=None,
                      targ_dist=10.,
                      plot_all=False,
                      ax=None,
                      target=None,
                      update_rate=60.,
                      decoder_rate=10.,
                      **kwargs):
    task_entry = dbfn.lookup_task_entries(task_entry)
    if reach_trajectories == None:
        reach_trajectories = task_entry.get_reach_trajectories()
    if target == None:
        target = np.array([targ_dist, 0])
    trajectories_dist_to_targ = [
        map(np.linalg.norm, traj.T - target) for traj in reach_trajectories
    ]

    step = update_rate / decoder_rate
    trajectories_dist_to_targ = map(lambda x: x[::step],
                                    trajectories_dist_to_targ)
    max_len = np.max([len(traj) for traj in trajectories_dist_to_targ])
    n_trials = len(trajectories_dist_to_targ)

    # TODO use masked arrays
    data = np.ones([n_trials, max_len]) * np.nan
    for k, traj in enumerate(trajectories_dist_to_targ):
        data[k, :len(traj)] = traj

    from scipy.stats import nanmean, nanstd
    mean_dist_to_targ = np.array([nanmean(data[:, k]) for k in range(max_len)])
    std_dist_to_targ = np.array([nanstd(data[:, k]) for k in range(max_len)])

    if ax == None:
        plt.figure()
        ax = plt.subplot(111)

    # time vector, assuming original screen update rate of 60 Hz
    time = np.arange(max_len) * 0.1
    if plot_all:
        for dist_to_targ in trajectories_dist_to_targ:
            ax.plot(dist_to_targ, **kwargs)
    else:
        ax.plot(time, mean_dist_to_targ, **kwargs)

    import plotutil
    #plotutil.set_ylim(ax, [0, targ_dist])
    plotutil.ylabel(ax, 'Distance to target')
    plotutil.xlabel(ax, 'Time (s)')
    plt.draw()
    def plot_rewards_per_min(self, ax=None, show=False, max_ylim=None, save=True, **kwargs):
        '''
        Make a plot of the rewards per minute
        '''
        import plotutil
        tvec, rewards_per_min = self.get_rewards_per_min(**kwargs)
        rewards_per_min = rewards_per_min[::900]
        tvec = tvec[::900]

        # find the time when CLDA turns off
        task_msgs = self.hdf.root.task_msgs[:]
        clda_stop = self.clda_stop_time

        if ax == None:
            plt.figure(figsize=(4,3))
            axes = plotutil.subplots(1, 1, return_flat=True, hold=True, left_offset=0.1)
            ax = axes[0]
        else:
            save = False

        try:
            # find the time when the assist turns off
            assist_level = self.hdf.root.task[:]['assist_level'].ravel()
            assist_stop = np.nonzero(assist_level == 0)[0][0]

            assist_stop *= min_per_sec * 1./self.update_rate # convert to min

            ax.axvline(assist_stop, label='Assist off', color='green', linewidth=2)
        except:
            pass
        ax.axvline(clda_stop, label='CLDA off', color='blue', linewidth=2, linestyle='--')
        ax.plot(tvec * min_per_sec, rewards_per_min, color='black', linewidth=2)
        if max_ylim == None:
            max_ylim = int(max(15, int(np.ceil(max(rewards_per_min)))))
        max_xlim = int(np.ceil(max(tvec * min_per_sec)))
        # plotutil.set_axlim(ax, [0, max_ylim], labels=range(max_ylim+1), axis='y')
        # plotutil.set_axlim(ax, [0, max_ylim], labels=range(0, max_ylim+1), axis='y')
        plotutil.set_xlim(ax, [0, max_xlim])
        plotutil.ylabel(ax, 'Rewards/min', offset=-0.08)
        plotutil.xlabel(ax, 'Time during block (min)')

        plotutil.legend(ax)
        ax.grid()

        if save: self.save_plot('rewards_per_min')

        if show:
            plt.show()
Beispiel #4
0
def plot_pair(perf, labels=['KF', 'PPF']):
    fig = plt.figure(figsize=(4, 8))
    axes = plotutil.subplots(4, 1, hold=True)

    # plot KF, PPFLC
    signs = [-1, +1, +1, -1]
    for k, key in enumerate(
        ['trials_per_min', 'ME', 'reach_time', 'perc_correct']):
        axes[k, 0].scatter(1 * np.ones(len(perf[key][0])), perf[key][0])
        axes[k, 0].scatter(2 * np.ones(len(perf[key][0])), perf[key][1])
        for a, b in izip(*perf[key]):
            axes[k, 0].plot([1., 2.], [a, b], color='black')
        axes[k, 0].set_xticks([1., 2.])
        axes[k, 0].set_xticklabels(labels)
        plotutil.set_xlim(axes[k, 0], axis='y')
        plotutil.ylabel(axes[k, 0], key)
        h, p_val = ttest_rel(perf[key][0], perf[key][1])
        print h, p_val
        if signs[k] * h > 0:
            p_val = p_val / 2
        else:
            pass
        plotutil.xlabel(axes[k, 0], 'p=%g, N=%d' % (p_val, len(perf[key][0])))
Beispiel #5
0
    def plot_2d(self, theta):
        import plotutil
        joint_locs = self.spatial_positions_of_joints(theta)

        targ_x_min = 0
        targ_x_max = 80.5
        targ_y_min = 0
        targ_y_max = 52
        targ_z_min = -40
        targ_z_max = 0

        n_fake_joints = 3 # number of "joints" used to just translate/rotate from positioner origin to exo origin
        shoulder_center = joint_locs[:, n_fake_joints]


        plt.figure(figsize=(9, 3))
        axes = plotutil.subplots2(1, 3, aspect=1, x=0.05)
        axes[0,0].plot(joint_locs[0,n_fake_joints:], joint_locs[1,n_fake_joints:])
        axes[0,0].scatter(shoulder_center[0], shoulder_center[1])
        # draw x-y positioner box
        axes[0,0].plot([targ_x_min, targ_x_min, targ_x_max, targ_x_max, targ_x_min], [targ_y_min, targ_y_max, targ_y_max, targ_y_min, targ_y_min], color='gray', linewidth=2)


        axes[0,1].plot(joint_locs[0,n_fake_joints:], joint_locs[2,n_fake_joints:])
        axes[0,1].scatter(shoulder_center[0], shoulder_center[2])
        # draw x-z positioner box
        axes[0,1].plot([targ_x_min, targ_x_min, targ_x_max, targ_x_max, targ_x_min], [targ_z_min, targ_z_max, targ_z_max, targ_z_min, targ_z_min], color='gray', linewidth=2)


        axes[0,2].plot(joint_locs[1,n_fake_joints:], joint_locs[2,n_fake_joints:])
        axes[0,2].scatter(shoulder_center[1], shoulder_center[2])
        # draw x-z positioner box
        axes[0,2].plot([targ_y_min, targ_y_min, targ_y_max, targ_y_max, targ_y_min], [targ_z_min, targ_z_max, targ_z_max, targ_z_min, targ_z_min], color='gray', linewidth=2)

        plotutil.clean_up_ticks(axes)
        plotutil.set_title(axes[0,0], 'Top view (x-y)')
        plotutil.set_title(axes[0,1], 'Front view (x-z)')
        plotutil.set_title(axes[0,2], 'Side view (y-z)')

        plotutil.xlabel(axes[0,0], 'x-axis')
        plotutil.ylabel(axes[0,0], 'y-axis')
        plotutil.xlabel(axes[0,1], 'x-axis')
        plotutil.ylabel(axes[0,1], 'z-axis')
        plotutil.xlabel(axes[0,2], 'y-axis')
        plotutil.ylabel(axes[0,2], 'z-axis')

        plt.show()
        plt.draw()        
Beispiel #6
0
blocks = [2274, 2275, 2276, 2277, 2281, 2282]
task_entry_set = dbfn.TaskEntrySet(blocks)

bins = np.arange(0.5, 40, 0.5)

labels = []
for te in task_entry_set.task_entries:
    if 'PPF' in te.decoder_type: labels.append(str(te.params['tau']))
    elif 'KF' in te.decoder_type: labels.append('KF')

plt.close('all')
plt.figure(facecolor='w')
axes = plotutil.subplots(2, 1, return_flat=True, hold=True)
#task_entry_set.histogram(lambda te: te.intended_kin_norm(slice(3,6)), axes[0], bins)
task_entry_set.histogram(lambda te: te.cursor_speed(), axes[1], bins, labels=labels)
#task_entry_set.histogram(lambda te: te.cursor_speed('assist_off'), axes[1], bins, labels=labels)
plt.legend()

axes[0].set_xticks([])

plotutil.xlabel(axes[0], 'Est. of intended speed (cm/s)')

plotutil.xlabel(axes[1], 'Actual speed during CLDA (no assist) (cm/s)')
plotutil.set_xlim(axes[0], axis='y')
plotutil.set_xlim(axes[1], axis='y')
plotutil.ylabel(axes, 'Density')
plotutil.set_xlim(axes, [0,40])

plt.savefig('/storage/plots/intended_vs_actual_speed.png', bbox_inches='tight')
plt.show()