def plot_demo_flyby(dataset, key):  


    trajec = dataset.trajecs[key]
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_ylim(-.15,.15)
    ax.set_xlim(-.25, .25)
    ax.set_autoscale_on(False)
    ax.set_aspect('equal')
    
    frames = np.arange(0,trajec.frames_of_flyby[-1]).tolist()
    ax.plot(trajec.positions[:,0], trajec.positions[:,1], color='gray')
    ax.plot(trajec.positions[frames,0], trajec.positions[frames,1], color='black')
    
    if len(trajec.all_saccades) > 0:
        for s in trajec.all_saccades:
            if s < trajec.frame_nearest_to_post:
                sac_range = fa.get_saccade_range(trajec, s) 
                ax.plot(trajec.positions[sac_range,0], trajec.positions[sac_range,1], '-', color='green', alpha=1, linewidth=1)
                sac = patches.Circle( (trajec.positions[sac_range[0],0], trajec.positions[sac_range[0],1]), radius=0.002, facecolor='green', edgecolor='none', alpha=1, zorder=100)
                ax.add_artist(sac)
    
    post = patches.Circle( (0, 0), radius=0.009565, facecolor='black', edgecolor='none', alpha=1)
    ax.add_artist(post)
    
    fig.savefig('demo_flyby_flydra.pdf', format='pdf')
def get_slipangles(movie, behavior='straight'):
    fa.prep_movie_trajec(movie)
    trajec = movie.trajec
    
    # look at all frames not in saccade range or within 1cm of post
    closest_dist = 0.01
    
    first_frame = sa1.get_frame_from_timestamp_flydra(movie, movie.timestamps[0])
    last_frame = sa1.get_frame_from_timestamp_flydra(movie, movie.timestamps[-1])
    last_frame = np.min([last_frame, len(trajec.speed)-1]) 
    
    saccade_frames = []
    if len(trajec.saccades) > 0:
        for s in trajec.saccades:
            sac_range = fa.get_saccade_range(trajec, s)
            saccade_frames.extend(sac_range)
    straight_frames = []
    saccade_frames = []
    landing_frames = []
    print first_frame, last_frame
    for f in range(first_frame, last_frame):
        print f
        if f in saccade_frames:
            print 'x'
            saccade_frames.append(f)
        if trajec.dist_to_stim_r_normed[f] < closest_dist and trajec.behavior == 'landing':
            print 'y'
            landing_frames.append(f)
        else:
            straight_frames.append(f)
            
    if behavior == 'straight':
        frames = straight_frames
    elif behavior == 'saccade':
        frames = saccade_frames
    elif behavior == 'landing':
        frames = landing_frames
    
    slipangles = []
    for f in frames:
        sa1f = sa1.get_frame_from_timestamp(movie, trajec.epoch_time[f])
        slipangles.append(movie.scaled.slipangle[sa1f])
        
    for i, s in enumerate(slipangles):
        while slipangles[i] > np.pi:
            slipangles[i] -= np.pi
        while slipangles[i] < -np.pi:
            slipangles[i] += np.pi
        
    return slipangles
def plot_demo_trajectory_speed_vs_angle(movie_dataset=None, movie_landing=None, movie_flyby=None, filename=None):
    
    if movie_dataset is not None:
        movie_landing = movie_dataset.movies['20101110_C001H001S0038']
        movie_flyby = movie_dataset.movies['20101101_C001H001S0024']
    
    fig = plt.figure()
    angleax = fig.add_subplot(111)

    
    ## landing    
    trajec = movie_landing.trajec
    ftp = np.arange(trajec.frames[0]-25, trajec.frames[-1]).tolist()
    angleax.plot( np.log(trajec.angle_subtended_by_post[ftp]), trajec.speed[ftp], color='black')
    angleax.plot( np.log(trajec.angle_at_deceleration), trajec.speed_at_deceleration, '.', markerfacecolor='blue', markeredgecolor='blue')
    
    
    movieinfo = movie_landing
    legextensionframe = movieinfo.legextensionrange[0] - movieinfo.firstframe_ofinterest
    time_of_leg_ext = movieinfo.timestamps[legextensionframe]
    flydra_frame_of_leg_ext = fa.get_flydra_frame_at_timestamp(trajec, time_of_leg_ext)+1
    angleax.plot( np.log(trajec.angle_subtended_by_post[flydra_frame_of_leg_ext]), trajec.speed[flydra_frame_of_leg_ext], '.', markerfacecolor='red', markeredgecolor='red')
    
    ## flyby
    trajec = movie_flyby.trajec
    ftp = np.arange(trajec.frames[0]-25, trajec.frames[-1]).tolist()
    angleax.plot( np.log(trajec.angle_subtended_by_post[ftp]), trajec.speed[ftp], '-', color='black')

    sf = fa.get_saccade_range(trajec, trajec.saccades[-1]) 
    angleax.plot( np.log(trajec.angle_subtended_by_post[sf[0]]), trajec.speed[sf[0]], '.', markerfacecolor='green', markeredgecolor='green')
    angleax.plot( np.log(trajec.angle_subtended_by_post[sf]), trajec.speed[sf], '-', color='green')
    angleax.plot( np.log(trajec.angle_at_deceleration), trajec.speed_at_deceleration, '.', markerfacecolor='blue', markeredgecolor='blue')
    
    fa.fix_angle_log_spine(angleax, histograms=False) 
    
    
    if filename is not None:
        fig.subplots_adjust(right=0.9, bottom=0.3)
        fig.savefig(filename, format='pdf')
    return angleax
