o
    Ö­j·à  ã                   @   sÜ   d dl Z d dlZd dlmZmZmZmZ ddlm	Z	 ddl
mZmZmZmZmZ ddlmZmZmZmZmZ ddlmZmZmZmZmZmZ 					d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 )é    N)ÚBoundsÚLinearConstraintÚNonlinearConstraintÚOptimizeResulté   )ÚTrustRegion)ÚObjectiveFunctionÚBoundConstraintsÚLinearConstraintsÚNonlinearConstraintsÚProblem)ÚMaxEvalErrorÚTargetSuccessÚCallbackSuccessÚFeasibleSuccessÚexact_1d_array)Ú
ExitStatusÚOptionsÚ	ConstantsÚDEFAULT_OPTIONSÚDEFAULT_CONSTANTSÚPRINT_OPTIONS© c           3      K   s
  |du ri }nt |ƒ}| tjttj ¡}t|ƒ}| tjttj ¡}	t|	ƒ}	| tjttj ¡}
t|
ƒ}
| tj	ttj	 ¡}t|ƒ}tj
|v rS|tj
 dkrStdƒ‚| tj
ttj
 ¡}t|ƒ}tj|v rq|tj dkrqtdƒ‚| tjttj ¡}t|ƒ}| tjttj ¡}t|ƒ}t|tƒs•|f}t| ||g|¢R Ž }t|dƒs§|g}t|ƒ}tt||ƒƒ}t|ƒ\}}t|||ƒ}t|||ƒ}t|||||||	|
