o
    iȲ                     @   s(  d dl mZ d dlmZmZmZmZmZmZm	Z	m
Z
mZ d dlZddlmZ ddlmZ ddlmZmZmZ ddlmZ dd	lmZmZ erLdd
lmZ dZeg dZG dd dZ G dd dZ!G dd dZ"dee dee#ef fddZ$d'ddZ%dd Z&dd Z'dd  Z(d(d#d$Z)d%d& Z*dS ))    )defaultdict)	TYPE_CHECKINGAnyCallableDictIterableListOptionalSetTupleN   )Errors)
Morphology)DocSpanToken)Example)SimpleFrozenListget_lang_class)Language)sentertaggermorphologizerparsernertextcat)Nr    c                	   @   s   e Zd ZdZdddddedededdfd	d
ZdefddZdd Zdd Zde	de	ddfddZ
edefddZedefddZedefddZdeeef fddZdS )PRFScorezA precision / recall / F score.r   tpfpfnr   r    r!   returnNc                C   s   || _ || _|| _d S Nr   )selfr   r    r!    r%   @/home/ubuntu/.local/lib/python3.10/site-packages/spacy/scorer.py__init__"   s   
zPRFScore.__init__c                 C   s   | j | j | j S r#   r   r$   r%   r%   r&   __len__-      zPRFScore.__len__c                 C   s4   |  j |j 7  _ |  j|j7  _|  j|j7  _| S r#   r   r$   otherr%   r%   r&   __iadd__0   s   zPRFScore.__iadd__c                 C   s&   t | j|j | j|j | j|j dS )Nr   )r   r   r    r!   r+   r%   r%   r&   __add__6   s   zPRFScore.__add__candgoldc                 C   sH   |  j t||7  _ |  jt|| 7  _|  jt|| 7  _d S r#   )r   lenintersectionr    r!   r$   r/   r0   r%   r%   r&   	score_set;   s   zPRFScore.score_setc                 C      | j | j | j d  S N0.++)r   r    r(   r%   r%   r&   	precision@      zPRFScore.precisionc                 C   r5   r6   )r   r!   r(   r%   r%   r&   recallD   r9   zPRFScore.recallc                 C   s$   | j }| j}d|| || d   S )N   r7   )r8   r:   )r$   prr%   r%   r&   fscoreH   s   zPRFScore.fscorec                 C   s   | j | j| jdS )N)r<   r=   f)r8   r:   r>   r(   r%   r%   r&   to_dictN   r*   zPRFScore.to_dict)__name__
__module____qualname____doc__intr'   r)   r-   r.   setr4   propertyfloatr8   r:   r>   r   strr@   r%   r%   r%   r&   r      s2    
r   c                   @   s8   e Zd ZdZdddZdddZdd	 Zed
d ZdS )ROCAUCScorezAn AUC ROC score. This is only defined for binary classification.
    Use the method is_binary before calculating the score, otherwise it
    may throw an error.r"   Nc                 C   s   g | _ g | _d| _d| _d S )N        r   )goldscandssaved_scoresaved_score_at_lenr(   r%   r%   r&   r'   W   s   
zROCAUCScore.__init__c                 C   s   | j | | j| d S r#   )rM   appendrL   r3   r%   r%   r&   r4   ]   s   zROCAUCScore.score_setc                 C   s   t t| jdkS Nr;   )r1   npuniquerL   r(   r%   r%   r&   	is_binarya   s   zROCAUCScore.is_binaryc                 C   sX   |   sttjjt| jdt| j| jkr| j	S t
| j| j| _	t| j| _| j	S )Nlabel)rT   
ValueErrorr   E165formatrF   rL   r1   rO   rN   _roc_auc_scorerM   r(   r%   r%   r&   scored   s   zROCAUCScore.score)r"   N)	rA   rB   rC   rD   r'   r4   rT   rG   r[   r%   r%   r%   r&   rJ   R   s    

