a
    >PÎjÓß  ã                   @  s   d Z ddlmZ ddlZddl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mZmZmZ ddlmZmZmZ ddlZdd	lmZmZ dd
lmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z. ddl/Z/ddl0m1Z1 ddl2Z2ddl3Z3ddl4m5Z5m6Z6 e*dƒZ7dZ8G dd„ de/j9ƒZ:dddœdd„Z;G dd„ de:ƒZ<G dd„ de:ƒZ=G dd„ de:ƒZ>G dd„ de:ƒZ?ddd œd!d"„Z@G d#d$„ d$ejAƒZBG d%d&„ d&ƒZCe5G d'd(„ d(ƒƒZDG d)d*„ d*eEƒZFe5G d+d,„ d,ƒƒZGG d-d.„ d.eƒZHe Id/¡d0d1d2d3d4œd5d6„ƒZJG d7d8„ d8ƒZKe Id9¡d:d;d<œd=d>„ƒZLd0d?d?d0d@œdAdB„ZMdždDdEdFdGœdHdI„ZNed0dJdKœdLdM„ƒZOed0dEdNdOœdPdM„ƒZOdCdœdQdM„ZOdRdS„ ZPdTdU„ ZQdVdW„ ZRdXdYdZœd[d\„ZSd]d]d^œd_d`„ZTdadbdcddœdedf„ZUdadgdddœdhdi„ZVdadjdkddœdldm„ZWdddnœdodp„ZXdqdr„ ZYdsdddtœdudv„ZZG dwdx„ dxƒZ[dydz„ Z\dŸd~d„Z]d€dEd�œd‚dƒ„Z^d„d…dnœd†d‡„Z_d„d…dnœdˆd‰„Z`d„d…dnœdŠd‹„Zad„d?d…dŒœd�dŽ„Zbd�dEd�œd‘d’„ZcdEd“œd”d•„Zdd?dEd–œd—d˜„Zed]d]d�œd™dš„Zfd]d]d]d]d›œdœd�„ZgdS ) z„
Data classes and utilities used by :class:`iminuit.Minuit`.

You can look up the interface of data classes that iminuit uses here.
é    ©ÚannotationsN)ÚOrderedDict)Ú	Namespace)Ú
_repr_htmlÚ
_repr_textÚ_deprecated)ÚKeyÚ	UserBoundÚCostÚ
CostVector)ÚIMinuitWarningÚHesseFailedWarningÚPerformanceWarning)ÚNDArrayÚ	ArrayLike)ÚoverloadÚAnyÚListÚUnionÚDictÚIterableÚ	GeneratorÚTupleÚOptionalÚCallableÚ
CollectionÚSequenceÚTypeVarÚ	AnnotatedÚSupportsIndexÚget_argsÚ
get_origin)Úperf_counter)Ú	dataclassÚasdictÚT)r   r   r   Ú	ValueViewÚ	FixedViewÚ	LimitViewÚMatrixÚFMinÚParamÚParamsÚMErrorÚMErrorsÚmake_func_codeÚmake_with_signatureÚmerge_signaturesÚdescribeÚgradientÚg2ÚhessianÚis_positive_definiteÚ
is_jupyterÚis_module_availablec                   @  s¾   e Zd ZdZdZd)dddœdd„Zd	d
œdd„Zdd
œdd„Zej	dddœdd„ƒZ
ej	ddddœdd„ƒZdddœdd„Zddddœdd„Zdddœd d!„Zd"d
œd#d$„Zd%d
œd&d'„Zd(S )*Ú	BasicViewz¸
    Array-like view of parameter state.

    Derived classes need to implement methods _set and _get to access
    specific properties of the parameter state.

    :meta private:
    ©Ú_minuitÚ_ndimr   r   Úint)ÚminuitÚndimc                 C  s   || _ || _d S ©Nr;   )Úselfr?   r@   © rC   ú\/mounts/lovelace/software/anaconda3/envs/metadmg/lib/python3.9/site-packages/iminuit/util.pyÚ__init__S   s    zBasicView.__init__r   ©Úreturnc                 c  s"   t t| ƒƒD ]}|  |¡V  qdS )zGet iterator over values.N)ÚrangeÚlenÚ_get)rB   ÚirC   rC   rD   Ú__iter__X   s    zBasicView.__iter__c                 C  s   | j jS )zGet number of paramters.)r<   Znpar©rB   rC   rC   rD   Ú__len__]   s    zBasicView.__len__©ÚidxrG   c                 C  s   t S rA   )ÚNotImplemented©rB   rP   rC   rC   rD   rJ   a   s    zBasicView._getÚNone©rP   ÚvaluerG   c                 C  s   d S rA   rC   ©rB   rP   rU   rC   rC   rD   Ú_sete   s    zBasicView._setr	   ©ÚkeyrG   c                   s4   t ˆ jj|ƒ}t|tƒr*‡ fdd„|D ƒS ˆ  |¡S )a  
        Get values of the view.

        Parameters
        ----------
        key: int, str, slice, list of int or str
            If the key is an int or str, return corresponding value.
            If it is a slice, list of int or str, return the corresponding subset.
        c                   s   g | ]}ˆ   |¡‘qS rC   ©rJ   ©Ú.0rK   rM   rC   rD   Ú
<listcomp>t   ó    z)BasicView.__getitem__.<locals>.<listcomp>)Ú
_key2indexr<   Ú_var2posÚ
isinstanceÚlistrJ   )rB   rY   ÚindexrC   rM   rD   Ú__getitem__h   s    

zBasicView.__getitem__)rY   rU   rG   c                 C  s’   | j  ¡  t| j j|ƒ}t|tƒr‚t|ƒ| jkrH|D ]}|  ||¡ q4qŽt|ƒt|ƒkr`t	dƒ‚t
||ƒD ]\}}|  ||¡ qjn|  ||¡ dS )zFAssign new value at key, which can be index, parameter name, or slice.z'length of argument does not match sliceN)r<   Z_copy_state_if_neededr_   r`   ra   rb   r=   rW   rI   Ú
ValueErrorÚzip)rB   rY   rU   rc   rK   ÚvrC   rC   rD   Ú__setitem__w   s    

zBasicView.__setitem__ÚobjectÚbool©ÚotherrG   c                 C  s"   t  | |¡\}}tt  ||k¡ƒS )z$Return true if all values are equal.)ÚnpZbroadcast_arraysrj   Úall)rB   rl   ÚaÚbrC   rC   rD   Ú__eq__‡   s    zBasicView.__eq__Ústrc                 C  sF   d| j j› �}t| jj| ƒD ]\}}|d|› d|› �7 }q|d7 }|S )ú!Get detailed text representation.ú<ú ú=ú>)Ú	__class__Ú__name__rf   r<   Ú_pos2var©rB   ÚsÚkrg   rC   rC   rD   Ú__repr__Œ   s
    zBasicView.__repr__zDict[str, float]c                   s   ‡ fdd„t ˆ jjƒD ƒS )zObtain dict representation.c                   s   i | ]\}}|ˆ   |¡“qS rC   rZ   )r\   rK   r}   rM   rC   rD   Ú