||||ƒ}t||jƒ tdi |¤Ž}|jjsît|ddt j!d|ƒS |jdkrýt|ddt j"d|ƒS |�r3t#d	ƒ t#d
|tj$ › d�ƒ t#d|tj% › d�ƒ t#d|tj& › d�ƒ t#d|tj' › d�ƒ t#ƒ  zt(|||ƒ}W nb t)�yO   t|ddt j*d|ƒ Y S  t+�yb   t|ddt j,d|ƒ Y S  t-�yu   t|ddt j.d|ƒ Y S  t/�yˆ   t|ddt j0d|ƒ Y S  t1j2j3�y�   t|ddt j4d|ƒ Y S w d}d}d}d}d}d}	 ||tj' k�r¸t j0}�nJ|d7 }t1j2 5|j6|j7j8j9 ¡|t:j; |j< k�rÖ| =|¡ |j<}| >|¡\} }!| |! }"t1j2 5|"¡}#|#|t:j? |j@ k�rY| j<|t:jA 9  _<||j@k�r
d}d}n|d7 }|d7 }|#d|j@ k�rd}|dk�p$|dk}$|$�r0d}d}d}%�nz| B¡ \}}&W n t1j2j3�yH   t j4}Y �nºw |&tC|j<|t:jD |j@ ƒk}%�næ| E|"¡}'|'�r;ztF|||"|ƒ\}(})}*W n; t)�y}   t j*}d}Y �n… t-�yŒ   t j.}d}Y �nv t+�y›   t j,}d}Y �ng t/�y¨   t jG}Y �nZw | H|j6|jI|jJ|jK¡}+| H|j6|" |(|)|*¡},|jLdk�r7|,|+k�r7t1j2 5| ¡|t:jM d |j< k�r7| N|"|¡}-t1j2 5|-¡dk�r7|"|-7 }"ztF|||"|ƒ\}(})}*W n; t)�y   t j*}d}Y �n÷ t-�y   t j.}d}Y �nè t+�y)   t j,}d}Y �nÙ t/�y6   t jG}Y �nÌw | O|"|(|)|*¡}.z| B|j6|" ¡d }W n t1j2j3�y[   t j4}Y �n§w z|j7 P||j6|" |(|)|*¡}/W n t1j2j3�y{   t j4}Y �n‡w | Q¡  | R|"|.¡ |j<|j@k�rð|.|t:jS k�r˜d}nX|d7 }|j7 T|j6¡}0z	|j7 U|j6¡}1W n t1j2j3�y¼   t j4}Y �nFw t1j2 5|0¡|t:jV t1j2 5|1¡ k �rÑd}|dk�rðz|j7 W¡  W n t1j2j3�yí   t j4}Y �nw d}| X|j6|" ¡ z| B¡ \}}&W n t1j2j3�y   t j4}Y nów |/�p(|.|t:jY k�o(|&tC|j<|t:jD |j@ ƒk}%||j@k�o9|.|t:jY k�o9|% }$nd}$d}%|$�r~|j@|tj% k�rQd}t jZ}n±| [|¡ | \¡  |�r~| ]|j6|jJ|jK¡}2t^d|j@› �|| _|j6¡|jI|2|j`|ƒ t#ƒ  |%�r z| a||¡}"W n t1j2j3�y˜   t j4}Y njw ztF|||"|ƒ\}(})}*W n7 t)�y´   t j*}d}Y nN t-�yÂ   t j.}d}Y n@ t+�yÐ   t j,}d}Y n2 t/�yÜ   t jG}Y n&w z|j7 P||j6|" |(|)|*¡ W n t1j2j3�yû   t j4}Y nw | Q¡  �q«t||jb||||ƒS )a¡?  
    Minimize a scalar function using the COBYQA method.

    The Constrained Optimization BY Quadratic Approximations (COBYQA) method is
    a derivative-free optimization method designed to solve general nonlinear
    optimization problems. A complete description of COBYQA is given in [3]_.

    Parameters
    ----------
    fun : {callable, None}
        Objective function to be minimized.

            ``fun(x, *args) -> float``

        where ``x`` is an array with shape (n,) and `args` is a tuple. If `fun`
        is ``None``, the objective function is assumed to be the zero function,
        resulting in a feasibility problem.
    x0 : array_like, shape (n,)
        Initial guess.
    args : tuple, optional
        Extra arguments passed to the objective function.
    bounds : {`scipy.optimize.Bounds`, array_like, shape (n, 2)}, optional
        Bound constraints of the problem. It can be one of the cases below.

        #. An instance of `scipy.optimize.Bounds`. For the time being, the
           argument ``keep_feasible`` is disregarded, and all the constraints
           are considered unrelaxable and will be enforced.
        #. An array with shape (n, 2). The bound constraints for ``x[i]`` are
           ``bounds[i][0] <= x[i] <= bounds[i][1]``. Set ``bounds[i][0]`` to
           :math:`-\infty` if there is no lower bound, and set ``bounds[i][1]``
           to :math:`\infty` if there is no upper bound.

        The COBYQA method always respect the bound constraints.
    constraints : {Constraint, list}, optional
        General constraints of the problem. It can be one of the cases below.

        #. An instance of `scipy.optimize.LinearConstraint`. The argument
           ``keep_feasible`` is disregarded.
        #. An instance of `scipy.optimize.NonlinearConstraint`. The arguments
           ``jac``, ``hess``, ``keep_feasible``, ``finite_diff_rel_step``, and
           ``finite_diff_jac_sparsity`` are disregarded.

        #. A list, each of whose elements are described in the cases above.

    callback : callable, optional
        A callback executed at each objective function evaluation. The method
        terminates if a ``StopIteration`` exception is raised by the callback
        function. Its signature can be one of the following:

            ``callback(intermediate_result)``

        where ``intermediate_result`` is a keyword parameter that contains an
        instance of `scipy.optimize.OptimizeResult`, with attributes ``x``
        and ``fun``, being the point at which the objective function is
        evaluated and the value of the objective function, respectively. The
        name of the parameter must be ``intermediate_result`` for the callback
        to be passed an instance of `scipy.optimize.OptimizeResult`.

        Alternatively, the callback function can have the signature:

            ``callback(xk)``

        where ``xk`` is the point at which the objective function is evaluated.
        Introspection is used to determine which of the signatures to invoke.
    options : dict, optional
        Options passed to the solver. Accepted keys are:

            disp : bool, optional
                Whether to print information about the optimization procedure.
                Default is ``False``.
            maxfev : int, optional
                Maximum number of function evaluations. Default is ``500 * n``.
            maxiter : int, optional
                Maximum number of iterations. Default is ``1000 * n``.
            target : float, optional
                Target on the objective function value. The optimization
                procedure is terminated when the objective function value of a
                feasible point is less than or equal to this target. Default is
                ``-numpy.inf``.
            feasibility_tol : float, optional
                Tolerance on the constraint violation. If the maximum
                constraint violation at a point is less than or equal to this
                tolerance, the point is considered feasible. Default is
                ``numpy.sqrt(numpy.finfo(float).eps)``.
            radius_init : float, optional
                Initial trust-region radius. Typically, this value should be in
                the order of one tenth of the greatest expected change to `x0`.
                Default is ``1.0``.
            radius_final : float, optional
                Final trust-region radius. It should indicate the accuracy
                required in the final values of the variables. Default is
                ``1e-6``.
            nb_points : int, optional
                Number of interpolation points used to build the quadratic
                models of the objective and constraint functions. Default is
                ``2 * n + 1``.
            scale : bool, optional
                Whether to scale the variables according to the bounds. Default
                is ``False``.
            filter_size : int, optional
                Maximum number of points in the filter. The filter is used to
                select the best point returned by the optimization procedure.
                Default is ``sys.maxsize``.
            store_history : bool, optional
                Whether to store the history of the function evaluations.
                Default is ``False``.
            history_size : int, optional
                Maximum number of function evaluations to store in the history.
                Default is ``sys.maxsize``.
            debug : bool, optional
                Whether to perform additional checks during the optimization
                procedure. This option should be used only for debugging
                purposes and is highly discouraged to general users. Default is
                ``False``.

        Other constants (from the keyword arguments) are described below. They
        are not intended to be changed by general users. They should only be
        changed by users with a deep understanding of the algorithm, who want
        to experiment with different settings.

    Returns
    -------
    `scipy.optimize.OptimizeResult`
        Result of the optimization procedure, with the following fields:

            message : str
                Description of the cause of the termination.
            success : bool
                Whether the optimization procedure terminated successfully.
            status : int
                Termination status of the optimization procedure.
            x : `numpy.ndarray`, shape (n,)
                Solution point.
            fun : float
                Objective function value at the solution point.
            maxcv : float
                Maximum constraint violation at the solution point.
            nfev : int
                Number of function evaluations.
            nit : int
                Number of iterations.

        If ``store_history`` is True, the result also has the following fields:

            fun_history : `numpy.ndarray`, shape (nfev,)
                History of the objective function values.
            maxcv_history : `numpy.ndarray`, shape (nfev,)
                History of the maximum constraint violations.

        A description of the termination statuses is given below.

        .. list-table::
            :widths: 25 75
            :header-rows: 1

            * - Exit status
              - Description
            * - 0
              - The lower bound for the trust-region radius has been reached.
            * - 1
              - The target objective function value has been reached.
            * - 2
              - All variables are fixed by the bound constraints.
            * - 3
              - The callback requested to stop the optimization procedure.
            * - 4
              - The feasibility problem received has been solved successfully.
            * - 5
              - The maximum number of function evaluations has been exceeded.
            * - 6
              - The maximum number of iterations has been exceeded.
            * - -1
              - The bound constraints are infeasible.
            * - -2
              - A linear algebra error occurred.

    Other Parameters
    ----------------
    decrease_radius_factor : float, optional
        Factor by which the trust-region radius is reduced when the reduction
        ratio is low or negative. Default is ``0.5``.
    increase_radius_factor : float, optional
        Factor by which the trust-region radius is increased when the reduction
        ratio is large. Default is ``numpy.sqrt(2.0)``.
    increase_radius_threshold : float, optional
        Threshold that controls the increase of the trust-region radius when
        the reduction ratio is large. Default is ``2.0``.
    decrease_radius_threshold : float, optional
        Threshold used to determine whether the trust-region radius should be
        reduced to the resolution. Default is ``1.4``.
    decrease_resolution_factor : float, optional
        Factor by which the resolution is reduced when the current value is far
        from its final value. Default is ``0.1``.
    large_resolution_threshold : float, optional
        Threshold used to determine whether the resolution is far from its
        final value. Default is ``250.0``.
    moderate_resolution_threshold : float, optional
        Threshold used to determine whether the resolution is close to its
        final value. Default is ``16.0``.
    low_ratio : float, optional
        Threshold used to determine whether the reduction ratio is low. Default
        is ``0.1``.
    high_ratio : float, optional
        Threshold used to determine whether the reduction ratio is high.
        Default is ``0.7``.
    very_low_ratio : float, optional
        Threshold used to determine whether the reduction ratio is very low.
        This is used to determine whether the models should be reset. Default
        is ``0.01``.
    penalty_increase_threshold : float, optional
        Threshold used to determine whether the penalty parameter should be
        increased. Default is ``1.5``.
    penalty_increase_factor : float, optional
        Factor by which the penalty parameter is increased. Default is ``2.0``.
    short_step_threshold : float, optional
        Factor used to determine whether the trial step is too short. Default
        is ``0.5``.
    low_radius_factor : float, optional
        Factor used to determine which interpolation point should be removed
        from the interpolation set at each iteration. Default is ``0.1``.
    byrd_omojokun_factor : float, optional
        Factor by which the trust-region radius is reduced for the computations
        of the normal step in the Byrd-Omojokun composite-step approach.
        Default is ``0.8``.
    threshold_ratio_constraints : float, optional
        Threshold used to determine which constraints should be taken into
        account when decreasing the penalty parameter. Default is ``2.0``.
    large_shift_factor : float, optional
        Factor used to determine whether the point around which the quadratic
        models are built should be updated. Default is ``10.0``.
    large_gradient_factor : float, optional
        Factor used to determine whether the models should be reset. Default is
        ``10.0``.
    resolution_factor : float, optional
        Factor by which the resolution is decreased. Default is ``2.0``.
    improve_tcg : bool, optional
        Whether to improve the steps computed by the truncated conjugate
        gradient method when the trust-region boundary is reached. Default is
        ``True``.

    References
    ----------
    .. [1] J. Nocedal and S. J. Wright. *Numerical Optimization*. Springer Ser.
       Oper. Res. Financ. Eng. Springer, New York, NY, USA, second edition,
       2006. `doi:10.1007/978-0-387-40065-5
       <https://doi.org/10.1007/978-0-387-40065-5>`_.
    .. [2] M. J. D. Powell. A direct search optimization method that models the
       objective and constraint functions by linear interpolation. In S. Gomez
       and J.-P. Hennart, editors, *Advances in Optimization and Numerical
       Analysis*, volume 275 of Math. Appl., pages 51--67. Springer, Dordrecht,
       Netherlands, 1994. `doi:10.1007/978-94-015-8330-5_4
       <https://doi.org/10.1007/978-94-015-8330-5_4>`_.
    .. [3] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods
       and Software*. PhD thesis, Department of Applied Mathematics, The Hong
       Kong Polytechnic University, Hong Kong, China, 2022. URL:
       https://theses.lib.polyu.edu.hk/handle/200/12294.

    Examples
    --------
    To demonstrate how to use `minimize`, we first minimize the Rosenbrock
    function implemented in `scipy.optimize` in an unconstrained setting.

    .. testsetup::

        import numpy as np
        np.set_printoptions(precision=3, suppress=True)

    >>> from cobyqa import minimize
    >>> from scipy.optimize import rosen

    To solve the problem using COBYQA, run:

    >>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
    >>> res = minimize(rosen, x0)
    >>> res.x
    array([1., 1., 1., 1., 1.])

    To see how bound and constraints are handled using `minimize`, we solve
    Example 16.4 of [1]_, defined as

    .. math::

        \begin{aligned}
            \min_{x \in \mathbb{R}^2}   & \quad (x_1 - 1)^2 + (x_2 - 2.5)^2\\
            \text{s.t.}                 & \quad -x_1 + 2x_2 \le 2,\\
                                        & \quad x_1 + 2x_2 \le 6,\\
                                        & \quad x_1 - 2x_2 \le 2,\\
                                        & \quad x_1 \ge 0,\\
                                        & \quad x_2 \ge 0.
        \end{aligned}

    >>> import numpy as np
    >>> from scipy.optimize import Bounds, LinearConstraint

    Its objective function can be implemented as:

    >>> def fun(x):
    ...     return (x[0] - 1.0)**2 + (x[1] - 2.5)**2

    This problem can be solved using `minimize` as:

    >>> x0 = [2.0, 0.0]
    >>> bounds = Bounds([0.0, 0.0], np.inf)
    >>> constraints = LinearConstraint([
    ...     [-1.0, 2.0],
    ...     [1.0, 2.0],
    ...     [1.0, -2.0],
    ... ], -np.inf, [2.0, 6.0, 2.0])
    >>> res = minimize(fun, x0, bounds=bounds, constraints=constraints)
    >>> res.x
    array([1.4, 1.7])

    To see how nonlinear constraints are handled, we solve Problem (F) of [2]_,
    defined as

    .. math::

        \begin{aligned}
            \min_{x \in \mathbb{R}^2}   & \quad -x_1 - x_2\\
            \text{s.t.}                 & \quad x_1^2 - x_2 \le 0,\\
                                        & \quad x_1^2 + x_2^2 \le 1.
        \end{aligned}

    >>> from scipy.optimize import NonlinearConstraint

    Its objective and constraint functions can be implemented as:

    >>> def fun(x):
    ...     return -x[0] - x[1]
    >>>
    >>> def cub(x):
    ...     return [x[0]**2 - x[1], x[0]**2 + x[1]**2]

    This problem can be solved using `minimize` as:

    >>> x0 = [1.0, 1.0]
    >>> constraints = NonlinearConstraint(cub, -np.inf, [0.0, 1.0])
    >>> res = minimize(fun, x0, constraints=constraints)
    >>> res.x
    array([0.707, 0.707])

    Finally, to see how to supply linear and nonlinear constraints
    simultaneously, we solve Problem (G) of [2]_, defined as

    .. math::

        \begin{aligned}
            \min_{x \in \mathbb{R}^3}   & \quad x_3\\
            \text{s.t.}                 & \quad 5x_1 - x_2 + x_3 \ge 0,\\
                                        & \quad -5x_1 - x_2 + x_3 \ge 0,\\
                                        & \quad x_1^2 + x_2^2 + 4x_2 \le x_3.
        \end{aligned}

    Its objective and nonlinear constraint functions can be implemented as:

    >>> def fun(x):
    ...     return x[2]
    >>>
    >>> def cub(x):
    ...     return x[0]**2 + x[1]**2 + 4.0*x[1] - x[2]

    This problem can be solved using `minimize` as:

    >>> x0 = [1.0, 1.0, 1.0]
    >>> constraints = [
    ...     LinearConstraint(
    ...         [[5.0, -1.0, 1.0], [-5.0, -1.0, 1.0]],
    ...         [0.0, 0.0],
    ...         np.inf,
    ...     ),
    ...     NonlinearConstraint(cub, -np.inf, 0.0),
    ... ]
    >>> res = minimize(fun, x0, constraints=constraints)
    >>> res.x
    array([ 0., -3., -3.])
    Nr   z)The size of the history must be positive.z(The size of the filter must be positive.Ú__len__ç        FTz$Starting the optimization procedure.zInitial trust-region radius: Ú.zFinal trust-region radius: z(Maximum number of function evaluations: zMaximum number of iterations: r   gš™™™™™¹?é   é   znonlinearly constrainedç       @zNew trust-region radius: r   )cÚdictÚgetr   ÚVERBOSEr   ÚboolÚFEASIBILITY_TOLÚfloatÚSCALEÚSTORE_HISTORYÚHISTORY_SIZEÚ
ValueErrorÚintÚFILTER_SIZEÚDEBUGÚ
isinstanceÚtupler   ÚhasattrÚlenr	   Ú_get_boundsÚ_get_constraintsr
   r   r   Ú_set_default_optionsÚnÚ_set_default_constantsÚboundsÚis_feasibleÚ_build_resultr   ÚINFEASIBLE_ERRORÚFIXED_SUCCESSÚprintÚRHOBEGÚRHOENDÚMAX_EVALÚMAX_ITERr   r   ÚTARGET_SUCCESSr   ÚCALLBACK_SUCCESSr   ÚFEASIBLE_SUCCESSr   ÚMAX_ITER_WARNINGÚnpÚlinalgÚLinAlgErrorÚLINALG_ERRORÚnormÚx_bestÚmodelsÚinterpolationÚx_baser   ÚLARGE_SHIFT_FACTORÚradiusÚshift_x_baseÚget_trust_region_stepÚSHORT_STEP_THRESHOLDÚ
resolutionÚDECREASE_RESOLUTION_FACTORÚget_index_to_removeÚmaxÚRESOLUTION_FACTORÚincrease_penaltyÚ_evalÚMAX_EVAL_WARNINGÚmeritÚfun_bestÚcub_bestÚceq_bestÚtypeÚBYRD_OMOJOKUN_FACTORÚ get_second_order_correction_stepÚget_reduction_ratioÚupdate_interpolationÚset_best_indexÚupdate_radiusÚVERY_LOW_RATIOÚfun_gradÚfun_alt_gradÚLARGE_GRADIENT_FACTORÚreset_modelsÚset_multipliersÚ	LOW_RATIOÚRADIUS_SUCCESSÚenhance_resolutionÚdecrease_penaltyÚmaxcvÚ_print_stepÚbuild_xÚn_evalÚget_geometry_stepÚpenalty)3ÚfunÚx0Úargsr5   ÚconstraintsÚcallbackÚoptionsÚkwargsÚverboseÚfeasibility_tolÚscaleÚstore_historyÚhistory_sizeÚfilter_sizeÚdebugÚobjÚn_origÚlinear_constraintsÚnonlinear_constraintsÚlinearÚ	nonlinearÚpbÚ	constantsÚ	frameworkÚsuccessÚn_iterÚk_newÚn_short_stepsÚn_very_short_stepsÚn_alt_modelsÚstatusÚradius_saveÚnormal_stepÚtangential_stepÚstepÚs_normrl   Úimprove_geometryÚdist_newÚsame_best_pointÚfun_valÚcub_valÚceq_valÚ	merit_oldÚ	merit_newÚsoc_stepÚratioÚill_conditionedÚgradÚgrad_altÚ	maxcv_valr   r   úS/var/www/html/CropPilot/venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/main.pyÚminimize$   s0     þþþþ

