a
    5gh{                 
   @  s^  d Z ddl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mZmZmZmZmZmZmZmZ ddlmZ ddl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% dd	l&m'Z'm(Z(m)Z) dd
l*m+Z+ ddl,m-Z- de_.dgZ/G dd dZ0dddddddZ1ddddddZ2G dd dZ3G dd dZ4dd Z5d dd!d"d#d$d!d%d&d'	d(d)Z6dS )*zMinuit class.    annotationsN)util)_replace_none)FCN
MnContoursMnHesseMnMachinePrecisionMnMigradMnMinosMnPrint	MnSimplex
MnStrategyMnUserParameterStateFunctionMinimum)ErrordefAlreadySetWarning)UnionOptionalCallableTupleListDictIterableAny
CollectionSetSized)	UserBoundCostCostGradient)optional_module_for)	ArrayLikeMinuitc                   @  s  e Zd ZU dZdZded< ded< dZ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jdddddZedd
dd Zejdddd!d Zedd
d"d#Zejdddd$d#Zed%d
d&d'Zejd(ddd)d'Zed(d
d*d+Zejd(dd,d-d+Zed.d
d/d0Zejd.ddd1d0Zed2d
d3d4Zejd5dd6d7d4Zed8d
d9d:Zejd5dd6d;d:Zed<d
d=d>Zejd5dd6d?d>Zed@d
dAdBZejd5dd6dCdBZedDd
dEdFZedd
dGdHZed(d
dIdJZed(d
dKdLZed(d
dMdNZedd
dOdPZedd
dQdRZedSd
dTdUZ edSd
dVdWZ!ed.d
dXdYZ"ed.d
dZd[Z#ed(d
d\d]Z$ed(d
d^d_Z%d`d`dadbdcdddeddfdgdhZ&didjdkdldmdnZ'dkd
dodpZ(ddsd(d.dkdtdudvZ)ddsdkdwdxdyZ*ddsdkdwdzd{Z+dd|dsd}d}d5d~dkdddZ,dddddZ-ddsdkdwddZ.d`d`ddddsdkdddZ/ddd`dddqdrddd(ddd.d(d(d.dd	ddZ0drdrddd.d.ddddZ1ddd`dddd(ddd.ddddZ2drdrddd.d.ddddZ3d(ddd.d.ddddZ4ddd`ddddd(ddd.ddddZ5ddddddZ6d`dddddqdrddddd(d(d.d(d(d.dd
ddZ7d`dddddddcd(d(d.d}dddZ8d`ddd`ddcd(d.d}dddZ9dddddZ:dd
ddZ;dd
ddĄZ<dddƜddȄZ=dddd̜dd΄Z>ddЄ Z?dd
dd҄Z@ddd
ddԄZAd(d
ddքZBd.d
dd؄ZCddڄ ZDdd܄ ZEddބ ZFdd ZGdd ZHdd(d(d(d(d(d.ddddZId`S )r"   z&Function minimizer and error computer.)_fcn	_strategy
_tolerance
_precision_values_errors_merrors_fixed_limits_fmin_covariance_var2pos_pos2var_init_state_last_statezOptional[mutil.FMin]r,   zOptional[mutil.Matrix]r-         ?      ?r   returnc                 C  s   | j S )zCGet cost function (usually a least-squares or likelihood function).)r#   self r8   ^/mounts/lovelace/software/anaconda3/envs/metaDMG/lib/python3.9/site-packages/iminuit/minuit.pyfcnK   s    z
Minuit.fcnz"Callable[[np.ndarray], np.ndarray]c                 C  s   | j jS )z+Get gradient function of the cost function.)r#   gradientr6   r8   r8   r9   gradP   s    zMinuit.gradTuple[str, ...]c                 C  s   | j S )zMap variable index to name.r/   r6   r8   r8   r9   pos2varU   s    zMinuit.pos2varzDict[str, int]c                 C  s   | j S )zMap variable name to index.)r.   r6   r8   r8   r9   var2posZ   s    zMinuit.var2posc                 C  s   | j S )z^
        Get tuple of parameter names.

        This is an alias for :attr:`pos2var`.
        r>   r6   r8   r8   r9   
parameters_   s    zMinuit.parametersfloatc                 C  s   | j jS )a  
        Access FCN increment above minimum that corresponds to one standard deviation.

        Default value is 1.0. `errordef` should be 1.0 for a least-squares cost function
        and 0.5 for a negative log-likelihood function. See section 1.5.1 on page 6 of
        the :download:`MINUIT2 User's Guide <mnusersguide.pdf>`. This parameter is also
        called *UP* in MINUIT documents.

        If FCN has an attribute ``errordef``, its value is used automatically and you
        should not set errordef by hand. Doing so will raise a
        ErrordefAlreadySetWarning.

        For the builtin cost functions in :mod:`iminuit.cost`, you don't need to set
        this value, because they all have the ``errordef`` attribute set.

        To make user code more readable, we provided two named constants::

            m_lsq = Minuit(a_least_squares_function)
            m_lsq.errordef = Minuit.LEAST_SQUARES  # == 1

            m_nll = Minuit(a_likelihood_function)
            m_nll.errordef = Minuit.LIKELIHOOD     # == 0.5
        )r#   	_errordefr6   r8   r8   r9   errordefh   s    zMinuit.errordefNone)valuer5   c                 C  sd   t | jjdd }|d ur0d| d}t|t |dkrHtd| d|| j_| jr`|| jj_	d S )NrD   z1cost function has an errordef attribute equal to z3, you should not override this with Minuit.errordefr   z	errordef=z must be a positive number)
getattrr#   warningswarnr   
ValueErrorrC   r,   _srcrD   )r7   rF   Zfcn_errordefmsgr8   r8   r9   rD      s    
Optional[float]c                 C  s   | j S )a  
        Access estimated precision of the cost function.

        Default: None. If set to None, Minuit assumes the cost function is computed in
        double precision. If the precision of the cost function is lower (because it
        computes in single precision, for example) set this to some multiple of the
        smallest relative change of a parameter that still changes the function.
        )r&   r6   r8   r8   r9   	precision   s    
zMinuit.precisionc                 C  s"   |d ur|dkst d|| _d S )Nr   z+precision must be a positive number or None)rJ   r&   r7   rF   r8   r8   r9   rN      s    c                 C  s   | j S )a  
        Access tolerance for convergence with the EDM criterion.

        Minuit detects converge with the EDM criterion. EDM stands for *Estimated
        Distance to Minimum*, it is mathematically described in the `MINUIT paper`_.
        The EDM criterion is well suited for statistical cost functions,
        since it stops the minimization when parameter improvements become small
        compared to parameter uncertainties.

        The convergence is detected when `edm < edm_max`, where `edm_max` is calculated
        as

            * Migrad: edm_max = 0.002 * tol * errordef
            * Simplex: edm_max = tol * errordef

        Users can set `tol` (default: 0.1) to a different value to either speed up
        convergence at the cost of a larger error on the fitted parameters and possibly
        invalid estimates for parameter uncertainties or smaller values to get more
        accurate parameter values, although this should never be necessary as the
        default is fine.

        If the tolerance is set to a very small value or zero, Minuit will use an
        internal lower limit for the tolerance. To restore the default use, one can
        assign `None`.

        Under some circumstances, Migrad is allowed to violate edm_max by a factor of
        10. Users should not try to detect convergence by comparing edm with edm_max,
        but query :attr:`iminuit.util.FMin.is_above_max_edm`.
        )r%   r6   r8   r8   r9   tol   s    z
Minuit.tolc                 C  s(   |d u rd}n|dk rt d|| _d S )Ng?r   ztolerance must be non-negative)rJ   r%   rO   r8   r8   r9   rP      s
    r   c                 C  s   | j S )a  
        Access current minimization strategy.

        You can assign an integer:

        - 0: Fast. Does not check a user-provided gradient. Does not improve Hesse
          matrix at minimum. Extra call to :meth:`hesse` after :meth:`migrad` is always
          needed for good error estimates. If you pass a user-provided gradient to
          MINUIT, convergence is **faster**.
        - 1: Default. Checks user-provided gradient against numerical gradient. Checks
          and usually improves Hesse matrix at minimum. Extra call to :meth:`hesse`
          after :meth:`migrad` is usually superfluous. If you pass a user-provided
          gradient to MINUIT, convergence is **slower**.
        - 2: Careful. Like 1, but does extra checks of intermediate Hessian matrix
          during minimization. The effect in benchmarks is a somewhat improved accuracy
          at the cost of more function evaluations. A similar effect can be achieved by
          reducing the tolerance :attr:`tol` for convergence at any strategy level.
        )r$   r6   r8   r8   r9   strategy   s    zMinuit.strategyintc                 C  s   || j _d S N)r$   rQ   rO   r8   r8   r9   rQ      s    c                 C  s   t jS )a  
        Access current print level.

        You can assign an integer:

        - 0: quiet (default)
        - 1: print minimal debug messages to terminal
        - 2: print more debug messages to terminal
        - 3: print even more debug messages to terminal

        Warnings
        --------
        Setting print_level has the unwanted side-effect of setting the level
        globally for all Minuit instances in the current Python session.
        r   global_levelr6   r8   r8   r9   print_level   s    zMinuit.print_level)levelr5   c                 C  s
   |t _d S rS   rT   )r7   rW   r8   r8   r9   rV      s    boolc                 C  s   | j jS )z
        Access whether to raise runtime error if the function evaluates to NaN.

        If you set this to True, an error is raised whenever the function evaluates
        to NaN.
        r#   Z
