"Notice that the 'barebones' (default) version of method 2 returns a DTW based on absolute differences, not on the Euclidean distance as in the 'cocky' version used by the tslearn library."
print('computation time of DTW 2 = '+str(time()-tic))
print('computation time of classical optimal path = '+str(time()-tic_1))
op_2_x=[col[0]forcolinoptimal_path_2]
op_2_y=[col[1]forcolinoptimal_path_2]
plt.imshow(dm_2.T,origin='lower')
plt.plot(op_2_x,op_2_y,':w',linewidth=2)
plt.title('DTW 2 = '+str(round(dtw_score_2,3)));
```
%% Cell type:markdown id: tags:
Notice that the 'barebones' (default) version of method 2 returns a DTW based on absolute differences, not on the Euclidean distance as in the 'cocky' version used by the tslearn library.
%% Cell type:code id: tags:
``` python
# traceback minimum-warp optimal path:
tic=time()
i,j=np.array(C.shape)-2
optimal_path_3=[[i,j]]
while (i>0)or(j>0):
this_query=(C[i,j],C[i,j+1],C[i+1,j])
this_min=np.min(this_query)
these_argmins=np.where(this_query==this_min)
ifthese_argmins[0][0]==0:
if (np.any(these_argmins[0][:]==1))and(i>j):
i-=1
elif (np.any(these_argmins[0][:]==2))and(j>i):
j-=1
else:
i-=1
j-=1
elifthese_argmins[0][0]==1:
i-=1
elifthese_argmins[0][0]==2:
j-=1
optimal_path_3.append([i,j])
print('computation time of minimum-warp optimal path = '+str(time()-tic))
op_3_x=[col[0]forcolinoptimal_path_3]
op_3_y=[col[1]forcolinoptimal_path_3]
plt.imshow(dm_2.T,origin='lower')
plt.plot(op_2_x,op_2_y,':w',linewidth=2)
plt.plot(op_3_x,op_3_y,':r',linewidth=2)
plt.title('DTW 2 = '+str(round(dtw_score_2,3)));
```
%% Cell type:markdown id: tags:
The algorithm for the minimum-warp optimal path (in red) tries to get closer to the diagonal.
%% Cell type:code id: tags:
``` python
pm=np.zeros(dm_2.shape)
fori_opinrange(0,len(optimal_path_3)):
pm[op_3_x[i_op],op_3_y[i_op]]=1
ax=plt.gca()
ax.imshow(pm.T,origin='lower')
ax.plot(range(0,dm_2.shape[0]),':w',linewidth=1);
xy_grid=np.arange(-0.5,dm_2.shape[0]+0.5)
ax.grid(1,linestyle=':')
ax.set_xticks(xy_grid)
ax.set_yticks(xy_grid)
ax.set_xticklabels('')
ax.set_yticklabels('')
ax.set_title('minimum-warp optimal path');
```
%% Cell type:code id: tags:
``` python
# pointwise lag of minimum-warp optimal path:
pm_r=np.fliplr(pm).T# rotate to get anti-diagonals (lag domain)
lags=np.zeros(pm_r.shape[0])
i_lags=0
i_adiag=-pm_r.shape[0]+1
whilei_adiag<=pm_r.shape[0]:# iterate through anti-adiagonals
this_adiag=pm_r.diagonal(i_adiag)
#print('this_adiag = %s'%this_adiag)
ifany(this_adiag):
i_center=int(np.floor(this_adiag.size/2))
ifnotthis_adiag[int(i_center)]:# value where the anti-adiagonal intersects the main adiagonal
i_match=int(np.where(this_adiag)[0])# where the path intersects this anti-diagonal
lags[i_lags]=i_center-i_match
i_adiag+=2
i_lags+=1
else:# see if there's anything in the next diagonal