<dictcomp>–   r^   z%BasicView.to_dict.<locals>.<dictcomp>)Ú	enumerater<   rz   rM   rC   rM   rD   Úto_dict”   s    zBasicView.to_dictN)r   )ry   Ú
__module__Ú__qualname__Ú__doc__Ú	__slots__rE   rL   rN   ÚabcÚabstractmethodrJ   rW   rd   rh   rq   r~   r�   rC   rC   rC   rD   r:   G   s   	r:   r   r>   ©ÚobjrG   c                 C  sB   d}t | tƒr>t | tƒs>|d7 }| D ]}|d ur$|}  qq$q>q|S )Nr   é   )ra   r   rr   )r‰   ÚndÚxrC   rC   rD   r=   ™   s    r=   c                   @  s2   e Zd ZdZdddœdd„Zddddœd	d
„ZdS )r'   z$Array-like view of parameter values.r>   ÚfloatrO   c                 C  s   | j j| jS rA   )r<   Ú_last_staterU   rR   rC   rC   rD   rJ   «   s    zValueView._getrS   rT   c                 C  s   | j j ||¡ d S rA   )r<   rŽ   Ú	set_valuerV   rC   rC   rD   rW   ®   s    zValueView._setN©ry   r‚   rƒ   r„   rJ   rW   rC   rC   rC   rD   r'   ¨   s   r'   c                   @  s2   e Zd ZdZdddœdd„Zddddœd	d
„ZdS )Ú	ErrorViewz$Array-like view of parameter errors.r>   r�   rO   c                 C  s   | j j| jS rA   )r<   rŽ   ÚerrorrR   rC   rC   rD   rJ   µ   s    zErrorView._getrS   rT   c                 C  s4   |dkr t jdtdd� t|ƒ}| jj ||¡ d S )Nr   zRAssigned errors must be positive. Non-positive values are replaced by a heuristic.é   ©Ú
stacklevel)ÚwarningsÚwarnr   Ú_guess_initial_stepr<   rŽ   Ú	set_errorrV   rC   rC   rD   rW   ¸   s    üzErrorView._setNr�   rC   rC   rC   rD   r‘   ²   s   r‘   c                   @  s@   e Zd ZdZdddœdd„Zddddœd	d
„Zddœdd„ZdS )r(   z0Array-like view of whether parameters are fixed.r>   rj   rO   c                 C  s   | j j| jS rA   )r<   rŽ   Úis_fixedrR   rC   rC   rD   rJ   Ç   s    zFixedView._getrS   rT   c                 C  s&   |r| j j |¡ n| j j |¡ d S rA   )r<   rŽ   ÚfixÚreleaserV   rC   rC   rD   rW   Ê   s    zFixedView._setrb   rF   c                   s   ‡ fdd„t tˆ ƒƒD ƒS )z#Return list with inverted elements.c                   s   g | ]}ˆ   |¡ ‘qS rC   rZ   r[   rM   rC   rD   r]   Ò   r^   z(FixedView.__invert__.<locals>.<listcomp>)rH   rI   rM   rC   rM   rD   Ú
__invert__Ð   s    zFixedView.__invert__N)ry   r‚   rƒ   r„   rJ   rW   r�   rC   rC   rC   rD   r(   Ä   s   r(   c                      sH   e Zd ZdZddœ‡ fdd„Zdddœd	d
„Zddddœdd„Z‡  ZS )r)   z$Array-like view of parameter limits.r   )r?   c                   s   t t| ƒ |d¡ d S )NrŠ   )Úsuperr)   rE   )rB   r?   ©rx   rC   rD   rE   Ø   s    zLimitView.__init__r>   úTuple[float, float]rO   c                 C  s2   | j j| }|jr|jntj |jr*|jntjfS rA   )r<   rŽ   Úhas_lower_limitÚlower_limitrm   ÚinfÚhas_upper_limitÚupper_limit)rB   rP   ÚprC   rC   rD   rJ   Ü   s    þzLimitView._getr
   rS   rT   c                 C  sÒ   | j j}|| j}|| j}| |¡ t|ƒ\}}|tj krl|tjkrl||kr\| |¡ qœ| 	|||¡ n0|tj kr†| 
||¡ n|tjkrœ| ||¡ ||k rª|}n||kr¶|}| ||¡ | ||¡ d S rA   )r<   rŽ   rU   r’   Zremove_limitsÚ_normalize_limitrm   r£   r›   Z
set_limitsZset_lower_limitZset_upper_limitr�   r™   )rB   rP   rU   ÚstateÚvalÚerrÚlowÚhighrC   rC   rD   rW   ã   s&    



zLimitView._set)ry   r‚   rƒ   r„   rE   rJ   rW   Ú__classcell__rC   rC   rŸ   rD   r)   Õ   s   r)   zOptional[Iterable]r    )ÚlimrG   c                 C  s\   | d u rt j t jfS | \}}|d u r.t j }|d u r<t j}||krTtd| ›d�ƒ‚||fS )Nzlimit z is invalid)rm   r£   re   )r®   ro   rp   rC   rC   rD   r§   ü   s    r§   c                      sÌ   e Zd ZdZdZdddœ‡ fdd„Zddd	œd
d„Zddœdd„Zddœdd„Zdddœ‡ fdd„Z	ddœdd„Z
ddœdd„Zdd„ Z‡ fd d!„Zd"d#„ Zd$d%„ Zd&d'„ Z‡ fd(d)„Z‡ fd*d+„Z‡  ZS ),r*   zØ
    Enhanced Numpy ndarray.

    Works like a normal ndarray in computations, but also supports pretty printing in
    ipython and Jupyter notebooks. Elements can be accessed via indices or parameter
    names.
    )r`   zUnion[Dict, Tuple]r   )Ú
parametersrG   c                   sZ   t |tƒr|}n&t |tƒr.dd„ t|ƒD ƒ}ntdƒ‚t|ƒ}tƒ  | ||f¡}||_|S )Nc                 S  s   i | ]\}}||“qS rC   rC   )r\   rK   rŒ   rC   rC   rD   r     r^   z"Matrix.__new__.<locals>.<dictcomp>z parameters must be tuple or dict)	ra   ÚdictÚtupler€   Ú	TypeErrorrI   rž   Ú__new__r`   )Úclsr¯   Úvar2posÚnr‰   rŸ   rC   rD   r³     s    

zMatrix.__new__rS   rˆ   c                 C  s"   |du ri | _ nt|di ƒ| _ dS )zFor internal use.Nr`   )r`   Úgetattr)rB   r‰   rC   rC   rD   Ú__array_finalize__!  s    zMatrix.__array_finalize__rj   rF   c                 C  s   | j dko| jd | jd kS )Nr“   r   rŠ   )r@   ÚshaperM   rC   rC   rD   Ú
_is_square(  s    zMatrix._is_squarezTuple[str, ...]c                 C  s@   |   ¡ r&| jd t| jƒkr&t| jƒS tdd„ tt| ƒƒD ƒƒS )Nr   c                 s  s   | ]}t |ƒV  qd S rA   )rr   r[   rC   rC   rD   Ú	<genexpr>0  r^   z Matrix._names.<locals>.<genexpr>)rº   r¹   rI   r`   r±   rH   rM   rC   rC   rD   Ú_names+  s    
zMatrix._namesz3Union[Key, Tuple[Key, Key], Iterable[Key], NDArray]r   rX   c                   s  | j ‰‡‡fdd„‰t|tƒrHˆ|ƒ}tƒ  ||f¡}tt| ƒƒ| }n‚t|tƒrºt|tt	t
jfƒsºt|ƒ}|r’tdd„ |D ƒƒr’tt
 |¡ƒ}n‡fdd„|D ƒ}tƒ  t
 ||¡¡}ntƒ  ˆ|ƒ¡S tˆƒt| ƒkrât	ˆƒnd‰ ˆ �r‡ fdd	„t|ƒD ƒni |_ |S )
zGet matrix element at key.c                   sZ   t | tƒrˆ|  S t | tƒr6tˆ | jƒˆ | jƒ| jƒS t | tƒrVt‡ fdd„| D ƒƒS | S )Nc                 3  s   | ]}ˆ |ƒV  qd S rA   rC   ©r\   r}   ©ÚtraforC   rD   r»   ?  r^   z4Matrix.__getitem__.<locals>.trafo.<locals>.<genexpr>)ra   rr   ÚsliceÚstartÚstopÚstepr±   ©rY   )r¿   rµ   rC   rD   r¿   9  s    


z!Matrix.__getitem__.<locals>.trafoc                 s  s   | ]}t |ttjfƒV  qd S rA   )ra   rj   rm   Úbool_r½   rC   rC   rD   r»   L  r^   z%Matrix.__getitem__.<locals>.<genexpr>c                   s   g | ]}ˆ |ƒ‘qS rC   rC   r½   r¾   rC   rD   r]   O  r^   z&Matrix.__getitem__.<locals>.<listcomp>rC   c                   s   i | ]\}}ˆ | |“qS rC   rC   )r\   rK   r¦   )ÚnamesrC   rD   r   V  r^   z&Matrix.__getitem__.<locals>.<dictcomp>)r`   ra   rÀ   rž   rd   rH   rI   r   rr   r±   rm   Úndarrayrb   rn   ZflatnonzeroZix_r€   )rB   rY   ÚslÚsubZ	positionsrŸ   )rÆ   r¿   rµ   rD   rd   2  s$    	
ÿ"zMatrix.__getitem__zDict[Tuple[str, str], float]c                 C  sV   |   ¡ }i }t|ƒD ]<\}}t|t|ƒƒD ]$}|| }t| ||f ƒ|||f< q*q|S )z�
        Convert matrix to dict.

        Since the matrix is symmetric, the dict only contains the upper triangular
        matrix.
        )r¼   r€   rH   rI   r�   )rB   rÆ   ÚdrK   ÚpiÚjZpjrC   rC   rD   r�   Y  s    zMatrix.to_dictz'Tuple[List[List[str]], Tuple[str, ...]]c                   s^   |   ¡ }t | ¡‰g }t| ƒ‰t|ƒD ].\‰ }| |g‡ ‡‡fdd„tˆƒD ƒ ¡ q&||fS )aá  
        Convert matrix to tabular format.

        The output is consumable by the external
        `tabulate <https://pypi.org/project/tabulate>`_ module.

        Examples
        --------
        >>> import tabulate as tab
        >>> from iminuit import Minuit
        >>> m = Minuit(lambda x, y: x ** 2 + y ** 2, x=1, y=2).migrad()
        >>> tab.tabulate(*m.covariance.to_table())
              x    y
        --  ---  ---
        x     1   -0
        y    -0    4
        c                   s   g | ]}ˆˆˆ  |  ‘qS rC   rC   )r\   rÌ   ©rK   r¶   ZnumsrC   rD   r]     r^   z#Matrix.to_table.<locals>.<listcomp>)r¼   r   Zmatrix_formatrI   r€   ÚappendrH   )rB   rÆ   ÚtabÚnamerC   rÍ   rD   Úto_tableh  s    