ôú
úÿÿúúúúúþÿý
	ÿþÿ
þ
üþüÿ

ÿÿÿüþüÿþþþþÿþÿ
þ
þþÿþÿýÿý
ÿ

ù	þþûþ � �â   úr¦   c                 C   sÀ   | du rt t |tj ¡t |tj¡ƒS t| t ƒr6| jj|fks'| jj|fkr/td|› d�ƒ‚t | j| jƒS t	| dƒr\t 
| ¡} | j|dfkrKtdƒ‚t | dd…df | dd…df ƒS td	ƒ‚)
z 
    Uniformize the bounds.
    NzThe bounds must have z
 elements.r   é   zGThe shape of the bounds is not compatible with the number of variables.r   r   zPThe bounds must be an instance of scipy.optimize.Bounds or an array-like object.)r   rC   ÚfullÚinfr,   ÚlbÚshapeÚubr(   r.   ÚasarrayÚ	TypeError)r5   r3   r   r   r¥   r0   q  s     


ÿ"ÿr0   c              	   C   s(  t | tƒs
t| dƒs| f} g }g }| D ]|}t |tƒr7t|jdƒ}t|jdƒ}| t|jgt	 
||¡¢R Ž ¡ qt |tƒrYt|jdƒ}t|jdƒ}| t|jgt	 
||¡¢R Ž ¡ qt |tƒrŒd|vsh|d dvrltdƒ‚d	|vsvt|d	 ƒsztd
ƒ‚| |d	 |d | dd¡dœ¡ qtdƒ‚||fS )z7
    Extract the linear and nonlinear constraints.
    r   z;The lower bound of the linear constraints must be a vector.z;The upper bound of the linear constraints must be a vector.z>The lower bound of the nonlinear constraints must be a vector.z>The upper bound of the nonlinear constraints must be a vector.r]   )ÚeqÚineqz+The constraint type must be "eq" or "ineq".rt   z)The constraint function must be callable.rv   r   )rt   r]   rv   zrThe constraints must be instances of scipy.optimize.LinearConstraint, scipy.optimize.NonlinearConstraint, or dict.)r,   r   r.   r   r   rª   r¬   ÚappendÚArC   Úbroadcast_arraysr   rt   r(   Úcallabler    r®   )rw   r„   r…   Ú
