similaritymeasures.similaritymeasures

  1from __future__ import division
  2import numpy as np
  3from scipy.spatial import distance
  4# MIT License
  5#
  6# Copyright (c) 2018,2019 Charles Jekel
  7#
  8# Permission is hereby granted, free of charge, to any person obtaining a copy
  9# of this software and associated documentation files (the "Software"), to deal
 10# in the Software without restriction, including without limitation the rights
 11# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 12# copies of the Software, and to permit persons to whom the Software is
 13# furnished to do so, subject to the following conditions:
 14#
 15# The above copyright notice and this permission notice shall be included in
 16# all copies or substantial portions of the Software.
 17#
 18# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 19# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 20# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 21# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 22# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 23# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 24# SOFTWARE.
 25
 26
 27def _cross2d(a, b):
 28    r"""
 29    Compute the scalar cross product of two 2-D vectors.
 30
 31    NumPy deprecated calling ``np.cross`` with 2-D vectors in NumPy 2.0. This
 32    helper preserves the previous 2-D behavior explicitly by returning the
 33    z-component of the equivalent 3-D cross product.
 34    """
 35    a = np.asarray(a)
 36    b = np.asarray(b)
 37    return a[..., 0] * b[..., 1] - a[..., 1] * b[..., 0]
 38
 39
 40def poly_area(x, y):
 41    r"""
 42    A function that computes the polygonal area via the shoelace formula.
 43
 44    This function allows you to take the area of any polygon that is not self
 45    intersecting. This is also known as Gauss's area formula. See
 46    https://en.wikipedia.org/wiki/Shoelace_formula
 47
 48    Parameters
 49    ----------
 50    x : ndarray (1-D)
 51        the x locations of a polygon
 52    y : ndarray (1-D)
 53        the y locations of the polygon
 54
 55    Returns
 56    -------
 57    area : float
 58        the calculated polygonal area
 59
 60    Notes
 61    -----
 62    The x and y locations need to be ordered such that the first vertex
 63    of the polynomial correspounds to x[0] and y[0], the second vertex
 64    x[1] and y[1] and so forth
 65
 66
 67    Thanks to Mahdi for this one line code
 68    https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates
 69    """
 70    return 0.5*np.abs(np.dot(x, np.roll(y, 1))-np.dot(y, np.roll(x, 1)))
 71
 72
 73def is_simple_quad(ab, bc, cd, da) -> bool:
 74    r"""
 75    Returns True if a quadrilateral is simple
 76
 77    This function performs cross products at the vertices of a quadrilateral.
 78    It is possible to use the results to decide whether a quadrilateral is
 79    simple or complex. This function returns True if the quadrilateral is
 80    simple, and False if the quadrilateral is complex. A complex quadrilateral
 81    is a self-intersecting quadrilateral.
 82
 83    Parameters
 84    ----------
 85    ab : array_like
 86        [x, y] location of the first vertex
 87    bc : array_like
 88        [x, y] location of the second vertex
 89    cd : array_like
 90        [x, y] location of the third vertex
 91    da : array_like
 92        [x, y] location of the fourth vertex
 93
 94    Returns
 95    -------
 96    simple : bool
 97        True if quadrilateral is simple, False if complex
 98    """
 99    #   Compute all four 2-D cross products