(zMatrix.to_tablec                 C  s.   |   ¡ }t |¡d }|t ||¡d  }|S )z°
        Compute and return correlation matrix.

        If the matrix is already a correlation matrix, this effectively returns a copy
        of the original matrix.
        ç      à?g0Žä.ÿ++)Úcopyrm   ÚdiagÚouter)rB   ro   rÊ   rC   rC   rD   Úcorrelation‚  s    zMatrix.correlationc                   s   t t| ƒ ¡ S )rs   )rž   r*   Ú__str__rM   rŸ   rC   rD   r~   Ž  s    zMatrix.__repr__c                 C  s   |   ¡ st| ƒS t | ¡S ©ú&Get user-friendly text representation.)rº   Úreprr   ÚmatrixrM   rC   rC   rD   r×   ’  s    zMatrix.__str__c                 C  s"   |   ¡ sdt| ƒ› d�S t | ¡S )Nz<pre>z</pre>)rº   rÚ   r   rÛ   rM   rC   rC   rD   Ú_repr_html_˜  s    zMatrix._repr_html_c                 C  s"   |r|  d¡ n|  t| ƒ¡ d S )Nz<Matrix ...>©Útextrr   ©rB   r¦   ÚcyclerC   rC   rD   Ú_repr_pretty_�  s    zMatrix._repr_pretty_c                   s    t ƒ  ¡ \}}}|||| jffS )z,Get representation for pickling and copying.)rž   Ú
__reduce__r`   )rB   ZrestoreÚargsr¨   rŸ   rC   rD   râ   ¤  s    zMatrix.__reduce__c                   s   |\}| _ tƒ  |¡ dS )zRestore from pickled state.N)r`   rž   Ú__setstate__)rB   r¨   rŸ   rC   rD   rä   ©  s    
zMatrix.__setstate__)ry   r‚   rƒ   r„   r…   r³   r¸   rº   r¼   rd   r�   rÑ   rÖ   r~   r×   rÜ   rá   râ   rä   r­   rC   rC   rŸ   rD   r*   	  s    'r*   c                
   @  sø  e Zd ZdZdZddddddddddœ	dd	„Zedd
œdd„ƒZedd
œdd„ƒZedd
œdd„ƒZ	edd
œdd„ƒZ
edd
œdd„ƒZedd
œdd„ƒZedd
œdd„ƒZedd
œdd„ƒZedd
œdd„ƒZedd
œdd„ƒZedd
œd d!„ƒZedd
œd"d#„ƒZedd
œd$d%„ƒZedd
œd&d'„ƒZedd
œd(d)„ƒZedd
œd*d+„ƒZedd
œd,d-„ƒZedd
œd.d/„ƒZedd
œd0d1„ƒZedd
œd2d3„ƒZedd
œd4d5„ƒZd6dd7œd8d9„Zdd
œd:d;„Zdd
œd<d=„Zdd
œd>d?„Zddd@dAœdBdC„Z dDS )Er+   aô  
    Function minimum view.

    This object provides detailed metadata about the function minimum. Inspect this to
    check what exactly happened if the fit did not converge. Use the attribute
    :attr:`iminuit.Minuit.fmin` to get the best fit values, their uncertainties, or the
    function value at the minimum. For convenience, you can also get a basic OK from
    :class:`iminuit.Minuit` with the methods :attr:`iminuit.Minuit.valid` and
    :attr:`iminuit.Minuit.accurate`.

    See Also
    --------
    :attr:`iminuit.Minuit.values`
    :attr:`iminuit.Minuit.errors`
    :attr:`iminuit.Minuit.merrors`
    :attr:`iminuit.Minuit.covariance`
    :attr:`iminuit.Minuit.fval`
    :attr:`iminuit.Minuit.valid`
    :attr:`iminuit.Minuit.accurate`
    )
Ú_srcÚ
_algorithmÚ_has_parameters_at_limitÚ_nfcnÚ_ngradÚ_ng2Ú	_nhessianÚ_ndofÚ	_edm_goalÚ_timer   rr   r>   r�   )	ÚfminÚ	algorithmÚnfcnÚngradÚng2ÚnhessianÚndofÚedm_goalÚtimec
                 C  s°   || _ || _d| _|jD ]h}
|
js|
js*q|
j}|
j}|
jrB|
j	nt
j }|
jrV|
jnt
j}|  jt|| || ƒd| k O  _q|| _|| _|| _|| _|| _|| _|	| _d S )NFrÒ   )rå   ræ   rç   r¨   rš   Ú
has_limitsrU   r’   r¡   r¢   rm   r£   r¤   r¥   Úminrè   ré   rê   rë   rì   rí   rî   )rB   rï   rð   rñ   rò   ró   rô   rõ   rö   r÷   Úmprg   ÚeZlbZubrC   rC   rD   rE   Ò  s$    
&zFMin.__init__rF   c                 C  s   | j S )z<Get algorithm that was used to compute the function minimum.)ræ   rM   rC   rC   rD   rð   ó  s    zFMin.algorithmc                 C  s   | j jS )aÂ  
        Get Estimated Distance to Minimum.

        Minuit uses this criterion to determine whether the fit converged. It depends
        on the gradient and the Hessian matrix. It measures how well the current
        second order expansion around the function minimum describes the function, by
        taking the difference between the predicted (based on gradient and Hessian)
        function value at the minimum and the actual value.
        )rå   ÚedmrM   rC   rC   rD   rü   ø  s    zFMin.edmc                 C  s   | j S )zŸ
        Get EDM threshold value for stopping the minimization.

        The threshold is allowed to be violated by a factor of 10 in some situations.
        )rí   rM   rC   rC   rD   rö     s    zFMin.edm_goalc                 C  s   | j jS )z'Get cost function value at the minimum.)rå   ÚfvalrM   rC   rC   rD   rý     s    z	FMin.fvalc                 C  s2   t  | j¡r,| jdkr,| jdkr,| j| j S t jS )uÂ   
        Get Ï‡Â²/ndof of the fit.

        This returns NaN if the cost function is unbinned, errordef is not 1,
        or if the cost function does not report the degrees of freedom.
        r   rŠ   )rm   Úisfiniterì   Úerrordefrý   ÚnanrM   rC   rC   rD   Úreduced_chi2  s     zFMin.reduced_chi2rj   c                 C  s   | j S )zó
        Return whether any bounded parameter was fitted close to a bound.

        The estimated error for the affected parameters is usually off. May be an
        indication to remove or loosen the limits on the affected parameter.
        )rç   rM   rC   rC   rD   Úhas_parameters_at_limit  s    zFMin.has_parameters_at_limitc                 C  s   | j S )z$Get number of function calls so far.)rè   rM   rC   rC   rD   rñ   )  s    z	FMin.nfcnc                 C  s   | j S )z$Get number of gradient calls so far.)ré   rM   rC   rC   rD   rò   .  s    z