rJ   c                   @   sf  e Zd ZdZddefded dedee ddfd	d
Zdddee	 de
deeef fddZedee	 deeef fddZeeeddee	 dedeeegef dee deeef f
ddZeeeddee	 dedeeegef dee deeef f
ddZeedddddee	 dedeeegee f deeege
f  de
de
deeef fd d!Zeee dddd"dee	 dedeeegef d#ee d$e
d%ee d&ee deeef fd'd(Zedee	 d)ee deeef fd*d+Zeed,ee ed-dee	 dedeeegef d.ed/eeegef d0ee dee deeef fd1d2ZdS )3ScorerzCompute evaluation scores.Nxxnlpr   default_langdefault_pipeliner"   c                 K   s<   || _ |r
|| _dS t| }|D ]}|| q|| _dS )zOInitialize the Scorer.

        DOCS: https://spacy.io/api/scorer#init
        N)cfgr^   r   add_pipe)r$   r^   r_   r`   ra   piper%   r%   r&   r'   r   s   


zScorer.__init__F)per_componentexamplesrd   c                C   s   i }t | jjdr)|r| jjj|fi | j|d< n|| jjj|fi | j | jjD ]%\}}t |drR|rE|j|fi | j||< q-||j|fi | j q-|S )aQ  Evaluate a list of Examples.

        examples (Iterable[Example]): The predicted annotations + correct annotations.
        per_component (bool): Whether to return the scores keyed by component
            name. Defaults to False.
        RETURNS (Dict): A dictionary of scores.

        DOCS: https://spacy.io/api/scorer#score
        r[   	tokenizer)hasattrr^   rf   r[   ra   updatepipeline)r$   re   rd   scoresname	componentr%   r%   r&   r[      s   
zScorer.scorec                 K   s  t  }t  }| D ]c}|j}|j}|jrq|j}t }t }	|D ]}
|
j r'q||
j	|
j	t
|
 f q|D ]-}
|
j r?q7|	|
j	|
j	t
|
 f |jj|
j dkr]| jd7  _q7| jd7  _q7||	| qt
|dkr}|j|j|j|jdS dddddS )a~  Returns accuracy and PRF scores for tokenization.
        * token_acc: # correct tokens / # gold tokens
        * token_p/r/f: PRF for token character spans

        examples (Iterable[Example]): Examples to score
        RETURNS (Dict[str, Any]): A dictionary containing the scores
            token_acc/p/r/f.

        DOCS: https://spacy.io/api/scorer#score_tokenization
        r   r   )	token_acctoken_ptoken_rtoken_fN)r   	reference	predictedhas_unknown_spaces	alignmentrF   orth_isspaceaddidxr1   x2ylengthsir    r   r4   r8   r:   r>   )re   ra   	acc_score	prf_scoreexamplegold_docpred_docalign
gold_spans
pred_spanstokenr%   r%   r&   score_tokenization   sB   

zScorer.score_tokenization)gettermissing_valuesattrr   r   c                K   s   t  }| D ]f}|j}|j}|j}	t }
t }t|D ]\}}|||}||vr2|
||||f q|| qt }|D ]'}|j rEq=|	j	j
|j dkrd|	j	|j d }||vrd|||||f q=|||
 q| d}t|dkr{|diS ||jiS )a  Returns an accuracy score for a token-level attribute.

        examples (Iterable[Example]): Examples to score
        attr (str): The attribute to score.
        getter (Callable[[Token, str], Any]): Defaults to getattr. If provided,
            getter(token, attr) should return the value of the attribute for an
            individual token.
        missing_values (Set[Any]): Attribute values to treat as missing annotation
            in the reference annotation.
        RETURNS (Dict[str, Any]): A dictionary containing the accuracy score
            under the key attr_acc.

        DOCS: https://spacy.io/api/scorer#score_token_attr
        r   r   _accN)r   rq   rr   rt   rF   	enumeraterw   ru   rv   ry   rz   r{   r4   r1   r>   )re   r   r   r   ra   	tag_scorer~   r   r   r   	gold_tagsmissing_indicesgold_ir   value	pred_tags	score_keyr%   r%   r&   score_token_attr   s4   



zScorer.score_token_attrc             	   K   s~  t  }i }| D ]}|j}|j}	|j}
i }t }t|	D ]J\}}|||}|	jj| }||vr`|tj	kr`|
tjD ]%}|
tj\}}||vrLt  ||< ||vrUt ||< || ||f q9q|| qi }|D ]]}|j rrqj|
jj|j dkr|
j|j d }||vr|||}|	jj| }||vr|tj	kr|
tjD ]%}|
tj\}}||vrt  ||< ||vrt ||< || ||f qqj|D ]$}|||t ||t  || ||t ||t  qqi }t|dkr!|j|| d< |j|| d< |j|| d< dd | D || d< |S d	|| d< d	|| d< d	|| d< d	|| d< |S )
a  Return micro PRF and PRF scores per feat for a token attribute in
        UFEATS format.

        examples (Iterable[Example]): Examples to score
        attr (str): The attribute to score.
        getter (Callable[[Token, str], Any]): Defaults to getattr. If provided,
            getter(token, attr) should return the value of the attribute for an
            individual token.
        missing_values (Set[Any]): Attribute values to treat as missing
            annotation in the reference annotation.
        RETURNS (dict): A dictionary containing the micro PRF scores under the
            key attr_micro_p/r/f and the per-feat PRF scores under
            attr_per_feat.
        r   r   _micro_p_micro_r_micro_fc                 S      i | ]	\}}||  qS r%   r@   .0kvr%   r%   r&   
<dictcomp>Q      z4Scorer.score_token_attr_per_feat.<locals>.<dictcomp>	_per_featN)r   rr   rq   rt   rF   r   vocabstringsr   EMPTY_MORPHsplitFEATURE_SEP	FIELD_SEPrw   ru   rv   ry   rz   r{   r4   getr1   r8   r:   r>   items)re   r   r   r   ra   micro_scoreper_featr~   r   r   r   gold_per_featr   r   r   r   morphfeatfieldvaluespred_per_featresultr%   r%   r&   score_token_attr_per_feat  sx   







z Scorer.score_token_attr_per_featT)r   has_annotationlabeledallow_overlapr   r   r   c                K   sb  t  }t }| D ]}	|	j}
|	j}|dur||sqtdd |||D }|du s1|dur?||
r?|tdd ||
|D O }dd |D }|D ]}||vrSt  ||< qHt }t }|||D ]$}|rn|j|j|jd f}n|j|jd f}|| ||j | q_dd |D }|du s|dur||
r|		||
||D ]$}|r|j|j|jd f}n|j|jd f}|| ||j | q|r|
 D ]\}}||v r||| ||  q||| q| d	d| d
d| ddi}|rd|| d< t|dkr/|j|| d	< |j|| d
< |j|| d< |r/dd |
 D || d< |S )ab  Returns PRF scores for labeled spans.

        examples (Iterable[Example]): Examples to score
        attr (str): The attribute to score.
        getter (Callable[[Doc, str], Iterable[Span]]): Defaults to getattr. If
            provided, getter(doc, attr) should return the spans for the
            individual doc.
        has_annotation (Optional[Callable[[Doc], bool]]) should return whether a `Doc`
            has annotation for this `attr`. Docs without annotation are skipped for
            scoring purposes.
        labeled (bool): Whether or not to include label information in
            the evaluation. If set to 'False', two spans will be considered
            equal if their start and end match, irrespective of their label.
        allow_overlap (bool): Whether or not to allow overlapping spans.
            If set to 'False', the alignment will automatically resolve conflicts.
        RETURNS (Dict[str, Any]): A dictionary containing the PRF scores under
            the keys attr_p/r/f and the per-type PRF scores under attr_per_type.

        DOCS: https://spacy.io/api/scorer#score_spans
        Nc                 S      g | ]}|j qS r%   label_r   r   r%   r%   r&   
<listcomp>      z&Scorer.score_spans.<locals>.<listcomp>c                 S   r   r%   r   r   r%   r%   r&   r     r   c                 S      i | ]}|t  qS r%   rF   r   rV   r%   r%   r&   r         z&Scorer.score_spans.<locals>.<dictcomp>r   c                 S   r   r%   r   r   r%   r%   r&   r     r   _p_r_f	_per_typer   c                 S   r   r%   r   r   r%   r%   r&   r         )r   dictrr   rq   rF   r   startendrw   get_aligned_spans_x2yr   r4   r1   r8   r:   r>   )re   r   r   r   r   r   ra   r[   score_per_typer~   r   r   labelsgold_per_typerV   r   r   span	gold_spanpred_per_type	pred_spanr   r   final_scoresr%   r%   r&   score_spansY  sp   






zScorer.score_spans)r   r   multi_labelpositive_label	thresholdr   r   r   r   c                   sN  |du r
|rdnd}|sd}dd  D }dd  D }	t   | D ]}
||
j|} fdd| D }||
j|} fdd| D } D ]}||d}||}|s\|s\d}|durh|	| || qI|r D ]F}||d}||}|dur||kr|d	kr||  jd
7  _qm||kr|d	kr||  jd
7  _qm||k r|d	kr||  jd
7  _qmq"|r|rt	| dd d\}}t	| dd d\}}||kr||  jd
7  _q"||  jd
7  _||  jd
7  _q"|rt	|dd d\}}|d	kr||  jd
7  _q"|r&t	| dd d\}}||  jd
7  _q"t
 }| D ]}| j|j7  _| j|j7  _| j|j7  _q.t|d }tdd | D | }tdd | D | }tdd | D | }tdd |	 D | }| dd| dd| d|j| d|j| d|j| d|| d|| d|| d|| d d!d | D | d"d#d |	 D i}t d$kr|s|r|| d  | d% }||| d< d&| d'|| d< |S |s|| d || d< d(|| d< |S || d || d< d)|| d< |S )*a  Returns PRF and ROC AUC scores for a doc-level attribute with a
        dict with scores for each label like Doc.cats. The reported overall
        score depends on the scorer settings.

        examples (Iterable[Example]): Examples to score
        attr (str): The attribute to score.
        getter (Callable[[Doc, str], Any]): Defaults to getattr. If provided,
            getter(doc, attr) should return the values for the individual doc.
        labels (Iterable[str]): The set of possible labels. Defaults to [].
        multi_label (bool): Whether the attribute allows multiple labels.
            Defaults to True. When set to False (exclusive labels), missing
            gold labels are interpreted as 0.0 and the threshold is set to 0.0.
        positive_label (str): The positive label for a binary task with
            exclusive classes. Defaults to None.
        threshold (float): Cutoff to consider a prediction "positive". Defaults
            to 0.5 for multi-label, and 0.0 (i.e. whatever's highest scoring)
            otherwise.
        RETURNS (Dict[str, Any]): A dictionary containing the scores, with
            inapplicable scores as None:
            for all:
                attr_score (one of attr_micro_f / attr_macro_f / attr_macro_auc),
                attr_score_desc (text description of the overall score),
                attr_micro_p,
                attr_micro_r,
                attr_micro_f,
                attr_macro_p,
                attr_macro_r,
                attr_macro_f,
                attr_macro_auc,
                attr_f_per_type,
                attr_auc_per_type

        DOCS: https://spacy.io/api/scorer#score_cats
        Ng      ?rK   c                 S   r   r%   )r   r   r%   r%   r&   r     r   z%Scorer.score_cats.<locals>.<dictcomp>c                 S   r   r%   )rJ   r   r%   r%   r&   r     r   c                       i | ]\}}| v r||qS r%   r%   r   r   r%   r&   r         c                    r   r%   r%   r   r   r%   r&   r     r   r   r   c                 S      | d S Nr   r%   itr%   r%   r&   <lambda>      z#Scorer.score_cats.<locals>.<lambda>)keyc                 S   r   r   r%   r   r%   r%   r&   r     r   c                 S   r   r   r%   r   r%   r%   r&   r     r   c                 S   r   r   r%   r   r%   r%   r&   r     r   r7   c                 s       | ]}|j V  qd S r#   r8   r   prfr%   r%   r&   	<genexpr>"      z$Scorer.score_cats.<locals>.<genexpr>c                 s   r   r#   r:   r   r%   r%   r&   r   #  r   c                 s   r   r#   r>   r   r%   r%   r&   r   $  r   c                 s   s"    | ]}|  r|jnd V  qdS )rK   NrT   r[   )r   aucr%   r%   r&   r   (  s     _score_score_descr   r   r   _macro_p_macro_r_macro_f
_macro_auc_f_per_typec                 S   r   r%   r   r   r%   r%   r&   r   5  r   _auc_per_typec                 S   s$   i | ]\}}||  r|jnd qS r#   r   r   r%   r%   r&   r   6  s    r;   r?   zF ()zmacro Fz	macro AUC)rF   rr   r   rq   r   r4   r   r    r!   maxr   r   r1   sumr8   r:   r>   )re   r   r   r   r   r   r   ra   
f_per_typeauc_per_typer~   	pred_cats	gold_catsrV   
pred_score
gold_score
pred_label
gold_label	micro_prf	label_prfn_catsmacro_pmacro_rmacro_f	macro_aucresultspositive_label_fr%   r   r&   
score_cats  s   .










zScorer.score_catsnegative_labelsc                K   s  i }| D ]}i }|j jD ]
}|||j|jf< q|jjD ]k}||j|jfd}|dur|j}	|	|vr7t ||	< |j}
|
dur|j}|
|v rJ||v rJq|
|krX||	  j	d7  _	q|
|v rf||	  j
d7  _
q||v rt||	  jd7  _q||	  j
d7  _
||	  jd7  _qqt }| D ]}| j	|j	7  _	| j|j7  _| j
|j
7  _
qt|d }tdd | D | }tdd | D | }tdd | D | }d|jd	d
d|jd|jd|jd|d|d|ddd | D i	}|S )a  Returns PRF for predicted links on the entity level.
        To disentangle the performance of the NEL from the NER,
        this method only evaluates NEL links for entities that overlap
        between the gold reference and the predictions.

        examples (Iterable[Example]): Examples to score
        negative_labels (Iterable[str]): The string values that refer to no annotation (e.g. "NIL")
        RETURNS (Dict[str, Any]): A dictionary containing the scores.

        DOCS: https://spacy.io/api/scorer#score_links
        Nr   r7   c                 s   r   r#   r   r   r%   r%   r&   r   {  r   z%Scorer.score_links.<locals>.<genexpr>c                 s   r   r#   r   r   r%   r%   r&   r   |  r   c                 s   r   r#   r   r   r%   r%   r&   r   }  r   	nel_scorenel_score_desczmicro Fnel_micro_pnel_micro_rnel_micro_fnel_macro_pnel_macro_rnel_macro_fnel_f_per_typec                 S   r   r%   r   r   r%   r%   r&   r     r   z&Scorer.score_links.<locals>.<dictcomp>)rq   ents
start_charend_charrr   r   r   r   kb_id_r   r    r!   r   r1   r   r>   r8   r:   r   )re   r  ra   r   r~   gold_ent_by_offsetgold_entpred_entr   rV   r0   predr   r   n_labelsr   r   r   r  r%   r%   r&   score_linksF  s`   
zScorer.score_linkshead)r   	head_attrhead_getterignore_labelsr   r  r  r  c             	   K   s  t  }t  }	t }
t }| D ]}|j}|j}|j}t }i }t|D ]B\}}|||}|||}||vr`||vr_|||j|f ||
vrKt  |
|< ||vrTt ||< || ||j|f q#|| q#t }i }|D ]}|j	
 ruqm|jj|j dkrd}n|j|j d }||vr|||}|||}||vr|j	 r|jj|j dkr|j|j d }nd}|du s|du r| jd7  _|	 jd7  _qm||||f ||
vrt  |
|< ||vrt ||< || |||f qm|	|| |
D ]}|
| ||t ||t  q|tdd |D tdd |D  qt|dkrC| d|j| d|	j| dd	d
 |
 D iS | dd| dd| ddiS )a2  Returns the UAS, LAS, and LAS per type scores for dependency
        parses.

        examples (Iterable[Example]): Examples to score
        attr (str): The attribute containing the dependency label.
        getter (Callable[[Token, str], Any]): Defaults to getattr. If provided,
            getter(token, attr) should return the value of the attribute for an
            individual token.
        head_attr (str): The attribute containing the head token. Defaults to
            'head'.
        head_getter (Callable[[Token, str], Token]): Defaults to getattr. If provided,
            head_getter(token, attr) should return the value of the head for an
            individual token.
        ignore_labels (Tuple): Labels to ignore while scoring (e.g., punct).
        missing_values (Set[Any]): Attribute values to treat as missing annotation
            in the reference annotation.
        RETURNS (Dict[str, Any]): A dictionary containing the scores:
            attr_uas, attr_las, and attr_las_per_type.

        DOCS: https://spacy.io/api/scorer#score_deps
        r   Nr   c                 s   s    | ]	}|d d V  qd S rQ   r%   )r   itemr%   r%   r&   r     s    z$Scorer.score_deps.<locals>.<genexpr>_uas_las_las_per_typec                 S   r   r%   r   r   r%   r%   r&   r     r   z%Scorer.score_deps.<locals>.<dictcomp>)r   r   rF   rq   rr   rt   r   rw   r{   ru   rv   ry   rz   stripr    r4   r   r1   r>   r   )re   r   r   r  r  r  r   ra   
unlabelledlabelledlabelled_per_depr   r~   r   r   r   	gold_depsgold_deps_per_depr   r   depr  	pred_depspred_deps_per_dep	gold_headr%   r%   r&   
score_deps  s   !









 
	

zScorer.score_deps)rA   rB   rC   rD   DEFAULT_PIPELINEr	   rI   r   r'   r   boolr   r   r[   staticmethodr   getattrMISSING_VALUESr   r   r
   r   r   r   r   r   r   rH   r  r  r*  r%   r%   r%   r&   r\   o   s    


 1
2
S
	d

 
D

r\   re   r"   c                 K   sp  t t}| D ]}|jdsqdd |jjD }|jj}|jjD ]Y}|j|vr-t ||j< ||j	|j
 }t|ry|j|d |d d  }tdd |D ry|j|d |d d f}	|	|v ro||j  jd7  _||	 q ||j  jd7  _q |D ]\}
}}||
  jd7  _q|qt }| D ]}||7 }qt|dkr|j|j|jd	d
 | D dS dddddS )zGCompute micro-PRF and per-entity PRF scores for a sequence of examples.ENT_IOBc                 S   s   h | ]
}|j |j|jfqS r%   )r   r   r   )r   er%   r%   r&   	<setcomp>  s    zget_ner_prf.<locals>.<setcomp>r   r   c                 s   s    | ]}|j d kV  qdS )r   N)ent_iob)r   r   r%   r%   r&   r   	  s    zget_ner_prf.<locals>.<genexpr>c                 S   r   r%   r   r   r%   r%   r&   r     r   zget_ner_prf.<locals>.<dictcomp>)ents_pents_rents_fents_per_typeN)r   r   yr   r  rt   ry   xr   r   r   r1   allr   remover    r!   r   r8   r:   r>   r   )re   kwargsr   egrL   	align_x2yr  indicesg_spanr   rV   r   r   totalsr   r%   r%   r&   get_ner_prf  sH   

rC        ?r3  c           
   
   C   s(  t | } |du r|}n)t |}|jdkr.t |}dg| j }|jd ||< ||}nt j||d}| j}tdg| }tdg| }tdd||< tdd||< z|| t| | t|   d |}	W |	S  t	y   t 
|}t 
| } t j|| t| | t|   d |}	Y |	S w )a  
    Integrate along the given axis using the composite trapezoidal rule.

    If `x` is provided, the integration happens in sequence along its
    elements - they are not sorted.

    Integrate `y` (`x`) along each 1d slice on the given axis, compute
    :math:`\int y(x) dx`.
    When `x` is specified, this integrates along the parametric curve,
    computing :math:`\int_t y(t) dt =
    \int_t y(t) \left.\frac{dx}{dt}\right|_{x=x(t)} dt`.

    Parameters
    ----------
    y : array_like
        Input array to integrate.
    x : array_like, optional
        The sample points corresponding to the `y` values. If `x` is None,
        the sample points are assumed to be evenly spaced `dx` apart. The
        default is None.
    dx : scalar, optional
        The spacing between sample points when `x` is None. The default is 1.
    axis : int, optional
        The axis along which to integrate.

    Returns
    -------
    trapezoid : float or ndarray
        Definite integral of `y` = n-dimensional array as approximated along
        a single axis by the trapezoidal rule. If `y` is a 1-dimensional array,
        then the result is a float. If `n` is greater than 1, then the result
        is an `n`-1 dimensional array.

    See Also
    --------
    cumulative_trapezoid, simpson, romb

    Notes
    -----
    Image [2]_ illustrates trapezoidal rule -- y-axis locations of points
    will be taken from `y` array, by default x-axis distances between
    points will be 1.0, alternatively they can be provided with `x` array
    or with `dx` scalar.  Return value will be equal to combined area under
    the red lines.

    References
    ----------
    .. [1] Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule

    .. [2] Illustration image:
           https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png

    Examples
    --------
    Use the trapezoidal rule on evenly spaced points:

    >>> import numpy as np
    >>> from scipy import integrate
    >>> integrate.trapezoid([1, 2, 3])
    4.0

    The spacing between sample points can be selected by either the
    ``x`` or ``dx`` arguments:

    >>> integrate.trapezoid([1, 2, 3], x=[4, 6, 8])
    8.0
    >>> integrate.trapezoid([1, 2, 3], dx=2)
    8.0

    Using a decreasing ``x`` corresponds to integrating in reverse:

    >>> integrate.trapezoid([1, 2, 3], x=[8, 6, 4])
    -8.0

    More generally ``x`` is used to integrate along a parametric curve. We can
    estimate the integral :math:`\int_0^1 x^2 = 1/3` using:

    >>> x = np.linspace(0, 1, num=50)
    >>> y = x**2
    >>> integrate.trapezoid(y, x)
    0.33340274885464394

    Or estimate the area of a circle, noting we repeat the sample which closes
    the curve:

    >>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True)
    >>> integrate.trapezoid(np.cos(theta), x=np.sin(theta))
    3.141571941375841

    ``trapezoid`` can be applied along a specified axis to do multiple
    computations in one call:

    >>> a = np.arange(6).reshape(2, 3)
    >>> a
    array([[0, 1, 2],
           [3, 4, 5]])
    >>> integrate.trapezoid(a, axis=0)
    array([1.5, 2.5, 3.5])
    >>> integrate.trapezoid(a, axis=1)
    array([2.,  8.])
    Nr   r   axisr3  g       @)rR   
asanyarrayndimdiffshapereshapeslicetupler   rW   asarrayrw   reduce)
r9  r:  dxrF  drJ  ndslice1slice2retr%   r%   r&   	trapezoid)  s0   
f


(

,rV  c                 C   sD   t t| dkrttjjt| dt| |\}}}t||S )a  Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC)
    from prediction scores.

    Note: this implementation is restricted to the binary classification task

    Parameters
    ----------
    y_true : array, shape = [n_samples] or [n_samples, n_classes]
        True binary labels or binary label indicators.
        The multiclass case expects shape = [n_samples] and labels
        with values in ``range(n_classes)``.

    y_score : array, shape = [n_samples] or [n_samples, n_classes]
        Target scores, can either be probability estimates of the positive
        class, confidence values, or non-thresholded measure of decisions
        (as returned by "decision_function" on some classifiers). For binary
        y_true, y_score is supposed to be the score of the class with greater
        label. The multiclass case expects shape = [n_samples, n_classes]
        where the scores correspond to probability estimates.

    Returns
    -------
    auc : float

    References
    ----------
    .. [1] `Wikipedia entry for the Receiver operating characteristic
            <https://en.wikipedia.org/wiki/Receiver_operating_characteristic>`_

    .. [2] Fawcett T. An introduction to ROC analysis[J]. Pattern Recognition
           Letters, 2006, 27(8):861-874.

    .. [3] `Analyzing a portion of the ROC curve. McClish, 1989
            <https://www.ncbi.nlm.nih.gov/pubmed/2668680>`_
    r;   rU   )	r1   rR   rS   rW   r   rX   rY   
