
    M/Phѩ                        d Z ddlmZ ddlmZ ddlmZ ddlZddl	m
Z
 ddlmZmZ ddZd Z G d d          Z	 	 	 d dZ	 	 	 d!dZ	 	 	 d dZ	 	 d dZ	 	 	 d dZ	 	 	 d dZ	 	 	 d dZ	 	 	 d dZ	 	 	 d dZdS )"z
Functions that are general enough to use for any model fitting. The idea is
to untie these from LikelihoodModel so that they may be re-used generally.
    )annotations)Any)SequenceN)optimize)SP_LT_15SP_LT_17kwargsdict[str, Any]allowedSequence[str]methodstrc           
     H   t          t          |                                                                         t          |                    }|rQdd l}|                    d| dd                    |           dd                    |           dt                     d S d S )Nr   zzKeyword arguments have been passed to the optimizer that have no effect. The list of allowed keyword arguments for method z is: z, z<. The list of unsupported keyword arguments passed include: z&. After release 0.14, this will raise.)setlistkeys
differencewarningswarnjoinFutureWarning)r	   r   r   extrar   s        Z/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/base/optimizer.pycheck_kwargsr      s    V[[]]##$$//W>>E 

-- - IIg..- - 2651A1A- - -
 	
 	
 	
 	
 	


 

    c                6    | |vrd| z  }t          |          d S )NzUnknown fit method %s)
ValueError)r   methodsmessages      r   _check_methodr       s-    W)F2!!! r   c                  &    e Zd Z	 	 d	dZd Zd ZdS )
	OptimizerNnewtond   TFc                   |                     dt                                }g d}||                                z  }|                                }t	          ||           t
          t          t          t          t          t          t          t          t          d	}|r|                    |           ||         } |||||||
