Beispiel #1
0
def landing_analysis_for_crash_comparison(dataset, keys=None):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    if keys is None:
        classified_keys = fa.get_classified_keys(dataset)
        keys = classified_keys['straight']
        keys = dataset.trajecs.keys()
        
    for key in keys:
        trajec = dataset.trajecs[key]
        ftp = np.arange(trajec.frames[0]-25, trajec.frames[-1]).tolist()
        ax.plot( np.log(trajec.angle_subtended_by_post[ftp]), trajec.speed[ftp], color='black', linewidth=0.5, alpha=0.05)

    keys_to_highlight = ['2_29065', '2_31060', '8_10323', '6_715']
    for key in keys:
    
        color = 'gray'
        dotcolor = 'blue'
        if key in keys_to_highlight:
            color = 'black'
            dotcolor = 'purple'
    
        trajec = dataset.trajecs[key]
        ftp = np.arange(trajec.frames[0]-25, trajec.frames[-1]).tolist()
        ax.plot( np.log(trajec.angle_subtended_by_post[ftp]), trajec.speed[ftp], color=color, linewidth=0.5, alpha=1)
        ax.plot( np.log(trajec.angle_at_deceleration), trajec.speed_at_deceleration, '.', color=dotcolor, alpha=1)
        
    fit, Rsq, x, y, yminus, yplus = fa.get_angle_vs_speed_curve(dataset, plot=False)
    ax.plot( x, y, color='purple')
    ax.fill_between(x, yplus, yminus, color='purple', linewidth=0, alpha=0.2)
        
    fa.fix_angle_log_spine(ax, histograms=False)
    fig.savefig('landing_for_crash_comparison.pdf', format='pdf')
def decleration_color_coded_for_post(dataset, plot=True):

    fa.calc_stats_at_deceleration(dataset, keys=None, time_offset=0, return_vals=False)
    angleok = np.where( (dataset.angle_at_deceleration < 2)*(dataset.angle_at_deceleration > .01) )[0].tolist()
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    black_post = []
    checkered_post = []
    for i, p in enumerate(dataset.post_type_at_deceleration):
        if i in angleok:
            if 'black' in p:
                black_post.append(i)
            if 'checkered' in p:
                checkered_post.append(i)
            
    print '*'*40
    print len(black_post), len(checkered_post)
    
    bins, hists, hist_std, curves = floris.histogram(ax, [np.log(dataset.angle_at_deceleration[black_post]), np.log(dataset.angle_at_deceleration[checkered_post])], bins=16, colors=['black', 'teal'], bin_width_ratio=0.9, edgecolor='none', bar_alpha=0.2, curve_fill_alpha=0, curve_line_alpha=0.8, return_vals=True, normed_occurences='total', bootstrap_std=True)
    
    ax.plot(np.log(dataset.angle_at_deceleration[black_post]), dataset.speed_at_deceleration[black_post], '.', color='black', alpha=1)
    ax.plot(np.log(dataset.angle_at_deceleration[checkered_post]), dataset.speed_at_deceleration[checkered_post], '.', color='teal', alpha=1)
    
    #ax.set_ylim(0,1.2)
    fa.fix_angle_log_spine(ax, histograms=True)
    
    fig.savefig('deceleration_color_coded.pdf', format='pdf')