_roc_curve_auc)y_truey_scorefprtpr_r%   r%   r&   rZ     s   $
rZ   c                 C   s   t | |\}}}tjd|f }tjd|f }tj|d d |f }|d dkr0ttj|j}n||d  }|d dkrEttj|j}n||d  }|||fS )a  Compute Receiver operating characteristic (ROC)

    Note: this implementation is restricted to the binary classification task.

    Parameters
    ----------

    y_true : array, shape = [n_samples]
        True binary labels. If labels are not either {-1, 1} or {0, 1}, then
        pos_label should be explicitly given.

    y_score : array, shape = [n_samples]
        Target scores, can either be probability estimates of the positive
        class, confidence values, or non-thresholded measure of decisions
        (as returned by "decision_function" on some classifiers).

    Returns
    -------
    fpr : array, shape = [>2]
        Increasing false positive rates such that element i is the false
        positive rate of predictions with score >= thresholds[i].

    tpr : array, shape = [>2]
        Increasing true positive rates such that element i is the true
        positive rate of predictions with score >= thresholds[i].

    thresholds : array, shape = [n_thresholds]
        Decreasing thresholds on the decision function used to compute
        fpr and tpr. `thresholds[0]` represents no instances being predicted
        and is arbitrarily set to `max(y_score) + 1`.

    Notes
    -----
    Since the thresholds are sorted from low to high values, they
    are reversed upon returning them to ensure they correspond to both ``fpr``
    and ``tpr``, which are sorted in reversed order during their calculation.

    References
    ----------
    .. [1] `Wikipedia entry for the Receiver operating characteristic
            <https://en.wikipedia.org/wiki/Receiver_operating_characteristic>`_

    .. [2] Fawcett T. An introduction to ROC analysis[J]. Pattern Recognition
           Letters, 2006, 27(8):861-874.
    r   r   r3  )_binary_clf_curverR   r_repeatnanrJ  )rY  rZ  fpstps