||||	|          \  }}||||	|
||||d	}|                    |           |||fS )aN"  
        Fit function for any model with an objective function.

        Parameters
        ----------
        objective : function
            Objective function to be minimized.
        gradient : function
            The gradient of the objective function.
        start_params : array_like, optional
            Initial guess of the solution for the loglikelihood maximization.
            The default is an array of zeros.
        fargs : tuple
            Extra arguments passed to the objective function, i.e.
            objective(x,*args)
        kwargs : dict[str, Any]
            Extra keyword arguments passed to the objective function, i.e.
            objective(x,**kwargs)
        hessian : str, optional
            Method for computing the Hessian matrix, if applicable.
        method : str {'newton','nm','bfgs','powell','cg','ncg','basinhopping',
            'minimize'}
            Method can be 'newton' for Newton-Raphson, 'nm' for Nelder-Mead,
            'bfgs' for Broyden-Fletcher-Goldfarb-Shanno, 'powell' for modified
            Powell's method, 'cg' for conjugate gradient, 'ncg' for Newton-
            conjugate gradient, 'basinhopping' for global basin-hopping
            solver, if available or a generic 'minimize' which is a wrapper for
            scipy.optimize.minimize. `method` determines which solver from
            scipy.optimize is used. The explicit arguments in `fit` are passed
            to the solver, with the exception of the basin-hopping solver. Each
            solver has several optional arguments that are not the same across
            solvers. See the notes section below (or scipy.optimize) for the
            available arguments and for the list of explicit arguments that the
            basin-hopping solver supports..
        maxiter : int
            The maximum number of iterations to perform.
        full_output : bool
            Set to True to have all available output in the Results object's
            mle_retvals attribute. The output is dependent on the solver.
            See LikelihoodModelResults notes section for more information.
        disp : bool
            Set to True to print convergence messages.
        callback : callable callback(xk)
            Called after each iteration, as callback(xk), where xk is the
            current parameter vector.
        retall : bool
            Set to True to return list of solutions at each iteration.
            Available in Results object's mle_retvals attribute.

        Returns
        -------
        xopt : ndarray
            The solution to the objective function
        retvals : dict, None
            If `full_output` is True then this is a dictionary which holds
            information returned from the solver used. If it is False, this is
            None.
        optim_settings : dict
            A dictionary that contains the parameters passed to the solver.

        Notes
        -----
        The 'basinhopping' solver ignores `maxiter`, `retall`, `full_output`
        explicit arguments.

        Optional arguments for the solvers (available in Results.mle_settings)::

            'newton'
                tol : float
                    Relative error in params acceptable for convergence.
            'nm' -- Nelder Mead
                xtol : float
                    Relative error in params acceptable for convergence
                ftol : float
                    Relative error in loglike(params) acceptable for
                    convergence
                maxfun : int
                    Maximum number of function evaluations to make.
            'bfgs'
                gtol : float
                    Stop when norm of gradient is less than gtol.
                norm : float
                    Order of norm (np.inf is max, -np.inf is min)
                epsilon
                    If fprime is approximated, use this value for the step
                    size. Only relevant if LikelihoodModel.score is None.
            'lbfgs'
                m : int
                    The maximum number of variable metric corrections used to
                    define the limited memory matrix. (The limited memory BFGS
                    method does not store the full hessian but uses this many
                    terms in an approximation to it.)
                pgtol : float
                    The iteration will stop when
                    ``max{|proj g_i | i = 1, ..., n} <= pgtol`` where pg_i is
                    the i-th component of the projected gradient.
                factr : float
                    The iteration stops when
                    ``(f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr * eps``,
                    where eps is the machine precision, which is automatically
                    generated by the code. Typical values for factr are: 1e12
                    for low accuracy; 1e7 for moderate accuracy; 10.0 for
                    extremely high accuracy. See Notes for relationship to
                    ftol, which is exposed (instead of factr) by the
                    scipy.optimize.minimize interface to L-BFGS-B.
                maxfun : int
                    Maximum number of iterations.
                epsilon : float
                    Step size used when approx_grad is True, for numerically
                    calculating the gradient
                approx_grad : bool
                    Whether to approximate the gradient numerically (in which
                    case func returns only the function value).
            'cg'
                gtol : float
                    Stop when norm of gradient is less than gtol.
                norm : float
                    Order of norm (np.inf is max, -np.inf is min)
                epsilon : float
                    If fprime is approximated, use this value for the step
                    size. Can be scalar or vector.  Only relevant if
                    Likelihoodmodel.score is None.
            'ncg'
                fhess_p : callable f'(x,*args)
                    Function which computes the Hessian of f times an arbitrary
                    vector, p.  Should only be supplied if
                    LikelihoodModel.hessian is None.
                avextol : float
                    Stop when the average relative error in the minimizer
                    falls below this amount.
                epsilon : float or ndarray
                    If fhess is approximated, use this value for the step size.
                    Only relevant if Likelihoodmodel.hessian is None.
            'powell'
                xtol : float
                    Line-search error tolerance
                ftol : float
                    Relative error in loglike(params) for acceptable for
                    convergence.
                maxfun : int
                    Maximum number of function evaluations to make.
                start_direc : ndarray
                    Initial direction set.
            'basinhopping'
                niter : int
                    The number of basin hopping iterations.
                niter_success : int
                    Stop the run if the global minimum candidate remains the
                    same for this number of iterations.
                T : float
                    The "temperature" parameter for the accept or reject
                    criterion. Higher "temperatures" mean that larger jumps
                    in function value will be accepted. For best results
                    `T` should be comparable to the separation (in function
                    value) between local minima.
                stepsize : float
                    Initial step size for use in the random displacement.
                interval : int
                    The interval for how often to update the `stepsize`.
                minimizer : dict
                    Extra keyword arguments to be passed to the minimizer
                    `scipy.optimize.minimize()`, for example 'method' - the
                    minimization method (e.g. 'L-BFGS-B'), or 'tol' - the
                    tolerance for termination. Other arguments are mapped from
                    explicit argument of `fit`:
                    - `args` <- `fargs`
                    - `jac` <- `score`
                    - `hess` <- `hess`
            'minimize'
                min_method : str, optional
                    Name of minimization method to use.
                    Any method specific arguments can be passed directly.
                    For a list of methods and their arguments, see
                    documentation of `scipy.optimize.minimize`.
                    If no method is specified, then BFGS is used.
        extra_fit_funcs)	r#   nmbfgslbfgspowellcgncgbasinhoppingminimize)	r#   r'   r(   r)   r+   r,   r*   r-   r.   )dispmaxitercallbackretallfull_outputhess)		optimizerstart_paramsr0   r3   r/   fargsr1   r2   r&   )getdictr   lowerr    _fit_newton_fit_nm	_fit_bfgs