Beispiel #3
0
def crash_analysis(dataset, dataset_landing, keys=None):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    keys = dataset.trajecs.keys()
        
    for key in keys:
        trajec = dataset.trajecs[key]
        ftp = np.arange(trajec.frames[0], trajec.frames[-1]).tolist()
        
        color = 'gray'
        dotcolor = 'blue'
        if key == '20101111_C001H001S0045':
            color = 'purple'
            dotcolor = 'purple'
            
        if trajec.angle_at_deceleration*180/np.pi > 90:
            print key
        
        ax.plot( np.log(trajec.angle_subtended_by_post[ftp]), trajec.speed[ftp], color=color, linewidth=0.5, alpha=1)
        ax.plot( np.log(trajec.angle_at_deceleration), trajec.speed_at_deceleration, '.', color=dotcolor, alpha=1)
        
    fit, Rsq, x, y, yminus, yplus = fa.get_angle_vs_speed_curve(dataset_landing, plot=False)
    ax.plot( x, y, color='purple')
    ax.fill_between(x, yplus, yminus, color='purple', linewidth=0, alpha=0.2)
    
    fa.fix_angle_log_spine(ax, histograms=False)
    fig.savefig('crash_spagetti.pdf', format='pdf')
def plot_tti_wrt_retinal_size(dataset, keys=None, tti_thresh=0.05, plot=False):
    
    if plot:
        fig = plt.figure()
        ax = fig.add_subplot(111)
    
    
    if keys is None:
        classified_keys = fa.get_classified_keys(dataset)
        keys = classified_keys['straight']
        keys = dataset.trajecs.keys()
        
    #keys = keys[0:10]
    
    tti_below_thresh = []
        
    for key in keys:
        trajec = dataset.trajecs[key]
        ftp = np.arange(trajec.frame_at_deceleration-10, trajec.frame_of_landing-1).tolist()
        # simulate
        if plot:
            ax.plot( np.log(trajec.angle_subtended_by_post[ftp]), trajec.time_to_impact[ftp], '.', color='black', alpha=0.3)
            
        #tti_check = (np.sin(angle_subtended/2.)-1) / (np.sin(angle_subtended/2.) + 0.5*1/np.tan(angle_subtended/2.)*expansion)
            
        try:
            tti_below_thresh.append( trajec.angle_subtended_by_post[ np.where( (trajec.time_to_impact < tti_thresh)*(trajec.angle_to_post < 45*np.pi/180.) )[0][0] ])
        except:
            pass
            
    print 
    print 'time to impact below threshold of ', str(tti_thresh), ' sec: '
    print 'mean: ', np.mean(tti_below_thresh)*180/np.pi
    print 'std dev: ', np.std(tti_below_thresh)*180/np.pi
    print 'n: ', len(tti_below_thresh)
    print 'percent: ', len(tti_below_thresh) / float(len(keys))
        
    if plot:
        fa.fix_angle_log_spine(ax, histograms=False, set_y=False)
        ax.set_ylim(0,0.4)
        ticks_y = np.linspace(0,0.4,5,endpoint=True)
        tick_strings_y = [str(s) for s in np.linspace(0,0.4,5,endpoint=True)]
        for i, s in enumerate(tick_strings_y):
            tick_strings_y[i] = s
        ax.set_yticks(ticks_y)
        ax.set_yticklabels(tick_strings_y)
        ax.set_ylabel('time to impact, sec')
        fig.savefig('time_to_impact_vs_angle.pdf', format='pdf')