_throw_nanr6   r8   r8   r9   	throw_nan   s    zMinuit.throw_nanc                 C  s   || j _d S rS   rY   rO   r8   r8   r9   rZ     s    zmutil.ValueViewc                 C  s   | j S )a  
        Access parameter values via an array-like view.

        Use to read or write current parameter values based on the parameter index
        or the parameter name as a string. If you change a parameter value and run
        :meth:`migrad`, the minimization will start from that value, similar for
        :meth:`hesse` and :meth:`minos`.

        See Also
        --------
        errors, fixed, limits
        r'   r6   r8   r8   r9   values  s    zMinuit.valuesr   argsr5   c                 C  s   || j d d < d S rS   r[   r7   r^   r8   r8   r9   r\     s    zmutil.ErrorViewc                 C  s   | j S )a  
        Access parameter parabolic errors via an array-like view.

        Like :attr:`values`, but instead of reading or writing the values, you read
        or write the errors (which double as step sizes for MINUITs numerical gradient
        estimation). Only positive values are accepted when assigning to errors.

        See Also
        --------
        values, fixed, limits
        r(   r6   r8   r8   r9   errors   s    zMinuit.errorsc                 C  s   || j d d < d S rS   r`   r_   r8   r8   r9   ra   /  s    zmutil.FixedViewc                 C  s   | j S )av  
        Access whether parameters are fixed via an array-like view.

        Use to read or write the fixation state of a parameter based on the parameter
        index or the parameter name as a string. If you change the state and run
        :meth:`migrad`, :meth:`hesse`, or :meth:`minos`, the new state is used.

        In case of complex fits, it can help to fix some parameters first and only
        minimize the function with respect to the other parameters, then release the
        fixed parameters and minimize again starting from that state.

        See Also
        --------
        values, errors, limits
        r*   r6   r8   r8   r9   fixed3  s    zMinuit.fixedc                 C  s   || j d d < d S rS   rb   r_   r8   r8   r9   rc   F  s    zmutil.LimitViewc                 C  s   | j S )at  
        Access parameter limits via a array-like view.

        Use to read or write the limits of a parameter based on the parameter index
        or the parameter name as a string. If you change the limits and run
        :meth:`migrad`, :meth:`hesse`, or :meth:`minos`, the new state is used.

        In case of complex fits, it can help to limit some parameters first, run Migrad,
        then remove the limits and run Migrad again. Limits will bias the result only if
        the best fit value is outside the limits, not if it is inside. Limits will
        affect the estimated Hesse uncertainties if the parameter is close to a limit.
        They do not affect the Minos uncertainties, because those are invariant to
        transformations and limits are implemented via a variable transformation.

        See Also
        --------
        values, errors, fixed
        r+   r6   r8   r8   r9   limitsJ  s    zMinuit.limitsc                 C  s   || j d d < d S rS   rd   r_   r8   r8   r9   re   `  s    mutil.MErrorsc                 C  s   | j S )z
        Return a dict-like with Minos data objects.

        The Minos data objects contain the full status information of the Minos run.

        See Also
        --------
        util.MError
        util.MErrors
        )r)   r6   r8   r8   r9   merrorsd  s    zMinuit.merrorsc                 C  s   | j S )a  
        Return covariance matrix.

        The square-root of the diagonal elements of the covariance matrix correspond to
        a standard deviation for each parameter with 68 % coverage probability in the
        asymptotic limit (large samples). To get k standard deviations, multiply the
        covariance matrix with k^2.

        The submatrix formed by two parameters describes an ellipse. The asymptotic
        coverage probabilty of the standard ellipse is lower than 68 %. It can be
        computed from the :math:`\chi^2` distribution with 2 degrees of freedom. In
        general, to obtain a (hyper-)ellipsoid with coverage probability CL, one has to
        multiply the submatrix of the corresponding k parameters with a factor. For k =
        1,2,3 and CL = 0.99 ::

            from scipy.stats import chi2

            chi2(1).ppf(0.99) # 6.63...
            chi2(2).ppf(0.99) # 9.21...
            chi2(3).ppf(0.99) # 11.3...

        See Also
        --------
        util.Matrix
        )r-   r6   r8   r8   r9   
covariancer  s    zMinuit.covariancec                 C  s
   t | jS )zGet number of parameters.)lenr1   r6   r8   r8   r9   npar  s    zMinuit.nparc                 C  s   | j t| j S )z?Get number of fitted parameters (fixed parameters not counted).)rj   sumrc   r6   r8   r8   r9   nfit  s    zMinuit.nfitc                 C  s   | j  | j S )a  
        Get number of degrees of freedom if cost function supports this.

        To support this feature, the cost function has to report the number of data
        points with a property called ``ndata``. Unbinned cost functions should return
        infinity.
        )r#   Z_ndatarl   r6   r8   r8   r9   ndof  s    	zMinuit.ndofc                 C  s   | j S )zh
        Get function minimum data object.

        See Also
        --------
        util.FMin
        )r,   r6   r8   r8   r9   fmin  s    	zMinuit.fminc                 C  s   | j }|r|jS dS )z
        Get function value at minimum.

        This is an alias for :attr:`iminuit.util.FMin.fval`.

        See Also
        --------
        util.FMin
        N)r,   fval)r7   fmr8   r8   r9   ro     s    zMinuit.fvalmutil.Paramsc                 C  s   t | j| jS )z
        Get list of current parameter data objects.

        See Also
        --------
        init_params, util.Params
        )_get_paramsr1   r)   r6   r8   r8   r9   params  s    	zMinuit.paramsc                 C  s   t | jt S )z
        Get list of current parameter data objects set to the initial fit state.

        See Also
        --------
        params, util.Params
        )rr   r0   mutilMErrorsr6   r8   r8   r9   init_params  s    	zMinuit.init_paramsc                 C  s   | j r| j jS dS )z
        Return True if the function minimum is valid.

        This is an alias for :attr:`iminuit.util.FMin.is_valid`.

        See Also
        --------
        util.FMin
        F)r,   is_validr6   r8   r8   r9   valid  s    zMinuit.validc                 C  s   | j r| j jS dS )z
        Return True if the covariance matrix is accurate.

        This is an alias for :attr:`iminuit.util.FMin.has_accurate_covar`.

        See Also
        --------
        util.FMin
        F)r,   Zhas_accurate_covarr6   r8   r8   r9   accurate  s    zMinuit.accuratec                 C  s   | j jS )z#Get total number of function calls.)r#   _nfcnr6   r8   r8   r9   nfcn  s    zMinuit.nfcnc                 C  s   | j jS )z#Get total number of gradient calls.)r#   _ngradr6   r8   r8   r9   ngrad  s    zMinuit.ngradN)r<   namer   zUnion[float, ArrayLike]zUnion[CostGradient, bool, None]zCollection[str])r:   r^   r<   r~   kwdsc          
        s(  d}t |dkr2t|d tr2d}t|d }n
t|}~tj|dd |du rt }t |dksx|rt |dkrtdd t	t |D }n(t |t  kr fd	d
t
 |D  t |dkrt |dkrtd|rdd| dnd t|| _dd
 t|D | _d| _td| _|du r:t|}n6|du rbt|}|du rptdn|du rpd}|durt|tstdt|||t|dd| _t| j||| _t| | _t| | _t| | _ t!| | _"t|dd| _#| $   % D ]\}}	|	dur|	| j&|< qdS )a  
        Initialize Minuit object.

        This does not start the minimization or perform any other work yet. Algorithms
        are started by calling the corresponding methods.

        Parameters
        ----------
        fcn :
            Function to minimize. See notes for details on what kind of functions are
            accepted.
        *args :
            Starting values for the minimization as positional arguments.
            See notes for details on how to set starting values.
        grad : callable, bool, or None, optional
            If grad is a callable, it must be a function that calculates the gradient
            and returns an iterable object with one entry for each parameter, which is
            the derivative of `fcn` for that parameter. If None (default), Minuit will
            call the function :func:`iminuit.util.gradient` on `fcn`. If this function
            returns a callable, it will be used, otherwise Minuit will internally
            compute the gradient numerically. Please see the documentation of
            :func:`iminuit.util.gradient` how gradients are detected. Passing a boolean
            override this detection. If grad=True is used, a ValueError is raised if no
            useable gradient is found. If grad=False, Minuit will internally compute the
            gradient numerically.
        name : sequence of str, optional
            If it is set, it overrides iminuit's function signature detection.
        **kwds :
            Starting values for the minimization as keyword arguments.
            See notes for details on how to set starting values.

        Notes
        -----
        *Callables*

        By default, Minuit assumes that the callable `fcn` behaves like chi-square
        function, meaning that the function minimum in repeated identical random
        experiments is chi-square distributed up to an arbitrary additive constant. This
        is important for the correct error calculation. If `fcn` returns a
        log-likelihood, one should multiply the result with -2 to adapt it. If the
        function returns the negated log-likelihood, one can alternatively set the
        attribute `fcn.errordef` = :attr:`Minuit.LIKELIHOOD` or :attr:`Minuit.errordef`
        = :attr:`Minuit.LIKELIHOOD` after initialization to make Minuit calculate errors
        properly.

        Minuit reads the function signature of `fcn` to detect the number and names of
        the function parameters. Two kinds of function signatures are understood.

        a) Function with positional arguments.

            The function has positional arguments, one for each fit
            parameter. Example::

                def fcn(a, b, c): ...

            The parameters a, b, c must accept a real number.

            iminuit automatically detects the parameters names in this case.
            More information about how the function signature is detected can
            be found in :func:`iminuit.util.describe`.

        b) Function with arguments passed as a single Numpy array.

            The function has a single argument which is a Numpy array.
            Example::

                def fcn_np(x): ...

            To use this form, starting values need to be passed to Minuit in form as
            an array-like type, e.g. a numpy array, tuple or list. For more details,
            see "Parameter Keyword Arguments" further down.

        In some cases, the detection fails, for example, for a function like this::

                def difficult_fcn(*args): ...

        To use such a function, set the `name` keyword as described further below.

        *Parameter initialization*

        Initial values for the minimization can be set with positional arguments or
        via keywords. This is best explained through an example::

            def fcn(x, y):
                return (x - 2) ** 2 + (y - 3) ** 2

        The following ways of passing starting values are equivalent::

            Minuit(fcn, x=1, y=2)
            Minuit(fcn, y=2, x=1) # order is irrelevant when keywords are used ...
            Minuit(fcn, 1, 2)     # ... but here the order matters

        Positional arguments can also be used if the function has no signature::

            def fcn_no_sig(*args):
                # ...

            Minuit(fcn_no_sig, 1, 2)

        If the arguments are explicitly named with the `name` keyword described
        further below, keywords can be used for initialization::

            Minuit(fcn_no_sig, x=1, y=2, name=("x", "y"))  # this also works

        If the function accepts a single Numpy array, then the initial values
        must be passed as a single array-like object::

            def fcn_np(x):
                return (x[0] - 2) ** 2 + (x[1] - 3) ** 2

            Minuit(fcn_np, (1, 2))

        Setting the values with keywords is not possible in this case. Minuit
        deduces the number of parameters from the length of the initialization
        sequence.

        See Also
        --------
        migrad, hesse, minos, scan, simplex, iminuit.util.gradient
        F   r   Tr   Nc                 s  s   | ]}d | V  qdS )xNr8   .0ir8   r8   r9   	<genexpr>      z"Minuit.__init__.<locals>.<genexpr>c                   s   i | ]\}}| | qS r8   r8   )r   oldnewZ	annotatedr8   r9   