_fit_lbfgs_fit_cg_fit_ncg_fit_powell_fit_basinhopping_fit_minimizeupdate)self	objectivegradientr6   r7   r	   hessianr   r0   r3   r/   r1   r2   r&   r   	fit_funcsfuncxoptretvalsoptim_settingss                       r   _fitzOptimizer._fit$   s.   j !**%6??/ / /?'')))fg&&& "!-%

 

	  	._--- Y,v"&($*")+ + +g
 (.|%,["&H$*P P 	f%%%Wn,,r   c                    t           )a  
        TODO: how to add constraints?

        Something like
        sm.add_constraint(Model, func)

        or

        model_instance.add_constraint(func)
        model_instance.add_constraint("x1 + x2 = 2")
        result = model_instance.fit()
        NotImplementedErrorrE   paramss     r   _fit_constrainedzOptimizer._fit_constrained   s
     "!r   c                    t           NrP   rR   s     r   _fit_regularizedzOptimizer._fit_regularized  s
    
 "!r   )Nr#   r$   TTNF)__name__
__module____qualname__rN   rT   rW    r   r   r"   r"   #   sQ        EI.3Z- Z- Z- Z-x" " "" " " " "r   r"   Tr$   Fc                   |                     dd           g dfd|                                D             }||d<   ||d<   g d}g d}|d         |v rd	}
|d         |v rd	}g d
}t          s|dgz  }t          s|dgz  }g d}d|                                v r|d         |v r	|d         }nd	}d|                                v r|d         |v r	|d         }nd}t          j        | |||d         ||
||||
  
        }|j        }d	}|	rbt          |dt          j
                  }|j        ||j        |j        |j        d}|r)|                    d|                                i           ||fS )a  
    Fit using scipy minimize, where kwarg `min_method` defines the algorithm.

    Parameters
    ----------
    f : function
        Returns negative log likelihood given parameters.
    score : function
        Returns gradient of negative log likelihood with respect to params.
    start_params : array_like, optional
        Initial guess of the solution for the loglikelihood maximization.
        The default is an array of zeros.
    fargs : tuple
        Extra arguments passed to the objective function, i.e.
        objective(x,*args)
    kwargs : dict[str, Any]
        Extra keyword arguments passed to the objective function, i.e.
        objective(x,**kwargs)
    disp : bool
        Set to True to print convergence messages.
    maxiter : int
        The maximum number of iterations to perform.
    callback : callable callback(xk)
        Called after each iteration, as callback(xk), where xk is the
        current parameter vector.
    retall : bool
        Set to True to return list of solutions at each iteration.
        Available in Results object's mle_retvals attribute.
    full_output : bool
        Set to True to have all available output in the Results object's
        mle_retvals attribute. The output is dependent on the solver.
        See LikelihoodModelResults notes section for more information.
    hess : str, optional
        Method for computing the Hessian matrix, if applicable.

    Returns
    -------
    xopt : ndarray
        The solution to the objective function
    retvals : dict, None
        If `full_output` is True then this is a dictionary which holds
        information returned from the solver used. If it is False, this is
        None.
    
min_methodBFGS)r&   niterr]   tolboundsconstraintsc                $    i | ]\  }}|v	||S r[   r[   ).0kvfilter_optss      r   
<dictcomp>z!_fit_minimize.<locals>.<dictcomp>N  s)    GGG1!;2F2Fq!2F2F2Fr   r/   r0   )Nelder-MeadPowellCGr^   COBYLASLSQP)ri   rj   rl   N)L-BFGS-BTNCrm   trust-constrrj   ri   )rl   rm   rp   ra   rb   r[   )argsr   jacr4   ra   rb   r1   optionsnitfopt
iterationsfcallswarnflag	convergedallvecs)
setdefaultitemsr   r   r   r   r.   xgetattrnpnanfunnfevstatussuccessrD   values)fscorer6   r7   r	   r/   r0   r1   r2   r3   r4   rs   no_hessno_jac
has_boundshas_constraintsra   rb   resrK   rL   rt   rg   s                         @r   rC   rC     s   ^ lF+++ ]\\KGGGGGGGGGFO GI IHHG000Flw&&lv%% >==J !xj 
 &}o%