FMin.ngradc                 C  s   | j S )zGet number of g2 calls so far.)rê   rM   rC   rC   rD   ró   3  s    zFMin.ng2c                 C  s   | j S )z#Get number of hessian calls so far.)rë   rM   rC   rC   rD   rô   8  s    zFMin.nhessianc                 C  s   | j j}|r| jdk rdS |S )a”  
        Return whether Migrad converged successfully.

        For it to return True, the following conditions need to be fulfilled:

          - :attr:`has_reached_call_limit` is False
          - :attr:`is_above_max_edm` is False

        Note: The actual verdict is computed inside the Minuit2 C++ code, so we
        cannot guarantee that is_valid is exactly equivalent to these conditions.
        r   F)rå   Úis_validrü   )rB   ZvalidrC   rC   rD   r  =  s    zFMin.is_validc                 C  s   | j S )zŽ
        Return whether parameters are valid.

        This is the same as :attr:`is_valid` and only kept for backward compatibility.
        )r  rM   rC   rC   rD   Úhas_valid_parametersO  s    zFMin.has_valid_parametersc                 C  s   | j jS )aî  
        Return whether the covariance matrix is accurate.

        While Migrad runs, it computes an approximation to the current Hessian
        matrix. If the strategy is set to 0 or if the fit did not converge, the
        inverse of this approximation is returned instead of the inverse of the
        accurately computed Hessian matrix. This property returns False if the
        approximation has been returned instead of an accurate matrix computed by
        the Hesse method.
        )rå   Úhas_accurate_covarrM   rC   rC   rD   r  X  s    zFMin.has_accurate_covarc                 C  s   | j jS )aŠ  
        Return whether the Hessian matrix is positive definite.

        This must be the case if the extremum is a minimum, otherwise it is a saddle
        point. If it returns False, the fitted result may be correct, but the reported
        uncertainties are false. This may affect some parameters or all of them.
        Possible causes:

            * Model contains redundanted parameters that are 100% correlated. Fix:
              remove the parameters that are 100% correlated.
            * Cost function is not computed in double precision. Fix: try adjusting
              :attr:`iminuit.Minuit.precision` or change the cost function to compute
              in double precision.
            * Cost function is not analytical near the minimum. Fix: change the cost
              function to something analytical. Functions are not analytical if:

                * It does computations based on (pseudo)random numbers.
                * It contains vertical steps, for example from code like this::

                      if cond:
                          return value1
                      else:
                          return value2
        )rå   Úhas_posdef_covarrM   rC   rC   rD   r  f  s    zFMin.has_posdef_covarc                 C  s   | j jS )as  
        Return whether the matrix was forced to be positive definite.

        While Migrad runs, it computes an approximation to the current Hessian matrix.
        It can happen that this approximation is not positive definite, but that is
        required to compute the next Newton step. Migrad then adds an appropriate
        diagonal matrix to enforce positive definiteness.

        If the fit has converged successfully, this should always return False. If
        Minuit forced the matrix to be positive definite, the parameter uncertainties
        are false, see :attr:`has_posdef_covar` for more details.
        )rå   Úhas_made_posdef_covarrM   rC   rC   rD   r  ‚  s    zFMin.has_made_posdef_covarc                 C  s   | j jS )z-Return whether the last call to Hesse failed.)rå   Úhesse_failedrM   rC   rC   rD   r  ’  s    zFMin.hesse_failedc                 C  s   | j jS )zà
        Return whether a covariance matrix was computed at all.

        This is false if the Simplex minimization algorithm was used instead of
        Migrad, in which no approximation to the Hessian is computed.
        )rå   Úhas_covariancerM   rC   rC   rD   r	  —  s    zFMin.has_covariancec                 C  s   | j jS )zŸ
        Return whether the EDM value is below the convergence threshold.

        Returns True, if the fit did not converge; otherwise returns False.
        )rå   Úis_above_max_edmrM   rC   rC   rD   r
  ¡  s    zFMin.is_above_max_edmc                 C  s   | j jS )zÇ
        Return whether Migrad exceeded the allowed number of function calls.

        Returns True true, the fit was stopped before convergence was reached;
        otherwise returns False.
        )rå   Úhas_reached_call_limitrM   rC   rC   rD   r  ª  s    zFMin.has_reached_call_limitc                 C  s   | j jS )zFEqual to the value of :attr:`iminuit.Minuit.errordef` when Migrad ran.)rå   rÿ   rM   rC   rC   rD   rÿ   ´  s    zFMin.errordefc                 C  s   | j S )zRuntime of the last algorithm.)rî   rM   rC   rC   rD   r÷   ¹  s    z	FMin.timeri   rk   c                   s>   t ˆ tƒstS dddddœdd„‰t‡ ‡‡fdd„ˆjD ƒƒS )	z(Return True if all attributes are equal.rr   ri   rj   )r}   ro   rp   rG   c                 S  s:   t || ƒ}t || ƒ}t|tƒr2t |¡r2t |¡S ||kS rA   )r·   ra   r�   rm   Úisnan)r}   ro   rp   rC   rC   rD   Úrelaxed_equalÃ  s
    


z"FMin.__eq__.<locals>.relaxed_equalc                 3  s   | ]}ˆ|ˆˆ ƒV  qd S rA   rC   r½   ©rl   r  rB   rC   rD   r»   Ê  r^   zFMin.__eq__.<locals>.<genexpr>)ra   r+   rQ   rn   r…   )rB   rl   rC   r  rD   rq   ¾  s    
zFMin.__eq__c                 C  sL   d}t t| ƒƒD ].}| d¡r qt| |ƒ}|d|› d|›�7 }q|d7 }|S )rs   z<FMinÚ_ru   rv   rw   )ÚsortedÚdirÚ
startswithr·   )rB   r|   rY   r©   rC   rC   rD   r~   Ì  s    

zFMin.__repr__c                 C  s
   t  | ¡S rØ   )r   rï   rM   rC   rC   rD   r×   ×  s    zFMin.__str__c                 C  s
   t  | ¡S rA   )r   rï   rM   rC   rC   rD   rÜ   Û  s    zFMin._repr_html_rS   ©r¦   rà   rG   c                 C  s"   |r|  d¡ n|  t| ƒ¡ d S )Nz
<FMin ...>rÝ   rß   rC   rC   rD   rá   Þ  s    zFMin._repr_pretty_N)!ry   r‚   rƒ   r„   r…   rE   Úpropertyrð   rü   rö   rý   r  r  rñ   rò   ró   rô   r  r  r  r  r  r  r	  r
  r  rÿ   r÷   rq   r~   r×   rÜ   rá   rC   rC   rC   rD   r+   ¯  sd   !			r+   c                   @  s¬   e Zd ZU dZded< ded< ded< ded< d	ed
< ded< ded< ded< ded< ddœdd„Zedd„ ƒZedd„ ƒZedd„ ƒZ	ddœdd„Z
ddddœdd „Zd!S )"r,   z#Data object for a single Parameter.r>   Únumberrr   rÐ   r�   rU   r’   úOptional[Tuple[float, float]]Úmerrorrj   Zis_constrš   zOptional[float]r¢   r¥   rF   c                 C  s@   g }t | ƒ ¡ D ]\}}| |› d|›�¡ qdd |¡ d S )rs   rv   zParam(z, ú))r%   ÚitemsrÎ   Újoin)rB   Úpairsr}   rg   rC   rC   rD   r~   ó  s    zParam.__repr__c                 C  s   | j p
| jS )z8Query whether the parameter has an lower or upper limit.)r¡   r¤   rM   rC   rC   rD   rø   ú  s    zParam.has_limitsc                 C  s
   | j duS )z*Query whether parameter has a lower limit.N)r¢   rM   rC   rC   rD   r¡   ÿ  s    zParam.has_lower_limitc                 C  s
   | j duS )z+Query whether parameter has an upper limit.N)r¥   rM   rC   rC   rD   r¤     s    zParam.has_upper_limitc                 C  s   t  | g¡S rØ   ©r   ÚparamsrM   rC   rC   rD   r×   	  s    zParam.__str__r   rS   r  c                 C  s"   |r|  d¡ n|  t| ƒ¡ d S )Nz
Param(...)rÝ   rß   rC   rC   rD   rá     s    zParam._repr_pretty_N)ry   r‚   rƒ   r„   Ú__annotations__r~   r  rø   r¡   r¤   r×   rá   rC   rC   rC   rD   r,   å  s&   