100    temp0 = _cross2d(ab, bc)
101    temp1 = _cross2d(bc, cd)
102    temp2 = _cross2d(cd, da)
103    temp3 = _cross2d(da, ab)
104    cross = np.array([temp0, temp1, temp2, temp3])
105    #   See that majority of cross products is non-positive or non-negative
106    #   They don't necessarily need to lie in the same 'Z' direction
107    if sum(cross > 0) < sum(cross < 0):
108        crossTF = cross <= 0
109    else:
110        crossTF = cross >= 0
111    return bool(sum(crossTF) > 2)
112
113
114def makeQuad(x, y):
115    r"""
116    Calculate the area from the x and y locations of a quadrilateral
117
118    This function first constructs a simple quadrilateral from the x and y
119    locations of the vertices of the quadrilateral. The function then
120    calculates the shoelace area of the simple quadrilateral.
121
122    Parameters
123    ----------
124    x : array_like
125        the x locations of a quadrilateral
126    y : array_like
127        the y locations of a quadrilateral
128
129    Returns
130    -------
131    area : float
132        Area of quadrilateral via shoelace formula
133
134    Notes
135    -----
136    This function rearranges the vertices of a quadrilateral until the
137    quadrilateral is "Simple" (meaning non-complex). Once a simple
138    quadrilateral is found, the area of the quadrilateral is calculated
139    using the shoelace formula.
140    """
141
142    # check to see if the provide point order is valid
143    # I need to get the values of the cross products of ABxBC, BCxCD, CDxDA,
144    # DAxAB, thus I need to create the following arrays AB, BC, CD, DA
145
146    AB = [x[1]-x[0], y[1]-y[0]]
147    BC = [x[2]-x[1], y[2]-y[1]]
148    CD = [x[3]-x[2], y[3]-y[2]]
149    DA = [x[0]-x[3], y[0]-y[3]]
150
151    isQuad = is_simple_quad(AB, BC, CD, DA)
152
153    if isQuad is False:
154        # attempt to rearrange the first two points
155        x[1], x[0] = x[0], x[1]
156        y[1], y[0] = y[0], y[1]
157        AB = [x[1]-x[0], y[1]-y[0]]
158        BC = [x[2]-x[1], y[2]-y[1]]
159        CD = [x[3]-x[2], y[3]-y[2]]
160        DA = [x[0]-x[3], y[0]-y[3]]
161
162        isQuad = is_simple_quad(AB, BC, CD, DA)
163
164        if isQuad is False:
165            # place the second and first points back where they were, and
166            # swap the second and third points
167            x[2], x[0], x[1] = x[0], x[1], x[2]
168            y[2], y[0], y[1] = y[0], y[1], y[2]
169            AB = [x[1]-x[0], y[1]-y[0]]
170            BC = [x[2]-x[1], y[2]-y[1]]
171            CD = [x[3]-x[2], y[3]-y[2]]
172            DA = [x[0]-x[3], y[0]-y[3]]
173
174            isQuad = is_simple_quad(AB, BC, CD, DA)
175
176    # calculate the area via shoelace formula
177    area = poly_area(x, y)
178    return area
179
180
181def get_arc_length(dataset):
182    r"""
183    Obtain arc length distances between every point in 2-D space
184
185    Obtains the total arc length of a curve in 2-D space (a curve of x and y)
186    as well as the arc lengths between each two consecutive data points of the
187    curve.
188
189    Parameters
190    ----------
191    dataset : ndarray (2-D)
192        The dataset of the curve in 2-D space.
193
194    Returns
195    -------
196    arcLength : float
197        The sum of all consecutive arc lengths
198    arcLengths : array_like
199        A list of the arc lengths between data points
200
201    Notes
202    -----
203    Your x locations of data points should be dataset[:, 0], and the y
204    locations of the data points should be dataset[:, 1]
205    """
206    #   split the dataset into two discrete datasets, each of length m-1
207    m = len(dataset)
208    a = dataset[0:m-1, :]
209    b = dataset[1:m, :]
210    #   use scipy.spatial to compute the euclidean distance
211    dataDistance = distance.cdist(a, b, 'euclidean')
212    #   this returns a matrix of the euclidean distance between all points
213    #   the arc length is simply the sum of the diagonal of this matrix
214    arcLengths = np.diagonal(dataDistance)
215    arcLength = sum(arcLengths)
216    return arcLength, arcLengths
217
218
219def area_between_two_curves(exp_data, num_data):
220    r"""
221    Calculates the area between two curves.
222
223    This calculates the area according to the algorithm in [1]_. Each curve is
224    constructed from discretized data points in 2-D space, e.g. each curve
225    consists of x and y data points.
226
227    Parameters
228    ----------
229    exp_data : ndarray (2-D)
230        Curve from your experimental data.
231    num_data : ndarray (2-D)
232        Curve from your numerical data.
233
234    Returns
235    -------
236    area : float
237        The area between exp_data and num_data curves.
238
239    Notes
240    -----
241    Your x locations of data points should be exp_data[:, 0], and the y
242    locations of the data points should be exp_data[:, 1]. Same for num_data.
243
244    .. [1] Jekel, C. F., Venter, G., Venter, M. P., Stander, N., & Haftka, R.
245        T. (2018). Similarity measures for identifying material parameters from
246        hysteresis loops using inverse analysis. International Journal of
247        Material Forming. https://doi.org/10.1007/s12289-018-1421-8
248    """
249    # Calculate the area between two curves using quadrilaterals
250    # Consider the test data to be data from an experimental test as exp_data
251    # Consider the computer simulation (results from numerical model) to be
252    # num_data
253    #
254    # Example on formatting the test and history data:
255    # Curve1 = [xi1, eta1]
256    # Curve2 = [xi2, eta2]
257    # exp_data = np.zeros([len(xi1), 2])
258    # num_data = np.zeros([len(xi2), 2])
259    # exp_data[:,0] = xi1
260    # exp_data[:,1] = eta1
261    # num_data[:, 0] = xi2
262    # num_data[:, 1] = eta2
263    #
264    # then you can calculate the area as
265    # area = area_between_two_curves(exp_data, num_data)
266
267    n_exp = len(exp_data)
268    n_num = len(num_data)
269
270    # the length of exp_data must be larger than the length of num_data
271    if n_exp < n_num:
272        temp = num_data.copy()
273        num_data = exp_data.copy()
274        exp_data = temp.copy()
275        n_exp = len(exp_data)
276        n_num = len(num_data)
277
278    # get the arc length data of the curves
279    # arcexp_data, _ = get_arc_length(exp_data)
280    _, arcsnum_data = get_arc_length(num_data)
281
282    # let's find the largest gap between point the num_data, and then
283    # linearally interpolate between these points such that the num_data
284    # becomes the same length as the exp_data
285    for i in range(0, n_exp-n_num):
286        a = num_data[0:n_num-1, 0]
287        b = num_data[1:n_num, 0]
288        nIndex = np.argmax(arcsnum_data)
289        newX = (b[nIndex] + a[nIndex])/2.0
290        #   the interpolation model messes up if x2 < x1 so we do a quick check
291        if a[nIndex] < b[nIndex]:
292            newY = np.interp(newX, [a[nIndex], b[nIndex]],
293                             [num_data[nIndex, 1], num_data[nIndex+1, 1]])
294        else:
295            newY = np.interp(newX, [b[nIndex], a[nIndex]],
296                             [num_data[nIndex+1, 1], num_data[nIndex, 1]])
297        num_data = np.insert(num_data, nIndex+1, newX, axis=0)
298        num_data[nIndex+1, 1] = newY
299
300        _, arcsnum_data = get_arc_length(num_data)
301        n_num = len(num_data)
302
303    # Calculate the quadrilateral area, by looping through all of the quads
304    area = []
305    for i in range(1, n_exp):
306        tempX = [exp_data[i-1, 0], exp_data[i, 0], num_data[i, 0],
307                 num_data[i-1, 0]]
308        tempY = [exp_data[i-1, 1], exp_data[i, 1], num_data[i, 1],
309                 num_data[i-1, 1]]
310        area.append(makeQuad(tempX, tempY))
311    return np.sum(area)
312
313
314def get_length(x, y, norm_seg_length=True):
315    r"""
316    Compute arc lengths of an x y curve.
317
318    Computes the arc length of a xy curve, the cumulative arc length of an xy,
319    and the total xy arc length of a xy curve. The euclidean distance is used
320    to determine the arc length.
321
322    Parameters
323    ----------
324    x : array_like
325        the x locations of a curve
326    y : array_like
327        the y locations of a curve
328    norm_seg_length : boolean
329        Whether to divide the segment length of each curve by the maximum.
330
331    Returns
332    -------
333    le : ndarray (1-D)
334        the euclidean distance between every two points
335    le_total : float
336        the total arc length distance of a curve
337    le_cum : ndarray (1-D)
338        the cumulative sum of euclidean distances between every two points
339
340    Examples
341    --------
342    >>> le, le_total, le_cum = get_length(x, y)
343
344    """
345    n = len(x)
346
347    if norm_seg_length:
348        xmax = np.max(np.abs(x))
349        ymax = np.max(np.abs(y))
350
351        # if your max x or y value is zero... you'll get np.inf
352        # as your curve length based measure
353        if xmax == 0:
354            xmax = 1e-15
355        if ymax == 0:
356            ymax = 1e-15
357    else:
358        ymax = 1.0
359        xmax = 1.0
360
361    le = np.zeros(n)
362    le[0] = 0.0
363    l_sum = np.zeros(n)
364    l_sum[0] = 0.0
365    for i in range(0, n-1):
366        le[i+1] = np.sqrt((((x[i+1]-x[i])/xmax)**2)+(((y[i+1]-y[i])/ymax)**2))
367        l_sum[i+1] = l_sum[i]+le[i+1]
368    return le, np.sum(le), l_sum
369
370
371def curve_length_measure(exp_data, num_data):
372    r"""
373    Compute the curve length based distance between two curves.
374
375    This computes the curve length similarity measure according to [2]_. This
376    implementation follows the OF2 form, which is a self normalizing form
377    based on the average value.
378
379    Parameters
380    ----------
381    exp_data : ndarray (2-D)
382        Curve from your experimental data.
383    num_data : ndarray (2-D)
384        Curve from your numerical data.
385
386    Returns
387    -------
388    r : float
389        curve length based similarity distance
390
391    Notes
392    -----
393    This uses the OF2 method from [2]_.
394
395    Examples
396    --------
397    >>> # Generate random experimental data
398    >>> x = np.random.random(100)
399    >>> y = np.random.random(100)
400    >>> exp_data = np.zeros((100, 2))
401    >>> exp_data[:, 0] = x
402    >>> exp_data[:, 1] = y
403    >>> # Generate random numerical data
404    >>> x = np.random.random(100)
405    >>> y = np.random.random(100)
406    >>> num_data = np.zeros((100, 2))
407    >>> num_data[:, 0] = x
408    >>> num_data[:, 1] = y
409    >>> r = curve_length_measure(exp_data, num_data)
410
411
412    .. [2] A Andrade-Campos, R De-Carvalho, and R A F Valente. Novel criteria
413        for determination of material model parameters. International Journal
414        of Mechanical Sciences, 54(1):294-305, 2012. ISSN 0020-7403. DOI
415        https://doi.org/10.1016/j.ijmecsci.2011.11.010 URL:
416        http://www.sciencedirect.com/science/article/pii/S0020740311002451
417
418    """
419    x_e = exp_data[:, 0]
420    y_e = exp_data[:, 1]
421    x_c = num_data[:, 0]
422    y_c = num_data[:, 1]
423
424    _, le_nj, le_sum = get_length(x_e, y_e)
425    _, lc_nj, lc_sum = get_length(x_c, y_c)
426
427    xmean = np.mean(x_e)
428    ymean = np.mean(y_e)
429
430    factor = lc_nj/le_nj
431
432    lieq = le_sum * factor
433
434    xinterp = np.interp(lieq, lc_sum, x_c)
435    yinterp = np.interp(lieq, lc_sum, y_c)
436
437    r_sq = np.log(1.0 + (np.abs(xinterp-x_e)/xmean))**2
438    r_sq += np.log(1.0 + (np.abs(yinterp-y_e)/ymean))**2
439    return np.sqrt(np.sum(r_sq))
440
441
442def frechet_dist(exp_data, num_data, p=2):
443    r"""
444    Compute the discrete Frechet distance
445
446    Compute the Discrete Frechet Distance between two N-D curves according to
447    [3]_. The Frechet distance has been defined as the walking dog problem.
448    From Wikipedia: "In mathematics, the Frechet distance is a measure of
449    similarity between curves that takes into account the location and
450    ordering of the points along the curves. It is named after Maurice Frechet.
451    https://en.wikipedia.org/wiki/Fr%C3%A9chet_distance
452
453    Parameters
454    ----------
455    exp_data : array_like
456        Curve from your experimental data. exp_data is of (M, N) shape, where
457        M is the number of data points, and N is the number of dimmensions
458    num_data : array_like
459        Curve from your numerical data. num_data is of (P, N) shape, where P
460        is the number of data points, and N is the number of dimmensions
461    p : float, 1 <= p <= infinity
462        Which Minkowski p-norm to use. Default is p=2 (Eculidean).
463        The manhattan distance is p=1.
464
465    Returns
466    -------
467    df : float
468        discrete Frechet distance
469
470    Notes
471    -----
472    Your x locations of data points should be exp_data[:, 0], and the y
473    locations of the data points should be exp_data[:, 1]. Same for num_data.
474
475    Thanks to Arbel Amir for the issue, and Sen ZHANG for the iterative code
476    https://github.com/cjekel/similarity_measures/issues/6
477
478    Examples
479    --------
480    >>> # Generate random experimental data
481    >>> x = np.random.random(100)
482    >>> y = np.random.random(100)
483    >>> exp_data = np.zeros((100, 2))
484    >>> exp_data[:, 0] = x
485    >>> exp_data[:, 1] = y
486    >>> # Generate random numerical data
487    >>> x = np.random.random(100)
488    >>> y = np.random.random(100)
489    >>> num_data = np.zeros((100, 2))
490    >>> num_data[:, 0] = x
491    >>> num_data[:, 1] = y
492    >>> df = frechet_dist(exp_data, num_data)
493
494    .. [3] Thomas Eiter and Heikki Mannila. Computing discrete Frechet
495        distance. Technical report, 1994.
496        http://www.kr.tuwien.ac.at/staff/eiter/et-archive/cdtr9464.pdf
497        http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.90.937&rep=rep1&type=pdf
498    """
499    n = len(exp_data)
500    m = len(num_data)
501    c = distance.cdist(exp_data, num_data, metric='minkowski', p=p)
502    ca = np.ones((n, m))
503    ca = np.multiply(ca, -1)
504    ca[0, 0] = c[0, 0]
505    for i in range(1, n):
506        ca[i, 0] = max(ca[i-1, 0], c[i, 0])
507    for j in range(1, m):
508        ca[0, j] = max(ca[0, j-1], c[0, j])
509    for i in range(1, n):
510        for j in range(1, m):
511            ca[i, j] = max(min(ca[i-1, j], ca[i, j-1], ca[i-1, j-1]),
512                           c[i, j])
513    return ca[n-1, m-1]
514
515
516def normalizeTwoCurves(x, y, w, z):
517    """
518    Normalize two curves for PCM method.
519
520    This normalizes the two curves for PCM method following [4]_.
521
522    Parameters
523    ----------
524    x : array_like (1-D)
525        x locations for first curve
526    y : array_like (1-D)
527        y locations for first curve
528    w : array_like (1-D)
529        x locations for second curve curve
530    z : array_like (1-D)
531        y locations for second curve
532
533    Returns
534    -------
535    xi : array_like
536        normalized x locations for first curve
537    eta : array_like
538        normalized y locations for first curve
539    xiP : array_like
540        normalized x locations for second curve
541    etaP : array_like
542        normalized y locations for second curve
543
544
545    Examples
546    --------
547    >>> xi, eta, xiP, etaP = normalizeTwoCurves(x,y,w,z)
548
549    .. [4] Katharina Witowski and Nielen Stander. "Parameter Identification of
550        Hysteretic Models Using Partial Curve Mapping", 12th AIAA Aviation
551        Technology, Integration, and Operations (ATIO) Conference and 14th
552        AIAA/ISSMO Multidisciplinary Analysis and Optimization Conference,
553        Aviation Technology, Integration, and Operations (ATIO) Conferences.
554        doi: doi:10.2514/6.2012-5580.
555    """
556    minX = np.min(x)
557    maxX = np.max(x)
558    minY = np.min(y)
559    maxY = np.max(y)
560
561    xi = (x - minX) / (maxX - minX)
562    eta = (y - minY) / (maxY - minY)
563    xiP = (w - minX) / (maxX - minX)
564    etaP = (z - minY) / (maxY - minY)
565    return xi, eta, xiP, etaP
566
567
568def pcm(exp_data, num_data, norm_seg_length=False):
569    """
570    Compute the Partial Curve Mapping area.
571
572    Computes the Partial Cuve Mapping (PCM) similarity measure as proposed by
573    [5]_.
574
575    Parameters
576    ----------
577    exp_data : ndarray (2-D)
578        Curve from your experimental data.
579    num_data : ndarray (2-D)
580        Curve from your numerical data.
581    norm_seg_length : boolean
582        Whether to divide the segment length of each curve by the maximum. The
583        default value is false, which more closely follows the algorithm
584        proposed in [1]_. Versions prior to 0.6.0 used `norm_seg_length=True`.
585
586    Returns
587    -------
588    p : float
589        pcm area measure
590
591    Notes
592    -----
593    Your x locations of data points should be exp_data[:, 0], and the y
594    locations of the data points should be exp_data[:, 1]. Same for num_data.
595
596    PCM distance was changed in version 0.6.0. To get the same results from
597    previous versions, set `norm_seg_length=True`.
598
599    Examples
600    --------
601    >>> # Generate random experimental data
602    >>> x = np.random.random(100)
603    >>> y = np.random.random(100)
604    >>> exp_data = np.zeros((100, 2))
605    >>> exp_data[:, 0] = x
606    >>> exp_data[:, 1] = y
607    >>> # Generate random numerical data
608    >>> x = np.random.random(100)
609    >>> y = np.random.random(100)
610    >>> num_data = np.zeros((100, 2))
611    >>> num_data[:, 0] = x
612    >>> num_data[:, 1] = y
613    >>> p = pcm(exp_data, num_data)
614
615    .. [5] Katharina Witowski and Nielen Stander. "Parameter Identification of
616        Hysteretic Models Using Partial Curve Mapping", 12th AIAA Aviation
617        Technology, Integration, and Operations (ATIO) Conference and 14th
618        AIAA/ISSMO Multidisciplinary Analysis and Optimization Conference,
619        Aviation Technology, Integration, and Operations (ATIO) Conferences.
620        doi: doi:10.2514/6.2012-5580.
621    """
622    # normalize the curves to the experimental data
623    xi1, eta1, xi2, eta2 = normalizeTwoCurves(exp_data[:, 0], exp_data[:, 1],
624                                              num_data[:, 0], num_data[:, 1])
625    # compute the arc lengths of each curve
626    le, le_nj, le_sum = get_length(xi1, eta1, norm_seg_length)
627    lc, lc_nj, lc_sum = get_length(xi2, eta2, norm_seg_length)
628    # scale each segment to the total polygon length
629    le = le / le_nj
630    le_sum = le_sum / le_nj
631    lc = lc / lc_nj
632    lc_sum = lc_sum / lc_nj
633    # right now exp_data is curve a, and num_data is curve b
634    # make sure a is shorter than a', if not swap the defintion
635    if lc_nj > le_nj:
636        # compute the arc lengths of each curve
637        le, le_nj, le_sum = get_length(xi2, eta2, norm_seg_length)
638        lc, lc_nj, lc_sum = get_length(xi1, eta1, norm_seg_length)
639        # scale each segment to the total polygon length
640        le = le / le_nj
641        le_sum = le_sum / le_nj
642        lc = lc / lc_nj
643        lc_sum = lc_sum / lc_nj
644        # swap xi1, eta1 with xi2, eta2
645        xi1OLD = xi1.copy()
646        eta1OLD = eta1.copy()
647        xi1 = xi2.copy()
648        eta1 = eta2.copy()
649        xi2 = xi1OLD.copy()
650        eta2 = eta1OLD.copy()
651
652    n_sum = len(le_sum)
653
654    min_offset = 0.0
655    max_offset = le_nj - lc_nj
656
657    # make sure the curves aren't the same length
658    # if they are the same length, don't loop 200 times
659    if min_offset == max_offset:
660        offsets = [min_offset]
661        pcm_dists = np.zeros(1)
662    else:
663        offsets = np.linspace(min_offset, max_offset, 200)
664        pcm_dists = np.zeros(200)
665
666    for i, offset in enumerate(offsets):
667        # create linear interpolation model for num_data based on arc length
668        # evaluate linear interpolation model based on xi and eta of exp data
669        xitemp = np.interp(le_sum+offset, lc_sum, xi2)
670        etatemp = np.interp(le_sum+offset, lc_sum, eta2)
671
672        d = np.sqrt((eta1-etatemp)**2 + (xi1-xitemp)**2)
673        d1 = d[:-1]
674
675        d2 = d[1:n_sum]
676
677        v = 0.5*(d1+d2)*le_sum[1:n_sum]
678        pcm_dists[i] = np.sum(v)
679    return np.min(pcm_dists)
680
681
682def dtw(exp_data, num_data, metric='euclidean', **kwargs):
683    r"""
684    Compute the Dynamic Time Warping distance.
685
686    This computes a generic Dynamic Time Warping (DTW) distance and follows
687    the algorithm from [6]_. This can use all distance metrics that are
688    available in scipy.spatial.distance.cdist.
689
690    Parameters
691    ----------
692    exp_data : array_like
693        Curve from your experimental data. exp_data is of (M, N) shape, where
694        M is the number of data points, and N is the number of dimmensions
695    num_data : array_like
696        Curve from your numerical data. num_data is of (P, N) shape, where P
697        is the number of data points, and N is the number of dimmensions
698    metric : str or callable, optional
699        The distance metric to use. Default='euclidean'. Refer to the
700        documentation for scipy.spatial.distance.cdist. Some examples:
701        'braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation',
702        'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'kulsinski',
703        'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao',
704        'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean',
705        'wminkowski', 'yule'.
706    **kwargs : dict, optional
707        Extra arguments to `metric`: refer to each metric documentation in
708        scipy.spatial.distance.
709        Some examples:
710
711        p : scalar
712            The p-norm to apply for Minkowski, weighted and unweighted.
713            Default: 2.
714
715        w : ndarray
716            The weight vector for metrics that support weights (e.g.,
717            Minkowski).
718
719        V : ndarray
720            The variance vector for standardized Euclidean.
721            Default: var(vstack([XA, XB]), axis=0, ddof=1)
722
723        VI : ndarray
724            The inverse of the covariance matrix for Mahalanobis.
725            Default: inv(cov(vstack([XA, XB].T))).T
726
727        out : ndarray
728            The output array
729            If not None, the distance matrix Y is stored in this array.
730
731    Returns
732    -------
733    r : float
734        DTW distance.
735    d : ndarray (2-D)
736        Cumulative distance matrix
737
738    Notes
739    -----
740    The DTW distance is d[-1, -1].
741
742    This has O(M, P) computational cost.
743
744    The latest scipy.spatial.distance.cdist information can be found at
745    https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html
746
747    Your x locations of data points should be exp_data[:, 0], and the y
748    locations of the data points should be exp_data[:, 1]. Same for num_data.
749
750    This uses the euclidean distance for now. In the future it should be
751    possible to support other metrics.
752
753    DTW is a non-metric distance, which means DTW doesn't hold the triangle
754    inequality.
755    https://en.wikipedia.org/wiki/Triangle_inequality
756
757    Examples
758    --------
759    >>> # Generate random experimental data
760    >>> x = np.random.random(100)
761    >>> y = np.random.random(100)
762    >>> exp_data = np.zeros((100, 2))
763    >>> exp_data[:, 0] = x
764    >>> exp_data[:, 1] = y
765    >>> # Generate random numerical data
766    >>> x = np.random.random(100)
767    >>> y = np.random.random(100)
768    >>> num_data = np.zeros((100, 2))
769    >>> num_data[:, 0] = x
770    >>> num_data[:, 1] = y
771    >>> r, d = dtw(exp_data, num_data)
772
773    The euclidean distance is used by default. You can use metric and **kwargs
774    to specify different types of distance metrics. The following example uses
775    the city block or Manhattan distance between points.
776
777    >>> r, d = dtw(exp_data, num_data, metric='cityblock')
778
779    .. [6] Senin, P., 2008. Dynamic time warping algorithm review. Information
780        and Computer Science Department University of Hawaii at Manoa Honolulu,
781        USA, 855, pp.1-23.
782        http://seninp.github.io/assets/pubs/senin_dtw_litreview_2008.pdf
783    """
784    c = distance.cdist(exp_data, num_data, metric=metric, **kwargs)
785
786    d = np.zeros(c.shape)
787    d[0, 0] = c[0, 0]
788    n, m = c.shape
789    for i in range(1, n):
790        d[i, 0] = d[i-1, 0] + c[i, 0]
791    for j in range(1, m):
792        d[0, j] = d[0, j-1] + c[0, j]
793    for i in range(1, n):
794        for j in range(1, m):
795            d[i, j] = c[i, j] + min((d[i-1, j], d[i, j-1], d[i-1, j-1]))
796    return d[-1, -1], d
797
798
799def dtw_path(d):
800    r"""
801    Calculates the optimal DTW path from a given DTW cumulative distance
802    matrix.
803
804    This function returns the optimal DTW path using the back propagation
805    algorithm that is defined in [7]_. This path details the index from each
806    curve that is being compared.
807
808    Parameters
809    ----------
810    d : ndarray (2-D)
811        Cumulative distance matrix.
812
813    Returns
814    -------
815    path : ndarray (2-D)
816        The optimal DTW path.
817
818    Notes
819    -----
820    Note that path[:, 0] represents the indices from exp_data, while
821    path[:, 1] represents the indices from the num_data.
822
823    .. [7] Senin, P., 2008. Dynamic time warping algorithm review. Information
824        and Computer Science Department University of Hawaii at Manoa Honolulu,
825        USA, 855, pp.1-23.
826        http://seninp.github.io/assets/pubs/senin_dtw_litreview_2008.pdf
827
828    Examples
829    --------
830    First calculate the DTW cumulative distance matrix.
831
832    >>> # Generate random experimental data
833    >>> x = np.random.random(100)
834    >>> y = np.random.random(100)
835    >>> exp_data = np.zeros((100, 2))
836    >>> exp_data[:, 0] = x
837    >>> exp_data[:, 1] = y
838    >>> # Generate random numerical data
839    >>> x = np.random.random(100)
840    >>> y = np.random.random(100)
841    >>> num_data = np.zeros((100, 2))
842    >>> num_data[:, 0] = x
843    >>> num_data[:, 1] = y
844    >>> r, d = dtw(exp_data, num_data)
845
846    Now you can calculate the optimal DTW path
847
848    >>> path = dtw_path(d)
849
850    You can visualize the path on the cumulative distance matrix using the
851    following code.
852
853    >>> import matplotlib.pyplot as plt
854    >>> plt.figure()
855    >>> plt.imshow(d.T, origin='lower')
856    >>> plt.plot(path[:, 0], path[:, 1], '-k')
857    >>> plt.colorbar()
858    >>> plt.show()
859
860    """
861    path = []
862    i, j = d.shape
863    i = i - 1
864    j = j - 1
865    # back propagation starts from the last point,
866    # and ends at d[0, 0]
867    path.append((i, j))
868    while i > 0 or j > 0:
869        if i == 0:
870            j = j - 1
871        elif j == 0:
872            i = i - 1
873        else:
874            temp_step = min([d[i-1, j], d[i, j-1], d[i-1, j-1]])
875            if d[i-1, j] == temp_step:
876                i = i - 1
877            elif d[i, j-1] == temp_step:
878                j = j - 1
879            else:
880                i = i - 1
881                j = j - 1
882        path.append((i, j))
883    path = np.array(path)
884    # reverse the order of path, such that it starts with [0, 0]
885    return path[::-1]
886
887
888def mae(exp_data, num_data):
889    """
890    Compute the Mean Absolute Error (MAE).
891
892    This computes the mean of absolute values of distances between two curves.
893    Each curve must have the same number of data points and the same dimension.
894
895    Parameters
896    ----------
897    exp_data : array_like
898        Curve from your experimental data. exp_data is of (M, N) shape, where
899        M is the number of data points, and N is the number of dimensions
900    num_data : array_like
901        Curve from your numerical data. num_data is of (M, N) shape, where M
902        is the number of data points, and N is the number of dimensions
903
904    Returns
905    -------
906    r : float
907        MAE.
908    """
909    c = np.abs(exp_data - num_data)
910    return np.mean(c)
911
912
913def mse(exp_data, num_data):
914    """
915    Compute the Mean Squared Error (MAE).
916
917    This computes the mean of sqaured distances between two curves.
918    Each curve must have the same number of data points and the same dimension.
919
920    Parameters
921    ----------
922    exp_data : array_like
923        Curve from your experimental data. exp_data is of (M, N) shape, where
924        M is the number of data points, and N is the number of dimensions
925    num_data : array_like
926        Curve from your numerical data. num_data is of (M, N) shape, where M
927        is the number of data points, and N is the number of dimensions
928
929    Returns
930    -------
931    r : float
932        MSE.
933    """
934    c = np.square(exp_data - num_data)
935    return np.mean(c)
def poly_area(x, y):
41def poly_area(x, y):
42    r"""
43    A function that computes the polygonal area via the shoelace formula.
44
45    This function allows you to take the area of any polygon that is not self
46    intersecting. This is also known as Gauss's area formula. See
47    https://en.wikipedia.org/wiki/Shoelace_formula
48
49    Parameters
50    ----------
51    x : ndarray (1-D)
52        the x locations of a polygon
53    y : ndarray (1-D)
54        the y locations of the polygon
55
56    Returns
57    -------
58    area : float
59        the calculated polygonal area
60
61    Notes
62    -----
63    The x and y locations need to be ordered such that the first vertex
64    of the polynomial correspounds to x[0] and y[0], the second vertex
65    x[1] and y[1] and so forth
66
67
68    Thanks to Mahdi for this one line code
69    https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates
70    """
71    return 0.5*np.abs(np.dot(x, np.roll(y, 1))-np.dot(y, np.roll(x, 1)))

