File: pattern.py

package info (click to toggle)
mir-eval 0.8.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 8,784 kB
  • sloc: python: 8,364; javascript: 261; makefile: 154
file content (663 lines) | stat: -rw-r--r-- 23,189 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
"""
Pattern discovery involves the identification of musical patterns (i.e. short
fragments or melodic ideas that repeat at least twice) both from audio and
symbolic representations.  The metrics used to evaluate pattern discovery
systems attempt to quantify the ability of the algorithm to not only determine
the present patterns in a piece, but also to find all of their occurrences.

Based on the methods described here:
    T. Collins. MIREX task: Discovery of repeated themes & sections.
    http://www.music-ir.org/mirex/wiki/2013:Discovery_of_Repeated_Themes_&_Sections,
    2013.

Conventions
-----------

The input format can be automatically generated by calling
:func:`mir_eval.io.load_patterns`.  This format is a list of a list of
tuples.  The first list collections patterns, each of which is a list of
occurrences, and each occurrence is a list of MIDI onset tuples of
``(onset_time, mid_note)``

A pattern is a list of occurrences. The first occurrence must be the prototype
of that pattern (i.e. the most representative of all the occurrences).  An
occurrence is a list of tuples containing the onset time and the midi note
number.

Metrics
-------

* :func:`mir_eval.pattern.standard_FPR`: Strict metric in order to find the
  possibly transposed patterns of exact length. This is the only metric that
  considers transposed patterns.
* :func:`mir_eval.pattern.establishment_FPR`: Evaluates the amount of patterns
  that were successfully identified by the estimated results, no matter how
  many occurrences they found.  In other words, this metric captures how the
  algorithm successfully *established* that a pattern repeated at least twice,
  and this pattern is also found in the reference annotation.
* :func:`mir_eval.pattern.occurrence_FPR`: Evaluation of how well an estimation
  can effectively identify all the occurrences of the found patterns,
  independently of how many patterns have been discovered. This metric has a
  threshold parameter that indicates how similar two occurrences must be in
  order to be considered equal.  In MIREX, this evaluation is run twice, with
  thresholds .75 and .5.
* :func:`mir_eval.pattern.three_layer_FPR`: Aims to evaluate the general
  similarity between the reference and the estimations, combining both the
  establishment of patterns and the retrieval of its occurrences in a single F1
  score.
* :func:`mir_eval.pattern.first_n_three_layer_P`: Computes the three-layer
  precision for the first N patterns only in order to measure the ability of
  the algorithm to sort the identified patterns based on their relevance.
* :func:`mir_eval.pattern.first_n_target_proportion_R`: Computes the target
  proportion recall for the first N patterns only in order to measure the
  ability of the algorithm to sort the identified patterns based on their
  relevance.
"""

import numpy as np
from . import util
import warnings
import collections


def _n_onset_midi(patterns):
    """Compute the number of onset_midi objects in a pattern

    Parameters
    ----------
    patterns
        A list of patterns using the format returned by
        :func:`mir_eval.io.load_patterns()`

    Returns
    -------
    n_onsets : int
        Number of onsets within the pattern.

    """
    return len([o_m for pat in patterns for occ in pat for o_m in occ])


def validate(reference_patterns, estimated_patterns):
    """Check that the input annotations to a metric look like valid pattern
    lists, and throws helpful errors if not.

    Parameters
    ----------
    reference_patterns : list
        The reference patterns using the format returned by
        :func:`mir_eval.io.load_patterns()`
    estimated_patterns : list
        The estimated patterns in the same format
    """
    # Warn if pattern lists are empty
    if _n_onset_midi(reference_patterns) == 0:
        warnings.warn("Reference patterns are empty.")
    if _n_onset_midi(estimated_patterns) == 0:
        warnings.warn("Estimated patterns are empty.")
    for patterns in [reference_patterns, estimated_patterns]:
        for pattern in patterns:
            if len(pattern) <= 0:
                raise ValueError(
                    "Each pattern must contain at least one " "occurrence."
                )
            for occurrence in pattern:
                for onset_midi in occurrence:
                    if len(onset_midi) != 2:
                        raise ValueError(
                            "The (onset, midi) tuple must "
                            "contain exactly 2 elements."
                        )


