def plot_odor_heading_book(pp, threshold_odor, path, config, dataset, keys=None):

    fig = plt.figure(figsize=(4,4))
    ax = fig.add_subplot(111)
    
    saccades_odor = {'saccade_angles': [], 'heading_prior': []}
    saccades_control = {'saccade_angles': [], 'heading_prior': []}

    for key in keys:
        trajec = dataset.trajecs[key]
        frames_in_odor = np.where(trajec.odor > threshold_odor)[0]
        odor_blocks = hf.find_continuous_blocks(frames_in_odor, 5, return_longest_only=False)
        
        for block in odor_blocks:
            #middle_of_block = int(np.mean(block))
            if len(block) < 5:
                continue
            # find next saccade
            first_sac = None
            #second_sac = None
            #third_sac = None
            for sac in trajec.saccades:
                if trajec.positions[sac[0],0] < -0.15 or trajec.positions[sac[0],0] > 0.9:
                    continue
                    
                if np.abs(trajec.positions[sac[0],1]) > 0.08:
                    continue
                if np.abs(trajec.positions[sac[0],2]) > 0.08:
                    continue
                    
                
                if sac[0] > block[0]:
                    if first_sac is None:
                        first_sac = sac
                        break
                    #elif second_sac is None:
                    #    if trajec.odor[sac[0]] < threshold_odor:
                    #        second_sac = sac
                    #elif third_sac is None:
                    #    if trajec.odor[sac[0]] < threshold_odor:
                    #        third_sac = sac
                    #    break
                
                    
            if first_sac is not None:
                next_sac = first_sac
                angle_of_saccade = tac.get_angle_of_saccade(trajec, next_sac)
                heading_prior_to_saccade = trajec.heading_smooth[next_sac[0]]
                # flip heading
                if heading_prior_to_saccade < 0:
                    heading_prior_to_saccade += np.pi
                else:
                    heading_prior_to_saccade -= np.pi
                
                    
                saccade_angles_after_odor.append(angle_of_saccade)
                heading_at_saccade_initiation.append(heading_prior_to_saccade)
                heading_after_saccade.append(heading_prior_to_saccade + angle_of_saccade)
                speed_at_saccade.append(trajec.speed[next_sac[0]])
        
    saccade_angles_after_odor = np.array(saccade_angles_after_odor)
    heading_at_saccade_initiation = np.array(heading_at_saccade_initiation)
    heading_after_saccade = np.array(heading_after_saccade)
    speed_at_saccade = np.array(speed_at_saccade)
    
    ax.plot(heading_at_saccade_initiation*180./np.pi, saccade_angles_after_odor*180./np.pi, '.', markersize=4)
    #fpl.scatter(ax, heading_at_saccade_initiation*180./np.pi, saccade_angles_after_odor*180./np.pi, color=speed_at_saccade, radius=1)
    #ax.plot(heading_at_saccade_initiation*180./np.pi, heading_after_saccade*180./np.pi, '.')
    
    xticks = [-180, -90, 0, 90, 180]
    yticks = [-180, -90, 0, 90, 180]
    fpl.adjust_spines(ax, ['left', 'bottom'], xticks=xticks, yticks=yticks)
    ax.set_xlabel('Heading before saccade')
    ax.set_ylabel('Angle of saccade')
    
    title_text = 'Odor: ' + trajec.odor_stimulus.title()
    ax.set_title(title_text)
    
    ax.text(0,-180, 'Upwind', horizontalalignment='center', verticalalignment='top')
    ax.text(90,-180, 'Starboard', horizontalalignment='center', verticalalignment='top')
    ax.text(-90,-180, 'Port', horizontalalignment='center', verticalalignment='top')
    
    ax.text(-180,90, 'Starboard', horizontalalignment='left', verticalalignment='center', rotation='vertical')
    ax.text(-180,-90, 'Port', horizontalalignment='left', verticalalignment='center', rotation='vertical')
    
    pp.savefig()
    plt.close('all')
        

    # angle of saccade histogram
    if 0:
        fig = plt.figure(figsize=(4,4))
        ax = fig.add_subplot(111)
        
        fpl.histogram_stack(ax, [np.array(time_to_saccade_cast)], bins=40, bin_width_ratio=0.9, colors=['red'], edgecolor='none', normed=True)

        ax.set_xlabel('Angle of Saccade')
        ax.set_ylabel('Occurences, normalized')
        #xticks = [-180, -90, 0, 90, 180]
        fpl.adjust_spines(ax, ['left', 'bottom'])

        ax.set_title(title_text)

        pp.savefig()
        plt.close('all')