A function that computes the polygonal area via the shoelace formula.

This function allows you to take the area of any polygon that is not self intersecting. This is also known as Gauss's area formula. See https://en.wikipedia.org/wiki/Shoelace_formula

Parameters
  • x (ndarray (1-D)): the x locations of a polygon
  • y (ndarray (1-D)): the y locations of the polygon
Returns
  • area (float): the calculated polygonal area
Notes

The x and y locations need to be ordered such that the first vertex of the polynomial correspounds to x[0] and y[0], the second vertex x[1] and y[1] and so forth

Thanks to Mahdi for this one line code https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates

def is_simple_quad(ab, bc, cd, da) -> bool:
 74def is_simple_quad(ab, bc, cd, da) -> bool:
 75    r"""
 76    Returns True if a quadrilateral is simple
 77
 78    This function performs cross products at the vertices of a quadrilateral.
 79    It is possible to use the results to decide whether a quadrilateral is
 80    simple or complex. This function returns True if the quadrilateral is
 81    simple, and False if the quadrilateral is complex. A complex quadrilateral
 82    is a self-intersecting quadrilateral.
 83
 84    Parameters
 85    ----------
 86    ab : array_like
 87        [x, y] location of the first vertex
 88    bc : array_like
 89        [x, y] location of the second vertex
 90    cd : array_like
 91        [x, y] location of the third vertex
 92    da : array_like
 93        [x, y] location of the fourth vertex
 94
 95    Returns
 96    -------
 97    simple : bool
 98        True if quadrilateral is simple, False if complex
 99    """