def _occurrence_intersection(occ_P, occ_Q):
    """Compute the intersection between two occurrences.

    Parameters
    ----------
    occ_P : list of tuples
        (onset, midi) pairs representing the reference occurrence.
    occ_Q : list
        second list of (onset, midi) tuples

    Returns
    -------
    S : set
        Set of the intersection between occ_P and occ_Q.

    """
    set_P = {tuple(onset_midi) for onset_midi in occ_P}
    set_Q = {tuple(onset_midi) for onset_midi in occ_Q}
    return set_P & set_Q  # Return the intersection


def _compute_score_matrix(P, Q, similarity_metric="cardinality_score"):
    """Compute the score matrix between the patterns P and Q.

    Parameters
    ----------
    P : list
        Pattern containing a list of occurrences.
    Q : list
        Pattern containing a list of occurrences.
    similarity_metric : str
        A string representing the metric to be used
        when computing the similarity matrix. Accepted values:
        - "cardinality_score":
            Count of the intersection between occurrences.
        (Default value = "cardinality_score")

    Returns
    -------
    sm : np.array
        The score matrix between P and Q using the similarity_metric.

    """
    sm = np.zeros((len(P), len(Q)))  # The score matrix
    for iP, occ_P in enumerate(P):
        for iQ, occ_Q in enumerate(Q):
            if similarity_metric == "cardinality_score":
                denom = float(np.max([len(occ_P), len(occ_Q)]))
                # Compute the score
                sm[iP, iQ] = len(_occurrence_intersection(occ_P, occ_Q)) / denom
            # TODO: More scores: 'normalised matching socre'
            else:
                raise ValueError(
                    "The similarity metric (%s) can only be: " "'cardinality_score'."
                )
    return sm


def standard_FPR(reference_patterns, estimated_patterns, tol=1e-5):
    """Compute the standard F1 Score, Precision and Recall.

    This metric checks if the prototype patterns of the reference match
    possible translated patterns in the prototype patterns of the estimations.
    Since the sizes of these prototypes must be equal, this metric is quite
    restrictive and it tends to be 0 in most of 2013 MIREX results.

    Examples
    --------
    >>> ref_patterns = mir_eval.io.load_patterns("ref_pattern.txt")
    >>> est_patterns = mir_eval.io.load_patterns("est_pattern.txt")
    >>> F, P, R = mir_eval.pattern.standard_FPR(ref_patterns, est_patterns)

    Parameters
    ----------
    reference_patterns : list
        The reference patterns using the format returned by
        :func:`mir_eval.io.load_patterns()`
    estimated_patterns : list
        The estimated patterns in the same format
    tol : float
        Tolerance level when comparing reference against estimation.
        Default parameter is the one found in the original matlab code by
        Tom Collins used for MIREX 2013.
        (Default value = 1e-5)

    Returns
    -------
    f_measure : float
        The standard F1 Score
    precision : float
        The standard Precision
    recall : float
        The standard Recall

    """
    validate(reference_patterns, estimated_patterns)
    nP = len(reference_patterns)  # Number of patterns in the reference
    nQ = len(estimated_patterns)  # Number of patterns in the estimation
    k = 0  # Number of patterns that match

    # If no patterns were provided, metric is zero
    if _n_onset_midi(reference_patterns) == 0 or _n_onset_midi(estimated_patterns) == 0:
        return 0.0, 0.0, 0.0

    # Find matches of the prototype patterns
    for ref_pattern in reference_patterns:
        P = np.asarray(ref_pattern[0])  # Get reference prototype
        for est_pattern in estimated_patterns:
            Q = np.asarray(est_pattern[0])  # Get estimation prototype

            if len(P) != len(Q):
                continue

            # Check transposition given a certain tolerance
            if len(P) == len(Q) == 1 or np.max(np.abs(np.diff(P - Q, axis=0))) < tol:
                k += 1
                break

    # Compute the standard measures
    precision = k / float(nQ)
    recall = k / float(nP)
    f_measure = util.f_measure(precision, recall)
    return f_measure, precision, recall