def plot_odor_heading_book(pp, threshold_odor, path, config, dataset, keys=None):

    fig = plt.figure(figsize=(4,4))
    
    ax = fig.add_subplot(111)
    

    saccade_angles_after_odor = []
    heading_at_saccade_initiation = []
    heading_after_saccade = []
    for key in keys:
        trajec = dataset.trajecs[key]
        frames_in_odor = np.where(trajec.odor > threshold_odor)[0]
        odor_blocks = hf.find_continuous_blocks(frames_in_odor, 5, return_longest_only=False)
        
        for block in odor_blocks:
            middle_of_block = int(np.mean(block))
            # find next saccade
            first_sac = None
            second_sac = None
            for sac in trajec.saccades:
                if sac[0] > middle_of_block:
                    if first_sac is None:
                        first_sac = sac
                    elif second_sac is None:
                        if trajec.odor[sac[0]] < threshold_odor:
                            second_sac = sac
                        break
                    
            if first_sac is not None:
                next_sac = first_sac
                angle_of_saccade = tac.get_angle_of_saccade(trajec, next_sac)
                heading_prior_to_saccade = trajec.heading_smooth[next_sac[0]]
                # flip heading
                if heading_prior_to_saccade < 0:
                    heading_prior_to_saccade += np.pi
                else:
                    heading_prior_to_saccade -= np.pi
                # flip saccade angle
                if angle_of_saccade < 0:
                    angle_of_saccade += np.pi
                else:
                    angle_of_saccade -= np.pi
                
                saccade_angles_after_odor.append(angle_of_saccade)
                heading_at_saccade_initiation.append(heading_prior_to_saccade)
                heading_after_saccade.append(heading_prior_to_saccade + angle_of_saccade)
        
    saccade_angles_after_odor = np.array(saccade_angles_after_odor)
    heading_at_saccade_initiation = np.array(heading_at_saccade_initiation)
    heading_after_saccade = np.array(heading_after_saccade)
    
    ax.plot(heading_at_saccade_initiation*180./np.pi, saccade_angles_after_odor*180./np.pi, '.')
    #ax.plot(heading_at_saccade_initiation*180./np.pi, heading_after_saccade*180./np.pi, '.')
    
    xticks = [-180, -90, 0, 90, 180]
    yticks = [-180, -90, 0, 90, 180]
    fpl.adjust_spines(ax, ['left', 'bottom'], xticks=xticks, yticks=yticks)
    ax.set_xlabel('Heading before saccade')
    ax.set_ylabel('Angle of saccade')
    
    title_text = 'Odor: ' + trajec.odor_stimulus.title()
    ax.set_title(title_text)
    
    ax.text(0,-180, 'Upwind', horizontalalignment='center', verticalalignment='top')
    ax.text(90,-180, 'Starboard', horizontalalignment='center', verticalalignment='top')
    ax.text(-90,-180, 'Port', horizontalalignment='center', verticalalignment='top')
    
    ax.text(-180,90, 'Starboard', horizontalalignment='left', verticalalignment='center', rotation='vertical')
    ax.text(-180,-90, 'Port', horizontalalignment='left', verticalalignment='center', rotation='vertical')
    
    pp.savefig()
    plt.close('all')
        

    # angle of saccade histogram
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    fpl.histogram_stack(ax, [saccade_angles_after_odor*180./np.pi], bins=20, bin_width_ratio=0.9, colors=['red'], edgecolor='none', normed=True)

    ax.set_xlabel('Angle of Saccade')
    ax.set_ylabel('Occurences, normalized')
    xticks = [-180, -90, 0, 90, 180]
    fpl.adjust_spines(ax, ['left', 'bottom'], xticks=xticks)

    ax.set_title(title_text)

    pp.savefig()
    plt.close('all')
