
    ^Mh                         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	Zd
 Zd Zd Z d Z!d Z"d Z#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                    |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 r%|t          j
                 dk    rt          d          |                    t          j
        t          t          j
                           }t          |          }t          j        |v r%|t          j                 dk    rt          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/          |||          }t1          |||          }t3          |||||||	|
||||          }t5          ||j                   t9          di |}|j        j        st?          |ddt@          j!        d|          S |j        dk    rt?          |ddt@          j"        d|          S |rtG          d	           tG          d
|t          j$                  d           tG          d|t          j%                  d           tG          d|t          j&                  d           tG          d|t          j'                  d           tG                       	 tQ          |||          }n# tR          $ r! t?          |ddt@          j*        d|          cY S tV          $ r! t?          |ddt@          j,        d|          cY S tZ          $ r! t?          |ddt@          j.        d|          cY S t^          $ r! t?          |ddt@          j0        d|          cY S tb          j2        j3        $ r! t?          |ddt@          j4        d|          cY S w xY wd}d}d}d}d}d}	 ||t          j'                 k    rt@          j0        }ni|dz  }tb          j2        5                    |j6        |j7        j8        j9        z
            |tt          j;                 |j<        z  k    r|=                    |           |j<        }|>                    |          \  } }!| |!z   }"tb          j2        5                    |"          }#|#|tt          j?                 |j@        z  k    r|xj<        |tt          jA                 z  c_<        ||j@        k    rd}d}n|dz  }|dz  }|#d|j@        z  k    rd}|dk    p|dk    }$|$rd}d}d}%nM	 |B                                \  }}&n'# tb          j2        j3        $ r t@          j4        }Y n w xY w|&t          |j<        |tt          jD                 |j@        z            k    }%n|E                    |"          }'|'r	 t          |||"|          \  }(})}*nk# tR          $ r t@          j*        }d}Y n~tZ          $ r t@          j.        }d}Y ndtV          $ r t@          j,        }d}Y nJt^          $ r t@          jG        }Y n2w xY w|H                    |j6        |jI        |jJ        |jK                  }+|H                    |j6        |"z   |(|)|*          },|jL        dk    r|,|+k    rtb          j2        5                    |           |tt          jM                 dz  |j<        z  k    r|N                    |"|          }-tb          j2        5                    |-          dk    r|"|-z  }"	 t          |||"|          \  }(})}*nk# tR          $ r t@          j*        }d}Y n!tZ          $ r t@          j.        }d}Y ntV          $ r t@          j,        }d}Y nt^          $ r t@          jG        }Y nw xY w|O                    |"|(|)|*          }.	 |B                    |j6        |"z             d         }n'# tb          j2        j3        $ r t@          j4        }Y nqw xY w	 |j7        P                    ||j6        |"z   |(|)|*          }/n'# tb          j2        j3        $ r t@          j4        }Y n"w xY w|Q                                 |R                    |"|.           |j<        |j@        k    r%|.|tt          jS                 k    rd}n|dz  }|j7        T                    |j6                  }0	 |j7        U                    |j6                  }1n'# tb          j2        j3        $ r t@          j4        }Y naw xY wtb          j2        5                    |0          |tt          jV                 tb          j2        5                    |1          z  k     rd}|dk    rD	 |j7        W                                 n'# tb          j2        j3        $ r t@          j4        }Y nw xY wd}|X                    |j6        |"z              	 |B                                \  }}&n'# tb          j2        j3        $ r t@          j4        }Y new xY w|/pF|.|tt          jY                 k    o0|&t          |j<        |tt          jD                 |j@        z            k    }%||j@        k    o|.|tt          jY                 k    o|% }$nd}$d}%|$r|j@        |t          j%                 k    rd}t@          jZ        }n|[                    |           |\                                 |rs|]                    |j6        |jJ        |jK                  }2t          d|j@         ||_                    |j6                  |jI        |2|j`        |           tG                       |%r	 |a                    ||          }"n&# tb          j2        j3        $ r t@          j4        }Y nw xY w	 t          |||"|          \  }(})}*ng# tR          $ r t@          j*        }d}Y ntZ          $ r t@          j.        }d}Y ntV          $ r t@          j,        }d}Y nt^          $ r t@          jG        }Y nhw xY w	 |j7        P                    ||j6        |"z   |(|)|*           n&# tb          j2        j3        $ r t@          j4        }Y nw xY w|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argsr7   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_normrn   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_vals3                                                      V/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/_lib/cobyqa/main.pyminimizer   $   s   F w--kk'/?7?+KLLG7mmGkk/0 O O,,OKKw}'EFFEKKEKK-. M ''Mw&&773G+HA+M+MDEEE;;,- L |$$Lg%%''2E*F!*K*KCDDD+++, K k""KKKw}'EFFEKKE dE"" w