def establishment_FPR(
    reference_patterns, estimated_patterns, similarity_metric="cardinality_score"
):
    """Compute the establishment F1 Score, Precision and Recall.

    Examples
    --------
    >>> ref_patterns = mir_eval.io.load_patterns("ref_pattern.txt")
    >>> est_patterns = mir_eval.io.load_patterns("est_pattern.txt")
    >>> F, P, R = mir_eval.pattern.establishment_FPR(ref_patterns,
    ...                                              est_patterns)

    Parameters
    ----------
    reference_patterns : list
        The reference patterns in the format returned by
        :func:`mir_eval.io.load_patterns()`

    estimated_patterns : list
        The estimated patterns in the same format

    similarity_metric : str
        A string representing the metric to be used when computing the
        similarity matrix. Accepted values:

            - "cardinality_score": Count of the intersection
              between occurrences.

        (Default value = "cardinality_score")

    Returns
    -------
    f_measure : float
        The establishment F1 Score
    precision : float
        The establishment Precision
    recall : float
        The establishment Recall

    """
    validate(reference_patterns, estimated_patterns)
    nP = len(reference_patterns)  # Number of elements in reference
    nQ = len(estimated_patterns)  # Number of elements in estimation
    S = np.zeros((nP, nQ))  # Establishment matrix

    # If no patterns were provided, metric is zero
    if _n_onset_midi(reference_patterns) == 0 or _n_onset_midi(estimated_patterns) == 0:
        return 0.0, 0.0, 0.0

    for iP, ref_pattern in enumerate(reference_patterns):
        for iQ, est_pattern in enumerate(estimated_patterns):
            s = _compute_score_matrix(ref_pattern, est_pattern, similarity_metric)
            S[iP, iQ] = np.max(s)

    # Compute scores
    precision = np.mean(np.max(S, axis=0))
    recall = np.mean(np.max(S, axis=1))
    f_measure = util.f_measure(precision, recall)
    return f_measure, precision, recall


def occurrence_FPR(
    reference_patterns,
    estimated_patterns,
    thres=0.75,
    similarity_metric="cardinality_score",
):
    """Compute the occurrence F1 Score, Precision and Recall.

    Examples
    --------
    >>> ref_patterns = mir_eval.io.load_patterns("ref_pattern.txt")
    >>> est_patterns = mir_eval.io.load_patterns("est_pattern.txt")
    >>> F, P, R = mir_eval.pattern.occurrence_FPR(ref_patterns,
    ...                                           est_patterns)

    Parameters
    ----------
    reference_patterns : list
        The reference patterns in the format returned by
        :func:`mir_eval.io.load_patterns()`

    estimated_patterns : list
        The estimated patterns in the same format

    thres : float
        How similar two occurrences must be in order to be considered
        equal
        (Default value = .75)

    similarity_metric : str
        A string representing the metric to be used
        when computing the similarity matrix. Accepted values:

            - "cardinality_score": Count of the intersection
              between occurrences.

        (Default value = "cardinality_score")

    Returns
    -------
    f_measure : float
        The occurrence F1 Score
    precision : float
        The occurrence Precision
    recall : float
        The occurrence Recall
    """
    validate(reference_patterns, estimated_patterns)
    # Number of elements in reference
    nP = len(reference_patterns)
    # Number of elements in estimation
    nQ = len(estimated_patterns)
    # Occurrence matrix with Precision and recall in its last dimension
    O_PR = np.zeros((nP, nQ, 2))

    # Index of the values that are greater than the specified threshold
    rel_idx = np.empty((0, 2), dtype=int)

    # If no patterns were provided, metric is zero
    if _n_onset_midi(reference_patterns) == 0 or _n_onset_midi(estimated_patterns) == 0:
        return 0.0, 0.0, 0.0

    for iP, ref_pattern in enumerate(reference_patterns):
        for iQ, est_pattern in enumerate(estimated_patterns):
            s = _compute_score_matrix(ref_pattern, est_pattern, similarity_metric)
            if np.max(s) >= thres:
                O_PR[iP, iQ, 0] = np.mean(np.max(s, axis=0))
                O_PR[iP, iQ, 1] = np.mean(np.max(s, axis=1))
                rel_idx = np.vstack((rel_idx, [iP, iQ]))

    # Compute the scores
    if len(rel_idx) == 0:
        precision = 0
        recall = 0
    else:
        P = O_PR[:, :, 0]
        precision = np.mean(np.max(P[np.ix_(rel_idx[:, 0], rel_idx[:, 1])], axis=0))
        R = O_PR[:, :, 1]
        recall = np.mean(np.max(R[np.ix_(rel_idx[:, 0], rel_idx[:, 1])], axis=1))
    f_measure = util.f_measure(precision, recall)
    return f_measure, precision, recall


