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 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