Skip to content

Commit e9dac64

Browse files
committed
optimized a uniform-time-warping function
1 parent 03bf387 commit e9dac64

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

ABXpy/distances/metrics/utw.py

+28-5
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,40 @@
88

99
import numpy as np
1010

11-
def utw(x, y, metric):
11+
def utw(x, y, div):
1212
"""
1313
Uniform Time Warping
14+
15+
Parameters
16+
----------
17+
x : numpy.Array
18+
Size m_x by n
19+
y : numpy.Array
20+
Size m_y by n
21+
div : function
22+
Takes two m by n arrays and returns a m by 1 array
23+
containing the distances between rows 1, rows 2, ...,
24+
rows m of the two arrays. Does not need to be a metric
25+
in the mathematical sense
26+
27+
Returns
28+
-------
29+
dis : float
30+
The UTW distance between x and y according to
31+
distance function div
1432
"""
1533
if x.shape[0] > y.shape[0]:
1634
z = x, y
1735
y, x = z
1836
n1 = x.shape[0]
1937
n2 = y.shape[0]
2038
i_half, j_half, i_whole, j_whole = distance_coordinates(n1, n2)
21-
d = np.sum([metric(x[i,:], y[j,:]) for i, j in zip(i_half, j_half)]) / 2. + \
22-
np.sum([metric(x[i,:], y[j,:]) for i, j in zip(i_whole, j_whole)])
23-
return d
39+
dis = 0
40+
if i_half.size > 0:
41+
dis = dis + np.sum(div(x[i_half,:], y[j_half,:])) / 2.
42+
if i_whole.size > 0:
43+
dis = dis + np.sum(div(x[i_whole,:], y[j_whole,:]))
44+
return dis
2445

2546

2647
def distance_coordinates(n1, n2):
@@ -40,7 +61,7 @@ def distance_coordinates(n1, n2):
4061

4162

4263
def test():
43-
metric = lambda x, y: np.sum(np.abs(x-y))
64+
metric = lambda x, y: np.sum(np.abs(x-y), axis=1)
4465
x = np.array([[0, 0],
4566
[0, -1],
4667
[0, 0],
@@ -54,3 +75,5 @@ def test():
5475
[1, 1]])
5576
assert(utw(x, y, metric) == 26.5)
5677
assert(utw(y, x, metric) == 26.5)
78+
79+
test()

0 commit comments

Comments
 (0)