コード例 #1
0
def dissCORT(x,y,q=1):
	'''
	Calculate the dissimilarity distance using the DTW and first and first order temporal correlation
	x: A 2D N*M numpy array (data)
	y: A vector M (a centroid)
	q: tunning factor between DTW and first order temporal correlation 0<q<5
	'''

	p=len(y)
	x1Index=np.ix_(range(len(x)),range(1,p))
	x2Index=np.ix_(range(len(x)),range(p-1))
	x=np.array(x)
	y=np.array(y)

	distance = [pydtw.dtw(i,y,pydtw.Settings(dist = 'euclid', 
                             	step  = 'dp1', 
                                window = 'palival_mod', param = 0.1,
                                 compute_path = True)).get_dist()  for i in x]
	
	
	corrTempOrder=np.nansum((x[x1Index]-x[x2Index])*(y[1:]-y[:(p-1)]),axis=1) / (np.sqrt( np.nansum((x[x1Index]-x[x2Index])**2,axis=1) )*np.sqrt(np.nansum((y[1:]-y[:(p-1)])**2)))

	if np.isnan(corrTempOrder).any():
		for i in np.where(np.isnan(corrTempOrder))[0]:
			corrTempOrder[i]=0

	return((2/( 1+ np.exp(q*corrTempOrder)))*distance)
コード例 #2
0
def warped_correlation(x, y):

    # dist, path = fastdtw(z_scores_x, z_scores_y, dist=distance.euclidean)

    path = pydtw.dtw(
        x,
        y,
        pydtw.Settings(
            step=
            'p0sym',  # Sakoe-Chiba symmetric step with slope constraint p = 0
            window='palival',  # type of the window
            param=2.0,  # window parameter
            norm=False,  # normalization
            compute_path=True)).get_path()

    x_path, y_path = zip(*path)
    x_path = np.asarray(x_path)
    y_path = np.asarray(y_path)

    x_warped = x[x_path]
    y_warped = y[y_path]

    corr = np.corrcoef(x_warped, y_warped)[0, 1]

    return corr
コード例 #3
0
ファイル: dtw.py プロジェクト: BalounJ/DTW-for-images
def dtw(sig1, sig2, window=5):
    return pydtw.dtw(
        sig1, sig2,
        pydtw.Settings(step='p0sym',
                       window='palival',
                       param=window,
                       norm=False,
                       compute_path=False)).get_dist()
コード例 #4
0
def fast_c_dtw_implementation(rec1, rec2, print_info=False):
    s1 = rec1.np_values
    s2 = rec2.np_values
    if print_info:
        print((s1))
        print((rec1.values))

    """
    Step class

        Class containts different step patterns for dynamic time warping algorithm.
        There are folowing step patterns available at the moment:
        Usual step patterns:
            'dp1' 
            'dp2' 
            'dp3'
        Sakoe-Chiba classification:
            'p0sym':
            'p0asym':
            'p05sym':
            'p05asym':
            'p1sym':
            'p1asym':
            'p2sym':
            'p2asym':

        You can see step pattern definition using print_step method
    """
    d = pydtw.dtw(s1, s2, pydtw.Settings(dist='manhattan',
                                         step='p2sym',  # Sakoe-Chiba symmetric step with slope constraint p =
                                         window='palival',  # type of the window: scband, itakura, palival, itakura_mod
                                         param=7.0,  # window parameter
                                         norm=True,  # normalization
                                         compute_path=print_info))

    distance = d.get_dist()
    if not np.isfinite(distance):
        distance = 9999999.
    if print_info:
        print(distance)
        d.plot_alignment()
        #d.plot_mat_path()
        #d.plot_seq_mat_path()
        print(d.get_path())
        print("next")

    if print_info:
        return float(distance), d.get_path()
    return float(distance)
コード例 #5
0
def warped_correlation(window_size, signals):
    X = signals[0]
    Y = signals[1]
    cdtw = pydtw.dtw(
        zscore(X),
        zscore(Y),
        pydtw.Settings(step = 'dp1',
            window = 'scband',
            param = window_size,
            norm = False,
            compute_path = True
        )
    )
    dist = cdtw.get_dist()
    path = len(cdtw.get_path())
    warped_corellation = 1 - dist / (2 * path)
    return warped_corellation
コード例 #6
0
def fast_c_dtw_implementation(rec1, rec2):

    s1 = rec1.np_values
    s2 = rec2.np_values

    d = pydtw.dtw(
        s1,
        s2,
        pydtw.Settings(
            step=
            'p0sym',  # Sakoe-Chiba symmetric step with slope constraint p = 0
            window='palival',  # type of the window
            param=2.0,  # window parameter
            norm=True,  # normalization
            compute_path=False))
    distance = d.get_dist()
    if not np.isfinite(distance):
        distance = 9999999.

    return float(distance)