constraintrª   r¬   r   r   r¥   r1   Š  sh   
þþÿ
þÿ
þþÿ
þÿ

ýÿÿr1   c                 C   s  t j| v r| t j dkrtdƒ‚t j| v r | t j dk r tdƒ‚t j| v r9t j| v r9| t j | t j k r8tdƒ‚n@t j| v rPt tt j | t j g¡| t jj< n)t j| v rgt tt j | t j g¡| t jj< ntt j | t jj< tt j | t jj< t	| t j ƒ| t jj< t	| t j ƒ| t jj< t j
| v rŸ| t j
 dkrŸtdƒ‚t j
| v rÃ| t j
 |d |d  d krÃtd	|d |d  d › d
�ƒ‚|  t j
jtt j
 |ƒ¡ t| t j
 ƒ| t j
j< t j| v rë| t j dkrëtdƒ‚|  t jjt tt j |ƒ| t j
 d g¡¡ t| t j ƒ| t jj< t j| v �r| t j dk�rtdƒ‚|  t jjtt j |ƒ¡ t| t j ƒ| t jj< |  t jjtt j ¡ t	| t j ƒ| t jj< |  t jjtt j ¡ t	| t j ƒ| t jj< |  t jjtt j ¡ t| t j ƒ| t jj< |  t jjtt j ¡ t| t j ƒ| t jj< |  t jjtt j ¡ t| t j ƒ| t jj< |  t jjtt j ¡ t| t j ƒ| t jj< |  t jjtt j ¡ t| t j ƒ| t jj< |  t jjtt j ¡ t| t j ƒ| t jj< | D ]}|t j ¡ v�rþt d|› d