def plot_expansion_for_sim_trajec(dataset, gain=[170000], keys=None):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    
    if keys is None:
        classified_keys = fa.get_classified_keys(dataset)
        keys = classified_keys['straight']
        #keys = dataset.trajecs.keys()
        
    keys = keys[0:10]
        
    for key in keys:
        trajec = dataset.trajecs[key]
        ftp = np.arange(trajec.frame_at_deceleration-10, trajec.frame_of_landing-1).tolist()
        # simulate
        angle, speed, expansion = sim_deceleration(trajec, gain)
        #ax.plot( np.log(angle), expansion, color='red', linewidth=0.5, alpha=0.5)
        ax.plot( np.log(trajec.angle_subtended_by_post[ftp]), trajec.expansion[ftp], color='black', linewidth=0.5, alpha=0.1)
        ax.plot( np.log(trajec.angle_at_deceleration), trajec.expansion_at_deceleration, '.', color='blue') 
        angle, speed, expansion = sim_deceleration(trajec, gain, constant_vel=True)
        #ax.plot( np.log(angle), expansion, color='green', linewidth=1, alpha=0.5)
        
    angle, expthreshold, expthreshold_tti = test_neural_threshold(save_plot=False, tti=0.05, tti_thresh=6)
    
    ax.plot(np.log(angle), expthreshold, color='blue')
    ax.plot(np.log(angle), expthreshold_tti, color='green')
    
    angle, expthreshold, expthreshold_tti = test_neural_threshold(save_plot=False, tti=0.12, tti_thresh=0.7)
    ax.plot(np.log(angle), expthreshold_tti, color='red')
        
    fa.fix_angle_log_spine(ax, histograms=False, set_y=False)
    exp_limit = 1500
    ax.set_ylim(0,exp_limit/180.*np.pi)
    rad_ticks_y = np.linspace(0,exp_limit*np.pi/180.,5,endpoint=True)
    deg_tick_strings_y = [str(s) for s in np.linspace(0,exp_limit,5,endpoint=True)]
    for i, s in enumerate(deg_tick_strings_y):
        deg_tick_strings_y[i] = s.split('.')[0]
    ax.set_yticks(rad_ticks_y)
    ax.set_yticklabels(deg_tick_strings_y)
    ax.set_ylabel('expansion threshold, deg/s')
    fig.savefig('deceleration_real.pdf', format='pdf')
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 landing_spagetti_plots(dataset, gain=[170000], keys=None):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    fig2 = plt.figure()
    ax2 = fig2.add_subplot(111)
    
    fig3 = plt.figure()
    ax3 = fig3.add_subplot(111)
    
    if keys is None:
        classified_keys = fa.get_classified_keys(dataset)
        keys = classified_keys['straight']
        #keys = dataset.trajecs.keys()
        
    #keys_to_highlight = [keys[2], keys[0], keys[4], keys[6]]
    keys_to_highlight = ['2_29065', '2_31060', '8_10323', '6_715']
    points_at_deceleration = True
        
    for key in keys:
        trajec = dataset.trajecs[key]
        ftp = np.arange(trajec.frames[0]-25, trajec.frame_of_landing-1).tolist()
        #ftp = np.arange(trajec.frame_at_deceleration-10, trajec.frame_of_landing-1).tolist()
        if key in keys_to_highlight:
            color = 'black'
            zorder = 10
        else:
            color = 'blue'
            zorder = 1
        ax.plot( np.log(trajec.angle_subtended_by_post[ftp]), trajec.speed[ftp], color=color, linewidth=0.5, alpha=1, zorder=zorder)
        if points_at_deceleration and key in keys_to_highlight:
            ax.plot( np.log(trajec.angle_at_deceleration), trajec.speed_at_deceleration, '.', color='black', alpha=1, zorder=zorder)
        
        ax3.plot( np.log(trajec.angle_subtended_by_post[ftp]), trajec.speed[ftp], color='black', linewidth=0.5, alpha=1)
        
        if 0:
            # simulate
            angle, speed, expansion = sim_deceleration(trajec, gain)
            if speed[0] > 0.1:        
                ax2.plot( np.log(angle), speed, color='black', linewidth=0.5, alpha=1)
                ax3.plot( np.log(angle), speed, color='black', linewidth=0.5, alpha=1)
                f = np.where( np.abs(speed-speed[0])>0 )[0][0]
                
                #ax2.plot( np.log(angle[f]), speed[f], '.', color='blue')
            
    fit, Rsq, x, y, yminus, yplus = fa.get_angle_vs_speed_curve(dataset, plot=False)
    ax2.plot( x, y, color='purple', alpha=1)
    ax2.fill_between(x, yplus, yminus, color='purple', linewidth=0, alpha=0.2)

    ax.plot( x, y, color='purple', alpha=1)
    ax.fill_between(x, yplus, yminus, color='purple', linewidth=0, alpha=0.2)
        
    fa.fix_angle_log_spine(ax, histograms=False)
    fig.savefig('deceleration_real.pdf', format='pdf')
    
    fa.fix_angle_log_spine(ax2, histograms=False)
    fig2.savefig('deceleration_sim.pdf', format='pdf')
    
    fa.fix_angle_log_spine(ax3, histograms=False)
    fig3.savefig('deceleration_comparison.pdf', format='pdf')
