コード例 #1
0
ファイル: beta.py プロジェクト: michaelerule/cgid
def estimate_beta_band(session,area,bw=8,epoch=None,doplot=False):
    '''
    return betapeak-0.5*bw,betapeak+0.5*bw
    '''
    print 'THIS IS NOT THE ONE YOU WANT TO USE'
    print 'IT IS EXPERIMENTAL COHERENCE BASED IDENTIFICATION OF BETA'
    assert 0
    if epoch is None: epoch = (6,-1000,3000)
    allco = []
    if not area is None:
        chs = get_good_channels(session,area)[:2]
        for a in chs:
            for b in chs:
                if a==b: continue
                for tr in get_good_trials(session):
                    x = get_filtered_lfp(session,area,a,tr,epoch,None,300)
                    y = get_filtered_lfp(session,area,b,tr,epoch,None,300)
                    co,fr = cohere(x,y,Fs=1000,NFFT=256)
                    allco.append(co)
    else:
        for area in areas:
            chs = get_good_channels(session,area)[:2]
            for a in chs:
                for b in chs:
                    if a==b: continue
                    for tr in get_good_trials(session):
                        x = get_filtered_lfp(session,area,a,tr,epoch,None,300)
                        y = get_filtered_lfp(session,area,b,tr,epoch,None,300)
                        co,fr = cohere(x,y,Fs=1000,NFFT=256)
                        allco.append(co)
    allco = array(allco)
    m = mean(allco,0)
    sem = std(allco,0)/sqrt(shape(allco)[0])
    # temporary in lieu of multitaper
    smooth = ceil(float(bw)/(diff(fr)[0]))
    smoothed = convolve(m,ones(smooth)/smooth,'same')
    use    = (fr<=56)&(fr>=5)
    betafr = (fr<=30-0.5*bw)&(fr>=15+0.5*bw)
    betapeak = fr[betafr][argmax(smoothed[betafr])]
    if doplot:
        clf()
        plot(fr[use],m[use],lw=2,color='k')
        plot(fr[use],smoothed[use],lw=1,color='r')
        plot(fr[use],(m+sem)[use],lw=1,color='k')
        plot(fr[use],(m-sem)[use],lw=1,color='k')
        positivey()
        xlim(*rangeover(fr[use]))
        shade([[betapeak-0.5*bw],[betapeak+0.5*bw]])
        draw()
    return betapeak-0.5*bw,betapeak+0.5*bw
コード例 #2
0
def video_overlay(pa,ned,pos_des,output_filename):
    # Generate video of the performance during loiter, this
    # includes the loiter position, current estimate of
    # position and raw gps position

    #output_filename = 'out.mp4'

    import matplotlib.animation as animation
    import scipy.signal as signal
    import matplotlib.pyplot as plt
    from numpy import nan, arange
    from numpy.lib.function_base import diff
    from matplotlib.pyplot import plot, xlabel, ylabel, xlim, ylim, draw
    from matplotlib.mlab import find

    ####### plot section

    fig, ax = plt.subplots(1,sharex=True)
    fig.set_size_inches([8,4])
    fig.patch.set_facecolor('green')

    t0_s = pa['time'][0]
    t1_s = pa['time'][-1]

    # nan out gaps between flights
    idx = find(diff(pos_des['time']) > 5000)
    pos_des['End'][idx,2] = nan

    # Plot position
    plot(pa['East'][:,0], pa['North'][:,0], linewidth=3, color=(0.2,0.2,0.2), label="Position")
    plot(pa['East'][:,0], pa['North'][:,0], linewidth=2, color=(0.8,0.8,0.8), label="Position")
    desired_marker = plot(pos_des['End'][0,1], pos_des['End'][0,0], '*k', markersize=15, label="Desired")
    ned_marker = plot(pa['East'][0,0], pa['North'][0,0], '.b', markersize=8)
    current_marker = plot(pa['East'][0,0], pa['North'][0,0], '.r', markersize=13)

    xlabel('East (m)')
    ylabel('North (m)')
    xlim(min(pa['East'][:,0]-20), max(pa['East'][:,0])+20)
    ylim(min(pa['North'][:,0]-10), max(pa['North'][:,0])+10)

    ax.set_axis_bgcolor('green')
    ax.xaxis.label.set_color('white')
    ax.yaxis.label.set_color('white')
    ax.spines['bottom'].set_color('white')
    ax.spines['top'].set_color('green')
    ax.spines['right'].set_color('green')
    ax.spines['left'].set_color('white')
    ax.tick_params(axis='x', colors='white')
    ax.tick_params(axis='y', colors='white')

    fig.set_facecolor('green')
    fig.subplots_adjust(left=0.15)
    fig.subplots_adjust(bottom=0.15)

    draw()

    def init(fig=fig):
        fig.set_facecolor('green')

    # Plot a segment of the path
    def update_img(t, pa=pa, pos_des=pos_des, ned=ned, desired_marker=desired_marker, current_marker=current_marker, ned_marker=ned_marker, t0_s=t0_s):

        import numpy as np
        import matplotlib.pyplot

        # convert to minutes
        t = t / 60

        idx = np.argmin(abs(np.double(pa['time']) / 60 - t))
        x = pa['East'][idx,0]
        y = pa['North'][idx,0]
        current_marker[0].set_xdata(x)
        current_marker[0].set_ydata(y)

        idx = np.argmin(abs(np.double(ned['time']) / 60 - t))
        ned_marker[0].set_xdata(ned['East'][idx])
        ned_marker[0].set_ydata(ned['North'][idx])

        idx = np.argmin(abs(np.double(pos_des['time']) / 60 - t))
        delta = abs(np.double(pos_des['time'][idx]) / 60 - t)
        if delta < (1/60.0):
            desired_marker[0].set_xdata(pos_des['End'][idx,1])
            desired_marker[0].set_ydata(pos_des['End'][idx,0])


    fig.patch.set_facecolor('green')

    fps = 30.0
    dpi = 150
    t = arange(t0_s, t1_s, 1/fps)

    ani = animation.FuncAnimation(fig,update_img,t,init_func=init,interval=0,blit=False)
    writer = animation.writers['ffmpeg'](fps=30)
    ani.save(output_filename,dpi=dpi,fps=30,writer=writer,savefig_kwargs={'facecolor':'green'})