r,   c                      sš   e Zd ZdZdZddœdd„Zddœdd	„Zed
ddœdd„ƒZedddœdd„ƒZedddœdd„ƒZdddœ‡ fdd„Zddœdd„Z	dd„ Z
‡  ZS )r-   z,Tuple-like holder of parameter data objects.rC   rr   rF   c                 C  s
   t  | ¡S rA   )r   r  rM   rC   rC   rD   rÜ     s    zParams._repr_html_z!Tuple[List[List[str]], List[str]]c              	   C  sÊ   g d¢}g }t | ƒD ]¬\}}|j}||g}|j}|rVtj|j|jg|¢R Ž \}}	}
}nt |j|j¡\}}	d}
d}|||	|
||jdurŽ|j› nd|jdur¢|j› nd|j	r®dndg7 }| 
|¡ q||fS )a  
        Convert parameter data to a tabular format.

        The output is consumable by the external
        `tabulate <https://pypi.org/project/tabulate>`_ module.

        Examples
        --------
        >>> import tabulate as tab
        >>> from iminuit import Minuit
        >>> m = Minuit(lambda x, y: x ** 2 + (y / 2) ** 2 + 1, x=0, y=0)
        >>> m.fixed["x"] = True
        >>> m.migrad().minos()
        >>> tab.tabulate(*m.params.to_table())
          pos  name      value    error  error-    error+    limit-    limit+    fixed
        -----  ------  -------  -------  --------  --------  --------  --------  -------
            0  x             0      0.1                                          yes
            1  y             0      1.4  -1.0      1.0
        )	ÚposrÐ   rU   r’   zerror-zerror+zlimit-zlimit+ÚfixedÚ NÚyes)r€   rÐ   r  r   Z
pdg_formatrU   r’   r¢   r¥   rš   rÎ   )rB   ÚheaderrÏ   rK   rú   rÐ   ÚrowÚmer©   rª   ZmelZmeurC   rC   rD   rÑ     s,    "ù	zParams.to_tabler    r,   rX   c                 C  s   d S rA   rC   ©rB   rY   rC   rC   rD   rd   R  s    zParams.__getitem__rÀ   ztuple[Param, ...]c                 C  s   d S rA   rC   r&  rC   rC   rD   rd   U  s    c                 C  s   d S rA   rC   r&  rC   rC   rD   rd   X  s    zstr | SupportsIndex | slicezParam | tuple[Param, ...]c                   sF   t |tƒr6t| ƒD ]\}}|j|kr|} q6qt|ƒ‚tt| ƒ |¡S )ú;Get item at key, which can be an index or a parameter name.)ra   rr   r€   rÐ   ÚKeyErrorrž   r-   rd   )rB   rY   rK   r¦   rŸ   rC   rD   rd   [  s    

c                 C  s
   t  | ¡S rØ   r  rM   rC   rC   rD   r×   h  s    zParams.__str__c                 C  s"   |r|  d¡ n|  t| ƒ¡ d S )NzParams(...)rÝ   rß   rC   rC   rD   rá   l  s    zParams._repr_pretty_)ry   r‚   rƒ   r„   r…   rÜ   rÑ   r   rd   r×   rá   r­   rC   rC   rŸ   rD   r-     s   6r-   c                   @  sÆ   e Zd ZU dZded< ded< ded< ded< d	ed
< d	ed< d	ed< d	ed< d	ed< d	ed< d	ed< ded< ded< ded< ded< ddœdd„Zddœdd„Zddœdd„Zdd	ddœdd „Zd!S )"r.   a*  
    Minos data object.

    Attributes
    ----------
    number : int
        Parameter index.
    name : str
        Parameter name.
    lower : float
        Lower error.
    upper : float
        Upper error.
    is_valid : bool
        Whether Minos computation was successful.
    lower_valid : bool
        Whether downward scan was successful.
    upper_valid : bool
        Whether upward scan was successful.
    at_lower_limit : bool
        Whether scan reached lower limit.
    at_upper_limit : bool
        Whether scan reached upper limit.
    at_lower_max_fcn : bool
        Whether allowed number of function evaluations was exhausted.
    at_upper_max_fcn : bool
        Whether allowed number of function evaluations was exhausted.
    lower_new_min : float
        Parameter value for new minimum, if one was found in downward scan.
    upper_new_min : float
        Parameter value for new minimum, if one was found in upward scan.
    nfcn : int
        Number of function calls.
    min : float
        Function value at the new minimum.
    r>   r  rr   rÐ   r�   ÚlowerÚupperrj   r  Zlower_validZupper_validZat_lower_limitZat_upper_limitZat_lower_max_fcnZat_upper_max_fcnZlower_new_minZupper_new_minrñ   rù   rF   c                 C  s:   d}t | ƒ ¡ D ]\}}|d|› d|›�7 }q|d7 }|S )rs   z<MErrorru   rv   rw   )r%   r  r{   rC   rC   rD   r~   ª  s
    zMError.__repr__c                 C  s   t  d| i¡S )rÙ   N©r   ÚmerrorsrM   rC   rC   rD   r×   ²  s    zMError.__str__c                 C  s   t  d | i¡S rA   ©r   r,  rM   rC   rC   rD   rÜ   ¶  s    zMError._repr_html_r   rS   r  c                 C  s"   |r|  d¡ n|  t| ƒ¡ d S )Nz<MError ...>rÝ   rß   rC   rC   rD   rá   ¹  s    zMError._repr_pretty_N)	ry   r‚   rƒ   r„   r  r~   r×   rÜ   rá   rC   rC   rC   rD   r.   s  s(   
%r.   c                   @  sV   e Zd ZdZdZddœdd„Zddœdd„Zddœd	d
„Zdd„ Zdddœdd„Z	dS )r/   z9Dict-like map from parameter name to Minos result object.rC   rr   rF   c                 C  s
   t  | ¡S rA   r-  rM   rC   rC   rD   rÜ   Å  s    zMErrors._repr_html_c                 C  s    dd  dd„ |  ¡ D ƒ¡ d S )rs   z<MErrors
  z,
  c                 s  s   | ]}t |ƒV  qd S rA   )rÚ   ©r\   rŒ   rC   rC   rD   r»   Ê  r^   z#MErrors.__repr__.<locals>.<genexpr>z
>)r  ÚvaluesrM   rC   rC   rD   r~   È  s    zMErrors.__repr__c                 C  s
   t  | ¡S rØ   r+  rM   rC   rC   rD   r×   Ì  s    zMErrors.__str__c                 C  s"   |r|  d¡ n|  t| ƒ¡ d S )Nz<MErrors ...>rÝ   rß   rC   rC   rD   rá   Ð  s    zMErrors._repr_pretty_zUnion[SupportsIndex, str]r.   rX   c                 C  sš   t |tƒsŽzt |¡}W n" ty:   td|›�ƒd‚Y n0 |dk rP|t| ƒ7 }|dk sd|t| ƒkrltdƒ‚t| ƒD ]\}}||krt|} qŽqtt 	| |¡S )r'  z.key must be an integer or parameter name, not Nr   zindex out of range)
ra   rr   Úoperatorrc   r²   rI   Ú
IndexErrorr€   r   rd   )rB   rY   rc   rK   r}   rC   rC   rD   rd   Ö  s$    
ÿþzMErrors.__getitem__N)
ry   r‚   rƒ   r„   r…   rÜ   r~   r×   rá   rd   rC   rC   rC   rD   r/   À  s   r/   z0use jacobi.propagate instead from jacobi libraryr   zCollection[float]zCollection[Collection[float]]zTuple[NDArray, NDArray])ÚfnrŒ   ÚcovrG   c                 C  sÈ   ddl m} t |¡}t |¡dkr,tdƒ‚t |¡}|jd |jd krRtdƒ‚d}t |¡| d }t 	|dk¡s~td	ƒ‚| |ƒ}t ||| |ƒ¡}	t 
d
|	|	|¡}
|t |¡dkrÂt |
¡n|
fS )a†  
    Numerically propagates the covariance into a new space.

    This function is deprecated and will be removed. Please use jacobi.propagate from
    the jacobi library, which is more accurate. The signatures of the two functions are
    compatible, so it is a drop-in replacement.

    Parameters
    ----------
    fn: callable
        Vectorized function that computes y = fn(x).
    x: array-like with shape (N,)
        Input vector.
    cov: array-like with shape (N, N)
        Covariance matrix of input vector.

    Returns
    -------
    y, ycov
        y is the result of fn(x)
        ycov is the propagated covariance matrix.
    r   )Úapprox_fprimer“   zcov must be 2D array-likerŠ   zcov must have shape (N, N)g»½×Ùß|Û=rÒ   z;diagonal elements of covariance matrix must be non-negativezij,kl,jl)Zscipy.optimizer4  rm   Z
atleast_1dr@   re   Ú
atleast_2dr¹   rÔ   rn   ZeinsumZsqueeze)r2  rŒ   r3  r4  ZvxZvcovÚtolÚdxÚyZjacZycovrC   rC   rD   Ú	propagateí  s    