def neural_threshold_tti_vs_rsdet_models(dataset_landing, save_plot=True, movie_dataset=None, ttc=None):
    
    distfig = plt.figure()
    distax = distfig.add_subplot(111)
    
    radius = 0.009565
    a = np.linspace(0,2.5,100)
    
    fit, Rsq, x, y, yminus, yplus = fa.get_angle_vs_speed_curve(dataset_landing, plot=False, plot_sample_trajecs=False, post_type=['checkered', 'checkered_angled', 'black', 'black_angled'], filename=None, keys=None, tti=None, color_code_posts=False)
    std = np.mean(yplus - y)
    
    # RSDET model
    m = fit[0]
    b = fit[1]
    vel = (m*np.log(a)+b)
    
    
    print std, fit
    
    expthreshold = expansion(vel, a=a)
    
    expthreshold_plus = expansion(vel+std, a=a)
    expthreshold_minus = expansion(vel-std, a=a)
    distax.plot( np.log(a), expthreshold, color='purple')
    distax.fill_between(np.log(a), expthreshold_plus, expthreshold_minus, color='purple', linewidth=0, alpha=0.3)
    
    # True time-to-contact model
    if ttc is None:
        ttc, ttc_threshold = match_ttc_to_rsdet(ttc0=0.13, ttc_threshold0=0)
    ttc_threshold = 0
    expthreshold_ttc = expansion_from_timetocontact(ttc, a) + ttc_threshold
    distax.plot( np.log(a), expthreshold_ttc, ':', color='purple')
    
    
    
    
    # plot a sample constant velocity trajectory
    vels = [0.2, 0.4, 0.8]
    
    for vel in vels:
        fps = 5000.0
        x = np.arange(.2, 0.0, -vel/fps)
        d = x+radius
        a = 2*np.arcsin(radius / (d))
        #exp = 2/np.sqrt(1-(radius/(d))**2) * (radius/(d)**2) * vel
        exp = expansion(vel, a=a)
        indices = np.where(exp<12)[0].tolist()
        distax.plot( np.log(a[indices]), exp[indices], color='gray', linewidth=0.5)
    
    
    # plot parameters    
    fa.fix_angle_log_spine(distax, histograms=False, set_y=False)
    ylim_max = 1000
    distax.set_ylim(0,ylim_max/180.*np.pi)
    rad_ticks_y = np.linspace(0,ylim_max*np.pi/180.,5,endpoint=True)
    deg_tick_strings_y = [str(s) for s in np.linspace(0,ylim_max,5,endpoint=True)]
    for i, s in enumerate(deg_tick_strings_y):
        deg_tick_strings_y[i] = s.split('.')[0]
    distax.set_yticks(rad_ticks_y)
    distax.set_yticklabels(deg_tick_strings_y)
    distax.set_ylabel('Expansion, deg/s')
    
    if save_plot:
        distfig.savefig('neural_threshold_distance.pdf', format='pdf')
        
    return
