Sliding window time histogram

Given the spike time, plot the event rate within a sliding window.

def sliding_window(ts,wsz=10):
    '''calculate sliding window time histogram
 
    Parameters
    ----------
    ts:  Array of time points
    wsz: Window size
 
    Returns
    -------
    tss:    Array of time points
    rates:  Firing rates at the time points
    '''
    tw = ts[0]-wsz # initialized with the time when the first event hits the window
    i0 = 0
    i1 = 0
    lt = len(ts)
    tts = [tw]
    rrs = [0]
    while i0<lt:
        if i1<lt and ts[i1]<ts[i0]+wsz:
            if tw<ts[i1]-wsz: # output only when window moves
                tn = ts[i1]-wsz
                if rrs[-1]==i1-i0: tts[-1]=tn # merge with previous interval
                else:
                    tts.extend((tw,tn))
                    rrs.extend((i1-i0,i1-i0))
                tw = tn
            i1 += 1
        else:
            if tw<ts[i0]: # output only when window moves
                tn = ts[i0]
                if rrs[-1]==i1-i0: tts[-1]=tn # merge with previous interval
                else:
                    tts.extend((tw,tn))
                    rrs.extend((i1-i0,i1-i0))
                tw = tn
            i0 += 1
    tts.append(tw)
    rrs.append(0)
    return np.array(tts)+wsz/2,np.array(rrs)/wsz

Example

a = np.array([1,3,6,11,24,33,36,44,44,52,54,55,55,55,59,64])
tts,rrs = sliding_window(a)
plt.plot(tts,rrs,'-')
plt.plot(a,np.zeros_like(a),'x')