thresholdsr[  r\  r%   r%   r&   rW    s   .
rW  c           	      C   s   d}t | } t |}| |k} t j|ddddd }|| }| | } d}t t |d }t j|| jd f }t| | | }d| | }|||| fS )a  Calculate true and false positives per binary classification threshold.

    Parameters
    ----------
    y_true : array, shape = [n_samples]
        True targets of binary classification

    y_score : array, shape = [n_samples]
        Estimated probabilities or decision function

    Returns
    -------
    fps : array, shape = [n_thresholds]
        A count of false positives, at index i being the number of negative
        samples assigned a score >= thresholds[i]. The total number of
        negative samples is equal to fps[-1] (thus true negatives are given by
        fps[-1] - fps).

    tps : array, shape = [n_thresholds <= len(np.unique(y_score))]
        An increasing count of true positives, at index i being the number
        of positive samples assigned a score >= thresholds[i]. The total
        number of positive samples is equal to tps[-1] (thus false negatives
        are given by tps[-1] - tps).

    thresholds : array, shape = [n_thresholds]
        Decreasing score values.
    rD  	mergesort)kindNr3  r   r   )rR   ravelargsortwhererI  r_  size_stable_cumsum)	rY  rZ  	pos_labeldesc_score_indicesweightdistinct_value_indicesthreshold_idxsrc  rb  r%   r%   r&   r^    s   