def landing(dataset_landing, movie_dataset, speed=0.2):

    behavior = 'landing'
    
    
    fps = 1000.
    dt = 1/fps
    r = 0.009565
    radius = r
    pos0 = [-0.2, 0]
    vel = [speed, 0]
    dvda = -0.2
    
    nf = 5000
    positions = np.zeros([nf, 2])
    positions[0] = pos0
    velocities = np.zeros([nf, 2])
    velocities[0] = vel
    speed = np.zeros([nf])
    speed[0] = np.linalg.norm(velocities[0])
    distance = np.zeros([nf])
    angle_subtended_by_post = np.zeros([nf])
    leg_ext = np.zeros([nf])
    frames = [0]
    frame_at_deceleration = None
    deceleration_initiated = False
    
    for f in range(1,nf): 
        if np.linalg.norm(positions[f-1])-radius <= 0.0001:
            landed = True
        else:
            landed = False
            
            
        if not landed:
            frames.append(f)
            positions[f] = positions[f-1] + velocities[f-1]*dt
            distance[f] = np.linalg.norm(positions[f]) - radius
            angle_subtended_by_post[f] = 2*np.arcsin( radius / (distance[f]+radius) )
            
            if f>5:
                #velocities[f,0] = -.21*np.log(angle_subtended_by_post[f])+.2
                da = np.log(angle_subtended_by_post[f])-np.log(angle_subtended_by_post[f-1])
                
                a = angle_subtended_by_post
                af = np.min([a[f], 3])
                exp0 = (a[f]-a[f-1])/dt #/ (-2.*np.tan(a[f]/2.))
                exp1 = (a[f-1]-a[f-2])/dt #/ (-2.*np.tan(a[f-1]/2.))
                
                m = -0.21/radius
                b = 0.159/radius
                expthreshold = (m*np.log(af)+b)*(2*np.tan(af/2.)*np.sin(af/2.))
        
                exp0 -= expthreshold
                exp1 -= expthreshold
                
                exp0 = np.max([exp0, 0])
                exp1 = np.max([exp1, 0])
                
                #c = -1*exp0 / 3500.
                
                dda = (exp1-exp0)/dt
                c = dda / 150000.
                print dda, velocities[f-1,0]
                
                c = np.min([c,0])
                v = np.max([speed[f-1] + c, 0.0])
                
                velocities[f,0] = v
            else:
                velocities[f] = velocities[f-1]

            speed[f] = np.linalg.norm(velocities[f])
            if speed[f] > -0.21*np.log(angle_subtended_by_post[f])+0.159:
                deceleration_initiated = True
                if frame_at_deceleration is None:
                    frame_at_deceleration = f
            else:
                deceleration_initiated = False
                
            if angle_subtended_by_post[f]*180/np.pi > 70 or np.isnan(angle_subtended_by_post[f]):
                leg_ext[f] = 1

    
    
            
            
    fig2 = plt.figure()  
    ax2 = fig2.add_subplot(111)
    
    fit, Rsq, x, y, yminus, yplus = fa.get_angle_vs_speed_curve(dataset_landing, plot=False)
    ax2.plot( x, y, color='blue', alpha=0.3)
    ax2.fill_between(x, yplus, yminus, color='blue', linewidth=0, alpha=0.2)
    
    angle_at_leg_extension, bins, data_filtered, xvals = fa.leg_extension_angle_histogram(movie_dataset, plot=False)
    ax2.plot(xvals, data_filtered, color='red', alpha=0.3)
    ax2.fill_between(xvals, data_filtered, np.zeros_like(xvals), color='red', linewidth=0, alpha=0.2)
    
    ax2.plot(np.log(angle_subtended_by_post), speed, color='black')
    
    fa.fix_angle_log_spine(ax2, histograms=False) 
    
    fig2.subplots_adjust(bottom=0.3, top=0.8, right=0.9, left=0.25)
    
    filename = 'landing_cartoon_plot.pdf'
    fig2.savefig(filename, format='pdf')