r9  c                   @  s$   e Zd Zdd„ Zdd„ Zdd„ ZdS )Ú_Timerc                 C  s   |r
|j nd| _d S )Ng        )r÷   rU   )rB   rï   rC   rC   rD   rE     s    z_Timer.__init__c                 C  s   |  j tƒ 8  _ d S rA   ©rU   r#   rM   rC   rC   rD   Ú	__enter__  s    z_Timer.__enter__c                 G  s   |  j tƒ 7  _ d S rA   r;  ©rB   rã   rC   rC   rD   Ú__exit__"  s    z_Timer.__exit__N)ry   r‚   rƒ   rE   r<  r>  rC   rC   rC   rD   r:    s   r:  zŽUse of ``func_code`` attribute to declare parameters is deprecated. Use ``_parameters`` instead, which is a dict of parameter names to limits.zCollection[str]r   )r  rG   c                 C  s   t t| ƒt| ƒd�S )zš
    Make a func_code object to fake a function signature.

    Example::

        def f(a, b): ...

        f.func_code = make_func_code(["x", "y"])
    )Úco_varnamesÚco_argcount)r   r±   rI   )r  rC   rC   rD   r0   &  s    r0   rr   )ÚcallableÚvarnamesÚreplacementsrG   c           	        s–   t ˆ dd�‰ˆr|tˆƒ}t|ƒ}|t|ƒkr4tdƒ‚||d|…< | ¡ D ]\}}| |¡}|||< qH‡fdd„t|ˆƒD ƒ‰G ‡ fdd„dƒ}|ˆƒS )	aÍ  
    Return new callable with altered signature.

    Parameters
    ----------
    callable:
        Original callable with positional arguments, whose names shall be changed.
    *varnames: sequence of str
        Replace the first N argument names with these.
    **replacements: mapping of str to str, optional
        Replace old argument name (key) with new argument name (value).

    Returns
    -------
    Callable with positional-only arguments.
    Tr   z'varnames longer than original signatureNc                   s   i | ]\}}|ˆ | “qS rC   rC   )r\   ÚnewÚold)ÚparsrC   rD   r   T  r^   z'make_with_signature.<locals>.<dictcomp>c                      s(   e Zd Zdd„ Zdddœ‡ fdd„ZdS )z#make_with_signature.<locals>.Callerc                 S  s
   || _ d S rA   )Ú_parameters)rB   r¯   rC   rC   rD   rE   W  s    z,make_with_signature.<locals>.Caller.__init__r   )rã   rG   c                   s   ˆ |Ž S rA   rC   r=  ©rA  rC   rD   Ú__call__Z  s    z,make_with_signature.<locals>.Caller.__call__N)ry   r‚   rƒ   rE   rI  rC   rH  rC   rD   ÚCallerV  s   rJ  )r3   rb   rI   re   r  rc   rf   )	rA  rB  rC  rã   r¶   rE  rD  rK   rJ  rC   )rA  rF  rD   r1   7  s    

r1   FzIterable[Callable]rj   zTuple[Any, List[List[int]]])Ú	callablesr   rG   c           
      C  s¶   g }g }g }| D ]€}g }t |dd� ¡ D ]\\}}||v rb| |¡}	| |	¡ ||	 du r„|||	< q(| t|ƒ¡ | |¡ | |¡ q(| |¡ q|r®dd„ t||ƒD ƒ|fS ||fS )a  
    Merge signatures of callables with positional arguments.

    This is best explained by an example::

        def f(x, y, z): ...

        def g(x, p): ...

        parameters, mapping = merge_signatures(f, g)
        # parameters is ('x', 'y', 'z', 'p')
        # mapping is ([0, 1, 2], [0, 3])

    Parameters
    ----------
    callables :
        Callables whose parameters can be extracted with :func:`describe`.
    annotations : bool, optional
        Whether to return the annotions. Default is False, for backward
        compatibility.

    Returns
    -------
    tuple(parameters, mapping)
        parameters is the tuple of the merged parameter names.
        mapping contains the mapping of parameters indices from the merged signature to
        the original signatures.
    Tr   Nc                 S  s   i | ]\}}||“qS rC   rC   )r\   r}   ro   rC   rC   rD   r   “  r^   z$merge_signatures.<locals>.<dictcomp>)r3   r  rc   rÎ   rI   rf   )
rK  r   rã   ÚannsÚmappingÚfZamapr}   ÚannrK   rC   rC   rD   r2   `  s$    



r2   z	List[str])rA  rG   c                 C  s   d S rA   rC   rH  rC   rC   rD   r3   —  s    r3   z(Dict[str, Optional[Tuple[float, float]]])rA  r   rG   c                C  s   d S rA   rC   )rA  r   rC   rC   rD   r3   ›  s    c                C  sL   t | ƒdkr|ri S g S t| di ƒp:t| ƒp:t| ƒp:t| ƒ}|rD|S t|ƒS )a°  
    Attempt to extract the function argument names and annotations.

    Parameters
    ----------
    callable : callable
        Callable whose parameter names should be extracted.
    annotations : bool, optional
        Whether to also extract annotations. Default is false.

    Returns
    -------
    list or dict
        If annotate is False, return list of strings with the parameters names if
        successful and an empty list otherwise. If annotations is True, return a dict,
        which maps parameter names to annotations. For parameters without annotations,
        the dict maps to None.

    Notes
    -----
    Parameter names are extracted with the following three methods, which are attempted
    in order. The first to succeed determines the result.

    1.  Using ``obj._parameters``, which is a dict that maps parameter names to
        parameter limits or None if the parameter has to limits. Users are encouraged
        to use this mechanism to provide signatures for objects that otherwise would
        not have a detectable signature. Example::

            def f(*args):  # no signature
                x, y = args
                return (x - 2) ** 2 + (y - 3) ** 2

            f._parameters = {"x": None, "y": (1, 4)}

        Here, the first parameter is declared to have no limits (values from minus to
        plus infinity are allowed), while the second parameter is declared to have
        limits, it cannot be smaller than 1 or larger than 4.

        Note: In the past, the ``func_code`` attribute was used for a similar purpose as
        ``_parameters``. It is still supported for legacy code, but should not be used
        anymore in new code, since it does not support declaring parameter limits.

        If an objects has a ``func_code`` attribute, it is used to detect the
        parameters. Example::

            from iminuit.util import make_func_code

            def f(*args): # no signature
                x, y = args
                return (x - 2) ** 2 + (y - 3) ** 2

            # deprecated, make_func_code will raise a warning
            f.func_code = make_func_code(("x", "y"))

    2.  Using :func:`inspect.signature`. The :mod:`inspect` module provides a general
        function to extract the signature of a Python callable. It works on most
        callables, including Functors like this::

            class MyLeastSquares:
                def __call__(self, a, b):
                    ...

        Limits are supported via annotations, using the Annotated type that was
        introduced in Python-3.9 and can be obtained from the external package
        typing_extensions in Python-3.8. In the following example, the second parameter
        has a lower limit at 0, because it must be positive::

            from typing import Annotated

            def my_cost_function(a: float, b: Annotated[float, 0:]):
                ...

        There are no standard annotations yet at the time of this writing. iminuit
        supports the annotations Gt, Ge, Lt, Le from the external package
        annotated-types, and interprets slice notation as limits.

    3.  Using the docstring. The docstring is textually parsed to detect the parameter
        names. This requires that a docstring is present which follows the Python
        standard formatting for function signatures. Here is a contrived example which
        is parsed correctly: fn(a, b: float, int c, d=1, e: float=2.2, double e=3).

    Ambiguous cases with positional and keyword argument are handled in the following
    way::

        def fcn(a, b, *args, **kwargs): ...
        # describe returns [a, b];
        # *args and **kwargs are ignored

        def fcn(a, b, c=1): ...
        # describe returns [a, b, c];
        # positional arguments with default values are detected

        def fcn(a, b, *, c=1): ...
        # describe returns [a, b];
        # keyword-only arguments are ignored, since the function is called
        # with positional arguments only
    r   rG  )Ú_address_of_cfuncr·   Ú_describe_impl_func_codeÚ_describe_impl_inspectÚ_describe_impl_docstringrb   )rA  r   rã   rC   rC   rD   r3   ¡  s    bÿþüc                 C  s.   t | dƒr*| j}dd„ |jd |j… D ƒS i S )NÚ	func_codec                 S  s   i | ]
}|d “qS rA   rC   r.  rC   rC   rD   r     r^   z,_describe_impl_func_code.<locals>.<dictcomp>)ÚhasattrrT  r?  r@  )rA  ÚfcrC   rC   rD   rQ    s    
rQ  c                 C  s†   zt  | ¡}W n ty$   i  Y S 0 i }|j ¡ D ]L\}}|jt jju rN q‚|jt jju r` q‚|jt jj	u rr q‚t
|jƒ||< q4|S rA   )ÚinspectÚ	signaturere   r¯   r  ÚkindÚ	ParameterÚVAR_POSITIONALÚVAR_KEYWORDÚKEYWORD_ONLYÚ
_get_limitÚ
annotation)rA  rX  ÚrrÐ   ZparrC   rC   rD   rR    s    
rR  c           
        s:  t  | ¡}|d u ri S z
