def _pathcount(template_ink, ink, alpha=0.5, penup_z=10.0): m = template_ink.shape[0] n = ink.shape[0] u = np.zeros(m) v = np.zeros(m) peak_count = np.zeros(m) d = _compute_combined_distance(ink, template_ink, alpha, penup_z) for i in xrange(n): new_u = np.zeros(m) new_v = np.zeros(m) new_u[0] = u[0] + d[i,0] new_v[0] = v[0] + 1 for j in xrange(1,m): t1 = u[j] t2 = u[j-1] if (t2 < t1) and (t2 < new_u[j-1]): new_u[j] = t2 + d[i,j] new_v[j] = v[j-1] + 1 elif (t1 < t2) and (t1 < new_u[j-1]): new_u[j] = t1 + d[i,j] new_v[j] = v[j] + 1 else: new_u[j] = new_u[j-1] + d[i,j] new_v[j] = new_v[j-1] + 1 max_ind = np.argmax(-new_u / new_v) peak_count[max_ind] += 1 u = new_u v = new_v return peak_count
def compute_dtw_vector(center_ink, ink_array, alpha=0.5, penup_z=1000.0): """Returns a vector representing the difference between `center_ink` and time-warped `ink_array`. The output vector always has the same length as `center_ink`.""" n = center_ink.shape[0] m = ink_array.shape[0] if (n <= 0 or m <= 0): raise ValueError('Both input arrays must have length > 0') combined_d = _compute_combined_distance(center_ink, ink_array, alpha, penup_z) dtw = np.zeros((n,m)) path = np.zeros((n,m)) _LEFT, _DIAG, _UP = 1, 2, 3 for i in xrange(1,n): dtw[i,0] = dtw[i-1,0] + combined_d[i,0] path[i,0] = _UP for j in xrange(1,m): dtw[0,j] = dtw[0,j-1] + combined_d[0,j] path[0,j] = _LEFT for i in xrange(1,n): for j in xrange(1,m): dtw[i,j] = combined_d[i,j] + min(dtw[i-1,j], dtw[i-1,j-1], dtw[i,j-1]) if (dtw[i-1,j-1] < dtw[i-1,j] and dtw[i-1,j-1] < dtw[i,j-1]): path[i,j] = _DIAG elif (dtw[i-1,j] < dtw[i-1,j-1] and dtw[i-1,j] < dtw[i,j-1]): path[i,j] = _UP else: path[i,j] = _LEFT # trace backwards i, j = n-1, m-1 mapping = np.zeros(n, dtype=np.int) while i >= 0 and j >= 0: mapping[i] = j if path[i,j] == _UP: i -= 1 elif path[i,j] == _LEFT: j -= 1 else: i -= 1 j -= 1 diff_array = ink_array[mapping,:] - center_ink return diff_array.reshape(-1)
def compute_dtw_distance(ink_array1, ink_array2, alpha=0.5, penup_z=10.0): """Returns the DTW distance between two trajectories.""" n = ink_array1.shape[0] m = ink_array2.shape[0] if (n <= 0 or m <= 0): raise ValueError('Both input arrays must have length > 0') combined_d = _compute_combined_distance(ink_array1, ink_array2, alpha, penup_z) return _execute_dtw_in_c(combined_d, m , n)