100    #   Compute all four 2-D cross products
101    temp0 = _cross2d(ab, bc)
102    temp1 = _cross2d(bc, cd)
103    temp2 = _cross2d(cd, da)
104    temp3 = _cross2d(da, ab)
105    cross = np.array([temp0, temp1, temp2, temp3])
106    #   See that majority of cross products is non-positive or non-negative
107    #   They don't necessarily need to lie in the same 'Z' direction
108    if sum(cross > 0) < sum(cross < 0):
109        crossTF = cross <= 0
110    else:
111        crossTF = cross >= 0
112    return bool(sum(crossTF) > 2)

Returns True if a quadrilateral is simple

This function performs cross products at the vertices of a quadrilateral. It is possible to use the results to decide whether a quadrilateral is simple or complex. This function returns True if the quadrilateral is simple, and False if the quadrilateral is complex. A complex quadrilateral is a self-intersecting quadrilateral.

Parameters
  • ab (array_like): [x, y] location of the first vertex
  • bc (array_like): [x, y] location of the second vertex
  • cd (array_like): [x, y] location of the third vertex
  • da (array_like): [x, y] location of the fourth vertex
Returns
  • simple (bool): True if quadrilateral is simple, False if complex
def makeQuad(x, y):
115def makeQuad(x, y):
116    r"""
117    Calculate the area from the x and y locations of a quadrilateral
118
119    This function first constructs a simple quadrilateral from the x and y
120    locations of the vertices of the quadrilateral. The function then
121    calculates the shoelace area of the simple quadrilateral.
122
123    Parameters
124    ----------
125    x : array_like
126        the x locations of a quadrilateral
127    y : array_like
128        the y locations of a quadrilateral
129
130    Returns
131    -------
132    area : float
133        Area of quadrilateral via shoelace formula
134
135    Notes
136    -----
137    This function rearranges the vertices of a quadrilateral until the
138    quadrilateral is "Simple" (meaning non-complex). Once a simple
139    quadrilateral is found, the area of the quadrilateral is calculated
140    using the shoelace formula.
141    """
142
143    # check to see if the provide point order is valid
144    # I need to get the values of the cross products of ABxBC, BCxCD, CDxDA,
145    # DAxAB, thus I need to create the following arrays AB, BC, CD, DA
146
147    AB = [x[1]-x[0], y[1]-y[0]]
148    BC = [x[2]-x[1], y[2]-y[1]]
149    CD = [x[3]-x[2], y[3]-y[2]]
150    DA = [x[0]-x[3], y[0]-y[3]]
151
152    isQuad = is_simple_quad(AB, BC, CD, DA)
153
154    if isQuad is False:
155        # attempt to rearrange the first two points
156        x[1], x[0] = x[0], x[1]
157        y[1], y[0] = y[0], y[1]
158        AB = [x[1]-x[0], y[1]-y[0]]
159        BC = [x[2]-x[1], y[2]-y[1]]
160        CD = [x[3]-x[2], y[3]-y[2]]
161        DA = [x[0]-x[3], y[0]-y[3]]
162
163        isQuad = is_simple_quad(AB, BC, CD, DA)
164
165        if isQuad is False:
166            # place the second and first points back where they were, and
167            # swap the second and third points
168            x[2], x[0], x[1] = x[0], x[1], x[2]
169            y[2], y[0], y[1] = y[0], y[1], y[2]
170            AB = [x[1]-x[0], y[1]-y[0]]
171            BC = [x[2]-x[1], y[2]-y[1]]
172            CD = [x[3]-x[2], y[3]-y[2]]
173            DA = [x[0]-x[3], y[0]-y[3]]
174
175            isQuad = is_simple_quad(AB, BC, CD, DA)
176
177    # calculate the area via shoelace formula
178    area = poly_area(x, y)
179    return area

Calculate the area from the x and y locations of a quadrilateral

This function first constructs a simple quadrilateral from the x and y locations of the vertices of the quadrilateral. The function then calculates the shoelace area of the simple quadrilateral.

Parameters
  • x (array_like): the x locations of a quadrilateral
  • y (array_like): the y locations of a quadrilateral
Returns
  • area (float): Area of quadrilateral via shoelace formula
Notes

This function rearranges the vertices of a quadrilateral until the quadrilateral is "Simple" (meaning non-complex). Once a simple quadrilateral is found, the area of the quadrilateral is calculated using the shoelace formula.