| j}W n ty6   i  Y S 0 |d }| |¡}|dk rVi S |t|ƒ7 }d}d}t||d … ƒD ]6\}}|dkr”|d7 }n|dkr¤|d8 }|dkrz q²qzdd„ |||| …  d¡D ƒ}t  | ¡rè|dd … }z| 	d¡}	|d |	… }W n t
�y   Y n0 d	d	d
œdd„‰ ‡ fdd„|D ƒS )Nú(r   rŠ   r  c                 S  s   g | ]}|  d ¡‘qS )z [])Ústripr.  rC   rC   rD   r]   S  r^   z,_describe_impl_docstring.<locals>.<listcomp>ú,z*argsrr   )r|   rG   c                 S  sn   |   d¡}|dkr| d |… } |   d¡}|dkr@| d |…  ¡ S |  ¡ } |   d¡}|dkrj| |d …  ¡ S | S )Nrv   r   ú:ru   )Úfindrb  )r|   rK   rC   rC   rD   Úextracti  s    


z)_describe_impl_docstring.<locals>.extractc                   s   i | ]}|d krˆ |ƒd“qS )Ú*NrC   r.  ©rf  rC   rD   r   z  r^   z,_describe_impl_docstring.<locals>.<dictcomp>)rW  Úgetdocry   ÚAttributeErrorre  rI   r€   ÚsplitÚismethodrc   re   )
rA  ÚdocrÐ   ÚtokenrÁ   ZnbraceZichÚchr  rK   rC   rh  rD   rS  1  s>    




 

rS  z'Union[type, Annotated[float, Any], str]r  )r_  rG   c                 C  s<  ddl m} t| tƒr<zt| d |jƒ} W n ty:   Y n0 | tjj	krLd S t
| ƒtur\d S t| ƒ^}}tj }tj}|D ]¸}t|tƒrª|jd ur˜|j}|jd urz|j}qzt|tƒrÌt|ttfƒsÌ|\}}qzt|dd ƒ}t|dd ƒ}t|dd ƒ}	t|dd ƒ}
|d u�r
|}|d u�r|}|	d u�r&|	}|
d urz|
}qz||fS )Nr   )ÚtypingÚgtÚgeÚltÚle)Úiminuitrp  ra   rr   ÚevalÚ__dict__Ú	ExceptionrW  rZ  Úemptyr"   r   r!   rm   r£   rÀ   rÁ   rÂ   r   Úbytesr·   )r_  rp  r  Úconstraintsr)  r*  Úcrq  rr  rs  rt  rC   rC   rD   r^  }  sH    






r^  r�   )r©   rG   c                 C  s   | dkrdt | ƒ S dS )Nr   ç{®Gáz„?gš™™™™™¹?)Úabs)r©   rC   rC   rD   r˜   ·  s    r˜   zDict[str, int]rÀ   z	List[int])rµ   rY   rG   c                 C  sf   t |jtƒr| |j n|j}t |jtƒr2| |j n|j}t|||jƒ t| ƒ¡\}}}tt	|||ƒƒS rA   )
ra   rÁ   rr   rÂ   rÀ   rÃ   ÚindicesrI   rb   rH   )rµ   rY   rÁ   rÂ   rÃ   rC   rC   rD   Ú_key2index_from_slice»  s    r€  zUnion[str, int]c                 C  sF   t |tƒr| | S |}|dk r*|t| ƒ7 }|dk s>|t| ƒkrBt‚|S )Nr   )ra   rr   rI   r1  )rµ   rY   rK   rC   rC   rD   Ú_key2index_itemÂ  s    
r�  r	   zUnion[int, List[int]]c                   s–   ˆ du rt ttˆƒƒƒS tˆ tƒr,tˆˆ ƒS tˆ tƒsŒtˆ tƒrŒt ˆ ƒ‰ ˆ rztˆ d tt	j
fƒrz‡ fdd„ttˆƒƒD ƒ‰ ‡fdd„ˆ D ƒS tˆˆ ƒS )N.r   c                   s   g | ]}ˆ | r|‘qS rC   rC   r½   rÄ   rC   rD   r]   Ý  r^   z_key2index.<locals>.<listcomp>c                   s   g | ]}t ˆ |ƒ‘qS rC   )r�  r½   )rµ   rC   rD   r]   Þ  r^   )rb   rH   rI   ra   rÀ   r€  rr   r   rj   rm   rÅ   r�  )rµ   rY   rC   )rY   rµ   rD   r_   Í  s    

r_   )ÚfcnrG   c                 C  sV   ddl m}m}m}m}m}m} |||||ƒƒ}t| dd ƒ} t| |ƒrR|| |ƒj	S dS )Nr   )Úc_void_pÚc_doubleÚc_uint32ÚPOINTERÚ	CFUNCTYPEÚcastÚctypes)
r‰  rƒ  r„  r…  r†  r‡  rˆ  r·   ra   rU   )r‚  rƒ  r„  r…  r†  r‡  Zctypes_castZc_sigrC   rC   rD   rP  â  s     	
rP  c                 c  s&   t | tƒs| V  n| D ]
}|V  qd S rA   )ra   r   )rŒ   ÚxirC   rC   rD   Ú_iterateô  s    
r‹  zOptional[T])rŒ   rg   rG   c                 C  s   | d u r|S | S rA   rC   )rŒ   rg   rC   rC   rD   Ú_replace_noneü  s    rŒ  c                   @  sV   e Zd ZU dZdZded< ded< dd„ Zdd	„ Zd
d„ Zdd„ Z	dd„ Z
dd„ ZdS )ÚProgressBarzZ
    Simple progress bar.

    Renders as nice HTML progressbar in Jupyter notebooks.
    r   r>   rU   Ú	max_valuec                 C  s(   | j  dd| d›d�¡ | j  ¡  d S )Núéd   ú.0fú %©Ú_outÚwriteÚflush)rB   ZfractionrC   rC   rD   Ú_update  s    zProgressBar._updatec                 C  s   | j  d¡ | j  ¡  d S )Nz     r“  rM   rC   rC   rD   Ú_finish  s    zProgressBar._finishc                   s²   || _ tj| _z€t ¡ �( t dt¡ ddlm	} W d  ƒ n1 sF0    Y  t
| j|ƒrŒddlm‰m‰  ‡ ‡fdd„| _‡ ‡fdd„| _W n ty    Y n0 |  | j¡ dS )	z„
        Initialize bar.

        Parameters
        ----------
        max_value: int
            Total number of entries.
        Úignorer   )Ú	OutStreamN)ÚdisplayÚHTMLc                   s*   ˆˆ dd|  d›dd|  d›d�ƒdd�S )Nz<progress value='r�  r‘  z' max='100'></progress> r’  T©ÚclearrC   )rg   ©rœ  r›  rC   rD   Ú<lambda>*  s   ÿÿûz&ProgressBar.__init__.<locals>.<lambda>c                     s   ˆˆ dƒdd�S )Nr!  Tr�  rC   rC   rŸ  rC   rD   r   1  r^   )rŽ  ÚsysÚstdoutr”  r–   Úcatch_warningsÚsimplefilterÚDeprecationWarningZipykernel.iostreamrš  ra   ÚIPython.displayr›  rœ  r—  r˜  ÚModuleNotFoundErrorrU   )rB   rŽ  rš  rC   rŸ  rD   rE     s    	