�td¡ �qédS )z"
    Set the default options.
    r   z1The initial trust-region radius must be positive.z2The final trust-region radius must be nonnegative.z_The initial trust-region radius must be greater than or equal to the final trust-region radius.r   z4The number of interpolation points must be positive.r   r§   z3The number of interpolation points must be at most r   z<The maximum number of function evaluations must be positive.z2The maximum number of iterations must be positive.zUnknown option: r   N)r   r;   r(   r<   rC   Úminr   ÚvaluerT   r$   ÚNPTÚ
setdefaultr)   r=   r>   ÚTARGETr#   r!   r"   r%   r*   r&   r'   r+   Ú__members__ÚvaluesÚwarningsÚwarnÚRuntimeWarning)ry   r3   Úkeyr   r   r¥   r2   Ï  s¸   ÿÿ
þÿ
þÿ
ÿÿÿþÿþ	þþÿþþþ€þr2   c                  K   sÖ  t | ƒ}| tjjttj ¡ t|tj ƒ|tjj< |tj dks(|tj dkr,tdƒ‚| tjjttj ¡ t|tj ƒ|tjj< |tj dkrMtdƒ‚tj	|v r]|tj	 dkr]tdƒ‚tj
|v rm|tj
 dkrmtdƒ‚tj	|v r†tj