def get_arc_length(dataset):
182def get_arc_length(dataset):
183    r"""
184    Obtain arc length distances between every point in 2-D space
185
186    Obtains the total arc length of a curve in 2-D space (a curve of x and y)
187    as well as the arc lengths between each two consecutive data points of the
188    curve.
189
190    Parameters
191    ----------
192    dataset : ndarray (2-D)
193        The dataset of the curve in 2-D space.
194
195    Returns
196    -------
197    arcLength : float
198        The sum of all consecutive arc lengths
199    arcLengths : array_like
200        A list of the arc lengths between data points
201
202    Notes
203    -----
204    Your x locations of data points should be dataset[:, 0], and the y
205    locations of the data points should be dataset[:, 1]
206    """
207    #   split the dataset into two discrete datasets, each of length m-1
208    m = len(dataset)
209    a = dataset[0:m-1, :]
210    b = dataset[1:m, :]
211    #   use scipy.spatial to compute the euclidean distance
212    dataDistance = distance.cdist(a, b, 'euclidean')
213    #   this returns a matrix of the euclidean distance between all points
214    #   the arc length is simply the sum of the diagonal of this matrix
215    arcLengths = np.diagonal(dataDistance)
216    arcLength = sum(arcLengths)
217    return arcLength, arcLengths

Obtain arc length distances between every point in 2-D space

Obtains the total arc length of a curve in 2-D space (a curve of x and y) as well as the arc lengths between each two consecutive data points of the curve.

Parameters
  • dataset (ndarray (2-D)): The dataset of the curve in 2-D space.
Returns
  • arcLength (float): The sum of all consecutive arc lengths
  • arcLengths (array_like): A list of the arc lengths between data points
Notes

Your x locations of data points should be dataset[:, 0], and the y locations of the data points should be dataset[:, 1]

def area_between_two_curves(exp_data, num_data):
220def area_between_two_curves(exp_data, num_data):
221    r"""
222    Calculates the area between two curves.
223
224    This calculates the area according to the algorithm in [1]_. Each curve is
225    constructed from discretized data points in 2-D space, e.g. each curve
226    consists of x and y data points.
227
228    Parameters
229    ----------
230    exp_data : ndarray (2-D)
231        Curve from your experimental data.
232    num_data : ndarray (2-D)
233        Curve from your numerical data.
234
235    Returns
236    -------
237    area : float
238        The area between exp_data and num_data curves.
239
240    Notes
241    -----
242    Your x locations of data points should be exp_data[:, 0], and the y
243    locations of the data points should be exp_data[:, 1]. Same for num_data.
244
245    .. [1] Jekel, C. F., Venter, G., Venter, M. P., Stander, N., & Haftka, R.
246        T. (2018). Similarity measures for identifying material parameters from
247        hysteresis loops using inverse analysis. International Journal of
248        Material Forming. https://doi.org/10.1007/s12289-018-1421-8
249    """
250    # Calculate the area between two curves using quadrilaterals
251    # Consider the test data to be data from an experimental test as exp_data
252    # Consider the computer simulation (results from numerical model) to be
253    # num_data
254    #
255    # Example on formatting the test and history data:
256    # Curve1 = [xi1, eta1]
257    # Curve2 = [xi2, eta2]
258    # exp_data = np.zeros([len(xi1), 2])
259    # num_data = np.zeros([len(xi2), 2])
260    # exp_data[:,0] = xi1
261    # exp_data[:,1] = eta1
262    # num_data[:, 0] = xi2
263    # num_data[:, 1] = eta2
264    #
265    # then you can calculate the area as
266    # area = area_between_two_curves(exp_data, num_data)
267
268    n_exp = len(exp_data)
269    n_num = len(num_data)
270
271    # the length of exp_data must be larger than the length of num_data
272    if n_exp < n_num:
273        temp = num_data.copy()
274        num_data = exp_data.copy()
275        exp_data = temp.copy()
276        n_exp = len(exp_data)
277        n_num = len(num_data)
278
279    # get the arc length data of the curves
280    # arcexp_data, _ = get_arc_length(exp_data)
281    _, arcsnum_data = get_arc_length(num_data)
282
283    # let's find the largest gap between point the num_data, and then
284    # linearally interpolate between these points such that the num_data
285    # becomes the same length as the exp_data
286    for i in range(0, n_exp-n_num):
287        a = num_data[0:n_num-1, 0]
288        b = num_data[1:n_num, 0]
289        nIndex = np.argmax(arcsnum_data)
290        newX = (b[nIndex] + a[nIndex])/2.0
291        #   the interpolation model messes up if x2 < x1 so we do a quick check
292        if a[nIndex] < b[nIndex]:
293            newY = np.interp(newX, [a[nIndex], b[nIndex]],
294                             [num_data[nIndex, 1], num_data[nIndex+1, 1]])
295        else:
296            newY = np.interp(newX, [b[nIndex], a[nIndex]],
297                             [num_data[nIndex+1, 1], num_data[nIndex, 1]])
298        num_data = np.insert(num_data, nIndex+1, newX, axis=0)
299        num_data[nIndex+1, 1] = newY
300
301        _, arcsnum_data = get_arc_length(num_data)
302        n_num = len(num_data)
303
304    # Calculate the quadrilateral area, by looping through all of the quads
305    area = []
306    for i in range(1, n_exp):
307        tempX = [exp_data[i-1, 0], exp_data[i, 0], num_data[i, 0],
308                 num_data[i-1, 0]]
309        tempY = [exp_data[i-1, 1], exp_data[i, 1], num_data[i, 1],
310                 num_data[i-1, 1]]
311        area.append(makeQuad(tempX, tempY))
312    return np.sum(area)

Calculates the area between two curves.

This calculates the area according to the algorithm in 1. Each curve is constructed from discretized data points in 2-D space, e.g. each curve consists of x and y data points.

Parameters
  • exp_data (ndarray (2-D)): Curve from your experimental data.
  • num_data (ndarray (2-D)): Curve from your numerical data.
Returns
  • area (float): The area between exp_data and num_data curves.
Notes

Your x locations of data points should be exp_data[:, 0], and the y locations of the data points should be exp_data[:, 1]. Same for num_data.


  1. Jekel, C. F., Venter, G., Venter, M. P., Stander, N., & Haftka, R. T. (2018). Similarity measures for identifying material parameters from hysteresis loops using inverse analysis. International Journal of Material Forming. https://doi.org/10.1007/s12289-018-1421-8 ↩

def get_length(x, y, norm_seg_length=True):
315def get_length(x, y, norm_seg_length=True):
316    r"""
317    Compute arc lengths of an x y curve.
318
319    Computes the arc length of a xy curve, the cumulative arc length of an xy,
320    and the total xy arc length of a xy curve. The euclidean distance is used
321    to determine the arc length.
322
323    Parameters
324    ----------
325    x : array_like
326        the x locations of a curve
327    y : array_like
328        the y locations of a curve
329    norm_seg_length : boolean
330        Whether to divide the segment length of each curve by the maximum.
331
332    Returns
333    -------
334    le : ndarray (1-D)
335        the euclidean distance between every two points
336    le_total : float
337        the total arc length distance of a curve
338    le_cum : ndarray (1-D)
339        the cumulative sum of euclidean distances between every two points
340
341    Examples
342    --------
343    >>> le, le_total, le_cum = get_length(x, y)
344
345    """
346    n = len(x)
347
348    if norm_seg_length:
349        xmax = np.max(np.abs(x))
350        ymax = np.max(np.abs(y))
351
352        # if your max x or y value is zero... you'll get np.inf
353        # as your curve length based measure
354        if xmax == 0:
355            xmax = 1e-15
356        if ymax == 0:
357            ymax = 1e-15
358    else:
359        ymax = 1.0
360        xmax = 1.0
361
362    le = np.zeros(n)
363    le[0] = 0.0
364    l_sum = np.zeros(n)
365    l_sum[0] = 0.0
366    for i in range(0, n-1):
367        le[i+1] = np.sqrt((((x[i+1]-x[i])/xmax)**2)+(((y[i+1]-y[i])/ymax)**2))
368        l_sum[i+1] = l_sum[i]+le[i+1]
369    return le, np.sum(le), l_sum

Compute arc lengths of an x y curve.

Computes the arc length of a xy curve, the cumulative arc length of an xy, and the total xy arc length of a xy curve. The euclidean distance is used to determine the arc length.

Parameters
  • x (array_like): the x locations of a curve
  • y (array_like): the y locations of a curve
  • norm_seg_length (boolean): Whether to divide the segment length of each curve by the maximum.
Returns
  • le (ndarray (1-D)): the euclidean distance between every two points
  • le_total (float): the total arc length distance of a curve
  • le_cum (ndarray (1-D)): the cumulative sum of euclidean distances between every two points
Examples
>>> le, le_total, le_cum = get_length(x, y)
def curve_length_measure(exp_data, num_data):
372def curve_length_measure(exp_data, num_data):
373    r"""
374    Compute the curve length based distance between two curves.
375
376    This computes the curve length similarity measure according to [2]_. This
377    implementation follows the OF2 form, which is a self normalizing form
378    based on the average value.
379
380    Parameters
381    ----------
382    exp_data : ndarray (2-D)
383        Curve from your experimental data.
384    num_data : ndarray (2-D)
385        Curve from your numerical data.
386
387    Returns
388    -------
389    r : float
390        curve length based similarity distance
391
392    Notes
393    -----
394    This uses the OF2 method from [2]_.
395
396    Examples
397    --------
398    >>> # Generate random experimental data
399    >>> x = np.random.random(100)
400    >>> y = np.random.random(100)
401    >>> exp_data = np.zeros((100, 2))
402    >>> exp_data[:, 0] = x
403    >>> exp_data[:, 1] = y
404    >>> # Generate random numerical data
405    >>> x = np.random.random(100)
406    >>> y = np.random.random(100)
407    >>> num_data = np.zeros((100, 2))
408    >>> num_data[:, 0] = x
409    >>> num_data[:, 1] = y
410    >>> r = curve_length_measure(exp_data, num_data)
411
412
413    .. [2] A Andrade-Campos, R De-Carvalho, and R A F Valente. Novel criteria
414        for determination of material model parameters. International Journal
415        of Mechanical Sciences, 54(1):294-305, 2012. ISSN 0020-7403. DOI
416        https://doi.org/10.1016/j.ijmecsci.2011.11.010 URL:
417        http://www.sciencedirect.com/science/article/pii/S0020740311002451
418
419    """
420    x_e = exp_data[:, 0]
421    y_e = exp_data[:, 1]
422    x_c = num_data[:, 0]
423    y_c = num_data[:, 1]
424
425    _, le_nj, le_sum = get_length(x_e, y_e)
426    _, lc_nj, lc_sum = get_length(x_c, y_c)
427
428    xmean = np.mean(x_e)
429    ymean = np.mean(y_e)
430
431    factor = lc_nj/le_nj
432
433    lieq = le_sum * factor
434
435    xinterp = np.interp(lieq, lc_sum, x_c)
436    yinterp = np.interp(lieq, lc_sum, y_c)
437
438    r_sq = np.log(1.0 + (np.abs(xinterp-x_e)/xmean))**2
439    r_sq += np.log(1.0 + (np.abs(yinterp-y_e)/ymean))**2
440    return np.sqrt(np.sum(r_sq))