def flyby(dataset_flyby, speed=0.5):

    behavior = 'flyby'
    
    
    fps = 100.
    dt = 1/fps
    r = 0.009565
    radius = r
    pos0 = [-0.2, 0]
    vel = [speed, 0]
    dvda = -0.2
    
    nf = 200
    positions = np.zeros([nf, 2])
    positions[0] = pos0
    velocities = np.zeros([nf, 2])
    velocities[0] = vel
    speed = np.zeros([nf])
    speed[0] = np.linalg.norm(velocities[0])
    distance = np.zeros([nf])
    angle_subtended_by_post = np.zeros([nf])
    frames = [0]
    frame_at_deceleration = None
    frame_at_saccade = None
    deceleration_initiated = False
    saccade_time = 0
    saccading = False
    
    for f in range(1,nf): 

        frames.append(f)
        positions[f] = positions[f-1] + velocities[f-1]*dt
        distance[f] = np.linalg.norm(positions[f]) - radius
        angle_subtended_by_post[f] = 2*np.arcsin( radius / (distance[f]+radius) )
        
        if saccading:
            saccade_rate = 400*np.pi/180.
            s = np.linalg.norm(velocities[f-1])
            velocities[f,1] = np.sin(saccade_rate)*s
            velocities[f,0] = np.cos(saccade_rate)*s
        elif deceleration_initiated:
            worldangle = np.arctan2(velocities[f-1,1], velocities[f-1,0])
            da = np.log(angle_subtended_by_post[f])-np.log(angle_subtended_by_post[f-1])
            velocities[f,1] = velocities[f-1,1] + dvda*da*np.sin(worldangle)
            velocities[f,0] = velocities[f-1,0] + dvda*da*np.cos(worldangle)
        else:
            velocities[f] = velocities[f-1]

        speed[f] = np.linalg.norm(velocities[f])
        if speed[f] > -0.1*np.log(angle_subtended_by_post[f])+0.212 and saccade_time == 0:
            deceleration_initiated = True
            print 'decelerating triggered'
            if frame_at_deceleration is None:
                frame_at_deceleration = f
        else:
            pass
            #deceleration_initiated = False
            
        if angle_subtended_by_post[f]*180/np.pi > 30 or np.isnan(angle_subtended_by_post[f]):
            if frame_at_saccade is None:
                frame_at_saccade = f
                saccading = True
            saccade_time += dt
            if saccade_time > 0.17:
                saccading = False
            
        if saccade_time > 0:
            deceleration_initiated = False
            
             

            
                
                
    # plot
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    flycon_flying = plt.imread('flying_flycon.png')
    
    for f in frames:
        '''
        if not leg_ext[f]:
            color = 'black'
        else:
            color = 'red'            
        if f == frame_at_deceleration:
            color = 'blue'
        '''
        color='black'
                 
        x = positions[f,0]
        y = positions[f,1]
        w = flycon_flying.shape[0]/(7*1000.*.8)
        h = flycon_flying.shape[1]/(5.*1000.*.8)
        
        if f == frame_at_deceleration:
            #ax.imshow(flycon_flying, extent=(x-2*w, x, y-h, y+h), aspect='equal')
            
            # show angle subtended
            d = np.linalg.norm([x-.001,y])
            half_angle_to_post = np.arcsin( radius / d )
            world_angle = np.arctan2(y,x-.001)
            
            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-.001,y]) )
            triangle = patches.Polygon( xy, facecolor='blue', edgecolor='none', zorder=-10, alpha=0.2 )
            ax.add_artist(triangle)
            
            '''
            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='blue', linewidth=1)
            ax.add_artist(arc)
            '''
            
        elif f == frame_at_saccade:
            #ax.imshow(flycon_flying, extent=(x-2*w, x, y-h, y+h), aspect='equal')
            
            # show angle subtended
            d = np.linalg.norm([x-.001,y])
            half_angle_to_post = np.arcsin( radius / d )
            world_angle = np.arctan2(y,x-.001)
            
            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-.001,y]) )
            triangle = patches.Polygon( xy, facecolor='green', edgecolor='none', zorder=-10, alpha=0.2 )
            ax.add_artist(triangle)
        
            
        else:
            pt = patches.Circle( (positions[f,0],positions[f,1]), radius=0.0005, facecolor=color, edgecolor='none')
            ax.add_artist(pt)  
            
    
         
    # post      
    post = patches.Circle( (0,0), radius=radius, facecolor='black', edgecolor='none')
    ax.add_artist(post)
            
    
    
    
            
    ax.set_aspect('equal')
    ax.set_xlim([-0.2, 0.01])
    ax.set_ylim([-0.08, 0.08])
    ax.set_axis_off()
    fig.set_size_inches(6.5,6.5)
    fig.subplots_adjust(bottom=0., top=1, right=0.95, left=0.05)
    filename = 'flyby_cartoon.pdf'
    fig.savefig(filename, format='pdf')
            
            
            
            
            
    fig2 = plt.figure()  
    ax2 = fig2.add_subplot(111)
    
    angle, bins, data_filtered, xvals, curve, yplus, yminus = fa.deceleration_angle_histogram_flyby(dataset_flyby, keys=None, plot=False, saccades=True)
    ax2.plot( curve[:,0], curve[:,1], color='blue', alpha=0.3)
    ax2.fill_between(curve[:,0], yplus, yminus, color='blue', linewidth=0, alpha=0.2)
    
    angle, bins, data_filtered, xvals = fa.saccade_angle_histogram(dataset_flyby, keys=None, plot=False)
    ax2.plot(xvals, data_filtered, color='green', alpha=0.3)
    ax2.fill_between(xvals, data_filtered, np.zeros_like(xvals), color='green', linewidth=0, alpha=0.2)
    
    ax2.plot(np.log(angle_subtended_by_post), speed, color='black')
    ax2.plot(np.log(angle_subtended_by_post[frame_at_saccade]), speed[frame_at_saccade], '.', color='green')
    
    fa.fix_angle_log_spine(ax2, histograms=False) 
    
    fig2.subplots_adjust(bottom=0.3, top=0.8, right=0.9, left=0.25)
    
    filename = 'flyby_cartoon_plot.pdf'
    fig2.savefig(filename, format='pdf') 
