def distance_aligned_frames_cyclic(K, T1, T2, tau=0):
    """ Compute the squared distance between aligned frames

    Parameters
    ----------
    K: (T1+T2) x (T1+T2) array,
        between frames kernel matrix

    T1: int,
        duration of time series 1

    T2: int,
        duration of time series 2

    tau: positive int, optional, default: 0,
         temporal shift (in frames) to apply to time series 2 before computing
         alignment, using "cyclic" padding

    Returns
    -------
    dme2: double,
          squared distance between aligned frames in the RKHS

    Notes
    -----
    Cyclic verion

        dme2 = K[0,0] - 1/T2 * sum_{t=0}^{T2} K[x1_t, x2_{(t+tau) % T2}]

    """
    assert T1 == T2, "the series should be of same duration"
    T = T1
    # constant base kernel value k(x,x)
    c = K[0, 0]
    # matrix of k(x,y)
    Kxy = K[:T, T:]
    # return the distance
    if tau:
        tr = Kxy.trace(offset=tau) + Kxy.trace(offset=tau - T)
    else:
        tr = Kxy.trace()
    return c - tr / float(T)