Compute the curve length based distance between two curves.

This computes the curve length similarity measure according to 1. This implementation follows the OF2 form, which is a self normalizing form based on the average value.

Parameters
  • exp_data (ndarray (2-D)): Curve from your experimental data.
  • num_data (ndarray (2-D)): Curve from your numerical data.
Returns
  • r (float): curve length based similarity distance
Notes

This uses the OF2 method from 2.

Examples
>>> # Generate random experimental data
>>> x = np.random.random(100)
>>> y = np.random.random(100)
>>> exp_data = np.zeros((100, 2))
>>> exp_data[:, 0] = x
>>> exp_data[:, 1] = y
>>> # Generate random numerical data
>>> x = np.random.random(100)
>>> y = np.random.random(100)
>>> num_data = np.zeros((100, 2))
>>> num_data[:, 0] = x
>>> num_data[:, 1] = y
>>> r = curve_length_measure(exp_data, num_data)

  1. A Andrade-Campos, R De-Carvalho, and R A F Valente. Novel criteria for determination of material model parameters. International Journal of Mechanical Sciences, 54(1):294-305, 2012. ISSN 0020-7403. DOI https://doi.org/10.1016/j.ijmecsci.2011.11.010 URL: http://www.sciencedirect.com/science/article/pii/S0020740311002451 ↩

  2. A Andrade-Campos, R De-Carvalho, and R A F Valente. Novel criteria for determination of material model parameters. International Journal of Mechanical Sciences, 54(1):294-305, 2012. ISSN 0020-7403. DOI https://doi.org/10.1016/j.ijmecsci.2011.11.010 URL: http://www.sciencedirect.com/science/article/pii/S0020740311002451 ↩

def frechet_dist(exp_data, num_data, p=2):
443def frechet_dist(exp_data, num_data, p=2):
444    r"""
445    Compute the discrete Frechet distance
446
447    Compute the Discrete Frechet Distance between two N-D curves according to
448    [3]_. The Frechet distance has been defined as the walking dog problem.
449    From Wikipedia: "In mathematics, the Frechet distance is a measure of
450    similarity between curves that takes into account the location and
451    ordering of the points along the curves. It is named after Maurice Frechet.
452    https://en.wikipedia.org/wiki/Fr%C3%A9chet_distance
453
454    Parameters
455    ----------
456    exp_data : array_like
457        Curve from your experimental data. exp_data is of (M, N) shape, where
458        M is the number of data points, and N is the number of dimmensions
459    num_data : array_like
460        Curve from your numerical data. num_data is of (P, N) shape, where P
461        is the number of data points, and N is the number of dimmensions
462    p : float, 1 <= p <= infinity
463        Which Minkowski p-norm to use. Default is p=2 (Eculidean).
464        The manhattan distance is p=1.
465
466    Returns
467    -------
468    df : float
469        discrete Frechet distance
470
471    Notes
472    -----
473    Your x locations of data points should be exp_data[:, 0], and the y
474    locations of the data points should be exp_data[:, 1]. Same for num_data.
475
476    Thanks to Arbel Amir for the issue, and Sen ZHANG for the iterative code
477    https://github.com/cjekel/similarity_measures/issues/6
478
479    Examples
480    --------
481    >>> # Generate random experimental data
482    >>> x = np.random.random(100)
483    >>> y = np.random.random(100)
484    >>> exp_data = np.zeros((100, 2))
485    >>> exp_data[:, 0] = x
486    >>> exp_data[:, 1] = y
487    >>> # Generate random numerical data
488    >>> x = np.random.random(100)
489    >>> y = np.random.random(100)
490    >>> num_data = np.zeros((100, 2))
491    >>> num_data[:, 0] = x
492    >>> num_data[:, 1] = y
493    >>> df = frechet_dist(exp_data, num_data)
494
495    .. [3] Thomas Eiter and Heikki Mannila. Computing discrete Frechet
496        distance. Technical report, 1994.
497        http://www.kr.tuwien.ac.at/staff/eiter/et-archive/cdtr9464.pdf
498        http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.90.937&rep=rep1&type=pdf
499    """
500    n = len(exp_data)
501    m = len(num_data)
502    c = distance.cdist(exp_data, num_data, metric='minkowski', p=p)
503    ca = np.ones((n, m))
504    ca = np.multiply(ca, -1)
505    ca[0, 0] = c[0, 0]
506    for i in range(1, n):
507        ca[i, 0] = max(ca[i-1, 0], c[i, 0])
508    for j in range(1, m):
509        ca[0, j] = max(ca[0, j-1], c[0, j])
510    for i in range(1, n):
511        for j in range(1, m):
512            ca[i, j] = max(min(ca[i-1, j], ca[i, j-1], ca[i-1, j-1]),
513                           c[i, j])
514    return ca[n-1, m-1]

Compute the discrete Frechet distance

Compute the Discrete Frechet Distance between two N-D curves according to 1. The Frechet distance has been defined as the walking dog problem. From Wikipedia: "In mathematics, the Frechet distance is a measure of similarity between curves that takes into account the location and ordering of the points along the curves. It is named after Maurice Frechet. https://en.wikipedia.org/wiki/Fr%C3%A9chet_distance

Parameters
  • exp_data (array_like): Curve from your experimental data. exp_data is of (M, N) shape, where M is the number of data points, and N is the number of dimmensions
  • num_data (array_like): Curve from your numerical data. num_data is of (P, N) shape, where P is the number of data points, and N is the number of dimmensions
  • p (float, 1 <= p <= infinity): Which Minkowski p-norm to use. Default is p=2 (Eculidean). The manhattan distance is p=1.
Returns
  • df (float): discrete Frechet distance
Notes

Your x locations of data points should be exp_data[:, 0], and the y locations of the data points should be exp_data[:, 1]. Same for num_data.

Thanks to Arbel Amir for the issue, and Sen ZHANG for the iterative code https://github.com/cjekel/similarity_measures/issues/6

Examples
>>> # Generate random experimental data
>>> x = np.random.random(100)
>>> y = np.random.random(100)
>>> exp_data = np.zeros((100, 2))
>>> exp_data[:, 0] = x
>>> exp_data[:, 1] = y
>>> # Generate random numerical data
>>> x = np.random.random(100)
>>> y = np.random.random(100)
>>> num_data = np.zeros((100, 2))
>>> num_data[:, 0] = x
>>> num_data[:, 1] = y
>>> df = frechet_dist(exp_data, num_data)

  1. Thomas Eiter and Heikki Mannila. Computing discrete Frechet distance. Technical report, 1994. http://www.kr.tuwien.ac.at/staff/eiter/et-archive/cdtr9464.pdf http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.90.937&rep=rep1&type=pdf ↩

def normalizeTwoCurves(x, y, w, z):
517def normalizeTwoCurves(x, y, w, z):
518    """
519    Normalize two curves for PCM method.
520
521    This normalizes the two curves for PCM method following [4]_.
522
523    Parameters
524    ----------
525    x : array_like (1-D)
526        x locations for first curve
527    y : array_like (1-D)
528        y locations for first curve
529    w : array_like (1-D)
530        x locations for second curve curve
531    z : array_like (1-D)
532        y locations for second curve
533
534    Returns
535    -------
536    xi : array_like
537        normalized x locations for first curve
538    eta : array_like
539        normalized y locations for first curve
540    xiP : array_like
541        normalized x locations for second curve
542    etaP : array_like
543        normalized y locations for second curve
544
545
546    Examples
547    --------
548    >>> xi, eta, xiP, etaP = normalizeTwoCurves(x,y,w,z)
549
550    .. [4] Katharina Witowski and Nielen Stander. "Parameter Identification of
551        Hysteretic Models Using Partial Curve Mapping", 12th AIAA Aviation
552        Technology, Integration, and Operations (ATIO) Conference and 14th
553        AIAA/ISSMO Multidisciplinary Analysis and Optimization Conference,
554        Aviation Technology, Integration, and Operations (ATIO) Conferences.
555        doi: doi:10.2514/6.2012-5580.
556    """
557    minX = np.min(x)
558    maxX = np.max(x)
559    minY = np.min(y)
560    maxY = np.max(y)
561
562    xi = (x - minX) / (maxX - minX)
563    eta = (y - minY) / (maxY - minY)
564    xiP = (w - minX) / (maxX - minX)
565    etaP = (z - minY) / (maxY - minY)
566    return xi, eta, xiP, etaP

Normalize two curves for PCM method.

This normalizes the two curves for PCM method following 1.

Parameters
  • x (array_like (1-D)): x locations for first curve
  • y (array_like (1-D)): y locations for first curve
  • w (array_like (1-D)): x locations for second curve curve
  • z (array_like (1-D)): y locations for second curve
Returns
  • xi (array_like): normalized x locations for first curve
  • eta (array_like): normalized y locations for first curve
  • xiP (array_like): normalized x locations for second curve
  • etaP (array_like): normalized y locations for second curve
Examples
>>> xi, eta, xiP, etaP = normalizeTwoCurves(x,y,w,z)

  1. Katharina Witowski and Nielen Stander. "Parameter Identification of Hysteretic Models Using Partial Curve Mapping", 12th AIAA Aviation Technology, Integration, and Operations (ATIO) Conference and 14th AIAA/ISSMO Multidisciplinary Analysis and Optimization Conference, Aviation Technology, Integration, and Operations (ATIO) Conferences. doi: doi:10.2514/6.2012-5580. ↩