C%
7$
7
7
7C 2y!! TWWFk&&99::F 1A0M0M--165AAF$%:GUKKI 


 
B  "$'''&0000I 9  
'
 
 	
 
$
 
 	
  	4555Hggn.EHHHIIIFGGN,CFFFGGG,w'(, , ,	
 	
 	
 	Kww7G/HKKKLLL3
GY77		 	
 	
 	
%
 
 	
 	
 	
  	
 	
 	
'
 
 	
 	
 	
  	
 	
 	
'
 
 	
 	
 	
  	
 	
 	
'
 
 	
 	
 	
 9  	
 	
 	
#
 
 	
 	
 	
	
 GFEML\' WW-...0F! INN 9#3#A#HH  569IIJ J
 ""7+++  &'0'F'Fw'O'O$__,%% 789;OOP P 	)*N OOY111 !%&""""a'"C)"6666)*&!.!!3!N7IQ7N!  !%&"#(  &/&C&C&E&EOE88y,   '4FE $,c$i9:*+/ / $   (88>>O ])05!	1 1-GWgg %   '6F"GE&   '8F"GE&   '8F"GE#   '8FE
 &OO$&&&	 	 &OO$t+Wgw 	 G888!I--	{33	 >?3F&'' '  )IIg   H y~~h//#55("8= " ) $ '	9 95GWgg  - " " "%/%>F&*G!E. " " "%/%@F&*G!E. " " "%/%@F&*G!E+ " " "%/%@F!E"
 "55	 %99!(4/ EE y,   '4FE
&/&6&K&Ky/$6' 'OO y,   '4FE ((*** ''e444 #y';;;	)*B CCC'($)(/889IJJ"'0'7'D'D ) 0( (HH  "y4 " " "%/%<F!E" 9>>$//)%;3INN84435 5 5 ,-L'1,,& ) 0 = = ? ? ? ?#%9#8 & & &)3)@ %& ,-L )))*:T*ABBB&/&C&C&E&EOE88y,   '4FE $ 	)*= >>  !(!)"=>#./  !  9#77 -9+>!??-,, #" &+"#(   	#ww~'>>>#2((111&&((( HH$i&8):L 	 F	0DFFJJy/00&I     &	' 225'BB9(   #0
,1"iw,O,O)''    #2"   #4"   #4   #4

 55$t+    9(   #0 $$&&&y\'| 
  s&  +P= =(T''T'T9'T"1TT8Z  Z43Z4\ ^5^^)^^ a7 7cc,ccc;#d  ee&e. . ffh/ / ii2k  k0/k0l+ + mmr* * sss( (uuu4uu&u7 7 vvc                 J   | Kt          t          j        |t          j                   t          j        |t          j                            S t	          | t                     rO| j        j        |fk    s| j        j        |fk    rt          d| d          t          | j        | j                  S t          | d          rTt          j
        |           } | j        |dfk    rt          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   rE   fullinfr.   lbshapeubr*   r0   asarray	TypeError)r7   r5   s     r   r2   r2   q  s"    ~bga"&))271bf+=+=>>>	FF	#	# 
9?qd""fio!&=&=BQBBBCCCfi+++		#	# 
F##<Aq6!!+   fQQQTlF111a4L111=
 
 	
    c           
         t          | t                    st          | d          s| f} g }g }| D ]}t          |t                    rct	          |j        d          }t	          |j        d          }|                    t          |j        gt          j
        ||          R             {t          |t                    rct	          |j        d          }t	          |j        d          }|                    t          |j        gt          j
        ||          R             t          |t                    rd|vs
|d         dvrt          d          d	|vst          |d	                   st          d
          |                    |d	         |d         |                    dd          d           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".rv   z)The constraint function must be callable.rx   r   )rv   r_   rx   zrThe constraints must be instances of scipy.optimize.LinearConstraint, scipy.optimize.NonlinearConstraint, or dict.)r.   r!   r0   r   r   r   r   appendArE   broadcast_arraysr   rv   r*   callabler"   r   )ry   r   r   
