示例#1
0
def knn_1d_density(x,k=10,eps=0.01):
    '''
    Uses local K nearest neighbors to estimate a density and center of
    mass at each point in a distribution. Returns a local density estimator in units of 1/input_units. For example, if a sequence
    of times in seconds is provided, the result is an estimate of
    the continuous time intensity function in units of Hz.

    Parameters
    ----------
    x : ndarray
        List of points to model
    k : integer
        Number of nearest neighbors to use in local density estimate
        Default is 10
    eps : number
        Small correction factor to avoid division by zero

    Returns
    -------
    centers : ndarray
        Point location of density estimates
    density :
        Density values at locations of centers
    '''
    x=np.float64(np.sort(x))
    # Handle duplicates by dithering
    duplicates = get_edges(np.diff(x)==0.)+1
    duplicates[duplicates>=len(x)-1]=len(x)-2
    duplicates[duplicates<=0]=1
    for a,b in zip(*duplicates):
        n = b-a+1
        q0 = x[a]
        q1 = (x[a-1]-q0)
        q2 = (x[b+1]-q0)
        #print(a,b,q0,q1,q2)
        x[a:b+1] += np.linspace(q1,q2,n+2)[1:-1]
    intervals = np.diff(x)
    centers   = (x[1:]+x[:-1])*0.5
    kernel    = np.hanning(min(x.shape[0]-1,k)+2)[1:-1]
    kernel   /=sum(kernel)
    intervals = np.convolve(intervals,kernel,'same')
    density = (eps+1.0)/(eps+intervals)
    return centers,density
示例#2
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