def pcm(exp_data, num_data, norm_seg_length=False):
569def pcm(exp_data, num_data, norm_seg_length=False):
570    """
571    Compute the Partial Curve Mapping area.
572
573    Computes the Partial Cuve Mapping (PCM) similarity measure as proposed by
574    [5]_.
575
576    Parameters
577    ----------
578    exp_data : ndarray (2-D)
579        Curve from your experimental data.
580    num_data : ndarray (2-D)
581        Curve from your numerical data.
582    norm_seg_length : boolean
583        Whether to divide the segment length of each curve by the maximum. The
584        default value is false, which more closely follows the algorithm
585        proposed in [1]_. Versions prior to 0.6.0 used `norm_seg_length=True`.
586
587    Returns
588    -------
589    p : float
590        pcm area measure
591
592    Notes
593    -----
594    Your x locations of data points should be exp_data[:, 0], and the y
595    locations of the data points should be exp_data[:, 1]. Same for num_data.
596
597    PCM distance was changed in version 0.6.0. To get the same results from
598    previous versions, set `norm_seg_length=True`.
599
600    Examples
601    --------
602    >>> # Generate random experimental data
603    >>> x = np.random.random(100)
604    >>> y = np.random.random(100)
605    >>> exp_data = np.zeros((100, 2))
606    >>> exp_data[:, 0] = x
607    >>> exp_data[:, 1] = y
608    >>> # Generate random numerical data
609    >>> x = np.random.random(100)
610    >>> y = np.random.random(100)
611    >>> num_data = np.zeros((100, 2))
612    >>> num_data[:, 0] = x
613    >>> num_data[:, 1] = y
614    >>> p = pcm(exp_data, num_data)
615
616    .. [5] Katharina Witowski and Nielen Stander. "Parameter Identification of
617        Hysteretic Models Using Partial Curve Mapping", 12th AIAA Aviation
618        Technology, Integration, and Operations (ATIO) Conference and 14th
619        AIAA/ISSMO Multidisciplinary Analysis and Optimization Conference,
620        Aviation Technology, Integration, and Operations (ATIO) Conferences.
621        doi: doi:10.2514/6.2012-5580.
622    """
623    # normalize the curves to the experimental data
624    xi1, eta1, xi2, eta2 = normalizeTwoCurves(exp_data[:, 0], exp_data[:, 1],
625                                              num_data[:, 0], num_data[:, 1])
626    # compute the arc lengths of each curve
627    le, le_nj, le_sum = get_length(xi1, eta1, norm_seg_length)
628    lc, lc_nj, lc_sum = get_length(xi2, eta2, norm_seg_length)
629    # scale each segment to the total polygon length
630    le = le / le_nj
631    le_sum = le_sum / le_nj
632    lc = lc / lc_nj
633    lc_sum = lc_sum / lc_nj
634    # right now exp_data is curve a, and num_data is curve b
635    # make sure a is shorter than a', if not swap the defintion
636    if lc_nj > le_nj:
637        # compute the arc lengths of each curve
638        le, le_nj, le_sum = get_length(xi2, eta2, norm_seg_length)
639        lc, lc_nj, lc_sum = get_length(xi1, eta1, norm_seg_length)
640        # scale each segment to the total polygon length
641        le = le / le_nj
642        le_sum = le_sum / le_nj
643        lc = lc / lc_nj
644        lc_sum = lc_sum / lc_nj
645        # swap xi1, eta1 with xi2, eta2
646        xi1OLD = xi1.copy()
647        eta1OLD = eta1.copy()
648        xi1 = xi2.copy()
649        eta1 = eta2.copy()
650        xi2 = xi1OLD.copy()
651        eta2 = eta1OLD.copy()
652
653    n_sum = len(le_sum)
654
655    min_offset = 0.0
656    max_offset = le_nj - lc_nj
657
658    # make sure the curves aren't the same length
659    # if they are the same length, don't loop 200 times
660    if min_offset == max_offset:
661        offsets = [min_offset]
662        pcm_dists = np.zeros(1)
663    else:
664        offsets = np.linspace(min_offset, max_offset, 200)
665        pcm_dists = np.zeros(200)
666
667    for i, offset in enumerate(offsets):
668        # create linear interpolation model for num_data based on arc length
669        # evaluate linear interpolation model based on xi and eta of exp data
670        xitemp = np.interp(le_sum+offset, lc_sum, xi2)
671        etatemp = np.interp(le_sum+offset, lc_sum, eta2)
672
673        d = np.sqrt((eta1-etatemp)**2 + (xi1-xitemp)**2)
674        d1 = d[:-1]
675
676        d2 = d[1:n_sum]
677
678        v = 0.5*(d1+d2)*le_sum[1:n_sum]
679        pcm_dists[i] = np.sum(v)
680    return np.min(pcm_dists)

Compute the Partial Curve Mapping area.

Computes the Partial Cuve Mapping (PCM) similarity measure as proposed by 1.

Parameters
  • exp_data (ndarray (2-D)): Curve from your experimental data.
  • num_data (ndarray (2-D)): Curve from your numerical data.
  • norm_seg_length (boolean): Whether to divide the segment length of each curve by the maximum. The default value is false, which more closely follows the algorithm proposed in [1]_. Versions prior to 0.6.0 used norm_seg_length=True.
Returns
  • p (float): pcm area measure
Notes

Your x locations of data points should be exp_data[:, 0], and the y locations of the data points should be exp_data[:, 1]. Same for num_data.

PCM distance was changed in version 0.6.0. To get the same results from previous versions, set norm_seg_length=True.

Examples
>>> # Generate random experimental data
>>> x = np.random.random(100)
>>> y = np.random.random(100)
>>> exp_data = np.zeros((100, 2))
>>> exp_data[:, 0] = x
>>> exp_data[:, 1] = y
>>> # Generate random numerical data
>>> x = np.random.random(100)
>>> y = np.random.random(100)
>>> num_data = np.zeros((100, 2))
>>> num_data[:, 0] = x
>>> num_data[:, 1] = y
>>> p = pcm(exp_data, num_data)

  1. Katharina Witowski and Nielen Stander. "Parameter Identification of Hysteretic Models Using Partial Curve Mapping", 12th AIAA Aviation Technology, Integration, and Operations (ATIO) Conference and 14th AIAA/ISSMO Multidisciplinary Analysis and Optimization Conference, Aviation Technology, Integration, and Operations (ATIO) Conferences. doi: doi:10.2514/6.2012-5580. ↩

def dtw(exp_data, num_data, metric='euclidean', **kwargs):
683def dtw(exp_data, num_data, metric='euclidean', **kwargs):
684    r"""
685    Compute the Dynamic Time Warping distance.
686
687    This computes a generic Dynamic Time Warping (DTW) distance and follows
688    the algorithm from [6]_. This can use all distance metrics that are
689    available in scipy.spatial.distance.cdist.
690
691    Parameters
692    ----------
693    exp_data : array_like
694        Curve from your experimental data. exp_data is of (M, N) shape, where
695        M is the number of data points, and N is the number of dimmensions
696    num_data : array_like
697        Curve from your numerical data. num_data is of (P, N) shape, where P
698        is the number of data points, and N is the number of dimmensions
699    metric : str or callable, optional
700        The distance metric to use. Default='euclidean'. Refer to the
701        documentation for scipy.spatial.distance.cdist. Some examples:
702        'braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation',
703        'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'kulsinski',
704        'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao',
705        'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean',
706        'wminkowski', 'yule'.
707    **kwargs : dict, optional
708        Extra arguments to `metric`: refer to each metric documentation in
709        scipy.spatial.distance.
710        Some examples:
711
712        p : scalar
713            The p-norm to apply for Minkowski, weighted and unweighted.
714            Default: 2.
715
716        w : ndarray
717            The weight vector for metrics that support weights (e.g.,
718            Minkowski).
719
720        V : ndarray
721            The variance vector for standardized Euclidean.
722            Default: var(vstack([XA, XB]), axis=0, ddof=1)
723
724        VI : ndarray
725            The inverse of the covariance matrix for Mahalanobis.
726            Default: inv(cov(vstack([XA, XB].T))).T
727
728        out : ndarray
729            The output array
730            If not None, the distance matrix Y is stored in this array.
731
732    Returns
733    -------
734    r : float
735        DTW distance.
736    d : ndarray (2-D)
737        Cumulative distance matrix
738
739    Notes
740    -----
741    The DTW distance is d[-1, -1].
742
743    This has O(M, P) computational cost.
744
745    The latest scipy.spatial.distance.cdist information can be found at
746    https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html
747
748    Your x locations of data points should be exp_data[:, 0], and the y
749    locations of the data points should be exp_data[:, 1]. Same for num_data.
750
751    This uses the euclidean distance for now. In the future it should be
752    possible to support other metrics.
753
754    DTW is a non-metric distance, which means DTW doesn't hold the triangle
755    inequality.
756    https://en.wikipedia.org/wiki/Triangle_inequality
757
758    Examples
759    --------
760    >>> # Generate random experimental data
761    >>> x = np.random.random(100)
762    >>> y = np.random.random(100)
763    >>> exp_data = np.zeros((100, 2))
764    >>> exp_data[:, 0] = x
765    >>> exp_data[:, 1] = y
766    >>> # Generate random numerical data
767    >>> x = np.random.random(100)
768    >>> y = np.random.random(100)
769    >>> num_data = np.zeros((100, 2))
770    >>> num_data[:, 0] = x
771    >>> num_data[:, 1] = y
772    >>> r, d = dtw(exp_data, num_data)
773
774    The euclidean distance is used by default. You can use metric and **kwargs
775    to specify different types of distance metrics. The following example uses
776    the city block or Manhattan distance between points.
777
778    >>> r, d = dtw(exp_data, num_data, metric='cityblock')
779
780    .. [6] Senin, P., 2008. Dynamic time warping algorithm review. Information
781        and Computer Science Department University of Hawaii at Manoa Honolulu,
782        USA, 855, pp.1-23.
783        http://seninp.github.io/assets/pubs/senin_dtw_litreview_2008.pdf
784    """
785    c = distance.cdist(exp_data, num_data, metric=metric, **kwargs)
786
787    d = np.zeros(c.shape)
788    d[0, 0] = c[0, 0]
789    n, m = c.shape
790    for i in range(1, n):
791        d[i, 0] = d[i-1, 0] + c[i, 0]
792    for j in range(1, m):
793        d[0, j] = d[0, j-1] + c[0, j]
794    for i in range(1, n):
795        for j in range(1, m):
796            d[i, j] = c[i, j] + min((d[i-1, j], d[i, j-1], d[i-1, j-1]))
797    return d[-1, -1], d