<dictcomp>  r   z#Minuit.__init__.<locals>.<dictcomp>zstarting value(s) are requiredz for [ ] c                 S  s   i | ]\}}||qS r8   r8   )r   r   kr8   r8   r9   r     r   z:gradient enforced, but iminuit.util.gradient returned Nonez'provided gradient is not a CostGradientrD   r2   rN   )'ri   
isinstancer   nparrayrt   ZdescribelisttuplerangezipRuntimeErrorjoinr/   	enumerater.   rP   r   r$   r;   rJ   r   r   rG   r#   _make_init_stater0   Z	ValueViewr'   Z	ErrorViewr(   Z	FixedViewr*   Z	LimitViewr+   rN   resetitemsre   )
r7   r:   r<   r~   r^   r   Z
array_callstartr   limr8   r   r9   __init__  sh     









zMinuit.__init__z	mutil.KeyzUnion[float, Iterable[float]]z'Minuit')keyrF   r5   c                 C  s   t | j|}t|trt |dkr>|D ]}| || q*qt|tsLJ t|tsZJ t	|t	|krrt
dt||D ]\}}| || q|n| j| | j|| | S )a
  
        Fix parameter and set it to value.

        This is a convenience function to fix a parameter and set it to a value
        at the same time. It is equivalent to calling :attr:`fixed` and :attr:`values`.

        Parameters
        ----------
        key : int, str, slice, list of int or str
            Key, which can be an index, name, slice, or list of indices or names.
        value : float or sequence of float
            Value(s) assigned to key(s).

        Returns
        -------
        self
        r   z'length of argument does not match slice)rt   Z
_key2indexr.   r   r   Z_ndimfixtor   r   ri   rJ   r   r1   fix	set_value)r7   r   rF   indexr   vr8   r8   r9   r     s    
zMinuit.fixtoc                 C  s2   | j | _d| _d| j_d| j_t | _d| _	| S )z
        Reset minimization state to initial state.

        Leaves :attr:`strategy`, :attr:`precision`, :attr:`tol`, :attr:`errordef`,
        :attr:`print_level` unchanged.
        Nr   )
r0   r1   r,   r#   rz   r|   rt   ru   r)   r-   r6   r8   r8   r9   r     s    
zMinuit.reset   TzOptional[int])ncalliterateuse_simplexr5   c              
   C  s   |dk rt dt| j}|6 t| j| jt|d| j| j	| j
||}W d   n1 s\0    Y  |j| _t|d| j| j| j| jdd|j| _|   | S )a  
        Run Migrad minimization.

        Migrad from the Minuit2 library is a robust minimisation algorithm which earned
        its reputation in 40+ years of almost exclusive usage in high-energy physics.
        How Migrad works is described in the `Minuit paper`_. It uses first and
        approximate second derivatives to achieve quadratic convergence near the
        minimum.

        Parameters
        ----------
        ncall : int or None, optional
            Approximate maximum number of calls before minimization will be aborted.
            If set to None, use the adaptive heuristic from the Minuit2 library
            (Default: None). Note: The limit may be slightly violated, because the
            condition is checked only after a full iteration of the algorithm, which
            usually performs several function calls.
        iterate : int, optional
            Automatically call Migrad up to N times if convergence was not reached
            (Default: 5). This simple heuristic makes Migrad converge more often even if
            the numerical precision of the cost function is low. Setting this to 1
            disables the feature.
        use_simplex: bool, optional
            If we have to iterate, set this to True to call the Simplex algorithm before
            each call to Migrad (Default: True). This may improve convergence in
            pathological cases (which we are in when we have to iterate).

        See Also
        --------
        simplex, scan
        r   ziterate must be at least 1r   NZMigradTmigrad_factor)rJ   rt   _Timerr,   _robust_low_level_fitr#   r1   replace_noner$   r%   r&   stateFMinr{   r}   rm   	_edm_goalrF   _make_covariance)r7   r   r   r   trp   r8   r8   r9   migrad  s4    %"
	zMinuit.migrad)r   r5   c              	   C  s   t | j| j| j}| jdur$| j|_t| j}|" |t	|d| j
}W d   n1 s\0    Y  |j| _t|d| j| j| j|  |j| _d| _t | _| S )a  
        Run Simplex minimization.

        Simplex from the Minuit2 C++ library is a variant of the Nelder-Mead algorithm
        to find the minimum of a function. It does not make use of derivatives. `The
        Wikipedia has a good article on the Nelder-Mead method
        <https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method>`_.

        Parameters
        ----------
        ncall :
            Approximate maximum number of calls before minimization will be aborted.
            If set to None, use the adaptive heuristic from the Minuit2 library
            (Default: None). Note: The limit may be slightly violated, because the
            condition is checked only after a full iteration of the algorithm, which
            usually performs several function calls.

        Notes
        -----
        The Simplex method usually converges more slowly than Migrad, but performs
        better in certain cases, the Rosenbrock function is a notable example. Unlike
        Migrad, the Simplex method does not have quadratic convergence near the minimum,
        so it is a good approach to run Migrad after Simplex to obtain an accurate
        solution in fewer steps. Simplex may also be useful to get close to the minimum
        from an unsuitable starting point.

        The convergence criterion for Simplex is also based on EDM, but the threshold
        is much more lax than that of Migrad (see :attr:`Minuit.tol` for details).
        This was made so that Simplex stops early when getting near the minimum, to give
        the user a chance to switch to the more efficient Migrad algorithm to finish the
        minimization. Early stopping can be avoided by setting Minuit.tol to an
        accordingly smaller value, however.
        Nr   ZSimplex)r   r#   r1   rQ   r&   rN   rt   r   r,   r   r%   r   r   r{   r}   rm   r   rF   r-   ru   r)   )r7   r   simplexr   rp   r8   r8   r9   r   /  s&    "
0	
zMinuit.simplexc              	     s  j }|du r }t|d|  jjkr>tj_tjd tj	j< t
j t D ]j\}\}}j| }j| }j| r||f |< ql|tj	 kr|| n||tj	kr|| n|f |< qlddd fddtj}| d W d   n1 s$0    Y   }	tjjj|	}
|
j_t|
d	jjj|	|j_d_t _S )
a  
        Brute-force minimization.

        Scans the function on a regular hypercube grid, whose bounds are defined either
        by parameter limits if present or by Minuit.values +/- Minuit.errors.
        Minuit.errors are initialized to very small values by default, too small for
        this scan. They should be increased before running scan or limits should be set.
        The scan evaluates the function exactly at the limit boundary, so the function
        should be defined there.

        Parameters
        ----------
        ncall :
            Approximate number of function calls to spend on the scan. The
            actual number will be close to this, the scan uses ncall^(1/npar) steps per
            cube dimension. If no value is given, a heuristic is used to set ncall.

        Notes
        -----
        The scan can return an invalid minimum, this is not a cause for alarm. It just
        minimizes the cost function, the EDM value is only computed after the scan found
        a best point. If the best point still has a bad EDM value, the minimum is
        considered invalid. But even if it is considered valid, it is probably not
        accurate, since the tolerance is very lax. One should always run :meth:`migrad`
        after the scan.

        This implementation here does a full scan of the hypercube in Python.
        Originally, this was supposed to use MnScan from C++ Minuit2, but MnScan is
        unsuitable. It does a 1D scan with 41 steps (not configurable) for each
        parameter in sequence, so it is not actually scanning the full hypercube. It
        first scans one parameter, then starts the scan of the second parameter from the
        best value of the first and so on. This fails easily when the parameters are
        correlated.
        Nr   rR   rE   )iparr5   c                   s   | j krRd j  }|j  k rN|j < d j  jd d < d S  |  \}}||kr||| < | d  n(t||D ]}|| < | d  qd S )Nr   )rj   r#   r\   r   linspace)r   rlowupxiZlimsZnsteprunr7   r   r8   r9   r     s    