*zProgressBar.__init__c                 G  s   | S )zNoop.rC   r=  rC   rC   rD   r<  7  s    zProgressBar.__enter__c                 G  s   |   ¡  dS )zClean up the bar.N)r˜  r=  rC   rC   rD   r>  ;  s    zProgressBar.__exit__c                 C  s$   |  j |7  _ |  | j | j ¡ | S )zIncrement progress.)rU   r—  rŽ  )rB   rg   rC   rC   rD   Ú__add__?  s    zProgressBar.__add__N)ry   r‚   rƒ   r„   rU   r  r—  r˜  rE   r<  r>  r¨  rC   rC   rC   rD   r�    s   
"r�  c                 C  s¸   |j dksJ ‚| d u r ||fgS g }d}d}d}t| ƒ}||k r´| | sR|d7 }q8|d }||k rt| | rt|d7 }qZ| |||| | … |||d … f¡ ||| 7 }|d }q8|S )NrŠ   r   )r@   rI   rÎ   )ÚmaskZxeZmaskedÚsegmentsro   rp   Úamr¶   rC   rC   rD   Ú_histogram_segmentsF  s&    

*
r¬  é   ç{®Gázt?é
   c                   sö  t ƒ }t |||¡}| |ƒ}	t |	¡}
t |	¡}dd„ t||	ƒD ƒ‰ |d d… }|dd … }d}t|ƒ�rØ|d7 }||kr¤d|› dtˆ ƒ› d�}tj|t	d	d
� �qØt ƒ | |krÜd|› dtˆ ƒ› d�}tj|t	d	d
� �qØd||  }| |ƒ}	t|
t |	¡ƒ}
t|t |	¡ƒ}t||	ƒD ]\}}|ˆ |< �qdt 
‡ fdd„|D ƒt¡t 
‡ fdd„|D ƒt¡  }t |	| ¡}t || ¡}||||
  k||t|| ƒ k@ }|| }|| }|| }t ||¡}t ||¡}q`tˆ  ¡ ƒ}| ¡  t |¡S )Nc                 S  s   i | ]\}}||“qS rC   rC   )r\   rŠ  ÚyirC   rC   rD   r   d  r^   z#_smart_sampling.<locals>.<dictcomp>éÿÿÿÿrŠ   r   zIteration limit z% in smart sampling reached, produced z pointsr“   r”   zTime limit rÒ   c                 3  s   | ]}ˆ | V  qd S rA   rC   )r\   Zai©r8  rC   rD   r»     r^   z"_smart_sampling.<locals>.<genexpr>c                 3  s   | ]}ˆ | V  qd S rA   rC   )r\   Zbir²  rC   rD   r»   €  r^   )r#   rm   Zlinspacerù   Úmaxrf   rI   r–   r—   ÚRuntimeWarningZfromiterr�   r~  rÎ   rb   r  ÚsortZ	transpose)rN  ZxminZxmaxrÁ   r6  ÚmaxiterZmaxtimeÚt0rŒ   ZynewZyminZymaxro   rp   ZniterÚmsgZxnewrŠ  r°  ZyintZdyr7  r©  ZxyrC   r²  rD   Ú_smart_sampling^  s^    


ÿÿÿÿÿÿ$r¹  r   )rŒ   rG   c                 C  sh   t  | ¡} | d dkrdS t  | ¡}t  t  | ¡¡}t  |¡t  |¡ }t  |¡t  |¡ }t||k ƒS )Nr   F)rm   rµ  ÚdiffÚlogZstdÚmeanrj   )rŒ   Zd_linZd_logZlin_rel_stdZlog_rel_stdrC   rC   rD   Ú_detect_log_spacing“  s    

r½  r   zOptional[CostVector]c                 C  s
   t | dƒS )a”  
    Return a callable which computes the gradient of fcn or None.

    Parameters
    ----------
    fcn: Cost
        Cost function which may provide a callable gradient. How the gradient
        is detected is specified below in the Notes.

    Notes
    -----
    This function checks whether the following attributes exist: `fcn.grad` and
    `fcn.has_grad`. If `fcn.grad` exists and and satisfies the
    :class:`iminuit.typing.CostVector` protocol, it is returned unless `fcn.has_grad`
    exists and is False. If no useable gradient is detected, None is returned.

    Returns
    -------
    callable or None
        The gradient function or None
    Zgrad©Ú_cost_extra_impl©r‚  rC   rC   rD   r4   Ÿ  s    r4   c                 C  s
   t | dƒS )a˜  
    Return a callable which computes the diagonal of the Hessian of fcn or None.

    Parameters
    ----------
    fcn: Cost
        Cost function which may provide a callable g2 function. How the g2
        is detected is specified below in the Notes.

    Notes
    -----
    This function checks whether the following attributes exist: `fcn.g2` and
    `fcn.has_g2`. If `fcn.g2` exists and and satisfies the
    :class:`iminuit.typing.CostVector` protocol, it is returned unless `fcn.has_g2` exists
    and is False. If no useable gradient is detected, None is returned.

    Returns
    -------
    callable or None
        The gradient function or None
    r5   r¾  rÀ  rC   rC   rD   r5   ¸  s    r5   c                 C  s
   t | dƒS )a¦  
    Return a callable which computes the Hessian matrix of fcn or None.

    Parameters
    ----------
    fcn: Cost
        Cost function which may provide a callable Hessian function. How the Hessian
        is detected is specified below in the Notes.

    Notes
    -----
    This function checks whether the following attributes exist: `fcn.hessian` and
    `fcn.has_hessian`. If `fcn.hessian` exists and satisfies the
    :class:`iminuit.typing.CostVector` protocol, it is returned unless `fcn.has_grad`
    exists and is False. If no useable gradient is detected, None is returned.

    Returns
    -------
    callable or None
        The gradient function or None
    r6   r¾  rÀ  rC   rC   rD   r6   Ñ  s    r6   )r‚  rY  rG   c                 C  s8   t | |d ƒ}t | d|› �dƒ}|r4t|tƒr4|r4|S d S )NZhas_T)r·   ra   r   )r‚  rY  ZauxZhas_auxrC   rC   rD   r¿  ê  s
    r¿  r   )ÚmrG   c                 C  s\   t  | ¡} t  | j| k¡rXzt j | ¡}W n t jjyB   Y dS 0 tt  t  |¡¡ƒS dS )aE  
    Return True if argument is a positive definite matrix.

    This test is somewhat expensive, because we attempt a cholesky decomposition.

    Parameters
    ----------
    m : array-like
        Matrix to be tested.

    Returns
    -------
    bool
        True if matrix is positive definite and False otherwise.
    F)	rm   r5  rn   r&   ZlinalgZcholeskyZLinAlgErrorrj   rþ   )rÁ  ZllrC   rC   rD   r7   ò  s    
r7   rF   c               	   C  sJ   z,ddl m}  | ƒ }|du r"W dS | d¡W S  ttfyD   Y dS 0 dS )z)Return True if we are running in Jupyter.r   )Úget_ipythonNFZkernel)ZIPythonrÂ  Z	has_traitr§  ÚImportError)rÂ  ÚiprC   rC   rD   r8     s    r8   )ÚmodulerG   c                 C  s,   zt j | ¡duW S  ty&   Y dS 0 dS )z%Return True if a module is available.NF)Ú	importlibÚutilÚ	find_specr§  )rÅ  rC   rC   rD   r9     s    r9   c                 C  s.   | dk rdnd}t | ƒtjkr*|tjj S | S )Nr   r±  rŠ   )r~  rm   r£   r¡  Ú
float_infor³  )rŒ   ÚsignrC   rC   rD   Ú_make_finite&  s    rË  )r©   ÚvminÚvmaxrG   c                 C  s$   t  |¡r t  |¡r d||  S dS )Nr}  )rm   rþ   )r©   rÌ  rÍ  rC   rC   rD   Ú_widget_guess_initial_step-  s    rÎ  )F)r­  r®  r­  r¯  )hr„   Ú
__future__r   rW  r0  Úimportlib.utilrÆ  Úcollectionsr   Úargparser   ru  r   r   r   Ziminuit.typingr	   r
   r   r   Ziminuit.warningsr   r   r   Únumpyrm   Znumpy.typingr   r   rp  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r†   r÷   r#   r–   r¡  Údataclassesr$   r%   r&   Ú__all__ÚABCr:   r=   r'   r‘   r(   r)   r§   rÇ   r*   r+   r,   r±   r-   r.   r/   Ú
deprecatedr9  r:  r0   r1   r2   r3   rQ  rR  rS  r^  r˜   r€  r�  r_   rP  r‹  rŒ  r�  r¬  r¹  r½  r4   r5   r6   r¿  r7   r8   r9   rË  rÎ  rC   rC   rC   rD   Ú<module>   s˜   LR
' '  8._L--ÿ* ÿ7r	L:C
5
