o
    siZ                     @   s   d Z ddlZddlmZ ddlZddlZdd Zdd Zd	d
 Z	dddZ
d ddZ	dddZ		d!ddZdd Zd"ddZd"ddZdd ZdS )#a  
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.
    N   )utilc                 C   s   t dd | D S )a$  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.

    c                 S   s$   g | ]}|D ]	}|D ]}|q
qqS  r   ).0patocco_mr   r   D/home/ubuntu/.local/lib/python3.10/site-packages/mir_eval/pattern.py
<listcomp>N   s   $ z!_n_onset_midi.<locals>.<listcomp>)len)patternsr   r   r	   _n_onset_midi?   s   r   c                 C   s   t | dkrtd t |dkrtd | |fD ]%}|D ] }t|dkr*td|D ]}|D ]}t|dkr<tdq0q,qqdS )ak  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
    r   zReference patterns are empty.zEstimated patterns are empty.z2Each pattern must contain at least one occurrence.   z8The (onset, midi) tuple must contain exactly 2 elements.N)r   warningswarnr   
ValueError)reference_patternsestimated_patternsr   pattern
occurrence
onset_midir   r   r	   validateQ   s*   

r   c                 C   s$   dd | D }dd |D }||@ S )aO  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.

    c                 S      h | ]}t |qS r   tupler   r   r   r   r	   	<setcomp>       z+_occurrence_intersection.<locals>.<setcomp>c                 S   r   r   r   r   r   r   r	   r      r   r   )occ_Pocc_Qset_Pset_Qr   r   r	   _occurrence_intersectionq   s   r"   cardinality_scorec           	      C   s   t t| t|f}t| D ]/\}}t|D ]&\}}|dkr:tt t|t|g}tt||| |||f< qtdq|S )aa  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.

    r#   z<The similarity metric (%s) can only be: 'cardinality_score'.)npzerosr   	enumeratefloatmaxr"   r   )	PQsimilarity_metricsmiPr   iQr   denomr   r   r	   _compute_score_matrix   s   
r0   h㈵>c              
   C   s   t | | t| }t|}d}t| dkst|dkrdS | D ]D}t|d }|D ]8}t|d }	t|t|	kr<q*t|t|	  krJdks\n tttj||	 dd|k rb|d7 } nq*q|t| }
|t| }t	
|
|}||
|fS )a  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

    r           r3   r3   r   axis)r   r   r   r$   asarrayr(   absdiffr'   r   	f_measure)r   r   tolnPnQkref_patternr)   est_patternr*   	precisionrecallr9   r   r   r	   standard_FPR   s*   
%@
rB   c                 C   s   t | | t| }t|}t||f}t| dks t|dkr"dS t| D ]\}}t|D ]\}}	t||	|}
t|
|||f< q.q&ttj|dd}ttj|dd}t	
||}|||fS )a;  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

    r   r2   r4   r   )r   r   r$   r%   r   r&   r0   r(   meanr   r9   )r   r   r+   r;   r<   Sr-   r>   r.   r?   sr@   rA   r9   r   r   r	   establishment_FPR   s   
(
rF         ?c              
   C   s  t | | t| }t|}t||df}tjdtd}t| dks(t|dkr*dS t| D ]A\}}	t|D ]8\}
}t|	||}t	||krnt
tj	|dd|||
df< t
tj	|dd|||
df< t|||
gf}q6q.t|dkr{d}d}nN|dddddf }t
tj	|t|dddf |dddf  dd}|dddddf }t
tj	|t|dddf |dddf  dd}t||}|||fS )	a  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
    r   )r   r   )dtyper   r2   r4   r   N)r   r   r$   r%   emptyintr   r&   r0   r(   rC   vstackix_r   r9   )r   r   thresr+   r;   r<   O_PRrel_idxr-   r>   r.   r?   rE   r@   rA   r)   Rr9   r   r   r	   occurrence_FPR+  s2   
/88
rQ   c                    s   t | | dd  fddd fdd	t| dks#t|dkr%d	S | |d
d}ttj|dd}ttj|dd}t||}|||fS )a  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

    c                 S   s6   t t| |}|tt |  }|tt | }||fS )a3  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
        )r   r"   r'   )ref_occsest_occsrE   r@   rA   r   r   r	   compute_first_layer_PR  s   z/three_layer_FPR.<locals>.compute_first_layer_PRc                    s:    | |}t t j|dd}t t j|dd}||fS )a:  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
        r   r4   r   )r$   rC   r(   )r>   r?   F_1r@   rA   )compute_layerr   r	   compute_second_layer_PR  s   
z0three_layer_FPR.<locals>.compute_second_layer_PRr   c                    s   |dkr|dkrt d| t| }t|}t||f}t|D ]+}t|D ]$}|dkr0 }n|dkr6}|| | || \}	}
t|	|
|||f< q'q!|S )a  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
        r   r   z-Layer (%d) must be an integer between 1 and 2)r   r   r$   r%   ranger   r9   )ref_elementsest_elementslayerr;   r<   Fr-   r.   funcr@   rA   )rT   rW   r   r	   rV     s   	z&three_layer_FPR.<locals>.compute_layerr   r2   r   )r[   r4   N)r   )r   r   r$   rC   r(   r   r9   )r   r   F_2precision_3recall_3f_measure_3r   )rT   rV   rW   r	   three_layer_FPR~  s   
&
rb      c                 C   sP   t | | t| dkst|dkrdS |dtt|| }t| |\}}}|S )a  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
    r   r2   N)r   r   minr   rb   r   r   nfn_est_patternsr\   r)   rP   r   r   r	   first_n_three_layer_P  s   
rh   c                 C   sP   t | | t| dkst|dkrdS |dtt|| }t| |\}}}|S )a  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.
    r   r2   N)r   r   rd   r   rF   re   r   r   r	   first_n_target_proportion_R*  s   
ri   c                 K   s(  t  }tjt| |fi |\|d< |d< |d< tjt| |fi |\|d< |d< |d< d|d< tjt| |fi |\|d	< |d
< |d< d|d< tjt| |fi |\|d< |d< |d< tjt| |fi |\|d< |d< |d< d|vrxd|d< tjt| |fi ||d< tjt	| |fi ||d< |S )a$  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.
    r\   r)   rP   F_estP_estR_estg      ?threshzF_occ.5zP_occ.5zR_occ.5rG   zF_occ.75zP_occ.75zR_occ.75F_3P_3R_3rf   rc   FFPFFTP_est)
collectionsOrderedDictr   filter_kwargsrB   rF   rQ   rb   rh   ri   )ref_patternsest_patternskwargsscoresr   r   r	   evaluateU  sR   

rz   )r#   )r1   )rG   r#   )rc   )__doc__numpyr$    r   r   rs   r   r   r"   r0   rB   rF   rQ   rb   rh   ri   rz   r   r   r   r	   <module>   s&    8 

%D
@
S

-+