zMinuit.scan.<locals>.runr   ZScan) rl   _migrad_maxcallrR   r1   r0   r   r   emptyrj   infr   re   r   r\   ra   rc   rt   r   r,   r   r   r#   rQ   r   r   r{   r}   rm   rF   r-   ru   r)   )r7   r   nr   r   r   r   er   edm_goalrp   r8   r   r9   scani  sH    2




(	
zMinuit.scanzUnion[str, Callable]r   zOptional[Dict[str, Any]])methodr   hesshesspconstraintsoptionsr5   c           -        s  z ddl m}m}m}	m}
m} W n4 tyT } z| jd7  _ W Y d}~n
d}~0 0 |du rf }t	j
jdd td  t	
jdd t	 }|rG fddd}|}|}G fdd	d	}nLG  fd
dd}G dd d|}G dd d|}G  fdd	d	}|jj}jj}|r>||nd}|rP||}r^||dur@t|tr|tdt|ts|g}nt|}t|D ]\}}t||	r||j|_nzt||
r4|s< }d| < t	|j|}|j| }|j| }t	|jdd f }|
||||j||< ntdq }g }g }g }d}j D ]} | j!rnq^|| j"O }| j#du rt	j$ n| j#}!| j%du rt	j$n| j%}"|!dkr|!d|j& 9 }!n |!dk r|!d|j& 9 }!n|j&}!|"dkr|"d|j& 9 }"n"|"dk r|"d|j& 9 }"n|j& }"t	'| j(|!|"}#|)|! |)|" |)|# q^|du rx|rhd}n|rtd}nd}|pi }d}$d|vr||d< d}$|dv rd|vr||d< |$r|d= |dv rd|vr||d< |$r|d= |dv r|du rd}t*+j,}%|%> |||||r2|||ddnd||||d 	W d   n1 sZ0    Y  j-dkrxt. j j/d! 7  _/|rj j01d"d7  _0d}&d}'d#v rĈj2}&nd$v r؈j3}&d}'t4|&r |&dusJ |&t	5j6}&t|pt}(|&du rT|(rTrFfd%d&t	5j6D }&n
|j7}&d}'|'rft	j89|&}&|&du rt	:j6j6f}&d}j D ],} | j!rq| j;d' |&||f< |d7 }qd(v r̈j<})n6d)v rވj=})n$t	>t	?|&d* }*|j7||*d+})j@dd,}+tAjBjCj7|&|)jjD|+jE||(
},|,jF_Bt*G|,d-| d.jEjHjI|+|%j(_,|(rtJ  njKjKdkrL  S )/a+  
        Minimize with SciPy algorithms.

        Parameters
        ----------
        method : str or Callable, optional
            Which scipy method to use.
        ncall : int, optional
            Function call limit.
        hess : Callable, optional
            Function that computes the Hessian matrix. It must use the exact same
            calling conversion as the original fcn (several arguments which are numbers
            or a single array argument).
        hessp : Callable, optional
            Function that computes the product of the Hessian matrix with a vector.
            It must use the same calling conversion as the original fcn (several
            arguments which are numbers or a single array argument) and end with another
            argument which is an arbitrary vector.
        constraints : scipy.optimize.LinearConstraint or
                      scipy.optimize.NonlinearConstraint, optional
            Linear or non-linear constraints, see docs of
            :func:`scipy.optimize.minimize` look for the `constraints` parameter. The
            function used in the constraint must use the exact same calling convention
            as the original fcn, see hess parameter for details. No parameters may be
            omitted in the signature, even if those parameters are not used in the
            constraint.
        options : dict, optional
            A dictionary of solver options to pass to the SciPy minimizer through the
            `options` parameter of :func:`scipy.optimize.minimize`. See each solver
            method for the options it accepts.

        Notes
        -----
        The call limit may be violated since many algorithms checks the call limit only
        after a full iteraction of their algorithm, which consists of several function
        calls. Some algorithms do not check the number of function calls at all, in this
        case the call limit acts on the number of iterations of the algorithm. This
        issue should be fixed in scipy.

        The SciPy minimizers use their own internal rule for convergence. The EDM
        criterion is evaluated only after the original algorithm already stopped. This
        means that usually SciPy minimizers will use more iterations than Migrad and
        the tolerance :attr:`tol` has no effect on SciPy minimizers.

        You can specify convergence tolerance and other options for the SciPy minimizers
        through the `options` parameter. Note that providing the SciPy options
        `"maxiter"`, `"maxfev"`, and/or `"maxfun"` (depending on the minimizer) takes
        precedence over providing a value for `ncall`. If you want to explicitly control
        the number of iterations or function evaluations for a particular SciPy minimizer,
        you should provide values for all of its relevant options.
        r   )minimizeBoundsNonlinearConstraintLinearConstraintapprox_fprimez:

Please install scipy to use scipy minimizers in iminuit.NZdtypec                      s2   e Zd ZdZdd Z jjr&dd Zndd ZdS )Minuit.scipy.<locals>.Wrappedr:   c                 S  s
   || _ d S rS   r   r7   r:   r8   r8   r9   r   +  s    &Minuit.scipy.<locals>.Wrapped.__init__c                 S  s
   |  |S rS   r   r7   parr8   r8   r9   __call__0  s    &Minuit.scipy.<locals>.Wrapped.__call__c                 S  s
   | j | S rS   r   r   r8   r8   r9   r   5  s    N__name__
__module____qualname__	__slots__r   r:   Z_array_callr   r8   r6   r8   r9   Wrapped(  s
   
r   c                      s2   e Zd ZdZdd Z jjr&dd Zndd ZdS )"Minuit.scipy.<locals>.WrappedHesspr   c                 S  s
   || _ d S rS   r   r   r8   r8   r9   r   >  s    +Minuit.scipy.<locals>.WrappedHessp.__init__c                 S  s   |  ||S rS   r   r7   r   r   r8   r8   r9   r   C  s    +Minuit.scipy.<locals>.WrappedHessp.__call__c                 S  s   | j g ||R  S rS   r   r   r8   r8   r9   r   H  s    Nr   r8   r6   r8   r9   WrappedHessp;  s
   
r   c                      s8   e Zd ZdZ fddZjjr,dd Zndd ZdS )r   r:   freer   c                   s   || _  | _| _d S rS   r   r   cfreecparr8   r9   r   P  s    r   c                 S  s   || j | j< | | j S rS   r   r   r:   r   r8   r8   r9   r   W  s    r   c                 S  s   || j | j< | j| j  S rS   r   r   r8   r8   r9   r   ]  s    Nr   r8   r   r   r7   r8   r9   r   M  s
   
c                      s   e Zd Z fddZ  ZS )z!Minuit.scipy.<locals>.WrappedGradc                   s   t  |}t|| j S rS   )superr   r   Z
atleast_1dr   )r7   r   g	__class__r8   r9   r   b  s    z*Minuit.scipy.<locals>.WrappedGrad.__call__)r   r   r   r   __classcell__r8   r8   r   r9   WrappedGrada  s   r   c                      s(   e Zd Z fddZ fddZ  ZS )z!Minuit.scipy.<locals>.WrappedHessc                   s8   t  | t| j| j| _t| j}||f| _d S rS   )r   r   r   outerr   freemrk   shape)r7   r:   r   r   r8   r9   r   g  s    z*Minuit.scipy.<locals>.WrappedHess.__init__c                   s$   t  |}t|| j | jS rS   )r   r   r   
atleast_2dr   Zreshaper   )r7   r   hr   r8   r9   r   m  s    z*Minuit.scipy.<locals>.WrappedHess.__call__)r   r   r   r   r   r   r8   r8   r   r9   WrappedHessf  s   r   c                      s8   e Zd ZdZ fddZjjr,dd Zndd ZdS )r   )r:   r   r   vecc                   s$   || _  | _| _t| j| _d S rS   )r:   r   r   r   Z
zeros_liker   r   r   r8   r9   r   t  s    r   c                 S  s.   || j | j< || j| j< | | j | j| j S rS   r   r   r   r:   r   r8   r8   r9   r   |  s    r   c                 S  s6   || j | j< || j| j< | jg | j | jR  | j S rS   r   r   r8   r8   r9   r     s    Nr   r8   r   r8   r9   r   q  s
   