コード例 #3
0
def video_overlay(pa,ned,pos_des,output_filename):
    # Generate video of the performance during loiter, this
    # includes the loiter position, current estimate of
    # position and raw gps position

    #output_filename = 'out.mp4'

    import matplotlib.animation as animation
    import scipy.signal as signal
    import matplotlib.pyplot as plt
    from numpy import nan, arange
    from numpy.lib.function_base import diff
    from matplotlib.pyplot import plot, xlabel, ylabel, xlim, ylim, draw
    from matplotlib.mlab import find

    ####### plot section

    fig, ax = plt.subplots(1,sharex=True)
    fig.set_size_inches([8,4])
    fig.patch.set_facecolor('green')

    t0_s = pa['time'][0]
    t1_s = pa['time'][-1]

    # nan out gaps between flights
    idx = find(diff(pos_des['time']) > 5000)
    pos_des['End'][idx,2] = nan

    # Plot position
    plot(pa['East'][:,0], pa['North'][:,0], linewidth=3, color=(0.2,0.2,0.2), label="Position")
    plot(pa['East'][:,0], pa['North'][:,0], linewidth=2, color=(0.8,0.8,0.8), label="Position")
    desired_marker = plot(pos_des['End'][0,1], pos_des['End'][0,0], '*k', markersize=15, label="Desired")
    ned_marker = plot(pa['East'][0,0], pa['North'][0,0], '.b', markersize=8)
    current_marker = plot(pa['East'][0,0], pa['North'][0,0], '.r', markersize=13)

    xlabel('East (m)')
    ylabel('North (m)')
    xlim(min(pa['East'][:,0]-20), max(pa['East'][:,0])+20)
    ylim(min(pa['North'][:,0]-10), max(pa['North'][:,0])+10)

    ax.set_axis_bgcolor('green')
    ax.xaxis.label.set_color('white')
    ax.yaxis.label.set_color('white')
    ax.spines['bottom'].set_color('white')
    ax.spines['top'].set_color('green')
    ax.spines['right'].set_color('green')
    ax.spines['left'].set_color('white')
    ax.tick_params(axis='x', colors='white')
    ax.tick_params(axis='y', colors='white')

    fig.set_facecolor('green')
    fig.subplots_adjust(left=0.15)
    fig.subplots_adjust(bottom=0.15)

    draw()

    def init(fig=fig):
        fig.set_facecolor('green')

    # Plot a segment of the path
    def update_img(t, pa=pa, pos_des=pos_des, ned=ned, desired_marker=desired_marker, current_marker=current_marker, ned_marker=ned_marker, t0_s=t0_s):

        import numpy as np
        import matplotlib.pyplot

        # convert to minutes
        t = t / 60

        idx = np.argmin(abs(np.double(pa['time']) / 60 - t))
        x = pa['East'][idx,0]
        y = pa['North'][idx,0]
        current_marker[0].set_xdata(x)
        current_marker[0].set_ydata(y)

        idx = np.argmin(abs(np.double(ned['time']) / 60 - t))
        ned_marker[0].set_xdata(ned['East'][idx])
        ned_marker[0].set_ydata(ned['North'][idx])

        idx = np.argmin(abs(np.double(pos_des['time']) / 60 - t))
        delta = abs(np.double(pos_des['time'][idx]) / 60 - t)
        if delta < (1/60.0):
            desired_marker[0].set_xdata(pos_des['End'][idx,1])
            desired_marker[0].set_ydata(pos_des['End'][idx,0])


    fig.patch.set_facecolor('green')

    fps = 30.0
    dpi = 150
    t = arange(t0_s, t1_s, 1/fps)

    ani = animation.FuncAnimation(fig,update_img,t,init_func=init,interval=0,blit=False)
    writer = animation.writers['ffmpeg'](fps=30)
    ani.save(output_filename,dpi=dpi,fps=30,writer=writer,savefig_kwargs={'facecolor':'green'})