constraintr   r   s         r   r3   r3     sO    +t$$ %GK,K,K %"n ! 7 7
j"233 6	M B  M B %% L(R00      
$788 '	 B   B "((#N(R00      
D)) 	Z'':f+= F , , !!NOOOJ&&hz%7H.I.I& !LMMM!((%e,&v.&NN6266     ?  
 444r   c                 X   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 rEt           j        | v r7| t           j                 | t           j                 k     rt          d          n
t           j        | v rNt	          j        t          t           j                 | t           j                 g          | t           j        j        <   nt           j        | v rNt	          j        t          t           j                 | t           j                 g          | t           j        j        <   nRt          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 rA| t           j
                 |dz   |dz   z  dz  k    rt          d	|dz   |dz   z  dz   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	          j        t          t           j                 |          | t           j
                 dz   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 ]A}|t           j                                        vrt5          j        d| d
t8          d           Bd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>   rE   minr   valuerV   r&   NPT
setdefaultr+   r?   r@   TARGETr%   r#   r$   r'   r,   r(   r)   r-   __members__valueswarningswarnRuntimeWarning)r{   r5   keys      r   r4   r4     s^    ~  WW^%<%C%CLMMM~  WW^%<s%B%BMNNN~  W^w%>%>7>"WW^%<<<B   =
 
7	"	"(*/')
 )
$%% 
7	"	"(*/')
 )