z/setting constraints with dicts is not supportedzqsetting constraints with dicts is not supported, use LinearConstraint or NonlinearConstraint from scipy.optimize.Fr   SLSQPL-BFGS-BZBFGSmaxiterT)zNelder-MeadZPowellZmaxfev)r   ZTNCZmaxfun)ZCOBYLAr   ztrust-constrr8   )keep_feasible)r   Zboundsjacr   r   r   r   ZnfevZnjevhess_invr   c                   s   g | ]} j |qS r8   )r   )r   ei)r   r   r8   r9   
<listcomp>$  r   z Minuit.scipy.<locals>.<listcomp>   r<   r   g|=)epsilonr   zSciPy[r   )Mscipy.optimizer   r   r   r   r   ModuleNotFoundErrorrL   r   r   r   rc   rX   r\   allr#   Z_gradr   dictrJ   r   r   r   ZfuncopydotAlbubr   r   _mnprecisionrs   is_fixed
has_limitslower_limitr   upper_limiteps2ZcliprF   appendrt   r   r,   rV   printrz   r|   getr   r   callableeyerl   r   linalginvZzeroserrorr<   r   sqrtZdiagr   r   r1   ZtraforD   r{   r   r   r}   rm   r   rQ   hesse)-r7   r   r   r   r   r   r   r   r   r   r   r   excZno_fixed_parametersr   r   r   r   r:   r<   r   cr   shiftr  r	  r  prr   lower_boundupper_boundr  pZaiZbir   Zadded_maxiterr   matrixZneeds_invertZaccurate_covarr   Zdxr   rp   r8   )r   r   r   r   r7   r9   scipy  s`   < 


















&












zMinuit.scipyr   )plotc                 K  s   |  || jfi |S )a  
        Visualize agreement of current model with data (requires matplotlib).

        This generates a plot of the data/model agreement, using the current
        parameter values, if the likelihood function supports this, otherwise
        AttributeError is raised.

        Parameters
        ----------
        plot : Callable, optional
            This function tries to call the visualize method on the cost function, which
            accepts the current model parameters as an array-like and potentially
            further keyword arguments, and draws a visualization into the current
            matplotlib axes. If the cost function does not provide a visualize method or
            if you want to override it, pass the function here.
        kwargs :
            Other keyword arguments are forwarded to the
            plot function.

        See Also
        --------
        Minuit.interactive
        )
_visualizer\   )r7   r#  kwargsr8   r8   r9   	visualize_  s    zMinuit.visualizec              	   C  s  | j dkr tjdtjdd | S |  rp| jdd}t| j| j	| j
|}t|d| j| j| j|d| _t | _| jdus~J | jj}t| j}t| j}|* || j|t|d| jj W d   n1 s0    Y  |j| _	t|| jj| j| j| j| jj|j| _|   | S )	am  
        Run Hesse algorithm to compute asymptotic errors.

        The Hesse method estimates the covariance matrix by inverting the matrix of
        `second derivatives (Hesse matrix) at the minimum
        <https://en.wikipedia.org/wiki/Hessian_matrix>`_. To get parameters correlations,
        you need to use this. The Minos algorithm is another way to estimate parameter
        uncertainties, see :meth:`minos`.

        Parameters
        ----------
        ncall :
            Approximate upper limit for the number of calls made by the Hesse algorithm.
            If set to None, use the adaptive heuristic from the Minuit2 library
            (Default: None).

        Notes
        -----
        The covariance matrix is asymptotically (in large samples) valid. By valid we
        mean that confidence intervals constructed from the errors contain the true
        value with a well-known coverage probability (68 % for each interval). In finite
        samples, this is likely to be true if your cost function looks like a
        hyperparabola around the minimum.

        In practice, the errors very likely have correct coverage if the results from
        Minos and Hesse methods agree. It is possible to construct artifical functions
        where this rule is violated, but in practice it should always work.

        See Also
        --------
        minos
        r   z&Hesse called with all parameters fixedr   )
stacklevelTr   ZExternalN)rl   rH   rI   rt   IMinuitWarning/_fmin_does_not_exist_or_last_state_was_modifiedr   r   r#   r1   r$   r   r{   r}   rm   r,   ru   r)   rK   r   rQ   r   r   r   r   	algorithmrF   r   )r7   r   r   rp   r  r   r8   r8   r9   r  y  sJ    #


8
zMinuit.hesse)clr   zUnion[int, str])rA   r+  r   r5   c                  s  t |dd}  r    jdus*J  jj} jsLtdt j t|dkrr fddt	 j
D }nFg }|D ]<} |\}}	 j| rtd|	tj qz|| qzt j}
|
 t j| t j| j}|D ]j} j| }||t|d j}t|j||j|j|j|j|j |j!|j"|j#|j$|j%|j&|j'|j( j)|< qW d   n1 sn0    Y  W d   n1 s0    Y   jr j' j_* j+ j_,|
j- j_. S )	a-
  
        Run Minos algorithm to compute confidence intervals.

        The Minos algorithm uses the profile likelihood method to compute (generally
        asymmetric) confidence intervals. It scans the negative log-likelihood or
        (equivalently) the least-squares cost function around the minimum to construct a
        confidence interval.

        Parameters
        ----------
        *parameters :
            Names of parameters to generate Minos errors for. If no positional
            arguments are given, Minos is run for each parameter.
        cl : float or None, optional
            Confidence level of the interval. If not set or None, a standard
            interval is computed (default). A standard interval has about 68.3 %
            confidence, which is the probability of being within one standard
            deviation around the mean of a normal distribution. If 0 < cl < 1,
            the value is interpreted as the confidence level (a probability).
            For convenience, values cl >= 1 are interpreted as the probability
            content of a central symmetric interval covering that many standard
            deviations of a normal distribution. For example, cl=1 is
            interpreted as about 68.3 %, and cl=2 as 84.3 %, and so on. Using
            values other than 0.68, 0.9, 0.95, 0.99, 1, 2, 3, 4, 5 require the
            scipy module.
        ncall : int or None, optional
            Limit the number of calls made by Minos. If None, an adaptive internal
            heuristic of the Minuit2 library is used (Default: None).

        Notes
        -----
        Asymptotically (large samples), the Minos interval has a coverage probability
        equal to the given confidence level. The coverage probability is the probability
        for the interval to contain the true value in repeated identical experiments.

        The interval is invariant to transformations and thus not distorted by parameter
        limits, unless the limits intersect with the confidence interval. As a
        rule-of-thumb: when the confidence intervals computed with the Hesse and Minos
        algorithms differ strongly, the Minos intervals are preferred. Otherwise, Hesse
        intervals are preferred.

        Running Minos is computationally expensive when there are many fit parameters.
        Effectively, it scans over one parameter in small steps and runs a full
        minimisation for all other parameters of the cost function for each scan point.
        This requires many more function evaluations than running the Hesse algorithm.
        r   r2   NFunction minimum is not valid: r   c                   s   g | ]} j | s|qS r8   rc   )r   r   r6   r8   r9   r     r   z Minuit.minos.<locals>.<listcomp>z!Cannot scan over fixed parameter )/_cl_to_errordefr)  r  r,   rK   rx   r   reprri   r   rj   _normalize_keyrc   rH   rI   rt   r(  r  r   _TemporaryErrordefr#   r   rQ   r/   r   r%   ZMErrornumberlowerupperrw   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{   minr)   rz   r}   r|   rF   _time)r7   r+  r   rA   factorrp   Ziparsr   ippnamer   minosr   mer8   r6   r9   r:    s^    4

L


zMinuit.minos   r   Fr   )sizeboundgridsubtract_minr   r   r   zUnion[float, UserBound]r!   z)Tuple[np.ndarray, np.ndarray, np.ndarray])	vnamer=  r>  r?  r@  r   r   r   r5   c             
   C  s   |  |\}	}
~|dur:tj|td}|jdkr\tdn"| |
|\}}tj|||td}t|}tj	t
|td}t| j}||	 td}t|D ]d\}}||	| t| j|||| j| j||}|jstd|
 d| tj |j||< |j||< q|r|t|8 }|||fS )a  
        Get Minos profile over a specified interval.

        Scans over one parameter and minimises the function with respect to all other
        parameters for each scan point.

        Parameters
        ----------
        vname : int or str
            Parameter to scan over.
        size : int, optional
            Number of scanning points (Default: 100). Ignored if grid is set.
        bound : tuple of float or float, optional
            If bound is tuple, (left, right) scanning bound.
            If bound is a number, it specifies an interval of N :math:`\sigma`
            symmetrically around the minimum (Default: 2). Ignored if grid is set.
        grid : array-like, optional
            Parameter values on which to compute the profile. If grid is set, size and
            bound are ignored.
        subtract_min : bool, optional
            If true, subtract offset so that smallest value is zero (Default: False).
        ncall : int, optional
            Approximate maximum number of calls before minimization will be aborted.
            If set to 0, use the adaptive heuristic from the Minuit2 library
            (Default: 0). Note: The limit may be slightly violated, because the
            condition is checked only after a full iteration of the algorithm, which
            usually performs several function calls.
        iterate : int, optional
            Automatically call Migrad up to N times if convergence was not reached
            (Default: 5). This simple heuristic makes Migrad converge more often even if
            the numerical precision of the cost function is low. Setting this to 1
            disables the feature.
        use_simplex: bool, optional
            If we have to iterate, set this to True to call the Simplex algorithm before
            each call to Migrad (Default: True). This may improve convergence in
            pathological cases (which we are in when we have to iterate).

        Returns
        -------
        array of float
            Parameter values where the profile was computed.
        array of float
            Profile values.
        array of bool
            Whether minimisation in each point succeeded or not.

        See Also
        --------
        profile, contour, mncontour
        Nr   r   grid must be 1D array-liker   zMIGRAD fails to converge for =)r0  r   r   rB   ndimrJ   _normalize_boundr   
empty_liker   ri   rX   r   r1   r   r   r   r   r   r#   r%   r&   rw   rH   rI   rt   r(  ro   r5  )r7   rA  r=  r>  r?  r@  r   r   r   r   r9  r   abystatusr   rQ   r   r   rp   r8   r8   r9   	mnprofile9  sD    >






zMinuit.mnprofile)bandtextzTuple[np.ndarray, np.ndarray])rA  rL  rM  r5   c          
      K  sJ   |  |\}}~d|vr d|d< | j|fi |\}}}	| |||||S )a  
        Draw Minos profile over a specified interval (requires matplotlib).

        See :meth:`mnprofile` for details and shared arguments. The following additional
        arguments are accepted.

        Parameters
        ----------
        vname: int or string
            Which variable to scan over, can be identified by index or name.
        band : bool, optional
            If true, show a band to indicate the Hesse error interval (Default: True).
        text : bool, optional
            If true, show text a title with the function value and the Hesse error
            (Default: True).
        **kwargs :
            Other keyword arguments are forwarded to :meth:`mnprofile`.

        Examples
        --------
        .. plot:: plots/mnprofile.py
            :include-source:

        See Also
        --------
        mnprofile, draw_profile, draw_contour, draw_mnmatrix
        r@  T)r0  rK  _draw_profile)