def three_layer_FPR(reference_patterns, estimated_patterns):
    """Three Layer F1 Score, Precision and Recall. As described by Meridith.

    Examples
    --------
    >>> ref_patterns = mir_eval.io.load_patterns("ref_pattern.txt")
    >>> est_patterns = mir_eval.io.load_patterns("est_pattern.txt")
    >>> F, P, R = mir_eval.pattern.three_layer_FPR(ref_patterns,
    ...                                            est_patterns)

    Parameters
    ----------
    reference_patterns : list
        The reference patterns in the format returned by
        :func:`mir_eval.io.load_patterns()`
    estimated_patterns : list
        The estimated patterns in the same format

    Returns
    -------
    f_measure : float
        The three-layer F1 Score
    precision : float
        The three-layer Precision
    recall : float
        The three-layer Recall

    """
    validate(reference_patterns, estimated_patterns)

    def compute_first_layer_PR(ref_occs, est_occs):
        """Compute the first layer Precision and Recall values given the
        set of occurrences in the reference and the set of occurrences in the
        estimation.

        Parameters
        ----------
        ref_occs
        est_occs

        Returns
        -------
        precision
        recall
        """
        # Find the length of the intersection between reference and estimation
        s = len(_occurrence_intersection(ref_occs, est_occs))

        # Compute the first layer scores
        precision = s / float(len(ref_occs))
        recall = s / float(len(est_occs))
        return precision, recall

    def compute_second_layer_PR(ref_pattern, est_pattern):
        """Compute the second layer Precision and Recall values given the
        set of occurrences in the reference and the set of occurrences in the
        estimation.

        Parameters
        ----------
        ref_pattern
        est_pattern

        Returns
        -------
        precision
        recall
        """
        # Compute the first layer scores
        F_1 = compute_layer(ref_pattern, est_pattern)

        # Compute the second layer scores
        precision = np.mean(np.max(F_1, axis=0))
        recall = np.mean(np.max(F_1, axis=1))
        return precision, recall

    def compute_layer(ref_elements, est_elements, layer=1):
        """Compute the F-measure matrix for a given layer. The reference and
        estimated elements can be either patterns or occurrences, depending
        on the layer.

        For layer 1, the elements must be occurrences.
        For layer 2, the elements must be patterns.

        Parameters
        ----------
        ref_elements
        est_elements
        layer
            (Default value = 1)

        Returns
        -------
        F : F-measure for the given layer
        """
        if layer != 1 and layer != 2:
            raise ValueError("Layer (%d) must be an integer between 1 and 2" % layer)

        nP = len(ref_elements)  # Number of elements in reference
        nQ = len(est_elements)  # Number of elements in estimation
        F = np.zeros((nP, nQ))  # F-measure matrix for the given layer
        for iP in range(nP):
            for iQ in range(nQ):
                if layer == 1:
                    func = compute_first_layer_PR
                elif layer == 2:
                    func = compute_second_layer_PR

                # Compute layer scores
                precision, recall = func(ref_elements[iP], est_elements[iQ])
                F[iP, iQ] = util.f_measure(precision, recall)
        return F

    # If no patterns were provided, metric is zero
    if _n_onset_midi(reference_patterns) == 0 or _n_onset_midi(estimated_patterns) == 0:
        return 0.0, 0.0, 0.0

    # Compute the second layer (it includes the first layer)
    F_2 = compute_layer(reference_patterns, estimated_patterns, layer=2)

    # Compute the final scores (third layer)
    precision_3 = np.mean(np.max(F_2, axis=0))
    recall_3 = np.mean(np.max(F_2, axis=1))
    f_measure_3 = util.f_measure(precision_3, recall_3)
    return f_measure_3, precision_3, recall_3


def first_n_three_layer_P(reference_patterns, estimated_patterns, n=5):
    """First n three-layer precision.

    This metric is basically the same as the three-layer FPR but it is only
    applied to the first n estimated patterns, and it only returns the
    precision. In MIREX and typically, n = 5.

    Examples
    --------
    >>> ref_patterns = mir_eval.io.load_patterns("ref_pattern.txt")
    >>> est_patterns = mir_eval.io.load_patterns("est_pattern.txt")
    >>> P = mir_eval.pattern.first_n_three_layer_P(ref_patterns,
    ...                                            est_patterns, n=5)

    Parameters
    ----------
    reference_patterns : list
        The reference patterns in the format returned by
        :func:`mir_eval.io.load_patterns()`
    estimated_patterns : list
        The estimated patterns in the same format
    n : int
        Number of patterns to consider from the estimated results, in
        the order they appear in the matrix
        (Default value = 5)

    Returns
    -------
    precision : float
        The first n three-layer Precision
    """
    validate(reference_patterns, estimated_patterns)
    # If no patterns were provided, metric is zero
    if _n_onset_midi(reference_patterns) == 0 or _n_onset_midi(estimated_patterns) == 0:
        return 0.0, 0.0, 0.0

    # Get only the first n patterns from the estimated results
    fn_est_patterns = estimated_patterns[: min(len(estimated_patterns), n)]

    # Compute the three-layer scores for the first n estimated patterns
    F, P, R = three_layer_FPR(reference_patterns, fn_est_patterns)

    return P  # Return the precision only