$%% )8(G$%(7(G$%$)''.*A$B$BGGN !$)''.*A$B$BGGN !{g''+"6!";"; % & & 	& 	wGK QUq1u$5!#;;;+Q1q5!a'+ + +
 
 	
 w{(/'+*Fq*I*IJJJ!$WW[%9!:!:GGK7""ww/?'@A'E'EJ
 
 	
 
 01!44$q(	
 	
   '*''2B*C&D&DGG"#7""ww/?'@A'E'EMNNN()!,,   '*''2B*C&D&DGG"#w~+_W^-LMMM$)''.*A$B$BGGN !%/0   .3'(. .GG#)* w,ogo.NOOO%)''/*B%C%CGGO!"w}*OGM,JKKK#'(>#?#?GGM !+,   *-WW5H-I)J)JGG%&#-.   ,08M0N+O+OGG!'(",-   +.gg6J.K*L*LGG &'w}*OGM,JKKK#'(>#?#?GGM   H Hg)002222M3S333^QGGGH Hr   c                  l   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    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 rEt          j
        |v r7|t          j
                 |t          j	                 k    rt          d          nt          j	        |v rTt          j        t
          t          j
                 dd|t          j	                 z   z  g          |t          j
        j        <   nt          j
        |v rQt          j        t
          t          j	                 d	|t          j
                 z  g          |t          j	        j        <   nRt
          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 rEt          j        |v r7|t          j                 |t          j                 k    rt          d          n
t          j        |v rNt          j        t
          t          j                 |t          j                 g          |t          j        j        <   nt          j        |v rNt          j        t
          t          j                 |t          j                 g          |t          j        j        <   nRt
          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 rEt          j        |v r7|t          j                 |t          j                 k    rt          d          n
t          j        |v rNt          j        t
          t          j                 |t          j                 g          |t          j        j        <   nt          j        |v rNt          j        t
          t          j                 |t          j                 g          |t          j        j        <   nRt
          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 rEt          j        |v r7|t          j                 |t          j                 k     rt          d          n
t          j        |v rNt          j        t
          t          j                 |t          j                 g          |t          j        j        <   nt          j        |v rNt          j        t
          t          j                 |t          j                 g          |t          j        j        <   nRt
          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    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        <   |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        <   |t          j                 dk    rt          d          |                    t          j        j        t
          t          j                            t=          |t          j                           |t          j        j        <   | D ]A}|t          j                                         vrtC          j"        d| dtF          d           B|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_THRESHOLDrE   r   rV   rT   LARGE_RESOLUTION_THRESHOLDMODERATE_RESOLUTION_THRESHOLDrl   
HIGH_RATIOrf   PENALTY_INCREASE_THRESHOLDPENALTY_INCREASE_FACTORrR   LOW_RADIUS_FACTORr`   THRESHOLD_RATIO_CONSTRAINTSrN   ri   rW   IMPROVE_TCGr$   r   r   r   r   r   )r|   r   r   s      r   r6   r6   7  sL    VI(.):;   9>)239 9Ii.45 	)23s::Y56#==
 
 	
 +1)=>   <A)56< <Ii178 45<<L
 
 	
 	(I55i673>>I
 
 	
 	+y88i9:cAAL
 
 	
 	(I55/9<< i9:9:; ; 4  ; 
	)Y	6	6?Av!)"EFsYy'GHHI@
 @
	)5;<< 
	,		9	9<>F!)"BCi	 CDD=
 =
	)2899 =N,=
	)289 iAB 	)5;<,2)>?   =B)67= =Ii289 	)673>>Y9:cAA
 
 	

 	,	99i:;sBBM
 
 	
 	/9<<i=>#EE
 
 	

 	,	993y@@ i=>	<=> > >  > 
	-	:	:CE6!)"IJ)>?D
 D
	)9?@@ 
	0I	=	=@B!)"FG)ABA
 A
	)6<== iBC 	)6<= iEF 	)9?@ i'')%&#--Y()S00D
 
 	
 y(()&'3..Y)*c11E
 
 	
 i''I,@I,M,MY()Ii6J,KKKD   L 
			)	)02!)"67)-.1
 1
	)&,-- 
		*	*/1v!)"56)./0
 0
	)%+,, 0A0
	)%+, 1B 1
	)&,-  &)23   16)*+1 1Ii&,- 	)*+s22Y-.#55I
 
 	
 	,	99i:;cAA*
 
 	

 	)Y66i78C??J
 
 	
 	,	99-:: i78	<=> > .  > 
	-	:	:=?V!)"CD)>?>
 >
	)39:: 
	*i	7	7@B!)"FG);<A
 A
	)6<== iBC 	)6<= >O->
	)39: &,)89   7<)017 7Ii,23 	)01S88Y34;;O
 
 	
 #))56   49)-.4 4Ii)/0 	)-.#55Y01S88L
 
 	
 &,)89   7<)017 7Ii,23 	)01S88Y34;;O
 
 	
 -3)?@   >C)78> >Ii39: 673>>N
 
 	
 $*)67   5:)./5 5Ii*01 -.44 ( ) ) 	)'-)9:   8=)128 8Ii-34 01S88H
 
 	
 #))56   49)-.4 4Ii)/0 ,-44D
 
 	
 #)/0   .2)'(. .Ii#)*
  J Ji+224444M5s555~qIIIr   c                 j   | j         |t          j                 k    rt          |j        |z   } | ||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.
    )rs   r   r?   r   rJ   ru   rp   r   r%   r   is_feasibilityr   )	r   r   r   r{   x_evalr   r   r   r_vals	            r   rY   rY     s     
yGG,---$F "69+< = =GWgHHVWg..E77>***WW4555	 Ugg.E&FFFGW$$r   c                    |                      |          \  }}}|o't          j        |          ot          j        |          }|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                 r| j        |	_        | j        |	_        |t          j                 r3tA          |	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_evalrE   isfiniter   rA   rC   r   r%   r   rm   r;   rB   rZ   rD   r:   rH   r"   messager   r   r   rr   xrv   rp   rs   nfevnitr(   fun_historymaxcv_historyr#   rq   )
r   ru   r   r   r   r{   r   rv   rp   results
             r   r9   r9     s   
 LL))MAsEA"+c**Ar{5/A/AGj/1LMMMGeww/F'GGF! $=! $2  #0# &># &@# &E# &5#%K!B!" 
c&'((# N$ FNLFMzz!}}FHFJFL)FKFJw$% 0^!/ w 	
NHJLKJ	
 	
 	
 Mr   c                    t                       t          |  d           t          d| d           t          d| d           |j        st          d|j         d| d           t          d| d           t          j        d	i t
          5  t          d| d           ddd           dS # 1 swxY w 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_namerE   printoptionsr   )r   r   r   r   r   rs   r   s          r   rq   rq     s2    
GGG	W---	
6V
6
6
6777	
,6
,
,
,--- ;999w999:::	
35
3
3
3444		)	)=	)	) , ,*a***+++, , , , , , , , , , , , , , , , , ,s   B33B7:B7)r   Nr   NN)%r   numpyrE   scipy.optimizer   r   r   r   r   r   problemr	   r
   r   r   r   utilsr   r   r   r   r   settingsr   r   r   r   r   r   r   r2   r3   r4   r6   rY   r9   rq   r   r   r   <module>r      s                   # " " " " "                                          
J J J JZ
 
 
2B5 B5 B5JeH eH eHPT T Tn
% % %&2 2 2j, , , , ,r   