r7   rA  rL  rM  r%  r   r9  r   rI  _r8   r8   r9   draw_mnprofile  s    zMinuit.draw_mnprofiled   )r=  r>  r?  r@  )rA  r=  r>  r?  r@  r5   c                C  s   |  |\}}~|dur:tj|td}|jdkr\tdn"| ||\}	}
tj|	|
|td}t|}t| j	}t
|D ]\}}|||< | |||< qz|r|t|8 }||fS )a  
        Calculate 1D cost function profile over a range.

        A 1D scan of the cost function around the minimum, useful to inspect the
        minimum. For a fit with several free parameters this is not the same as the
        Minos profile computed by :meth:`mncontour`.

        Parameters
        ----------
        vname : int or str
            Parameter to scan over.
        size : int, optional
            Number of scanning points (Default: 100). Ignored if grid is set.
        bound : tuple of float or float, optional
            If bound is tuple, (left, right) scanning bound.
            If bound is a number, it specifies an interval of N :math:`\sigma`
            symmetrically around the minimum (Default: 2). Ignored if grid is set.
        grid : array-like, optional
            Parameter values on which to compute the profile. If grid is set, size and
            bound are ignored.
        subtract_min : bool, optional
            If true, subtract offset so that smallest value is zero (Default: False).

        Returns
        -------
        array of float
            Parameter values.
        array of float
            Function values.

        See Also
        --------
        mnprofile, contour, mncontour
        Nr   r   rB  )r0  r   r   rB   rD  rJ   rE  r   rF  r\   r   r#   r5  )r7   rA  r=  r>  r?  r@  r   r   r   rG  rH  rI  r\   r   vir8   r8   r9   profile  s     +


zMinuit.profilec          	      K  sH   |  |\}}~d|vr d|d< | j|fi |\}}| |||||S )a^  
        Draw 1D cost function profile over a range (requires matplotlib).

        See :meth:`profile` for details and shared arguments. The following additional
        arguments are accepted.

        Parameters
        ----------
        band : bool, optional
            If true, show a band to indicate the Hesse error interval (Default: True).

        text : bool, optional
            If true, show text a title with the function value and the Hesse error
            (Default: True).

        See Also
        --------
        profile, draw_mnprofile, draw_contour, draw_mncontourprofile
        r@  T)r0  rS  rN  )	r7   rA  rL  rM  r%  r   r9  r   rI  r8   r8   r9   draw_profile  s    zMinuit.draw_profile
np.ndarray)r   r   rI  rL  rM  r5   c                 C  s  ddl m} | j| }||| || |d | j| }|j|ddd d }	d }
|| jv r|| j| j	 }	|| j| j
 }
n|| j|  }	|| j|  }
|	d ur|r|j|	|
dd |r|j|	d u r| d	|d
nd||||	 |
| dd ||fS )Nr   pyplotr   r   --)colorZ	linestylez0.8)Z	facecolorz = z.3gz{} = {:.3g} - {:.3g} + {:.3g}Zlarge)Zfontsize)
matplotlibrW  r/   r#  xlabelylabelr\   axvlinerg   r3  r4  ra   Zaxvspantitleformat)r7   r   r   rI  rL  rM  pltr9  r   ZvminZvmaxr8   r8   r9   rN  %  s4    




zMinuit._draw_profile2   z+Union[float, Iterable[Tuple[float, float]]]zTuple[ArrayLike, ArrayLike])r   rI  r=  r>  r?  r@  r5   c                C  s  |  |\}}|  |\}	}
~~|durj|\}}tj|td}tj|td}|jdks`|jdkrtdnt|tr|\}}| ||}| |
|}n t|}| ||}| |
|}t|tr|\}}n|}|}t	|d |d |}t	|d |d |}tj
t|t|ftd}t| j}t|D ]@\}}|||< t|D ]$\}}|||	< | ||||f< qDq,|r|t|8 }|||fS )aT  
        Get a 2D contour of the function around the minimum.

        It computes the contour via a function scan over two parameters, while keeping
        all other parameters fixed. The related :meth:`mncontour` works differently: for
        each pair of parameter values in the scan, it minimises the function with the
        respect to all other parameters.

        This method is useful to inspect the function near the minimum to detect issues
        (the contours should look smooth). It is not a confidence region unless the
        function only has two parameters. Use :meth:`mncontour` to compute confidence
        regions.

        Parameters
        ----------
        x : int or str
            First parameter for scan.
        y : int or str
            Second parameter for scan.
        size : int or tuple of int, optional
            Number of scanning points per parameter (Default: 50). A tuple is
            interpreted as the number of scanning points per parameter.
            Ignored if grid is set.
        bound : float or tuple of floats, optional
            If bound is 2x2 array, [[v1min,v1max],[v2min,v2max]].
            If bound is a number, it specifies how many :math:`\sigma`
            symmetrically from minimum (minimum+- bound*:math:`\sigma`).
            (Default: 2). Ignored if grid is set.
        grid : tuple of array-like, optional
            Grid points to scan over. If grid is set, size and bound are ignored.
        subtract_min :
            Subtract minimum from return values (Default: False).

        Returns
        -------
        array of float
            Parameter values of first parameter.
        array of float
            Parameter values of second parameter.
        2D array of float
            Function values.

        See Also
        --------
        mncontour, mnprofile, profile
        Nr   r   z(grid per parameter must be 1D array-liker   )r0  r   r   rB   rD  rJ   r   r   rE  r   r   ri   r\   r   r#   r5  )r7   r   rI  r=  r>  r?  r@  ixxnameiyynamexgZygZxvZyvxbZybxrangeZyranger   ZxsizeZysizeZzvr\   r   r   jyir8   r8   r9   contourS  sB    8



zMinuit.contour)r   rI  r5   c                   s   ddl m}  |\}} |\}}~~d|vr<d|d<  j||fi |\}	}
} fddtdD }||	|
|j|}||| || || |j	 j
| dd	d
 |j j
| dd	d
 |	|
|fS )aW  
        Draw 2D contour around minimum (requires matplotlib).

        See :meth:`contour` for details on parameters and interpretation. Please also
        read the docs of :meth:`mncontour` to understand the difference between the two.

        See Also
        --------
        contour, draw_mncontour, draw_profile, draw_mnmatrix
        r   rV  r@  Tc                   s   g | ]} j |d   qS )r   )rD   r   r6   r8   r9   r     r   z'Minuit.draw_contour.<locals>.<listcomp>   r   rX  )rY  Zls)rZ  rW  r0  rk  r   Tclabelr[  r\  axhliner\   r]  )r7   r   rI  r%  r`  rb  rc  rd  re  ZvxZvyZvzr   CSr8   r6   r9   draw_contour  s     

zMinuit.draw_contour)r+  r=  interpolatedexperimentalr   r   r   )
r   rI  r+  r=  rr  rs  r   r   r   r5   c             	   C  s  |  |\}
}|  |\}}~~t|dd}|  r<|   | jsVtdt| j ||h|   }|rxt	d| |r| 
||
|||||	}n^t| j|B | jdusJ t| j| jj| j}||
||d }W d   n1 s0    Y  t|}tj||dd dd}||krtd	N dd
lm} tddt|}|||dd}|tdd|}W d   n1 s|0    Y  |S )a   
        Get 2D Minos confidence region.

        This scans over two parameters and minimises all other free parameters for each
        scan point. This scan produces a statistical confidence region according to the
        `profile likelihood method <https://en.wikipedia.org/wiki/Likelihood_function>`_
        with a confidence level `cl`, which is asymptotically equal to the coverage
        probability of the confidence region according to `Wilks' theorem
        <https://en.wikipedia.org/wiki/Wilks%27_theorem>`. Note that 1D projections of
        the 2D confidence region are larger than 1D Minos intervals computed for the
        same confidence level. This is not an error, but a consequence of Wilks'
        theorem.

        The calculation is expensive since a numerical minimisation has to be performed
        at various points.

        Parameters
        ----------
        x : str
            Variable name of the first parameter.
        y : str
            Variable name of the second parameter.
        cl : float or None, optional
            Confidence level of the contour. If not set or None, a standard 68 % contour
            is computed (default). If 0 < cl < 1, the value is interpreted as the
            confidence level (a probability). For convenience, values cl >= 1 are
            interpreted as the probability content of a central symmetric interval
            covering that many standard deviations of a normal distribution. For
            example, cl=1 is interpreted as 68.3 %, and cl=2 is 84.3 %, and so on. Using
            values other than 0.68, 0.9, 0.95, 0.99, 1, 2, 3, 4, 5 require the scipy
            module.
        size : int, optional
            Number of points on the contour to find (default: 100). Increasing this
            makes the contour smoother, but requires more computation time.
        interpolated : int, optional
            Number of interpolated points on the contour (default: 0). If you set this
            to a value larger than size, cubic spline interpolation is used to generate
            a smoother curve and the interpolated coordinates are returned. Values
            smaller than size are ignored. Good results can be obtained with size=20,
            interpolated=200. This requires scipy.
        experimental : bool, optional
            If true, use experimental implementation to compute contour, otherwise use
            MnContour from the Minuit2 library. The experimental implementation was
            found to succeed in cases where MnContour produced no reasonable result, but
            is slower and not yet well tested in practice. Use with caution and report
            back any issues via Github.
        ncall : int, optional
            This parameter only takes effect if ``experimental`` is True.
            Approximate maximum number of calls before minimization will be aborted. If
            set to 0, use the adaptive heuristic from the Minuit2 library (Default: 0).
        iterate : int, optional
            This parameter only takes effect if ``experimental`` is True.
            Automatically call Migrad up to N times if convergence was not reached
            (Default: 5). This simple heuristic makes Migrad converge more often even if
            the numerical precision of the cost function is low. Setting this to 1
            disables the feature.
        use_simplex: bool, optional
            This parameter only takes effect if ``experimental`` is True.
            If we have to iterate, set this to True to call the Simplex algorithm before
            each call to Migrad (Default: True). This may improve convergence in
            pathological cases (which we are in when we have to iterate).

        Returns
        -------
        array of float (N x 2)
            Contour points of the form [[x1, y1]...[xn, yn]].
            Note that N = size + 1, the last point [xn, yn] is identical to [x1, y1].
            This makes it easier to draw a closed contour.

        See Also
        --------
        contour, mnprofile, profile
        r   (\?r,  z5mncontour can only be run on free parameters, not on Nr   r   )Zaxisinterpolation)CubicSplineZperiodic)Zbc_type)r0  r.  r)  r  rx   r   r/  r,   _free_parametersrJ   _experimental_mncontourr1  r#   r   rK   rQ   r   Zasarrayr  r    Zscipy.interpolaterv  r   ri   )r7   r   rI  r+  r=  rr  rs  r   r   r   rb  rc  rd  re  r7  parsceZmncptsrv  rf  Zsplr8   r8   r9   	mncontour  s>    V.