def plot_landing_histogram(config, dataset, save_figure_path=''):
    keys = get_keys(dataset)
    print 'number of keys: ', len(keys)
    if len(keys) < 1:
        print 'No data'
        return
        
    threshold_distance_min = 0.05
        
    keys_tmp = dataset.trajecs.keys()
    keys = []
    keys_not_near_post = []
    for key in keys_tmp:
        trajec = dataset.trajecs[key]
        if trajec.distance_to_post_min < threshold_distance_min:
            keys.append(key)
        else:
            keys_not_near_post.append(key)
            
    timestamps_not_landings = []
    timestamps_landings = []
    timestamps_not_near_post = []
    for i, key in enumerate(keys):
        trajec = dataset.trajecs[key]
        if 'landing' in trajec.post_behavior:
            timestamps_landings.append( trajec.timestamp_local_float )
        else:
            timestamps_not_landings.append( trajec.timestamp_local_float )
    for key in keys_not_near_post:
        trajec = dataset.trajecs[key]
        timestamps_not_near_post.append(trajec.timestamp_local_float)
    
    # shift so time continuous
    for i, t in enumerate(timestamps_not_landings):
        if t > 12: timestamps_not_landings[i] = t-24
    for i, t in enumerate(timestamps_landings):
        if t > 12: timestamps_landings[i] = t-24
    for i, t in enumerate(timestamps_not_near_post):
        if t > 12: timestamps_not_near_post[i] = t-24
    
            
    timestamps_not_landings = np.array(timestamps_not_landings)
    timestamps_landings = np.array(timestamps_landings)
    timestamps_not_near_post = np.array(timestamps_not_near_post)
    
    fig = plt.figure(figsize=(4,4))
    ax = fig.add_subplot(111)
    
    nbins = 36 # note: if show_smoothed=True with default butter filter, nbins needs to be > ~15 
    bins1 = np.linspace(-12,-0.21,int(nbins/2.),endpoint=True)
    bins2 = np.linspace(-.21,12,int(nbins/2.),endpoint=True)
    #bins = [16.05-24, 17.05-24, 18.05-24, 19.05-24, 20.05-24, 21.05-24, 22.05-24, 23.05-24, 0.05, 1.05, 2.05, 3.05, 4.05, 5.05, 6.05, 7.05, 8.05, 9.05, 10.05]
    bins = np.arange(16.05-24,10.05, 0.5)
    
    
    data = [timestamps_landings, timestamps_not_landings, timestamps_not_near_post]
    if save_figure_path == '':
        save_figure_path = os.path.join(config.path, config.figure_path, 'activity/')
    colors = ['black', 'green']
    
    fpl.histogram_stack(ax, data, bins=bins, bin_width_ratio=0.8, colors=['green', 'black', 'gray'], edgecolor='none', normed=True)
    #fpl.histogram(ax, data, bins=bins, bin_width_ratio=0.8, colors=colors, edgecolor='none', bar_alpha=1, curve_fill_alpha=0.4, curve_line_alpha=0, curve_butter_filter=[3,0.3], return_vals=False, show_smoothed=False, normed=True, normed_occurences=False, bootstrap_std=False, exponential_histogram=False)
    
    if 'on' in config.odor_stimulus.keys():
        odor_on = config.odor_stimulus['on']
        if type(odor_on[0]) is not list: 
            ax.fill_between(np.array(odor_on), -10, 10, color='red', alpha=0.25, zorder=-10, edgecolor='none')
        else:
            for vals in odor_on:
                odor_start = vals[0]
                odor_end = vals[-1]
                if odor_start > 12:
                    odor_start -= 24
                if odor_end > 12:
                    odor_end -= 24
                print 'odor on for time ranges: '
                print odor_start, odor_end
                ax.fill_between(np.array([odor_start, odor_end]), -10, 10, color='red', alpha=0.25, zorder=-10, edgecolor='none')
    
    #xticks = [0,6,12,18,24]
    xticks = [-12,-6,0,6,12]
    fpl.adjust_spines(ax, ['left', 'bottom'], xticks=xticks)
    
    ax.set_xlabel('Time of day, hours')
    ax.set_ylabel('Occurences, normalized')
    ax.set_title('Landings: green -- Nonlandings: black')
    
    fig.set_size_inches(4,4)
    if save_figure_path == '':
        save_figure_path = os.path.join(config.path, config.figure_path, 'activity/')
    figname = save_figure_path + 'landing_histogram' + '.pdf'
    fig.savefig(figname, format='pdf')