|v r†|tj
 |tj	 kr…tdƒ‚nFtj	|v r¡t ttj
 dd|tj	   g¡|tj
j< n+tj
|v rºt ttj	 d	|tj
  g¡|tj	j< nttj	 |tj	j< ttj
 |tj
j< | tjjttj ¡ t|tj ƒ|tjj< |tj dksð|tj dkrôtd
ƒ‚tj|v �r|tj dk�rtdƒ‚tj|v �r|tj dk�rtdƒ‚tj|v �r4tj|v �r4|tj |tj k�r3tdƒ‚nBtj|v �rLt ttj |tj g¡|tjj< n*tj|v �rdt ttj |tj g¡|tjj< nttj |tjj< ttj |tjj< tj|v �r�|tj dk�sŒ|tj dk�r�tdƒ‚tj|v �rª|tj dk�s¦|tj dk�rªtdƒ‚tj|v �rÆtj|v �rÆ|tj |tj k�rÅtdƒ‚nBtj|v �rÞt ttj |tj g¡|tjj< n*tj|v �röt ttj |tj g¡|tjj< nttj |tjj< ttj |tjj< | tjjttj ¡ t|tj ƒ|tjj< |tj dk�s.|tj dk�r2tdƒ‚tj|v �rD|tj dk �rDtdƒ‚tj|v �rV|tj dk�rVtdƒ‚tj|v �rrtj|v �rr|tj |tj k �rqtdƒ‚nBtj|v �rŠt ttj |tj g¡|tjj< n*tj|v �r¢t ttj |tj g¡|tjj< nttj |tjj< ttj |tjj< | tjjttj ¡ t|tj ƒ|tjj< |tj dk�sÚ|tj dk�rÞtdƒ‚| tjjttj ¡ t|tj ƒ|tjj< |tj dk�s|tj dk�rtdƒ‚| tjjttj ¡ t|tj ƒ|tjj< |tj dk�s.|tj dk�r2tdƒ‚| tjjttj ¡ t|tj ƒ|tjj< |tj dk�rTtdƒ‚| tjjttj ¡ t|tj ƒ|tjj< |tj dk �rvtdƒ‚| tjjttj ¡ t|tj ƒ|tjj< |tj dk�r˜tdƒ‚| tjjttj ¡ t|tj ƒ|tjj< |tj dk�rºtdƒ‚| tjjttj ¡ t|tj ƒ|tjj< | D ]}|tj  ¡ v�rçt! "d|› d�t#d¡ �qÒ|S )z$
    Set the default constants.
    r   g      ð?zCThe constant decrease_radius_factor must be in the interval (0, 1).z>The constant increase_radius_threshold must be greater than 1.z;The constant increase_radius_factor must be greater than 1.z>The constant decrease_radius_threshold must be greater than 1.zPThe constant decrease_radius_threshold must be less than increase_radius_factor.g      à?r   zGThe constant decrease_resolution_factor must be in the interval (0, 1).z?The constant large_resolution_threshold must be greater than 1.zBThe constant moderate_resolution_threshold must be greater than 1.zVThe constant moderate_resolution_threshold must be at most large_resolution_threshold.z6The constant low_ratio must be in the interval (0, 1).z7The constant high_ratio must be in the interval (0, 1).z2The constant low_ratio must be at most high_ratio.z;The constant very_low_ratio must be in the interval (0, 1).zKThe constant penalty_increase_threshold must be greater than or equal to 1.z<The constant penalty_increase_factor must be greater than 1.zaThe constant penalty_increase_factor must be greater than or equal to penalty_increase_threshold.zAThe constant short_step_threshold must be in the interval (0, 1).z>The constant low_radius_factor must be in the interval (0, 1).zAThe constant byrd_omojokun_factor must be in the interval (0, 1).z@The constant threshold_ratio_constraints must be greater than 1.z4The constant large_shift_factor must be nonnegative.z:The constant large_gradient_factor must be greater than 1.z6The constant resolution_factor must be greater than 1.zUnknown constant: r   r   )$r   r¹   r   ÚDECREASE_RADIUS_FACTORr·   r   r$   r(   ÚINCREASE_RADIUS_THRESHOLDÚINCREASE_RADIUS_FACTORÚDECREASE_RADIUS_THRESHOLDrC   r¶   rT   rR   ÚLARGE_RESOLUTION_THRESHOLDÚMODERATE_RESOLUTION_THRESHOLDrj   Ú
HIGH_RATIOrd   ÚPENALTY_INCREASE_THRESHOLDÚPENALTY_INCREASE_FACTORrP   ÚLOW_RADIUS_FACTORr^   ÚTHRESHOLD_RATIO_CONSTRAINTSrL   rg   rU   ÚIMPROVE_TCGr"   r»   r¼   r½   r¾   r¿   )rz   r‰   rÀ   r   r   r¥   r4   7  s2  þÿÿþÿÿ
ÿ
ÿ

ÿÿý
þÿ
þÿÿ
ÿþÿÿÿÿÿÿýþÿþÿ
ÿ
ÿÿÿÿÿþÿþÿÿÿþÿÿÿÿÿÿýþÿþÿ
ÿÿþÿÿþÿÿþÿÿþÿÿþÿþÿÿþÿÿþÿ€r4   c           	      C   s€   | j |tj kr
t‚|j| }| ||jƒ\}}}|  |||¡}||tj kr/||tj kr/t	‚| j
r;||tj kr;t‚|||fS )z:
    Evaluate the objective and constraint functions.
    )rq   r   r=   r   rH   rs   rn   rº   r#   r   Úis_feasibilityr   )	rˆ   rŠ   r•   ry   Úx_evalrš   r›   rœ   Úr_valr   r   r¥   rW   Ž  s   