def first_n_target_proportion_R(reference_patterns, estimated_patterns, n=5):
    """First n target proportion establishment recall metric.

    This metric is similar is similar to the establishment FPR score, but it
    only takes into account the first n estimated patterns and it only
    outputs the Recall value of it.

    Examples
    --------
    >>> ref_patterns = mir_eval.io.load_patterns("ref_pattern.txt")
    >>> est_patterns = mir_eval.io.load_patterns("est_pattern.txt")
    >>> R = mir_eval.pattern.first_n_target_proportion_R(
    ...                                 ref_patterns, est_patterns, n=5)

    Parameters
    ----------
    reference_patterns : list
        The reference patterns in the format returned by
        :func:`mir_eval.io.load_patterns()`
    estimated_patterns : list
        The estimated patterns in the same format
    n : int
        Number of patterns to consider from the estimated results, in
        the order they appear in the matrix.
        (Default value = 5)

    Returns
    -------
    recall : float
        The first n target proportion Recall.
    """
    validate(reference_patterns, estimated_patterns)
    # If no patterns were provided, metric is zero
    if _n_onset_midi(reference_patterns) == 0 or _n_onset_midi(estimated_patterns) == 0:
        return 0.0, 0.0, 0.0

    # Get only the first n patterns from the estimated results
    fn_est_patterns = estimated_patterns[: min(len(estimated_patterns), n)]

    F, P, R = establishment_FPR(reference_patterns, fn_est_patterns)
    return R


def evaluate(ref_patterns, est_patterns, **kwargs):
    """Load data and perform the evaluation.

    Examples
    --------
    >>> ref_patterns = mir_eval.io.load_patterns("ref_pattern.txt")
    >>> est_patterns = mir_eval.io.load_patterns("est_pattern.txt")
    >>> scores = mir_eval.pattern.evaluate(ref_patterns, est_patterns)

    Parameters
    ----------
    ref_patterns : list
        The reference patterns in the format returned by
        :func:`mir_eval.io.load_patterns()`
    est_patterns : list
        The estimated patterns in the same format
    **kwargs
        Additional keyword arguments which will be passed to the
        appropriate metric or preprocessing functions.

    Returns
    -------
    scores : dict
        Dictionary of scores, where the key is the metric name (str) and
        the value is the (float) score achieved.
    """
    # Compute all the metrics
    scores = collections.OrderedDict()

    # Standard scores
    scores["F"], scores["P"], scores["R"] = util.filter_kwargs(
        standard_FPR, ref_patterns, est_patterns, **kwargs
    )

    # Establishment scores
    scores["F_est"], scores["P_est"], scores["R_est"] = util.filter_kwargs(
        establishment_FPR, ref_patterns, est_patterns, **kwargs
    )

    # Occurrence scores
    # Force these values for thresh
    kwargs["thresh"] = 0.5
    scores["F_occ.5"], scores["P_occ.5"], scores["R_occ.5"] = util.filter_kwargs(
        occurrence_FPR, ref_patterns, est_patterns, **kwargs
    )
    kwargs["thresh"] = 0.75
    scores["F_occ.75"], scores["P_occ.75"], scores["R_occ.75"] = util.filter_kwargs(
        occurrence_FPR, ref_patterns, est_patterns, **kwargs
    )

    # Three-layer scores
    scores["F_3"], scores["P_3"], scores["R_3"] = util.filter_kwargs(
        three_layer_FPR, ref_patterns, est_patterns, **kwargs
    )

    # First Five Patterns scores
    # Set default value of n
    if "n" not in kwargs:
        kwargs["n"] = 5
    scores["FFP"] = util.filter_kwargs(
        first_n_three_layer_P, ref_patterns, est_patterns, **kwargs
    )
    scores["FFTP_est"] = util.filter_kwargs(
        first_n_target_proportion_R, ref_patterns, est_patterns, **kwargs
    )

    return scores