r^  h㈵>:0yE>c              	   C   sV   t j| |t jd}t j| |t jd}t t j|jd|d|||dds)ttj	|S )a  Use high precision for cumsum and check that final value matches sum

    Parameters
    ----------
    arr : array-like
        To be cumulatively summed as flat
    axis : int, optional
        Axis along which the cumulative sum is computed.
        The default (None) is to compute the cumsum over the flattened array.
    rtol : float
        Relative tolerance, see ``np.allclose``
    atol : float
        Absolute tolerance, see ``np.allclose``
    )rF  dtyper3  rE  T)rtolatol	equal_nan)
rR   cumsumfloat64r   r;  isclosetakerW   r   E163)arrrF  rt  ru  outexpectedr%   r%   r&   rk  R  s   
rk  c                 C   s   t | } t |}d}t | }t |dk r+t |dkr"d}n	ttjj| d|t	||  }t
|t jr>|j|}|S )a  Compute Area Under the Curve (AUC) using the trapezoidal rule

    This is a general function, given points on a curve.  For computing the
    area under the ROC-curve, see :func:`roc_auc_score`.

    Parameters
    ----------
    x : array, shape = [n]
        x coordinates. These must be either monotonic increasing or monotonic
        decreasing.
    y : array, shape = [n]
        y coordinates.

    Returns
    -------
    auc : float
    r   r   r3  )r:  )rR   rg  rI  anyr;  rW   r   E164rY   rV  
isinstancememmaprs  type)r:  r9  	directionrP  arear%   r%   r&   rX  l  s   


rX  )NrD  r3  )Nrq  rr  )+collectionsr   typingr   r   r   r   r   r   r	   r
   r   numpyrR   errorsr   
morphologyr   tokensr   r   r   trainingr   utilr   r   languager   r+  	frozensetr/  r   rJ   r\   rI   rC  rV  rZ   rW  r^  rk  rX  r%   r%   r%   r&   <module>   s8    ,3     
1 *C
6