2zMinuit.mncontourr+  r=  rr  rs  )r   rI  r+  r=  rr  rs  r5   c             	   C  sV  ddl m} ddl m} ddlm}	 ddlm}
 ddlm} | 	|\}}| 	|\}}||}dd	 t
|D }g }g }g }|D ]p}| j||||||d
}t|d }|dk r|d8 }|| ||g ||	jg|	jg|  |	jg g qt|t|ks"J t| dt| |
| |||}|| || || |S )a  
        Draw 2D Minos confidence region (requires matplotlib).

        See :meth:`mncontour` for details on the interpretation of the region
        and for the parameters accepted by this function.

        Examples
        --------
        .. plot:: plots/mncontour.py
            :include-source:

        Returns
        -------
        ContourSet
            Instance of a ContourSet class from matplot.contour.

        See Also
        --------
        mncontour, draw_contour, draw_mnmatrix, draw_profile
        r   )__version__rV  )Path)
ContourSetr   )parse_versionc                 S  s   g | ]}t |d qS rt  r   r   r   r8   r8   r9   r     r   z)Minuit.draw_mncontour.<locals>.<listcomp>r}  r   )   r   r   )rZ  r~  rW  Zmatplotlib.pathr  Zmatplotlib.contourr  Z_parse_versionr  r0  rt   _iterater|  ri   r  ZMOVETOZLINETOZ	CLOSEPOLYZgcarn  r[  r\  )r7   r   rI  r+  r=  rr  rs  Zmpl_version_stringr`  r  r  r  rb  rc  rd  re  Zmpl_versionclsZc_valZc_ptscodesr{  Zn_linetocsr8   r8   r9   draw_mncontourY  sB    
&,


zMinuit.draw_mncontour)r+  r=  rs  figsize)r+  r=  rs  r5   c          "        sR   j stdt j  fdd jD }t|}|dkrFtddd t|D }t|dkrntdddl	m
} |j|||d	d
d\}	}
dd |D }tj|||d  d | t|  d}t|D ]\}}||
||f  d}t|D ]2\}}t|dd}t||}|j|d| d q|d d }tdD ]V} j||d	d\}}}|| }|| }|d |kr|d |kr q|d9 }qD|d7 }|||d || \}}g }tt||D ]b\}\}}||k r
||d  |kr
|||d   ||kr||d  |k r|| q|r^tg ||R  }tg ||R  }||f||< |d|d  t|D ]}|| }||
||f  |j j|  j| ddd t|D ]\}} j|||||d}|d7 }t|dkrt|\}}|j||d| d ||f||ffD ]B\} }!||! \}}tt| |}tt| |}||f||!< q.q|
||f d
 qqW d   n1 s0    Y  t|D ]\}}|
||f j||   |dkr|
|df | |
d|f  | t|D ]:}|| }|
||f j||   |
||f j!||   q
q|	|
fS )a1  
        Draw matrix of Minos scans (requires matplotlib).

        This draws a matrix of Minos likelihood scans, meaning that the likelihood is
        minimized with respect to the parameters that are not scanned over. The diagonal
        cells of the matrix show the 1D scan, the off-diagonal cells show 2D scans for
        all unique pairs of parameters.

        The projected edges of the 2D contours do not align with the 1D intervals,
        because of Wilks' theorem. The levels for 2D confidence regions are higher. For
        more information on the interpretation of 2D confidence regions, see
        :meth:`mncontour`.

        Parameters
        ----------
        cl : float or array-like of floats, optional
            See :meth:`mncontour`.
        size : int, optional
            See :meth:`mncontour`
        experimental : bool, optional
            See :meth:`mncontour`
        figsize : (float, float) or None, optional
            Width and height of figure in inches.

        Examples
        --------
        .. plot:: plots/mnmatrix.py
            :include-source:

        Returns
        -------
        fig, ax
            Figure and axes instances generated by matplotlib.

        See Also
        --------
        mncontour, mnprofile, draw_mncontour, draw_contour, draw_profile
        r,  c                   s   g | ]} j | s|qS r8   r-  r   r   r6   r8   r9   r     r   z(Minuit.draw_mnmatrix.<locals>.<listcomp>r   zall parameters are fixedc                 S  s   g | ]}t |d qS r  r  r  r8   r8   r9   r     r   zcl must have at least one valuerV  TF)r  constrained_layoutZsqueezec                 S  s   i | ]}|t jt j fqS r8   )r   r   r  r8   r8   r9   r     r   z(Minuit.draw_mnmatrix.<locals>.<dictcomp>r   r   )Z	max_valuert  C)rY  r3   r   )r>  r@  g?r   +)r+  r=  rs  N)"rx   r   r/  r,   rA   ri   rt   r  rJ   rZ  rW  ZsubplotsProgressBarr   Zscar.  maxro  r   rK  r#  r   r  r5  Zylimr\   r|  r   Z	transposeZset_visibleZset_xlimZ
set_ylabelZ
set_xlabelZset_ylim)"r7   r+  r=  rs  r  ry  rj   r  r`  figaxZprangebarr   Zpar1Zfmaxr   fr>  iterr   rI  okrG  rH  ZextremesZxkZykri  Zpar2clir{  r   r   r8   r6   r9   draw_mnmatrix  s    .


8
zMinuit.draw_mnmatrixc                 K  s:   |  |}t r ddlm} nddlm} || |||S )a  
        Interactive GUI for fitting.

        Starts a fitting application (requires PySide6, matplotlib) in which the
        fit is visualized and the parameters can be manipulated to find good
        starting parameters and to debug the fit.

        When called in a Jupyter notebook (requires ipywidgets, IPython, matplotlib),
        a fitting widget is returned instead, which can be displayed.

        Parameters
        ----------
        plot : Callable, optional
            To visualize the fit, interactive tries to access the visualize method on
            the cost function, which accepts the current model parameters as an
            array-like and potentially further keyword arguments, and draws a
            visualization into the current matplotlib axes. If the cost function does
            not provide a visualize method or if you want to override it, pass the
            function here.
        raise_on_exception : bool, optional
            The default is to catch exceptions in the plot function and convert them
            into a plotted message. In unit tests, raise_on_exception should be set to
            True to allow detecting errors.
        **kwargs :
            Any other keyword arguments are forwarded to the plot function.

        Examples
        --------
        .. plot:: plots/interactive.py
            :include-source:

        See Also
        --------
        Minuit.visualize
        r   )make_widget)r$  rt   
is_jupyterZiminuit.ipywidgetr  Ziminuit.qtwidget)r7   r#  Zraise_on_exceptionr%  r  r8   r8   r9   interactive$	  s
    )
zMinuit.interactivezSet[str]c                 C  s   t dd | jD S )Nc                 s  s   | ]}|j s|jV  qd S rS   )r  r~   r   mpr8   r8   r9   r   X	  r   z*Minuit._free_parameters.<locals>.<genexpr>)setr1   r6   r8   r8   r9   rw  W	  s    zMinuit._free_parametersr	   c                 C  s   t  }| jd ur| j|_|S rS   )r	   r&   eps)r7   r  r8   r8   r9   r
  Z	  s    
zMinuit._mnprecisionzTuple[int, str])r   r5   c                 C  s`   t |tr:|| jkr,td| d| j d|| j| fS || jvrRtd|| j| |fS )Nz
parameter z is out of range (max: )zunknown parameter )r   rR   rj   rJ   r/   r.   )r7   r   r8   r8   r9   r0  `	  s    


zMinuit._normalize_keystrz,Union[float, UserBound, Tuple[float, float]]zTuple[float, float])rA  r>  r5   c                 C  sT   t |trt|S | js(tdtj | j| }| j	| }|||  |||  fS )Nz8Specified nsigma bound, but error matrix is not accurate)
r   r   rt   Z_normalize_limitry   rH   rI   r(  r\   ra   )r7   rA  r>  r   sigmar8   r8   r9   rE  i	  s    



zMinuit._normalize_boundc                 C  s&   | j r"| j| j jjkr"t| j| _d S rS   )r,   r1   rK   r   r   r6   r8   r8   r9   _copy_state_if_neededx	  s    	zMinuit._copy_state_if_neededc                 C  s   | j jr| j j}t| j}t|}|j| jk ri }d}| j D ]}|j	s>|||j
< |d7 }q>|d | D ].\}}| D ]\}	}
|||
f |||	f< q~qnn8t|}t|D ]&}t|D ]}
|||
f |||
f< qq|| _nd | _d S Nr   r   )r1   Zhas_covariancerh   rt   ZMatrixr.   ri   Znrowrj   r  r2  fillr   r   r-   )r7   Zcovmr   Zext2intr   r  r   r   r  ri  r8   r8   r9   r   	  s*    