Compute the Dynamic Time Warping distance.

This computes a generic Dynamic Time Warping (DTW) distance and follows the algorithm from 1. This can use all distance metrics that are available in scipy.spatial.distance.cdist.

Parameters
  • exp_data (array_like): Curve from your experimental data. exp_data is of (M, N) shape, where M is the number of data points, and N is the number of dimmensions
  • num_data (array_like): Curve from your numerical data. num_data is of (P, N) shape, where P is the number of data points, and N is the number of dimmensions
  • metric (str or callable, optional): The distance metric to use. Default='euclidean'. Refer to the documentation for scipy.spatial.distance.cdist. Some examples: 'braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation', 'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'wminkowski', 'yule'.
  • **kwargs (dict, optional): Extra arguments to metric: refer to each metric documentation in scipy.spatial.distance. Some examples:

    p : scalar The p-norm to apply for Minkowski, weighted and unweighted. Default: 2.

    w : ndarray The weight vector for metrics that support weights (e.g., Minkowski).

    V : ndarray The variance vector for standardized Euclidean. Default: var(vstack([XA, XB]), axis=0, ddof=1)

    VI : ndarray The inverse of the covariance matrix for Mahalanobis. Default: inv(cov(vstack([XA, XB].T))).T

    out : ndarray The output array If not None, the distance matrix Y is stored in this array.

Returns
  • r (float): DTW distance.
  • d (ndarray (2-D)): Cumulative distance matrix
Notes

The DTW distance is d[-1, -1].

This has O(M, P) computational cost.

The latest scipy.spatial.distance.cdist information can be found at https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html

Your x locations of data points should be exp_data[:, 0], and the y locations of the data points should be exp_data[:, 1]. Same for num_data.

This uses the euclidean distance for now. In the future it should be possible to support other metrics.

DTW is a non-metric distance, which means DTW doesn't hold the triangle inequality. https://en.wikipedia.org/wiki/Triangle_inequality

Examples
>>> # Generate random experimental data
>>> x = np.random.random(100)
>>> y = np.random.random(100)
>>> exp_data = np.zeros((100, 2))
>>> exp_data[:, 0] = x
>>> exp_data[:, 1] = y
>>> # Generate random numerical data
>>> x = np.random.random(100)
>>> y = np.random.random(100)
>>> num_data = np.zeros((100, 2))
>>> num_data[:, 0] = x
>>> num_data[:, 1] = y
>>> r, d = dtw(exp_data, num_data)

The euclidean distance is used by default. You can use metric and **kwargs to specify different types of distance metrics. The following example uses the city block or Manhattan distance between points.

>>> r, d = dtw(exp_data, num_data, metric='cityblock')

  1. Senin, P., 2008. Dynamic time warping algorithm review. Information and Computer Science Department University of Hawaii at Manoa Honolulu, USA, 855, pp.1-23. http://seninp.github.io/assets/pubs/senin_dtw_litreview_2008.pdf ↩

def dtw_path(d):
800def dtw_path(d):
801    r"""
802    Calculates the optimal DTW path from a given DTW cumulative distance
803    matrix.
804
805    This function returns the optimal DTW path using the back propagation
806    algorithm that is defined in [7]_. This path details the index from each
807    curve that is being compared.
808
809    Parameters
810    ----------
811    d : ndarray (2-D)
812        Cumulative distance matrix.
813
814    Returns
815    -------
816    path : ndarray (2-D)
817        The optimal DTW path.
818
819    Notes
820    -----
821    Note that path[:, 0] represents the indices from exp_data, while
822    path[:, 1] represents the indices from the num_data.
823
824    .. [7] Senin, P., 2008. Dynamic time warping algorithm review. Information
825        and Computer Science Department University of Hawaii at Manoa Honolulu,
826        USA, 855, pp.1-23.
827        http://seninp.github.io/assets/pubs/senin_dtw_litreview_2008.pdf
828
829    Examples
830    --------
831    First calculate the DTW cumulative distance matrix.
832
833    >>> # Generate random experimental data
834    >>> x = np.random.random(100)
835    >>> y = np.random.random(100)
836    >>> exp_data = np.zeros((100, 2))
837    >>> exp_data[:, 0] = x
838    >>> exp_data[:, 1] = y
839    >>> # Generate random numerical data
840    >>> x = np.random.random(100)
841    >>> y = np.random.random(100)
842    >>> num_data = np.zeros((100, 2))
843    >>> num_data[:, 0] = x
844    >>> num_data[:, 1] = y
845    >>> r, d = dtw(exp_data, num_data)
846
847    Now you can calculate the optimal DTW path
848
849    >>> path = dtw_path(d)
850
851    You can visualize the path on the cumulative distance matrix using the
852    following code.
853
854    >>> import matplotlib.pyplot as plt
855    >>> plt.figure()
856    >>> plt.imshow(d.T, origin='lower')
857    >>> plt.plot(path[:, 0], path[:, 1], '-k')
858    >>> plt.colorbar()
859    >>> plt.show()
860
861    """
862    path = []
863    i, j = d.shape
864    i = i - 1
865    j = j - 1
866    # back propagation starts from the last point,
867    # and ends at d[0, 0]
868    path.append((i, j))
869    while i > 0 or j > 0:
870        if i == 0:
871            j = j - 1
872        elif j == 0:
873            i = i - 1
874        else:
875            temp_step = min([d[i-1, j], d[i, j-1], d[i-1, j-1]])
876            if d[i-1, j] == temp_step:
877                i = i - 1
878            elif d[i, j-1] == temp_step:
879                j = j - 1
880            else:
881                i = i - 1
882                j = j - 1
883        path.append((i, j))
884    path = np.array(path)
885    # reverse the order of path, such that it starts with [0, 0]
886    return path[::-1]

Calculates the optimal DTW path from a given DTW cumulative distance matrix.

This function returns the optimal DTW path using the back propagation algorithm that is defined in 1. This path details the index from each curve that is being compared.

Parameters
  • d (ndarray (2-D)): Cumulative distance matrix.
Returns
  • path (ndarray (2-D)): The optimal DTW path.
Notes

Note that path[:, 0] represents the indices from exp_data, while path[:, 1] represents the indices from the num_data.

Examples

First calculate the DTW cumulative distance matrix.

>>> # Generate random experimental data
>>> x = np.random.random(100)
>>> y = np.random.random(100)
>>> exp_data = np.zeros((100, 2))
>>> exp_data[:, 0] = x
>>> exp_data[:, 1] = y
>>> # Generate random numerical data
>>> x = np.random.random(100)
>>> y = np.random.random(100)
>>> num_data = np.zeros((100, 2))
>>> num_data[:, 0] = x
>>> num_data[:, 1] = y
>>> r, d = dtw(exp_data, num_data)

Now you can calculate the optimal DTW path

>>> path = dtw_path(d)

You can visualize the path on the cumulative distance matrix using the following code.

>>> import matplotlib.pyplot as plt
>>> plt.figure()
>>> plt.imshow(d.T, origin='lower')
>>> plt.plot(path[:, 0], path[:, 1], '-k')
>>> plt.colorbar()
>>> plt.show()

  1. Senin, P., 2008. Dynamic time warping algorithm review. Information and Computer Science Department University of Hawaii at Manoa Honolulu, USA, 855, pp.1-23. http://seninp.github.io/assets/pubs/senin_dtw_litreview_2008.pdf ↩

def mae(exp_data, num_data):
889def mae(exp_data, num_data):
890    """
891    Compute the Mean Absolute Error (MAE).
892
893    This computes the mean of absolute values of distances between two curves.
894    Each curve must have the same number of data points and the same dimension.
895
896    Parameters
897    ----------
898    exp_data : array_like
899        Curve from your experimental data. exp_data is of (M, N) shape, where
900        M is the number of data points, and N is the number of dimensions
901    num_data : array_like
902        Curve from your numerical data. num_data is of (M, N) shape, where M
903        is the number of data points, and N is the number of dimensions
904
905    Returns
906    -------
907    r : float
908        MAE.
909    """
910    c = np.abs(exp_data - num_data)
911    return np.mean(c)

Compute the Mean Absolute Error (MAE).

This computes the mean of absolute values of distances between two curves. Each curve must have the same number of data points and the same dimension.

Parameters
  • exp_data (array_like): Curve from your experimental data. exp_data is of (M, N) shape, where M is the number of data points, and N is the number of dimensions
  • num_data (array_like): Curve from your numerical data. num_data is of (M, N) shape, where M is the number of data points, and N is the number of dimensions
Returns
  • r (float): MAE.
def mse(exp_data, num_data):
914def mse(exp_data, num_data):
915    """
916    Compute the Mean Squared Error (MAE).
917
918    This computes the mean of sqaured distances between two curves.
919    Each curve must have the same number of data points and the same dimension.
920
921    Parameters
922    ----------
923    exp_data : array_like
924        Curve from your experimental data. exp_data is of (M, N) shape, where
925        M is the number of data points, and N is the number of dimensions
926    num_data : array_like
927        Curve from your numerical data. num_data is of (M, N) shape, where M
928        is the number of data points, and N is the number of dimensions
929
930    Returns
931    -------
932    r : float
933        MSE.
934    """
935    c = np.square(exp_data - num_data)
936    return np.mean(c)

Compute the Mean Squared Error (MAE).

This computes the mean of sqaured distances between two curves. Each curve must have the same number of data points and the same dimension.

Parameters
  • exp_data (array_like): Curve from your experimental data. exp_data is of (M, N) shape, where M is the number of data points, and N is the number of dimensions
  • num_data (array_like): Curve from your numerical data. num_data is of (M, N) shape, where M is the number of data points, and N is the number of dimensions
Returns
  • r (float): MSE.