コード例 #4
0
ファイル: beta.py プロジェクト: michaelerule/cgid
def get_high_beta_events(session,area,channel,epoch,
    MINLEN  = 40,   # ms
    BOXLEN  = 50,   # ms
    THSCALE = 1.5,  # sigma (standard deviations)
    lowf    = 10.0, # Hz
    highf   = 45.0, # Hz
    pad     = 200,  # ms
    clip    = True,
    audit   = False
    ):
    '''
    get_high_beta_events(session,area,channel,epoch) will identify periods of
    elevated beta-frequency power for the given channel.

    Thresholds are selected per-channel based on all available trials.
    The entire trial time is used when estimating the average beta power.
    To avoid recomputing, we extract beta events for all trials at once.

    By default events that extend past the edge of the specified epoch will
    be clipped. Passing clip=False will discard these events.

    returns the event threshold, and a list of event start and stop
    times relative to session time (not per-trial or epoch time)

    passing audit=True will enable previewing each trial and the isolated
    beta events.

    >>> thr,events = get_high_beta_events('SPK120925','PMd',50,(6,-1000,0))
    '''

    # get LFP data
    signal = get_raw_lfp_session(session,area,channel)

    # esimate threshold for beta events
    beta_trials = [get_filtered_lfp(session,area,channel,t,(6,-1000,0),lowf,highf) for t in get_good_trials(session)]
    threshold   = np.std(beta_trials)*THSCALE
    print 'threshold=',threshold

    N = len(signal)
    event,start,stop = epoch
    all_events = []
    all_high_beta_times = []
    for trial in get_good_trials(session):
        evt        = get_trial_event(session,area,trial,event)
        trialstart = get_trial_event(session,area,trial,4)
        epochstart = evt + start + trialstart
        epochstop  = evt + stop  + trialstart
        tstart     = max(0,epochstart-pad)
        tstop      = min(N,epochstop +pad)
        filtered   = bandfilter(signal[tstart:tstop],lowf,highf)
        envelope   = abs(hilbert(filtered))
        smoothed   = convolve(envelope,ones(BOXLEN)/float(BOXLEN),'same')
        E = array(get_edges(smoothed>threshold))+tstart
        E = E[:,(diff(E,1,0)[0]>=MINLEN)
                & (E[0,:]<epochstop )
                & (E[1,:]>epochstart)]
        if audit: print E
        if clip:
            E[0,:] = np.maximum(E[0,:],epochstart)
            E[1,:] = np.minimum(E[1,:],epochstop )
        else:
            E = E[:,(E[1,:]<=epochstop)&(E[0,:]>=epochstart)]
        if audit:
            clf()
            axvspan(epochstart,epochstop,color=(0,0,0,0.25))
            plot(arange(tstart,tstop),filtered,lw=0.7,color='k')
            plot(arange(tstart,tstop),envelope,lw=0.7,color='r')
            plot(arange(tstart,tstop),smoothed,lw=0.7,color='b')
            ylim(-80,80)
            for a,b in E.T:
                axvspan(a,b,color=(1,0,0,0.5))
            axhline(threshold,color='k',lw=1.5)
            xlim(tstart,tstop)
            draw()
            wait()
        all_events.extend(E.T)
        assert all(diff(E,0,1)>=MINLEN)
    return threshold, all_events