zMinuit._make_covariancec                 C  s(   t | j| j |  j}|r$|d9 }|S )NgMb`?)r  rP   rD   r
  r  )r7   r   r   r8   r8   r9   r   	  s    
zMinuit._edm_goalc                 C  s   | j }dd|  d| |  S )N   rQ  r   )rl   )r7   r   r8   r8   r9   r   	  s    zMinuit._migrad_maxcallc                 C  s   | j  p| j jj| juS rS   )r,   rK   r   r1   r6   r8   r8   r9   r)  	  s    z6Minuit._fmin_does_not_exist_or_last_state_was_modifiedc                 C  sh   g }| j dur|t| j  |t| j | jrD|t| j | jdur^|t| j d|S )z!Get detailed text representation.N
)rn   r  r/  rs   rg   rh   r   r7   sr8   r8   r9   __repr__	  s    

zMinuit.__repr__c                 C  sh   g }| j dur|t| j  |t| j | jrD|t| j | jdur^|t| j d|S )z&Get user-friendly text representation.Nr  )rn   r  r  rs   rg   rh   r   r  r8   r8   r9   __str__	  s    

zMinuit.__str__c              
   C  s  d}| j d ur|| j  7 }|| j 7 }| jr>|| j 7 }| jd urV|| j 7 }| j d urzdd lm} dd l}tddf | 	  |
 6}|j|ddd |d || 7 }W d    n1 s0    Y  W d    n1 s0    Y  W n tttfy   Y n0 |S )Nr   r   r   rl  svg
   )r_  Zdpi)rn   _repr_html_rs   rg   rh   Zmatplotlib.pyplotrW  io_TemporaryFigurer&  StringIOZsavefigseekreadr  AttributeErrorrJ   )r7   r  r`  r  r8   r8   r9   r  	  s*    



LzMinuit._repr_html_c                 C  s"   |r| d n| t|  d S )Nz<Minuit ...>)rM  r  )r7   r   cycler8   r8   r9   _repr_pretty_	  s    zMinuit._repr_pretty_c                 C  s>   | j j }|d u r:t|dr"|j}nd|jj d}t||S )Nr&  zclass zX has no visualize method, please use the 'plot' keyword to pass a visualization function)r#   hasattrr&  r   r   r  )r7   r#  ZpyfcnrL   r8   r8   r9   r$  	  s    
zMinuit._visualizezList[Tuple[float, float]])r7  rb  rd  r=  r   r   r   r5   c              
     s  ddl m} 	jg 	jd us(J tj	jf 	jf g	jf 	jf gg\}	|	 d td
g }
tjtj	 tj	|ddD ]	fdd  	
f	dd	}d}||dkr|d
kr|d9 }q|d
k r|

tjtjf qd}||dk r:|dk r:|d9 }q|dkrT|

 | q||||fdd}|

|jr| |jn
tjtjf q|
S )Nr   )root_scalarr3   F)Zendpointc                   s   | d  t  | d  t  f }|d  d  }j }|d urjt|d t||d }|d  d  }|d urt|d t||d }||fS r  )r   cossinre   r  r5  )zr   r   r   rI  )centerrb  phir  r7   ur8   r9   r^   
  s    
z,Minuit._experimental_mncontour.<locals>.argsc              	     sz   t j}| |  | }||d  ||d  tj|jj}|jj jj	  S r  )
r   r1   r   r   r   r#   r%   r&   ro   rC   )r  r   Zxyrp   )	r^   r7  r   rb  rd  r   r7   rQ   r   r8   r9   r   
  s"    



z,Minuit._experimental_mncontour.<locals>.scangHz>g333333?   g?gMbP?)ZbracketZxtol)r  r  r\   rh   r   r  Zeigr   r   pir  nanZ	convergedroot)r7   r7  rb  rd  r=  r   r   r   r  r   rz  r   rG  rH  r   r8   )r^   r  r7  r   rb  rd  r   r  r  r7   rQ   r  r   r9   rx  	  s:    



&zMinuit._experimental_mncontour)Nr   T)N)N)NNNNNN)N)N)NF)F)Jr   r   r   __doc__r   __annotations__ZLEAST_SQUARESZ
LIKELIHOODpropertyr:   r<   r?   r@   rA   rD   setterrN   rP   rQ   rV   rZ   r\   ra   rc   re   rg   rh   rj   rl   rm   rn   ro   rs   rv   rx   ry   r{   r}   r   r   r   r   r   r   r"  r&  r  r:  rK  rP  rS  rT  rN  rk  rq  r|  r  r  r  rw  r
  r0  rE  r  r   r   r   r)  r  r  r  r  r$  rx  r8   r8   r8   r9   r"   -   sV  
 	



 C#   D:p         Vq"i)B3a*$ H 	  3	r=   rU  zDict[str, float]r   )r?   r^   r   r5   c           
      C  s   t |}|r |rTtd| n4|D ]&}|| vr$t| dd|  dq$t |}t | |krxt| dt |  dt }t| D ]4\}}|r|| n|| }t|}	||||	 q|S )NzFpositional arguments cannot be mixed with parameter keyword arguments z is not one of the parameters [r   r   z values given for z function parameter(s))ri   r   r   r   r   rt   Z_guess_initial_stepadd)
r?   r^   r   nargskwr   r   r   valerrr8   r8   r9   r   I
  s0    
r   rf   rq   )mpsrg   r5   c                   s,   dddfdd t  fdd| D S )Nr  zOptional[Tuple[float, float]])r~   r5   c                   s    |  v r |  }|j |jfS d S rS   )r3  r4  )r~   r;  )rg   r8   r9   get_mej
  s    z_get_params.<locals>.get_mec                 3  sR   | ]J}t |j|j|j|j |j|j|j|jr6|j	nd |j
rD|jnd 	V  qd S rS   )rt   Paramr2  r~   rF   r  Zis_constr  Zhas_lower_limitr  Zhas_upper_limitr  r  )r  r8   r9   r   q
  s   z_get_params.<locals>.<genexpr>)rt   ZParams)r  rg   r8   )r  rg   r9   rr   i
  s    
rr   c                   @  s:   e Zd ZdddddZdddd	Zd
ddddZdS )r1  r   rB   )r:   r7  c                 C  s"   |j | _|| _| j j |9  _ d S rS   )rC   savedr:   )r7   r:   r7  r8   r8   r9   r   
  s    z_TemporaryErrordef.__init__rE   r4   c                 C  s   d S rS   r8   r6   r8   r8   r9   	__enter__
  s    z_TemporaryErrordef.__enter__objectr]   c                 G  s   | j | j_d S rS   )r  r:   rC   r_   r8   r8   r9   __exit__
  s    z_TemporaryErrordef.__exit__Nr   r   r   r   r  r  r8   r8   r8   r9   r1  
  s   r1  c                   @  s2   e Zd Zdd ZddddZdddd	d
ZdS )r  c                 C  s,   ddl m} || _| jj||fdd| _d S )Nr   rV  T)r  r  )rZ  rW  r`  Zfigurer  )r7   wr   r`  r8   r8   r9   r   
  s    z_TemporaryFigure.__init__rE   r4   c                 C  s   d S rS   r8   r6   r8   r8   r9   r  
  s    z_TemporaryFigure.__enter__r  r]   c                 G  s   | j | j d S rS   )r`  closer  r_   r8   r8   r9   r  
  s    z_TemporaryFigure.__exit__Nr  r8   r8   r8   r9   r  
  s   r  c              
   C  s  d|  k rdk sn J t | d u r(|n| } | dkr>td|dkrp| dkrX| d }qddd	d
d| d}n dddddddddd	| d}|dkrzddlm} W n4 ty } z| jd7  _ W Y d }~n
d }~0 0 | dkr|d| d } ||| }|S )Nr   r  zcl must be positiver   r2   r   g'ns?gi@g~N@g%U"@)rt  ?ffffff?Gz?g        gcq;@gUk@gs{B@gUk"@gȒK]@g fe@gyh'@g{U3@gϤAHc<@)	rt  r  r  r  r2   g       @g      @g      @g      @)chi2zT

You set an uncommon cl value, scipy is needed to process it. Please install scipy.)	rB   rJ   r  Zscipy.statsr  r  rL   ZcdfZppf)r+  rj   defaultr7  r  r  r8   r8   r9   r.  
  sL    


r.  r   rR   r   rB   rM   rX   r   )	r:   r   r   rQ   	tolerancerN   r   r   r5   c                 C  s   t | ||}|d ur||_|||}	td}t | |	j|}|	js|	js|dkr|rt| |	j|}
|d urn||
_|
||}	t | |	j|}|d ur||_|||}	|d8 }q:|	S )Nr   r   )r
   rN   r   r   rw   Zhas_reached_call_limitr   )r:   r   r   rQ   r  rN   r   r   r   rp   r   r8   r8   r9   r   
  s$    



r   )7r  
__future__r   rH   Ziminuitr   rt   Ziminuit.utilr   r   Ziminuit._corer   r   r   r	   r
   r   r   r   r   r   r   Ziminuit.warningsr   numpyr   typingr   r   r   r   r   r   r   r   r   r   r   Ziminuit.typingr   r   r   Ziminuit._optional_dependenciesr    Znumpy.typingr!   rU   __all__r"   r   rr   r1  r  r.  r   r8   r8   r8   r9   <module>   sP   44                    0 0