999O6;;==  VL%9Z%G%G!%%&*>/*Q*Q]+

A|%|@T %D[%-w@ @ @C 5DG 6c5"&))7# X3: #- -  	6NNIszz||4555=r   绽|=c                   t          |dd           |                    dd          }|                    dd          }d}t          j        }t          j        |          }|r||g}||k     rt          j        t          j        ||z
            |k              rt          j         |
|                    }t          j        |dk              s-|t          j        |j	        d                   xx         |z  cc<   |}|t          j
                            | ||                    z
  }|r|                    |           | ||           |d	z  }||k     r-t          j        t          j        ||z
            |k               | |g|R  }||k    r8d	}|r3t          d
           t          d|z             t          d|z             n7d}|r3t          d           t          d|z             t          d|z             |	rL| | |g|R  | ||           |
|          f\  }}}}}| }||||||d}|r|                    d|i           n|}d}||fS )a  
    Fit using Newton-Raphson algorithm.

    Parameters
    ----------
    f : function
        Returns negative log likelihood given parameters.
    score : function
        Returns gradient of negative log likelihood with respect to params.
    start_params : array_like, optional
        Initial guess of the solution for the loglikelihood maximization.
        The default is an array of zeros.
    fargs : tuple
        Extra arguments passed to the objective function, i.e.
        objective(x,*args)
    kwargs : dict[str, Any]
        Extra keyword arguments passed to the objective function, i.e.
        objective(x,**kwargs)
    disp : bool
        Set to True to print convergence messages.
    maxiter : int
        The maximum number of iterations to perform.
    callback : callable callback(xk)
        Called after each iteration, as callback(xk), where xk is the
        current parameter vector.
    retall : bool
        Set to True to return list of solutions at each iteration.
        Available in Results object's mle_retvals attribute.
    full_output : bool
        Set to True to have all available output in the Results object's
        mle_retvals attribute. The output is dependent on the solver.
        See LikelihoodModelResults notes section for more information.
    hess : str, optional
        Method for computing the Hessian matrix, if applicable.
    ridge_factor : float
        Regularization factor for Hessian matrix.

    Returns
    -------
    xopt : ndarray
        The solution to the objective function
    retvals : dict, None
        If `full_output` is True then this is a dictionary which holds
        information returned from the solver used. If it is False, this is
        None.
    )r`   ridge_factorr#   r`   g:0yE>r   r   r   N   z8Warning: Maximum number of iterations has been exceeded.z#         Current function value: %fz         Iterations: %dz%Optimization terminated successfully.z         Iterations %d)rv   rw   r   Hessianry   rz   r{   )r   r|   r   infasarrayanyabsalldiag_indicesshapelinalgsolveappendprintrD   )r   r   r6   r7   r	   r/   r0   r1   r2   r3   r4   r   r`   rw   	oldparams	newparamshistoryHfvalry   rK   rv   r_   gopthoptrz   rL   s                              r   r;   r;     s   b 0(;;;


E4
(
(C$$^U;;LJI
<((I )i(BF26)2;3< ,= ,=?B,C %D %DJttI'' vla'(( 	;boagaj))***l:***		553C3C D DD	 	&NN9%%%HYa
 BF26)2;3< ,= ,=?B,C %D %D 1YDW 	:    7$>???+j8999 	99:::7$>???*Z7888 !11Y#7#7#7#7"EE)$4$4Y)	tU	t !L	ut" )+ +  	1NNIw/000 =r   c                   t          |dd           |                    dd          }|                    dt          j                  }|                    dd          }t	          j        | ||||||||	|||          }|	r?|s|\  }}}}}}}n|\  }}}}}}}}| }|||||||d	}|r|                    d
|i           n|}d}||fS )a  
    Fit using Broyden-Fletcher-Goldfarb-Shannon algorithm.

    Parameters
    ----------
    f : function
        Returns negative log likelihood given parameters.
    score : function
        Returns gradient of negative log likelihood with respect to params.
    start_params : array_like, optional
        Initial guess of the solution for the loglikelihood maximization.
        The default is an array of zeros.
    fargs : tuple
        Extra arguments passed to the objective function, i.e.
        objective(x,*args)
    kwargs : dict[str, Any]
        Extra keyword arguments passed to the objective function, i.e.
        objective(x,**kwargs)
    disp : bool
        Set to True to print convergence messages.
    maxiter : int
        The maximum number of iterations to perform.
    callback : callable callback(xk)
        Called after each iteration, as callback(xk), where xk is the
        current parameter vector.
    retall : bool
        Set to True to return list of solutions at each iteration.
        Available in Results object's mle_retvals attribute.
    full_output : bool
        Set to True to have all available output in the Results object's
        mle_retvals attribute. The output is dependent on the solver.
        See LikelihoodModelResults notes section for more information.
    hess : str, optional
        Method for computing the Hessian matrix, if applicable.

    Returns
    -------
    xopt : ndarray
        The solution to the objective function
    retvals : dict, None
        If `full_output` is True then this is a dictionary which holds
        information returned from the solver used. If it is False, this is
        None.
    gtolnormepsilonr(   r   h㈵>r   r         P>)	rq   r   r   r   r0   r3   r/   r2   r1   )rv   r   Hinvrx   gcallsry   rz   r{   N)r   r|   r   r   r   	fmin_bfgsrD   )r   r   r6   r7   r	   r/   r0   r1   r2   r3   r4   r   r   r   rL   rK   rv   r   r   rx   r   ry   r{   rz   s                           r   r=   r=     s-   ^ 4f===V%;<<DVRV,,D	+ABBG L%e&*w)0k&*6HN N NG   	2?F<D$dFFHH +2(T4tVXw L	t#vi9 9  	1NNIw/000=r   c           	        t          dd                               ddgt          |          z            }                    dd           d}fd|D             }                    d	d
          }                    dd                              dd          }|rd}|r|st	          d          |rrt	          d          rfd}n|r| }||d<   n|r| }t          j        ||f|||||d|}|	r6|\  }}}|d         }|dk    }|d         }|d         }|d         }||||||d}n
|d         }d}||fS )aa  
    Fit using Limited-memory Broyden-Fletcher-Goldfarb-Shannon algorithm.

    Parameters
    ----------
    f : function
        Returns negative log likelihood given parameters.
    score : function
        Returns gradient of negative log likelihood with respect to params.
    start_params : array_like, optional
        Initial guess of the solution for the loglikelihood maximization.
        The default is an array of zeros.
    fargs : tuple
        Extra arguments passed to the objective function, i.e.
        objective(x,*args)
    kwargs : dict[str, Any]
        Extra keyword arguments passed to the objective function, i.e.
        objective(x,**kwargs)
    disp : bool
        Set to True to print convergence messages.
    maxiter : int
        The maximum number of iterations to perform.
    callback : callable callback(xk)
        Called after each iteration, as callback(xk), where xk is the
        current parameter vector.
    retall : bool
        Set to True to return list of solutions at each iteration.
        Available in Results object's mle_retvals attribute.
    full_output : bool
        Set to True to have all available output in the Results object's
        mle_retvals attribute. The output is dependent on the solver.
        See LikelihoodModelResults notes section for more information.
    hess : str, optional
        Method for computing the Hessian matrix, if applicable.

    Returns
    -------
    xopt : ndarray
        The solution to the objective function
    retvals : dict, None
        If `full_output` is True then this is a dictionary which holds
        information returned from the solver used. If it is False, this is
        None.

    Notes
    -----
    Within the mle part of statsmodels, the log likelihood function and
    its gradient with respect to the parameters do not have notationally
    consistent sign.
    )	mpgtolfactrmaxfunr   approx_gradra   loglike_and_scoreiprintr)   ra   )NNr   r   )r   r   r   r   r   r   c                *    i | ]}|v ||         S r[   r[   )rd   r~   r	   s     r   rh   z_fit_lbfgs.<locals>.<dictcomp>r  s$    ???Q1;;Avay;;;r   r   Fr   Nr   zRa finite-differences epsilon was provided even though we are not using approx_gradzagradient approximation was requested even though an analytic loglike_and_score function was givenc                D    t          d  | g|R  D                       S )Nc              3     K   | ]}| V  d S rV   r[   )rd   r~   s     r   	<genexpr>z/_fit_lbfgs.<locals>.<lambda>.<locals>.<genexpr>  s$      "H"H!A2"H"H"H"H"H"Hr   )tuple)par   s     r   <lambda>z_fit_lbfgs.<locals>.<lambda>  s2    U"H"H/@/@/GQ/G/G/G"H"H"HHH r   fprime)r0   r1   rq   ra   r/   ry   gradfuncallsrt   )rv   r   rx   ry   rz   rw   )r   r|   lenr8   r   r   fmin_l_bfgs_b)r   r   r6   r7   r	   r/   r0   r1   r2   r3   r4   ra   namesextra_kwargsr   r   rJ   rL   rK   rv   dry   rz   r   rx   rw   r   s       `                     @r   r>   r>   1  s   h l   x,#l:K:K)KLLF
h"""
 HE????%???L **]E22K

#6==jjD))G    E{ E D E E 	E &( & % & & 	&  HHHH	 !&X	 $T< 5.6U,25 5 (45 5G
  dA
 Z=]	y:uX
'i!+- - qz=r   c                l   t          |dd           |                    dd          }|                    dd          }|                    dd          }t          j        | |||||||	|||          }|	r9|s	|\  }}}}}n	|\  }}}}}}| }|||||d	}|r|                    d
|i           n|}d}||fS )a  
    Fit using Nelder-Mead algorithm.

    Parameters
    ----------
    f : function
        Returns negative log likelihood given parameters.
    score : function
        Returns gradient of negative log likelihood with respect to params.
    start_params : array_like, optional
        Initial guess of the solution for the loglikelihood maximization.
        The default is an array of zeros.
    fargs : tuple
        Extra arguments passed to the objective function, i.e.
        objective(x,*args)
    kwargs : dict[str, Any]
        Extra keyword arguments passed to the objective function, i.e.
        objective(x,**kwargs)
    disp : bool
        Set to True to print convergence messages.
    maxiter : int
        The maximum number of iterations to perform.
    callback : callable callback(xk)
        Called after each iteration, as callback(xk), where xk is the
        current parameter vector.
    retall : bool
        Set to True to return list of solutions at each iteration.
        Available in Results object's mle_retvals attribute.
    full_output : bool
        Set to True to have all available output in the Results object's
        mle_retvals attribute. The output is dependent on the solver.
        See LikelihoodModelResults notes section for more information.
    hess : str, optional
        Method for computing the Hessian matrix, if applicable.

    Returns
    -------
    xopt : ndarray
        The solution to the objective function
    retvals : dict, None
        If `full_output` is True then this is a dictionary which holds
        information returned from the solver used. If it is False, this is
        None.
    )xtolftolr   r'   r   -C6?r   r   N)	rq   r   r   r0   r   r3   r/   r2   r1   ru   r{   )r   r|   r   fminrD   )r   r   r6   r7   r	   r/   r0   r1   r2   r3   r4   r   r   r   rL   rK   rv   r_   rx   ry   r{   rz   s                         r   r<   r<     s   ^ 3T:::VV,,DVV,,Dx..FmA|%d!%wv(3$v%-/ / /G   	C29/D$vxx;B8D$vx L	u# )+ +  	1NNIw/000=r   c                   t          |dd           |                    dd          }|                    dt          j                  }|                    dd          }t	          j        | |||||||	|||          }|	r9|s	|\  }}}}}n	|\  }}}}}}| }|||||d	}|r|                    d
|i           n|}d}||fS )a  
    Fit using Conjugate Gradient algorithm.

    Parameters
    ----------
    f : function
        Returns negative log likelihood given parameters.
    score : function
        Returns gradient of negative log likelihood with respect to params.
    start_params : array_like, optional
        Initial guess of the solution for the loglikelihood maximization.
        The default is an array of zeros.
    fargs : tuple
        Extra arguments passed to the objective function, i.e.
        objective(x,*args)
    kwargs : dict[str, Any]
        Extra keyword arguments passed to the objective function, i.e.
        objective(x,**kwargs)
    disp : bool
        Set to True to print convergence messages.
    maxiter : int
        The maximum number of iterations to perform.
    callback : callable callback(xk)
        Called after each iteration, as callback(xk), where xk is the
        current parameter vector.
    retall : bool
        Set to True to return list of solutions at each iteration.
        Available in Results object's mle_retvals attribute.
    full_output : bool
        Set to True to have all available output in the Results object's
        mle_retvals attribute. The output is dependent on the solver.
        See LikelihoodModelResults notes section for more information.
    hess : str, optional
        Method for computing the Hessian matrix, if applicable.

    Returns
    -------
    xopt : ndarray
        The solution to the objective function
    retvals : dict, None
        If `full_output` is True then this is a dictionary which holds
        information returned from the solver used. If it is False, this is
        None.
    r   r+   r   r   r   r   r   )r   r   r   r0   r3   r/   r2   r1   )rv   rx   r   ry   rz   r{   N)r   r|   r   r   r   fmin_cgrD   )r   r   r6   r7   r	   r/   r0   r1   r2   r3   r4   r   r   r   rL   rK   rv   rx   r   ry   r{   rz   s                         r   r?   r?     s   ^ 4d;;;V%;<<DVRV,,D	+ABBGq,Dt'.+6T&,xA A AG   	D3:0D$<C9D$' L	6V'iA A 	1NNIw/000 =r   c                v   t          |dd           |                    dd          }|                    dd          }|                    dd          }t          j        | ||||
|||||	|||	          }|	r<|s
|\  }}}}}}n
|\  }}}}}}}| }||||||d
}|r|                    d|i           n|}d}||fS )a  
    Fit using Newton Conjugate Gradient algorithm.

    Parameters
    ----------
    f : function
        Returns negative log likelihood given parameters.
    score : function
        Returns gradient of negative log likelihood with respect to params.
    start_params : array_like, optional
        Initial guess of the solution for the loglikelihood maximization.
        The default is an array of zeros.
    fargs : tuple
        Extra arguments passed to the objective function, i.e.
        objective(x,*args)
    kwargs : dict[str, Any]
        Extra keyword arguments passed to the objective function, i.e.
        objective(x,**kwargs)
    disp : bool
        Set to True to print convergence messages.
    maxiter : int
        The maximum number of iterations to perform.
    callback : callable callback(xk)
        Called after each iteration, as callback(xk), where xk is the
        current parameter vector.
    retall : bool
        Set to True to return list of solutions at each iteration.
        Available in Results object's mle_retvals attribute.
    full_output : bool
        Set to True to have all available output in the Results object's
        mle_retvals attribute. The output is dependent on the solver.
        See LikelihoodModelResults notes section for more information.
    hess : str, optional
        Method for computing the Hessian matrix, if applicable.

    Returns
    -------
    xopt : ndarray
        The solution to the objective function
    retvals : dict, None
        If `full_output` is True then this is a dictionary which holds
        information returned from the solver used. If it is False, this is
        None.
    )fhess_pavextolr   r,   r   Nr   r   r   r   )
r   fhessrq   r   r   r0   r3   r/   r2   r1   )rv   rx   r   hcallsry   rz   r{   )r   r|   r   fmin_ncgrD   )r   r   r6   r7   r	   r/   r0   r1   r2   r3   r4   r   r   r   rL   rK   rv   rx   r   r   ry   r{   rz   s                          r   r@   r@   @  s(   ^ :EBBB	400G	+ABBG	+ABBG<&*(/,7d'-	B B BG
   	;B8D$  BD$' L	6V# )+ +  	1NNIw/000=r   c                   t          |dd           |                    dd          }|                    dd          }|                    dd          }|                    dd          }t          j        | |||||||	||||	          }|	r<|s
|\  }}}}}}n
|\  }}}}}}}| }||||||d
}|r|                    d|i           n|}d}||fS )a  
    Fit using Powell's conjugate direction algorithm.

    Parameters
    ----------
    f : function
        Returns negative log likelihood given parameters.
    score : function
        Returns gradient of negative log likelihood with respect to params.
    start_params : array_like, optional
        Initial guess of the solution for the loglikelihood maximization.
        The default is an array of zeros.
    fargs : tuple
        Extra arguments passed to the objective function, i.e.
        objective(x,*args)
    kwargs : dict[str, Any]
        Extra keyword arguments passed to the objective function, i.e.
        objective(x,**kwargs)
    disp : bool
        Set to True to print convergence messages.
    maxiter : int
        The maximum number of iterations to perform.
    callback : callable callback(xk)
        Called after each iteration, as callback(xk), where xk is the
        current parameter vector.
    retall : bool
        Set to True to return list of solutions at each iteration.
        Available in Results object's mle_retvals attribute.
    full_output : bool
        Set to True to have all available output in the Results object's
        mle_retvals attribute. The output is dependent on the solver.
        See LikelihoodModelResults notes section for more information.
    hess : str, optional
        Method for computing the Hessian matrix, if applicable.

    Returns
    -------
    xopt : ndarray
        The solution to the objective function
    retvals : dict, None
        If `full_output` is True then this is a dictionary which holds
        information returned from the solver used. If it is False, this is
        None.
    )r   r   r   start_direcr*   r   r   r   r   Nr   )
rq   r   r   r0   r   r3   r/   r2   r1   direc)rv   r   rw   rx   ry   rz   r{   )r   r|   r   fmin_powellrD   )r   r   r6   r7   r	   r/   r0   r1   r2   r3   r4   r   r   r   r   rL   rK   rv   r   r_   rx   ry   r{   rz   s                           r   rA   rA     s6   ^ BHMMMVV,,DVV,,Dx..F##M488K"1lT(,gf/:*08)4	6 6 6G
   	9@6D$ufhh  @D$ufh L	%u# )+ +  	1NNIw/000=r   c                   t          |dd           d |                                D             }|                    dd          }|                    dd          }|                    dd	          }|                    d
d          }|                    dd          }|                    d          }|                    di           }||d<   ||d<   |                    dd          }|r|dk    r|
|d<   t	          j        | ||||||||||          }|j        }|	r$|j        |j        |j	        d|j
        d         v d}nd}||fS )a  
    Fit using Basin-hopping algorithm.

    Parameters
    ----------
    f : function
        Returns negative log likelihood given parameters.
    score : function
        Returns gradient of negative log likelihood with respect to params.
    start_params : array_like, optional
        Initial guess of the solution for the loglikelihood maximization.
        The default is an array of zeros.
    fargs : tuple
        Extra arguments passed to the objective function, i.e.
        objective(x,*args)
    kwargs : dict[str, Any]
        Extra keyword arguments passed to the objective function, i.e.
        objective(x,**kwargs)
    disp : bool
        Set to True to print convergence messages.
    maxiter : int
        The maximum number of iterations to perform.
    callback : callable callback(xk)
        Called after each iteration, as callback(xk), where xk is the
        current parameter vector.
    retall : bool
        Set to True to return list of solutions at each iteration.
        Available in Results object's mle_retvals attribute.
    full_output : bool
        Set to True to have all available output in the Results object's
        mle_retvals attribute. The output is dependent on the solver.
        See LikelihoodModelResults notes section for more information.
    hess : str, optional
        Method for computing the Hessian matrix, if applicable.

    Returns
    -------
    xopt : ndarray
        The solution to the objective function
    retvals : dict, None
        If `full_output` is True then this is a dictionary which holds
        information returned from the solver used. If it is False, this is
        None.
    )r_   niter_successTstepsizeinterval	minimizerseedr-   c                    i | ]\  }}||	S r[   r[   )rd   re   rf   s      r   rh   z%_fit_basinhopping.<locals>.<dictcomp>  s    ...tq!a...r   r_   r$   r   Nr   g      ?r   g      ?r   2   r   r   rq   rr   r   rn   r4   )	minimizer_kwargsr_   r   r   r   r/   r1   r   r   zcompleted successfullyr   )rv   rw   rx   rz   )r   r}   r|   r8   r   r-   r~   r   rt   r   r   )r   r   r6   r7   r	   r/   r0   r1   r2   r3   r4   r_   r   r   r   r   r   r   r   rL   rK   s                        r   rB   rB     s   ^ T  
 /.v||~~...Fgs++E%%ot<<M#s##A  S11H  R00H::fDzz+r22$V#U!!(D11F (&J&&#' #A|5E*/}&'(-5)-/ / /G 9D K!+l1W_Q5GG	
 
 =r   )r	   r
   r   r   r   r   )Tr$   NFTN)Tr$   NFTNr   )__doc__
__future__r   typingr   collections.abcr   numpyr   scipyr   statsmodels.compat.scipyr   r   r   r    r"   rC   r;   r=   r>   r<   r?   r@   rA   rB   r[   r   r   <module>r      s$    # " " " " "       $ $ $ $ $ $           7 7 7 7 7 7 7 7
 
 
 
" " "q" q" q" q" q" q" q" q"p ?C5:)-a a a aH =A38:?e e e eP ;?16%)G G G GT JMCGz z z zz 9=/4#'F F F FR 9=/4#'F F F FR :>05$(H H H HV =A38'+I I I IX CG9>-1S S S S S Sr   