def plot_demo_trajectory(movieinfo, nudge, filename=None):
    trajec = movieinfo.trajec

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_autoscale_on(False)
    ax.set_xlim(-0.02, 0.05)
    ax.set_ylim(-0.02, 0.05)
    ax.set_axis_off()
    cl = colorline.Colorline( xlim=ax.get_xlim(), ylim=ax.get_ylim(), norm=(0,0.8), colormap = 'jet', hide_colorbar=True, ax0=ax)
    # plot trajectory
    frames = np.arange(50, trajec.frame_of_landing).tolist()
    cl.colorline( trajec.positions[frames,0], trajec.positions[frames,1], trajec.speed[frames],linewidth=1, alpha=0.5)

    # parameters
    radius = trajec.radius_at_nearest
    
    if trajec.behavior == 'landing':
        # show pt of deceleration
        f = trajec.frame_at_deceleration
        x = trajec.positions[f,0]
        y = trajec.positions[f,1]
        pt_of_deceleration = patches.Circle( (x,y), radius=0.0005, facecolor='blue', edgecolor='none')
        ax.add_artist(pt_of_deceleration)
        
        # anotate deceleration point
        string = 'deceleration initiation'
        string_position = (x-0.005, y+.015)
        arrow = {'facecolor':'blue', 'arrowstyle':"->", 'edgecolor':'blue', 'linewidth':1}
        ax.annotate(string, (x-.0001,y+.0001),
            xytext=string_position,
            arrowprops=arrow,
            horizontalalignment='right', verticalalignment='top', color='blue')
        
    # show angle subtended
    if trajec.behavior == 'landing':
        f = trajec.frames[20]
        x = np.mean(trajec.positions[f-1:f+1,0])
        y = np.mean(trajec.positions[f-1:f+1,1])
    else:   
        f = trajec.frames[17]
        x = trajec.positions[f,0]
        y = trajec.positions[f,1]
    d = np.linalg.norm([x,y])
    half_angle_to_post = np.arcsin( radius / d )
    world_angle = np.arctan2(y,x)
    
    a = half_angle_to_post - world_angle
    visual_intercept_1 = [0+np.cos(np.pi/2.-a)*radius, 0+np.sin(np.pi/2.-a)*radius]
    
    a = half_angle_to_post + world_angle
    visual_intercept_2 = [0+np.cos(np.pi/2.-a)*radius, 0-np.sin(np.pi/2.-a)*radius]
    
    xy = np.vstack( (visual_intercept_1, visual_intercept_2, [x,y]) )
    triangle = patches.Polygon( xy, facecolor='purple', edgecolor='none', zorder=-10, alpha=0.2 )
    ax.add_artist(triangle)
    
    # dist to post
    ox = np.cos(world_angle)*radius
    oy = np.sin(world_angle)*radius
    ax.plot([ox,x], [oy,y], color='brown', linewidth=1, alpha=0.5)
    
        
    # angle arc
    if trajec.behavior == 'landing':
        arc = patches.Arc( (x,y), .03, .03, 180, np.abs((half_angle_to_post - world_angle))*180/np.pi, (half_angle_to_post + world_angle)*180/np.pi, edgecolor='purple', linewidth=0.5)
    else:
        arc = patches.Arc( (x,y), .05, .05, 180, (world_angle - half_angle_to_post)*180/np.pi, (half_angle_to_post + world_angle)*180/np.pi, edgecolor='purple', linewidth=1)
    ax.add_artist(arc)
    if trajec.behavior == 'landing':
        ax.text(.02, .006, 'retinal size', color='purple', horizontalalignment='center', verticalalignment='center')
        ax.text(.02, 0, 'distance\nto post', color='brown', horizontalalignment='center', verticalalignment='center')
    else:
        ax.text(.02, -0.01, 'retinal size', color='purple', horizontalalignment='center', verticalalignment='center')
        ax.text(.02, -0.015, 'distance\nto post', color='brown', horizontalalignment='center', verticalalignment='center')
    
    if trajec.behavior == 'landing': 
        # show pt of leg extension
        legextensionframe = movieinfo.legextensionrange[0] - movieinfo.firstframe_ofinterest
        time_of_leg_ext = movieinfo.timestamps[legextensionframe]
        flydra_frame_of_leg_ext = fa.get_flydra_frame_at_timestamp(trajec, time_of_leg_ext)+1
        x = trajec.positions[flydra_frame_of_leg_ext, 0]
        y = trajec.positions[flydra_frame_of_leg_ext, 1]
        pt_of_leg_ext = patches.Circle( (x,y), radius=0.0005, facecolor='red', edgecolor='none')
        ax.add_artist(pt_of_leg_ext)

        # anotate leg extension point
        string = 'leg extension'
        string_position = (x, y+.01)
        arrow = {'facecolor':'red', 'arrowstyle':"->", 'edgecolor':'red', 'linewidth':1}
        ax.annotate(string, (x-.0001,y+.0001),
            xytext=string_position,
            arrowprops=arrow,
            horizontalalignment='center', verticalalignment='top', color='red')
            
                    
    if trajec.behavior == 'flyby':
        '''
        s = trajec.saccades[0]
        x = trajec.positions[s, 0]
        y = trajec.positions[s, 1]
        pt_of_saccade = patches.Circle( (x,y), radius=0.0005, facecolor='green', edgecolor='none')
        ax.add_artist(pt_of_saccade)
        '''
        
        # show saccade duration
        saccade_frames = fa.get_saccade_range(trajec, trajec.saccades[-1])
        x = trajec.positions[saccade_frames, 0]
        y = trajec.positions[saccade_frames, 1]
        ax.plot(x,y,'-', color='green')
        
        s = saccade_frames[0]
        x = trajec.positions[s, 0]
        y = trajec.positions[s, 1]
        pt_of_saccade = patches.Circle( (x,y), radius=0.0005, facecolor='green', edgecolor='none')
        ax.add_artist(pt_of_saccade)
        
        # anotate saccade point
        string = 'saccade initiation'
        string_position = (x+0.01, y+.01)
        arrow = {'facecolor':'green', 'arrowstyle':"->", 'edgecolor':'green', 'linewidth':1}
        ax.annotate(string, (x-.0001,y+.0001),
            xytext=string_position,
            arrowprops=arrow,
            horizontalalignment='right', verticalalignment='top', color='green')
            
            
            
        if trajec.frame_at_deceleration is not None:
            x = trajec.positions[trajec.frame_at_deceleration, 0]
            y = trajec.positions[trajec.frame_at_deceleration, 1]
            pt_of_deceleration = patches.Circle( (x,y), radius=0.0005, facecolor='blue', edgecolor='none')
            ax.add_artist(pt_of_deceleration)
            
            # anotate deceleration point
            string = 'deceleration initiation'
            string_position = (x-0.005, y+.015)
            arrow = {'facecolor':'blue', 'arrowstyle':"->", 'edgecolor':'blue', 'linewidth':1}
            ax.annotate(string, (x-.0001,y+.0001),
                xytext=string_position,
                arrowprops=arrow,
                horizontalalignment='right', verticalalignment='top', color='blue')
    
    post = patches.Circle( (0,0), radius=radius, facecolor='black', edgecolor='none')
    ax.add_artist(post)
    
    # annotate post
    ax.text( 0,0, 'post\n(top view)', color='gray', verticalalignment='center', horizontalalignment='center', fontsize=9)
    
    if movieinfo is not None:
        strobe = sa1.strobe_from_movieinfo(movieinfo, interval=200)
        ax.imshow(strobe.T, plt.get_cmap('gray'), origin='lower', extent = [-1*movieinfo.post_pos[0]*movieinfo.scale+nudge[0], (1024-movieinfo.post_pos[0])*movieinfo.scale+nudge[0], -1*movieinfo.post_pos[1]*movieinfo.scale+nudge[1], (1024-movieinfo.post_pos[1]+nudge[1])*movieinfo.scale], zorder=-20)
    
    
    
    
    # scale bar
    ax.hlines(-.012, -.005+.04, .005+.04, color='black')
    ax.vlines(-.005+.04, -.012+.0005, -.012-.0005, color='black')
    ax.vlines(.005+.04, -.012+.0005, -.012-.0005, color='black')
    ax.text( .04, -.0125, '1 cm', horizontalalignment='center', verticalalignment='top', fontsize=9)
    
    
    ax.set_aspect('equal')
    fig.subplots_adjust(bottom=0., top=1, right=1, left=0)
    #fig.set_size_inches(6.5,3.25)
    fig.savefig(filename, format='pdf')
        
    return