コード例 #7
0
def dtw(src, tgt, stflag=None):
    """
    DTW for the glossectomy patients

    Args:
        stflag (str): None or 'src' or 'tgt'
            if set None, align freely
            if set 'src', align according to the number of frames of src
            if set 'tgt', align according to the number of frames of tgt
    """

    # extract mcep only
    src_mc = src[:, 0:cf.mcep_dim + 1]
    tgt_mc = tgt[:, 0:cf.mcep_dim + 1]

    # DTW calc only power component for distance cost
    # when gllossectomy cases, it's difficult to matching by Mel-CD cost
    src_pow = src_mc[:, 0]
    tgt_pow = tgt_mc[:, 0]
    """
    dist=距離計算関数
    step=ステップ計算の形 ["dp1","dp2","dp3","p05sym","p05asym","p1sym","p1asym","p2sym","p2asym"]
    window=制限窓の種類
    param=制限窓の幅

    試行錯誤の結果,"p05asym"が最も良く動作することが分かった
    p05asym: Sakoe-Chiba classification p = 0.5, asymmetric step pattern
    https://maxwell.ict.griffith.edu.au/spl/publications/papers/sigpro82_kkp_dtw.pdf
    """
    d = pydtw.dtw(
        src_pow, tgt_pow,
        pydtw.Settings(dist='euclid',
                       step="p05asym",
                       window='nowindow',
                       compute_path=True))
    twf = np.array(d.get_path()).T

    if stflag == 'src':
        sf, index = np.unique(twf[0], return_index=True)
        twf = np.c_[sf, twf[1][index]].T
    elif stflag == 'tgt':
        tf, index = np.unique(twf[1], return_index=True)
        twf = np.c_[twf[0][index], tf].T

    # # DTW by melcd
    # def distance_func(x, y): return melcd(x, y)
    #
    # _, path = fastdtw(src_mc, tgt_mc, dist=distance_func)
    # twf = np.array(path).T

    # alignment
    src_aligned = src[twf[0]]
    tgt_aligned = tgt[twf[1]]

    # debug: check whether dtw works well
    # plot matching path
    # d.plot_alignment()
    # exit()

    global dtw_flag
    if dtw_flag:
        import matplotlib.pyplot as plt
        plt.plot(src[:, 0])
        plt.plot(tgt[:, 0])
        plt.show()
        plt.clf()

        plt.plot(src_aligned[:, 0])
        plt.plot(tgt_aligned[:, 0])
        plt.show()
        plt.clf()
        dtw_flag = False

    # import matplotlib.pyplot as plt
    # plt.plot(src[:,0])
    # plt.plot(tgt[:,0])
    # plt.show()
    # plt.clf()
    #
    # plt.plot(src_aligned[:,0])
    # plt.plot(tgt_aligned[:,0])
    # plt.show()
    # plt.clf()
    # exit()

    return src_aligned, tgt_aligned
コード例 #8
0
                     ",ucr," + str(ucrdist) + "," +
                     str(timet.microseconds) + ',' +
                     str(ucrloc + count) + ',' + str(ucrloc + count))
 with open(
         'paths/' + str(amp + 1) + "," + str(window + 1) +
         '_loc_ucr.txt', "w") as text_file:
     text_file.write(str(ucrloc))
 #cydtw
 timeb = datetime.now()
 cdtw_master = pydtw.dtw(
     x,
     y,
     pydtw.Settings(
         step=
         'p0sym',  #Sakoe-Chiba symmetric step with slope constraint p = 0
         window='palival',  #type of the window
         param=2.0,  #window parameter
         norm=False,  #normalization
         compute_path=True))
 timet = datetime.now() - timeb
 print("cdtw complete on amp " + str(amp + 1))
 cdtwpath1, cdtwpath2 = zip(*cdtw_master.get_path())
 cdtwpath1 = np.asarray(cdtwpath1)
 cdtwpath2 = np.asarray(cdtwpath2)
 with open("bench_log.txt", "a") as text_file:
     text_file.write("\n" + str(amp + 1) + "," + str(window + 1) +
                     ",cdtw," + str(cdtw_master.get_dist()) + "," +
                     str(timet.microseconds) + ',' +
                     str(cdtwpath2[0] + count) + ',' +
                     str(cdtwpath2[-1] + count))
 path1 = np.savetxt('paths/' + "amp_" + str(amp + 1) + "_window_" +
コード例 #9
0
            else:
                guyzz.append(np.genfromtxt('records/'+filename,delimiter=',',dtype=None))



    n_waves=np.shape(guyzz[0])[1]

    comb=list(itertools.combinations(range(np.shape(guyzz)[0]),2))
    # ^^this is so f*****g brutal^^
    matrix=np.zeros([np.shape(guyzz)[0],np.shape(guyzz)[0]])
    for i in comb:
        correlation_vector=0
        firstguy=guyzz[i[0]]
        secondguy=guyzz[i[1]]
        minValue= np.min([np.shape(firstguy)[0],np.shape(secondguy)[0]])
        firstguy2=firstguy[0:minValue][:]
        secondguy2=secondguy[0:minValue][:] #trim the f**k out

        for waves in range(n_waves):
            d= pydtw.dtw(firstguy[:][waves], secondguy[:][waves],
                         pydtw.Settings(dist='manhattan',step='dp2',window='nowindow',
                                        compute_path=True,norm=True))
            correlation_vector+=d.get_dist()

        correlation_vector/=n_waves
        matrix[i[0]][i[1]]=correlation_vector

    print(name + " : ")
    print(matrix)
    print('---------------')