rW   c           
      C   s  |   |¡\}}}|ot |¡ot |¡}|tjtjfvr%|o$||tj k}tƒ }	tj	dtjdtj
dtjdtjdtjdtjdtjdtjd	i	 |d
¡|	_||	_|j|	_|  |¡|	_||	_||	_| j|	_||	_|tj rq| j|	_| j|	_|tj r†t |	j| |	j|	j|	j|	j|	jƒ |	S )z7
    Build the result of the optimization process.
    z<The lower bound for the trust-region radius has been reachedz4The target objective function value has been reachedz0All variables are fixed by the bound constraintsz9The callback requested to stop the optimization procedurez=The feasibility problem received has been solved successfullyz<The maximum number of function evaluations has been exceededz2The maximum number of iterations has been exceededz$The bound constraints are infeasiblezA linear algebra error occurredzUnknown exit status)!Ú	best_evalrC   Úisfiniter   r?   rA   r   r#   r   rk   r9   r@   rX   rB   r8   rF   r    Úmessager‹   r·   r‘   rp   Úxrt   rn   rq   ÚnfevÚnitr&   Úfun_historyÚmaxcv_historyr!   ro   )
rˆ   rs   r‹   r‘   rŒ   ry   rÓ   rt   rn   Úresultr   r   r¥   r7   ¡  sL   ðï

ù	r7   c                 C   s¨   t ƒ  t | › d�ƒ t d|› d�ƒ t d|› d�ƒ |js)t d|j› d|› d�ƒ t d|› d�ƒ tjd	i t¤Ž� t d|› d�ƒ W d  ƒ dS 1 sMw   Y  dS )
zP
    Print information about the current state of the optimization process.
    r   z Number of function evaluations: zNumber of iterations: zLeast value of z: zMaximum constraint violation: zCorresponding point: Nr   )r:   rÍ   Úfun_namerC   Úprintoptionsr   )rÒ   rˆ   rÓ   rš   rÏ   rq   rŒ   r   r   r¥   ro   Ö  s   "ÿro   )r   Nr   NN)%r½   ÚnumpyrC   Úscipy.optimizer   r   r   r   rŠ   r   Úproblemr   r	   r
   r   r   Úutilsr   r   r   r   r   Úsettingsr   r   r   r   r   r   r¦   r0   r1   r2   r4   rW   r7   ro   r   r   r   r¥   Ú<module>   s8     
ù      SEh  Y5