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
def plot_leg_ext_exp(movie_dataset, delay=0.05):
    
    keys = movie_dataset.movies.keys()
    landing_keys = movie_dataset.get_movie_keys(behavior='landing')
    
    angle = []
    expansion = []
    dist = []
    speed = []
    n = 0
    for key in keys:
        movie = movie_dataset.movies[key]
        if movie.legextensionrange is not None:
            try:
                s = movie.scaled
            except:
                s = None
                print key, ': excepted'
            
            legextensionframe = movie.legextensionrange[0] - movie.firstframe_ofinterest
            if movie.landingframe is not None and movie.trajec is not None and s is not None and 'crash' not in movie.subbehavior and legextensionframe < movie.landingframe_relative:
                
                frame = legextensionframe - int(delay*movie.framerate)
                
                a = movie.scaled.angle_subtended_by_post[frame]
                '''
                while a < -np.pi:
                    a += np.pi
                while a > np.pi:
                    a -= np.pi
                '''
                angle.append(a)
                
                
                e = floris.diffa(movie.scaled.angle_subtended_by_post)
                e *= movie.framerate
                expansion.append(e[frame])
                
                dist.append(movie.scaled.dist_head_to_post[frame])
                speed.append(movie.scaled.speed[frame])
                n += 1
            else:
                print key
            
            
    angle = np.array(angle)
    expansion = np.array(expansion)
    dist = np.array(dist)
    speed = np.array(speed)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    ax.plot(angle*180/np.pi, expansion*180/np.pi, '.')
    
    
    filename = 'leg_extension_angle_expansion.pdf'
    fig.savefig(filename, format='pdf')
    
    print 'mean angle subtended: ', np.mean(angle)*180/np.pi, '+/-', np.std(angle)*180/np.pi, ' deg'
    print 'distance head to post: ', np.mean(dist), '+/-', np.std(dist)
    print 'time to impact: ', np.mean(dist/speed), '+/-', np.std(dist/speed)
    print 'n = ', n
def sim_deceleration(trajec, gain, constant_vel=False):  
    # plot constant velocity comparison
    fps = 2000.
    dt = 1/fps
    r = 0.009565
    r = 0.009565
    radius = r
    
    
    nf = 5000
    positions = np.zeros([nf])
    speed = np.zeros([nf])
    distance = np.zeros([nf])
    angle = np.zeros([nf])
    
    for i in range(2):
        positions[i] = -0.22#-1*(trajec.dist_to_stim_r[trajec.frame_at_deceleration]+radius)
        speed[i] = trajec.speed[trajec.frame_at_deceleration]
        #angle[i] = trajec.angle_subtended_by_post[trajec.frame_at_deceleration]
        distance[i] = np.linalg.norm(positions[i]) - radius
        angle[i] = 2*np.arcsin( radius / (distance[i]+radius) )
    frames = [0,2]
    
    
    for f in range(frames[-1],nf-1): 
        if np.linalg.norm(positions[f-1])-radius <= 0.001:
            landed = True
            break
        else:
            landed = False
            
            
        if not landed:
            frames.append(f)
            positions[f] = positions[f-1] + speed[f-1]*dt
            distance[f] = np.linalg.norm(positions[f]) - radius
            angle[f] = 2*np.arcsin( radius / (distance[f]+radius) )
            
            a = angle
            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(a[f])+b)*(2*np.tan(a[f]/2.)*np.sin(a[f]/2.))
            #tti_threshold = 0.15
            #expthreshold = 2*np.tan(af/2.) / tti_threshold
    
            exp0 -= expthreshold
            exp1 -= expthreshold
            
            #tti = 2*np.tan(af/2.) / exp0
            #tti = np.max([tti, 0])
            
            
            exp0 = np.max([exp0, 0])
            exp1 = np.max([exp1, 0])
            
            c = -1*exp0 / 3500.
            
            dda = -1*np.max([(exp0-exp1)/dt, 0])
            #dda = -1*(exp0-exp1)/dt
            c = dda / gain[0]
            
            if c > 0:
                print c, dda, np.max((exp0-exp1)/dt, 0)
            
            
            
            
            #c = np.min([c,0])
            #max_accel = -.007
            #c = np.max([c,max_accel])
            if constant_vel is False:
                v = np.max([speed[f-1] + c, 0.07])
            else:
                v = speed[f-1]    
            speed[f] = v
        
            
    expansion = floris.diffa(angle)/dt
    return angle[frames], speed[frames], expansion[frames]