def neural_threshold_tti_vs_rsdet_models(save_plot=True, tti=0.12, tti_thresh=0.7, movie_dataset=None):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    distfig = plt.figure()
    distax = distfig.add_subplot(111)
    
    radius = 0.009565
    a = np.linspace(0,2.5,100)
    m = -0.21/radius
    b = 0.159/radius
    expthreshold = (m*np.log(a)+b)*(2*np.tan(a/2.)*np.sin(a/2.))
    
    vel = (expthreshold*radius/(2*np.tan(a/2.)*np.sin(a/2.)))[1:]
    print vel
    
    f = np.where(vel<0.07)[0][0]+1
    print f
    expthreshold_clipped = expthreshold[0:f]
    a_clipped = a[0:f]
    #a_clipped_flipped = (a_clipped[::-1]-a_clipped[-1])[::-1]
    
    #a_clipped_mirrored = np.hstack( (a_clipped_flipped, a_clipped) )
    #expthreshold_clipped_mirrored = np.hstack( (expthreshold_clipped[::-1], expthreshold_clipped) )
    
    ax.plot( a_clipped, expthreshold_clipped, color='purple' )
    ax.fill_between(a_clipped, expthreshold_clipped, np.ones_like(a_clipped)*30, facecolor='purple', edgecolor=None, alpha=0.1 )
    #ax.plot( a_clipped, expthreshold_clipped, color='blue' )
    #ax.plot( a_clipped[::-1]-a_clipped[-1], expthreshold_clipped, color='blue')
    #ax.fill_between( a_clipped, expthreshold_clipped, np.ones_like(a_clipped)*30, facecolor='blue', edgecolor=None, alpha=0.2 )
    #ax.fill_between( a_clipped[::-1]-a_clipped[-1], expthreshold_clipped, np.ones_like(a_clipped)*30, facecolor='blue', edgecolor=None, alpha=0.2 )
    
    # distance plot
    distax.plot( np.log(a), expthreshold, color='purple')
    
    # for true time to impact model
    #tti = 0.05
    expthreshold_tti = 2*np.tan(a/2.) / tti - tti_thresh
    vel = (expthreshold_tti*radius/(2*np.tan(a/2.)*np.sin(a/2.)))[1:]
    #f = np.where(vel<0.07)[0][0]+1
    expthreshold_tti_clipped = expthreshold_tti#[0:f]
    a_clipped = a#[0:f]
    
    ax.plot( a_clipped, expthreshold_tti_clipped, color='black' )
    #ax.plot( a_clipped[::-1]-a_clipped[-1], expthreshold_tti_clipped, color='red')
    
    #deg_ticks = np.array([-90, -45, 0, 45, 90])
    #deg_tick_strings = [str(d) for d in deg_ticks]
    #rad_ticks = [-np.pi, -np.pi/2., 0, np.pi/2., np.pi]
    
    distax.plot( np.log(a), expthreshold_tti, color='black')
    
    
    
    
    ######## plot a sample constant velocity trajectory ##############
    
    vel = 0.4
    fps = 200.0
    x = np.arange(.2, 0, -vel/fps)
    d = x+radius
    a = 2*np.arcsin(radius / (d))
    #exp = 2*vel*np.tan(a/2.)*np.sin(a/2.)
    exp = floris.diffa(a)*fps
    exp = 2/np.sqrt(1-(radius/(d))**2) * (radius/(d)**2) * vel
    distax.plot( np.log(a), exp, color='gray')
    
    
    #return x, a
    
    
    
    ## plot paramters    
    ax.set_ylim([0,1000*np.pi/180.])
    rad_ticks_y = np.linspace(0,1000*np.pi/180.,5,endpoint=True)
    deg_tick_strings_y = [str(s) for s in np.linspace(0,1000,5,endpoint=True)]
    
    for i, s in enumerate(deg_tick_strings_y):
        deg_tick_strings_y[i] = s.split('.')[0]
    
    ax.set_autoscale_on(False)
    
    fa.fix_angle_log_spine(ax, set_y=False, histograms=False)
    
    #fa.adjust_spines(ax, ['left', 'bottom'])
    #ax.set_xlabel('Retinal size')
    ax.set_ylabel('expansion threshold, deg/s')
    
    ax.set_yticks(rad_ticks_y)
    ax.set_yticklabels(deg_tick_strings_y)
    
    
    if save_plot:
        fig.savefig('neural_threshold.pdf', format='pdf')
        
    if movie_dataset is not None:
        angle_at_leg_extension, bins, data_filtered, xvals = fa.leg_extension_angle_histogram(movie_dataset, plot=False)
        #ax2.plot(xvals, data_filtered, color='green', alpha=0.3)
        data_filtered /= np.max(data_filtered)
        data_filtered *= 7
        distax.fill_between(xvals, data_filtered, np.zeros_like(xvals), color='green', linewidth=0, alpha=0.2)
    
    fa.fix_angle_log_spine(distax, histograms=False, set_y=False)
    ylim_max = 1000
    distax.set_ylim(0,ylim_max/180.*np.pi)
    rad_ticks_y = np.linspace(0,ylim_max*np.pi/180.,5,endpoint=True)
    deg_tick_strings_y = [str(s) for s in np.linspace(0,ylim_max,5,endpoint=True)]
    for i, s in enumerate(deg_tick_strings_y):
        deg_tick_strings_y[i] = s.split('.')[0]
    distax.set_yticks(rad_ticks_y)
    distax.set_yticklabels(deg_tick_strings_y)
    distax.set_ylabel('expansion threshold, deg/s')
    
    if save_plot:
        distfig.savefig('neural_threshold_distance.pdf', format='pdf')
        
    return a, expthreshold, expthreshold_tti