
    ^Mh                         d Z ddlmZ ddlZddlZddlZddlZddlZddl	m
Z
 ddlmZmZmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ dgZ	 	 ddddZ G d d          Z G d d          Z G d d          ZdS )z<shgo: The simplicial homology global optimisation algorithm.    )
namedtupleN)spatial)OptimizeResultminimizeBounds)
MemoizeJac)new_bounds_to_old)standardize_constraints)_FunctionWrapper)Complexshgo d      
simplicial)workersc
                   t          |t                    r-t          |j        |j        t          |j                            }t          | |||||||||	|
          5 }|                                 ddd           n# 1 swxY w Y   |j        s|j	        rt          j        d           t          |j        j                  dk    r~|                                 d|_        |                    d|j                    |j        |j        _        |j        |j        _        |j        |j        _        |j        |j        _        n	 |j        sd|j        _        d|j        _        |j        S )	aJ  
    Finds the global minimum of a function using SHG optimization.

    SHGO stands for "simplicial homology global optimization".

    Parameters
    ----------
    func : callable
        The objective function to be minimized.  Must be in the form
        ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array
        and ``args`` is a tuple of any additional fixed parameters needed to
        completely specify the function.
    bounds : sequence or `Bounds`
        Bounds for variables. There are two ways to specify the bounds:

        1. Instance of `Bounds` class.
        2. Sequence of ``(min, max)`` pairs for each element in `x`.

    args : tuple, optional
        Any additional fixed parameters needed to completely specify the
        objective function.
    constraints : {Constraint, dict} or List of {Constraint, dict}, optional
        Constraints definition. Only for COBYLA, COBYQA, SLSQP and trust-constr.
        See the tutorial [5]_ for further details on specifying constraints.

        .. note::

           Only COBYLA, COBYQA, SLSQP, and trust-constr local minimize methods
           currently support constraint arguments. If the ``constraints``
           sequence used in the local optimization problem is not defined in
           ``minimizer_kwargs`` and a constrained method is used then the
           global ``constraints`` will be used.
           (Defining a ``constraints`` sequence in ``minimizer_kwargs``
           means that ``constraints`` will not be added so if equality
           constraints and so forth need to be added then the inequality
           functions in ``constraints`` need to be added to
           ``minimizer_kwargs`` too).
           COBYLA only supports inequality constraints.

        .. versionchanged:: 1.11.0

           ``constraints`` accepts `NonlinearConstraint`, `LinearConstraint`.

    n : int, optional
        Number of sampling points used in the construction of the simplicial
        complex. For the default ``simplicial`` sampling method 2**dim + 1
        sampling points are generated instead of the default ``n=100``. For all
        other specified values `n` sampling points are generated. For
        ``sobol``, ``halton`` and other arbitrary `sampling_methods` ``n=100`` or
        another specified number of sampling points are generated.
    iters : int, optional
        Number of iterations used in the construction of the simplicial
        complex. Default is 1.
    callback : callable, optional
        Called after each iteration, as ``callback(xk)``, where ``xk`` is the
        current parameter vector.
    minimizer_kwargs : dict, optional
        Extra keyword arguments to be passed to the minimizer
        ``scipy.optimize.minimize``. Some important options could be:

        method : str
            The minimization method. If not given, chosen to be one of
            BFGS, L-BFGS-B, SLSQP, depending on whether or not the
            problem has constraints or bounds.
        args : tuple
            Extra arguments passed to the objective function (``func``) and
            its derivatives (Jacobian, Hessian).
        options : dict, optional
            Note that by default the tolerance is specified as
            ``{ftol: 1e-12}``

    options : dict, optional
        A dictionary of solver options. Many of the options specified for the
        global routine are also passed to the ``scipy.optimize.minimize``
        routine. The options that are also passed to the local routine are
        marked with "(L)".

        Stopping criteria, the algorithm will terminate if any of the specified
        criteria are met. However, the default algorithm does not require any
        to be specified:

        maxfev : int (L)
            Maximum number of function evaluations in the feasible domain.
            (Note only methods that support this option will terminate
            the routine at precisely exact specified value. Otherwise the
            criterion will only terminate during a global iteration)
        f_min : float
            Specify the minimum objective function value, if it is known.
        f_tol : float
            Precision goal for the value of f in the stopping
            criterion. Note that the global routine will also
            terminate if a sampling point in the global routine is
            within this tolerance.
        maxiter : int
            Maximum number of iterations to perform.
        maxev : int
            Maximum number of sampling evaluations to perform (includes
            searching in infeasible points).
        maxtime : float
            Maximum processing runtime allowed
        minhgrd : int
            Minimum homology group rank differential. The homology group of the
            objective function is calculated (approximately) during every
            iteration. The rank of this group has a one-to-one correspondence
            with the number of locally convex subdomains in the objective
            function (after adequate sampling points each of these subdomains
            contain a unique global minimum). If the difference in the hgr is 0
            between iterations for ``maxhgrd`` specified iterations the
            algorithm will terminate.

        Objective function knowledge:

        symmetry : list or bool
            Specify if the objective function contains symmetric variables.
            The search space (and therefore performance) is decreased by up to
            O(n!) times in the fully symmetric case. If `True` is specified
            then all variables will be set symmetric to the first variable.
            Default
            is set to False.

            E.g.  f(x) = (x_1 + x_2 + x_3) + (x_4)**2 + (x_5)**2 + (x_6)**2

            In this equation x_2 and x_3 are symmetric to x_1, while x_5 and
            x_6 are symmetric to x_4, this can be specified to the solver as::

                symmetry = [0,  # Variable 1
                            0,  # symmetric to variable 1
                            0,  # symmetric to variable 1
                            3,  # Variable 4
                            3,  # symmetric to variable 4
                            3,  # symmetric to variable 4
                            ]

        jac : bool or callable, optional
            Jacobian (gradient) of objective function. Only for CG, BFGS,
            Newton-CG, L-BFGS-B, TNC, SLSQP, dogleg, trust-ncg. If ``jac`` is a
            boolean and is True, ``fun`` is assumed to return the gradient
            along with the objective function. If False, the gradient will be
            estimated numerically. ``jac`` can also be a callable returning the
            gradient of the objective. In this case, it must accept the same
            arguments as ``fun``. (Passed to `scipy.optimize.minimize`
            automatically)

        hess, hessp : callable, optional
            Hessian (matrix of second-order derivatives) of objective function
            or Hessian of objective function times an arbitrary vector p.
            Only for Newton-CG, dogleg, trust-ncg. Only one of ``hessp`` or
            ``hess`` needs to be given. If ``hess`` is provided, then
            ``hessp`` will be ignored. If neither ``hess`` nor ``hessp`` is
            provided, then the Hessian product will be approximated using
            finite differences on ``jac``. ``hessp`` must compute the Hessian
            times an arbitrary vector. (Passed to `scipy.optimize.minimize`
            automatically)

        Algorithm settings:

        minimize_every_iter : bool
            If True then promising global sampling points will be passed to a
            local minimization routine every iteration. If True then only the
            final minimizer pool will be run. Defaults to True.

        local_iter : int
            Only evaluate a few of the best minimizer pool candidates every
            iteration. If False all potential points are passed to the local
            minimization routine.

        infty_constraints : bool
            If True then any sampling points generated which are outside will
            the feasible domain will be saved and given an objective function
            value of ``inf``. If False then these points will be discarded.
            Using this functionality could lead to higher performance with
            respect to function evaluations before the global minimum is found,
            specifying False will use less memory at the cost of a slight
            decrease in performance. Defaults to True.

        Feedback:

        disp : bool (L)
            Set to True to print convergence messages.

    sampling_method : str or function, optional
        Current built in sampling method options are ``halton``, ``sobol`` and
        ``simplicial``. The default ``simplicial`` provides
        the theoretical guarantee of convergence to the global minimum in
        finite time. ``halton`` and ``sobol`` method are faster in terms of
        sampling point generation at the cost of the loss of
        guaranteed convergence. It is more appropriate for most "easier"
        problems where the convergence is relatively fast.
        User defined sampling functions must accept two arguments of ``n``
        sampling points of dimension ``dim`` per call and output an array of
        sampling points with shape `n x dim`.

    workers : int or map-like callable, optional
        Sample and run the local serial minimizations in parallel.
        Supply -1 to use all available CPU cores, or an int to use
        that many Processes (uses `multiprocessing.Pool <multiprocessing>`).

        Alternatively supply a map-like callable, such as
        `multiprocessing.Pool.map` for parallel evaluation.
        This evaluation is carried out as ``workers(func, iterable)``.
        Requires that `func` be pickleable.

        .. versionadded:: 1.11.0

    Returns
    -------
    res : OptimizeResult
        The optimization result represented as a `OptimizeResult` object.
        Important attributes are:
        ``x`` the solution array corresponding to the global minimum,
        ``fun`` the function output at the global solution,
        ``xl`` an ordered list of local minima solutions,
        ``funl`` the function output at the corresponding local solutions,
        ``success`` a Boolean flag indicating if the optimizer exited
        successfully,
        ``message`` which describes the cause of the termination,
        ``nfev`` the total number of objective function evaluations including
        the sampling calls,
        ``nlfev`` the total number of objective function evaluations
        culminating from all local search optimizations,
        ``nit`` number of iterations performed by the global routine.

    Notes
    -----
    Global optimization using simplicial homology global optimization [1]_.
    Appropriate for solving general purpose NLP and blackbox optimization
    problems to global optimality (low-dimensional problems).

    In general, the optimization problems are of the form::

        minimize f(x) subject to

        g_i(x) >= 0,  i = 1,...,m
        h_j(x)  = 0,  j = 1,...,p

    where x is a vector of one or more variables. ``f(x)`` is the objective
    function ``R^n -> R``, ``g_i(x)`` are the inequality constraints, and
    ``h_j(x)`` are the equality constraints.

    Optionally, the lower and upper bounds for each element in x can also be
    specified using the `bounds` argument.

    While most of the theoretical advantages of SHGO are only proven for when
    ``f(x)`` is a Lipschitz smooth function, the algorithm is also proven to
    converge to the global optimum for the more general case where ``f(x)`` is
    non-continuous, non-convex and non-smooth, if the default sampling method
    is used [1]_.

    The local search method may be specified using the ``minimizer_kwargs``
    parameter which is passed on to ``scipy.optimize.minimize``. By default,
    the ``SLSQP`` method is used. In general, it is recommended to use the
    ``SLSQP``, ``COBYLA``, or ``COBYQA`` local minimization if inequality
    constraints are defined for the problem since the other methods do not use
    constraints.

    The ``halton`` and ``sobol`` method points are generated using
    `scipy.stats.qmc`. Any other QMC method could be used.

    References
    ----------
    .. [1] Endres, SC, Sandrock, C, Focke, WW (2018) "A simplicial homology
           algorithm for lipschitz optimisation", Journal of Global
           Optimization.
    .. [2] Joe, SW and Kuo, FY (2008) "Constructing Sobol' sequences with
           better  two-dimensional projections", SIAM J. Sci. Comput. 30,
           2635-2654.
    .. [3] Hock, W and Schittkowski, K (1981) "Test examples for nonlinear
           programming codes", Lecture Notes in Economics and Mathematical
           Systems, 187. Springer-Verlag, New York.
           http://www.ai7.uni-bayreuth.de/test_problem_coll.pdf
    .. [4] Wales, DJ (2015) "Perspective: Insight into reaction coordinates and
           dynamics from the potential energy landscape",
           Journal of Chemical Physics, 142(13), 2015.
    .. [5] https://docs.scipy.org/doc/scipy/tutorial/optimize.html#constrained-minimization-of-multivariate-scalar-functions-minimize

    Examples
    --------
    First consider the problem of minimizing the Rosenbrock function, `rosen`:

    >>> from scipy.optimize import rosen, shgo
    >>> bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)]
    >>> result = shgo(rosen, bounds)
    >>> result.x, result.fun
    (array([1., 1., 1., 1., 1.]), 2.920392374190081e-18)

    Note that bounds determine the dimensionality of the objective
    function and is therefore a required input, however you can specify
    empty bounds using ``None`` or objects like ``np.inf`` which will be
    converted to large float numbers.

    >>> bounds = [(None, None), ]*4
    >>> result = shgo(rosen, bounds)
    >>> result.x
    array([0.99999851, 0.99999704, 0.99999411, 0.9999882 ])

    Next, we consider the Eggholder function, a problem with several local
    minima and one global minimum. We will demonstrate the use of arguments and
    the capabilities of `shgo`.
    (https://en.wikipedia.org/wiki/Test_functions_for_optimization)

    >>> import numpy as np
    >>> def eggholder(x):
    ...     return (-(x[1] + 47.0)
    ...             * np.sin(np.sqrt(abs(x[0]/2.0 + (x[1] + 47.0))))
    ...             - x[0] * np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0))))
    ...             )
    ...
    >>> bounds = [(-512, 512), (-512, 512)]

    `shgo` has built-in low discrepancy sampling sequences. First, we will
    input 64 initial sampling points of the *Sobol'* sequence:

    >>> result = shgo(eggholder, bounds, n=64, sampling_method='sobol')
    >>> result.x, result.fun
    (array([512.        , 404.23180824]), -959.6406627208397)

    `shgo` also has a return for any other local minima that was found, these
    can be called using:

    >>> result.xl
    array([[ 512.        ,  404.23180824],
           [ 283.0759062 , -487.12565635],
           [-294.66820039, -462.01964031],
           [-105.87688911,  423.15323845],
           [-242.97926   ,  274.38030925],
           [-506.25823477,    6.3131022 ],
           [-408.71980731, -156.10116949],
           [ 150.23207937,  301.31376595],
           [  91.00920901, -391.283763  ],
           [ 202.89662724, -269.38043241],
           [ 361.66623976, -106.96493868],
           [-219.40612786, -244.06020508]])

    >>> result.funl
    array([-959.64066272, -718.16745962, -704.80659592, -565.99778097,
           -559.78685655, -557.36868733, -507.87385942, -493.9605115 ,
           -426.48799655, -421.15571437, -419.31194957, -410.98477763])

    These results are useful in applications where there are many global minima
    and the values of other global minima are desired or where the local minima
    can provide insight into the system (for example morphologies
    in physical chemistry [4]_).

    If we want to find a larger number of local minima, we can increase the
    number of sampling points or the number of iterations. We'll increase the
    number of sampling points to 64 and the number of iterations from the
    default of 1 to 3. Using ``simplicial`` this would have given us
    64 x 3 = 192 initial sampling points.

    >>> result_2 = shgo(eggholder,
    ...                 bounds, n=64, iters=3, sampling_method='sobol')
    >>> len(result.xl), len(result_2.xl)
    (12, 23)

    Note the difference between, e.g., ``n=192, iters=1`` and ``n=64,
    iters=3``.
    In the first case the promising points contained in the minimiser pool
    are processed only once. In the latter case it is processed every 64
    sampling points for a total of 3 times.

    To demonstrate solving problems with non-linear constraints consider the
    following example from Hock and Schittkowski problem 73 (cattle-feed)
    [3]_::

        minimize: f = 24.55 * x_1 + 26.75 * x_2 + 39 * x_3 + 40.50 * x_4

        subject to: 2.3 * x_1 + 5.6 * x_2 + 11.1 * x_3 + 1.3 * x_4 - 5    >= 0,

                    12 * x_1 + 11.9 * x_2 + 41.8 * x_3 + 52.1 * x_4 - 21
                        -1.645 * sqrt(0.28 * x_1**2 + 0.19 * x_2**2 +
                                      20.5 * x_3**2 + 0.62 * x_4**2)      >= 0,

                    x_1 + x_2 + x_3 + x_4 - 1                             == 0,

                    1 >= x_i >= 0 for all i

    The approximate answer given in [3]_ is::

        f([0.6355216, -0.12e-11, 0.3127019, 0.05177655]) = 29.894378

    >>> def f(x):  # (cattle-feed)
    ...     return 24.55*x[0] + 26.75*x[1] + 39*x[2] + 40.50*x[3]
    ...
    >>> def g1(x):
    ...     return 2.3*x[0] + 5.6*x[1] + 11.1*x[2] + 1.3*x[3] - 5  # >=0
    ...
    >>> def g2(x):
    ...     return (12*x[0] + 11.9*x[1] +41.8*x[2] + 52.1*x[3] - 21
    ...             - 1.645 * np.sqrt(0.28*x[0]**2 + 0.19*x[1]**2
    ...                             + 20.5*x[2]**2 + 0.62*x[3]**2)
    ...             ) # >=0
    ...
    >>> def h1(x):
    ...     return x[0] + x[1] + x[2] + x[3] - 1  # == 0
    ...
    >>> cons = ({'type': 'ineq', 'fun': g1},
    ...         {'type': 'ineq', 'fun': g2},
    ...         {'type': 'eq', 'fun': h1})
    >>> bounds = [(0, 1.0),]*4
    >>> res = shgo(f, bounds, n=150, constraints=cons)
    >>> res
     message: Optimization terminated successfully.
     success: True
         fun: 29.894378159142136
        funl: [ 2.989e+01]
           x: [ 6.355e-01  1.137e-13  3.127e-01  5.178e-02] # may vary
          xl: [[ 6.355e-01  1.137e-13  3.127e-01  5.178e-02]] # may vary
         nit: 1
        nfev: 142 # may vary
       nlfev: 35 # may vary
       nljev: 5
       nlhev: 0

    >>> g1(res.x), g2(res.x), h1(res.x)
    (-5.062616992290714e-14, -2.9594104944408173e-12, 0.0)

    )	argsconstraintsniterscallbackminimizer_kwargsoptionssampling_methodr   Nz/Successfully completed construction of complex.r   TzCFailed to find a feasible minimizer point. Lowest sampling point = )mesz%Optimization terminated successfully.)
isinstancer   r	   lbublenSHGOiterate_allbreak_routinedisplogginginfoLMCxl_mapsfind_lowest_vertexfail_routinef_lowestresfunx_lowestxfnnfev	n_sampledtnevmessagesuccess)funcboundsr   r   r   r   r   r   r   r   r   shcs               T/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/optimize/_shgo.pyr   r      s   N &&!! I"69fiVYHH
 
dF;!X 0	
  
  
   $'                L8 	LLJKKK 37?q   	     G8;G G 	H 	H 	HlL	v} 	  A 7Ns   A>>BBc                       e Zd Z	 	 	 d(dZd Zd Zd Zd	 Zd
 Zd Z	d Z
d Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd)dZd Zd Zd Zd Zd*dZd*dZd Zd+d!Zd)d"Zd# Zd$ Z d% Z!d,d'Z"dS )-r!   r   Nr   r   c           	      L    ddl m} g d}t          |
t                    r9|
|vr5t	          d                    d                    |                              	 |d         du rBt          |d                   s-t          |           _	         j	        j
        }||d<    j	        }n| _	        n# t          t          f$ r
 | _	        Y nw xY wt          ||           _	        | _        | _        | _        t#          j        |t&                    }t#          j        |          d          _        t#          j        |           }d||d d df         df<   d	||d d d
f         d
f<   |d d df         |d d d
f         k    }|                                r0t	          dd                    d |D                        d          | _        | _        || _        g  _        g  _        t9          |t#          j         j        t&                    d           _         j        D ]x}|d         dv rl j                            |d                    	  j                            |d                    N# t          $ r  j                            d           Y tw xY wyt?           j                   _        t?           j                   _        nd  _        d  _        d j        i  j        d _         | j         !                    |           nddi j         d<    j         d         "                                dv r|d|vr| j         j         j         d<   |	 #                    |	           nTd  _$        d _%        d  _&        d  _'        d  _(        d  _)        d  _$        d  _*        d  _+        d _,        d _-        d _.        g d _/        i dg dd g d!g d"dgd#dgd$g d%d&dd'gd(dd'gd)dd*gd+g d,d-g d.d/dd0gd1g d%d2g d%d3dd0gd4g d5} j         d         } xj/        ||"                                         z  c_/        d6 } | j          j/                    | j         d          j/        dgz              d _0        d _1        | _2        d _3        | _4        d _5        d _6        d _7        d _8        d _9        d _:         j4        & j2        |
d7k    rd8 j        z  d
z    _4        d _5         j2        d
 _2         j4        |
d7k    sd9x _4         _4        d _5         j4        d9k    r|
d7k    rd8 j        z  d
z    _4         j&         j'         j(         j*         j$        d  _2        tw           j         j         j	        d j+         j        |:           _<        |
d7k    r j=         _>        |
 _?        n|
d;v st          |
t                    sЉ j@         _>        |
d;v r|
d<k    rqt          d8t#          jB        t#          jC         j4                            z             _4        d _5        d< _?        |D                     j        dd=           _E        n)d> _?        |F                     j        dd=           _E         fd?}
nd@ _?         jG         _H        |
 _I        d _J        d _K        g  _L        t                       _N        t                       _P        d jP        _Q        d jP        _R        d jP        _S        d jP        _T        d S )ANr   )qmc)haltonsobolr   z4Unknown sampling_method specified. Valid methods: {}z, jacTgd~Qgd~QJr   zError: lb > ub in bounds c              3   4   K   | ]}t          |          V  d S N)str).0bs     r9   	<genexpr>z SHGO.__init__.<locals>.<genexpr>  s(      )A)AQ#a&&)A)A)A)A)A)A    .oldtypeineqr-   r   r   SLSQP)methodr7   r   r   ftolg-q=r   rL   )slsqpcobylacobyqatrust-constrr   F)r-   x0r   r   r   rL   _custom)r?   hesshesspr7   r   znelder-meadpowellcgbfgsz	newton-cgr?   rT   rU   zl-bfgs-br7   tncrO   catolrP   )r7   r   feasibility_tolrN   )r?   r7   r   doglegrT   z	trust-ncgztrust-krylovztrust-exactrQ   )r?   rT   rU   r   c                 z    t          |           }|t          |          z
  D ]}|                     |d           dS )z8Remove keys from dictionary if not in goodkeys - inplaceN)setpop)
dictionarygoodkeysexistingkeyskeys       r9   _restrict_to_keysz(SHGO.__init__.<locals>._restrict_to_keys  sH    z??L#c(mm3 * *sD))))* *rF   r      r   )dimdomainsfieldsfield_argssymmetryr   r   )r=   r>   r>   )dscrambleseedr=   c                 8    j                             |           S rA   )
qmc_enginerandom)r   rl   selfs     r9   r   z&SHGO.__init__.<locals>.sampling_method  s    ?11!444rF   custom)Uscipy.statsr<   r   rB   
ValueErrorformatjoincallabler   r6   
derivative	TypeErrorKeyErrorr   r7   r   r   nparrayfloatshaperg   isfiniteanyr   min_consg_consg_argsr
   emptyappendtupler   updatelowerinit_options
f_min_trueminimize_every_itermaxitermaxfevmaxevmaxtimeminhgrdrk   infty_cons_sampl
local_iterr$   min_solver_argsstop_globalr#   r   
iters_doner   ncn_prcr2   r0   hgrqhull_incrementalr   HCiterate_hypercubeiterate_complexr   iterate_delaunayintceillog2Sobolrp   Haltonsampling_customsamplingsampling_functionstop_l_iterstop_complex_iterminimizer_pool	LMapCacher'   r   r,   r1   nlfevnljevnlhev)rr   r6   r7   r   r   r   r   r   r   r   r   r   r<   methodsr?   aboundinfindbnderrconssolver_argsrL   re   s   `                     r9   __init__zSHGO.__init__  s    	$#####333os++ 	Pw0N0N 34:F499W;M;M4N4NP P P
	!%(D00!"25"9:: 1&t,,	i**- 'y 	8$ 	 	 	DIII	 %T400		  &%((8F##A& +f%%%"'vaaad|Q"&vaaad|Q 1qqq!t,::<< 	F E $		)A)A&)A)A)A A AE E E F F F  '"'DMDKDK  75))   D
 ( / /<F++K&&tE{333/**4<8888# / / /**2...../	 ,  ,,DK,,DKKDKDK ,3+/;,.-1]!# !#
 '!(()9:::: 17D!), !(+1133 8H H H !,%555'[$37=D!-0 g&&&&"DO'+D$  DLDKDJDL"DODL !DM %)D!#DO DI A  A  A
HHH
2
 b
 5'	

 UG
 111
 )
 E8$
 }g.
 BBB
 555
 ufo
 111
 444
 E6?
  CCC!
$ &x0FLLNN ;;	* 	* 	* 	$/1EFFF$/	:.&9	; 	; 	;
 !"

!% FN!3$44$(]Q&DFDG:DJFN_%D%D!!DFTVDGFcMM< ? ?$(]Q&DF%DK,?
"\)0GDJ dht{!%#'=&*&6")	+ + + l**#'#9D #2D   33344 4#'#8D "555"g-- bgbgdfoo&>&>!>??DF  DG+2D(&)ii$(U56 '0 '8 '8DOO ,4D(&)jj48d67 '1 '9 '9DO5 5 5 5 5 5
 (0$ 0DM%4D" !!& ! ;; "##s%   AB/ /C
	C
 I22$JJc                    | j         d                             |           dD ]9}|| j         d         v r(| j         d                             |          | j         |<   :|                    dd          | _        |                    dd          | _        |                    dd          | _        |                    dd          | _        t          j                    | _	        |                    d	d          | _
        d
|v r)|d
         | _        |                    dd          | _        nd| _        |                    dd          | _        |                    dd          | _        | j        rdgt          | j                  z  | _        nd| _        |                    dd          | _        |                    dd          | _        |                    dd          | _        dS )z
        Initiates the options.

        Can also be useful to change parameters after class initiation.

        Parameters
        ----------
        options : dict

        Returns
        -------
        None

        r   rY   r   Tr   Nr   r   r   f_minf_tolg-C6?r   rk   Fr   r   infty_constraintsr$   )r   r   r`   getr   r   r   r   timeinitr   r   r   r   rk   r    r7   r   r   r$   )rr   r   opts      r9   r   zSHGO.init_options  s   " 	i(//888 , 	? 	?Cd+I666))488== %c* $+;;/Dd#K#K  {{9d33kk(D11 [[$//
IKK	{{9d33g%g.DO Wd33DJJ"DO{{9d33  J66= 	!E#dk"2"22DMM DM "++lE:: ',? F F KK..			rF   c                     | S rA   r   rr   s    r9   	__enter__zSHGO.__enter__-  s    rF   c                 4     | j         j        j        j        | S rA   )r   V_mapwrapper__exit__)rr   r   s     r9   r   zSHGO.__exit__0  s    -twy$-t44rF   c                 J   | j         rt          j        d           | j        s7| j        rn/|                                  |                                  | j        7| j        s| j        s|                                  | j	        | j
        _        | j        j        j        | _        dS )z
        Construct for `iters` iterations.

        If uniform sampling is used, every iteration adds 'n' sampling points.

        Iterations if a stopping criteria (e.g., sampling points or
        processing time) has been met.

        zSplitting first generationN)r$   r%   r&   r   r#   iteratestopping_criteriar   find_minimar   r,   nitr   r   r1   r0   r   s    r9   r"   zSHGO.iterate_all5  s     9 	7L5666" 	%! LLNNN""$$$ " 	% ' 	#% #  """').rF   c                    | j         rt          j        d           |                                  t	          | j                  dk    rQ|                     | j                   |                                  | j	        j
        | _        | j	        j        | _        n|                                  | j         rt          j        d| j                    dS dS )z
        Construct the minimizer pool, map the minimizers to local minima
        and sort the results into a global return object.
        zSearching for minimizer pool...r   zMinimiser pool = SHGO.X_min = N)r$   r%   r&   
minimizersr    X_minminimise_poolr   sort_resultr,   r-   r+   r/   r.   r)   r   s    r9   r   zSHGO.find_minimaS  s    
 9 	<L:;;;tz??a t/// !HLDM HJDMM##%%%9 	HLF$*FFGGGGG	H 	HrF   c                 `   t           j        | _        | j        j        j        D ]}| j        j        |         j        | j        k     rk| j        r,t          j	        d| j        j        |         j                    | j        j        |         j        | _        | j        j        |         j
        | _        | j        j        D ]K}| j        |         j        | j        k     r.| j        |         j        | _        | j        |         j        | _        L| j        t           j        k    rd | _        d | _        d S d S )Nzself.HC.V[x].f = )r|   infr+   r   r   cachefr$   r%   r&   x_ar.   r'   r   x_l)rr   r/   lmcs      r9   r)   zSHGO.find_lowest_vertexn  s      	1 	1Awy|~--9 GL!ETWYq\^!E!EFFF $	! $	! 08> 	2 	2Cx}"T]22 $ 3 $ 1=BF"" DM DMMM #"rF   c                    t          d | j        | j        fD                       }| j        rt	          j        d| j         d|            | j        | j        | j        k    rd| _        | j        | j        | j        k    rd| _        | j        S )Nc              3      K   | ]}||V  	d S rA   r   )rC   r/   s     r9   rE   z)SHGO.finite_iterations.<locals>.<genexpr>  s"      HHq!-----HHrF   zIterations done =  / T)minr   r   r$   r%   r&   r   r   )rr   mis     r9   finite_iterationszSHGO.finite_iterations  s    HHTZ6HHHHH9 	HLFdoFF"FFGGG:!4:..#' <#4<00#' rF   c                     | j         r$t          j        d| j         d| j                    | j        | j        k    rd| _        | j        S )NzFunction evaluations done = r   T)r$   r%   r&   r0   r   r   r   s    r9   
finite_fevzSHGO.finite_fev  sR    9 	SLQQQDKQQRRR7dk!!#DrF   c                     | j         r$t          j        d| j         d| j                    | j        | j        k    r	d| _        d S d S )NzSampling evaluations done = r   T)r$   r%   r&   r2   r   r   r   s    r9   	finite_evzSHGO.finite_ev  sg    9 	,L + + +"j+ + , , ,>TZ''#D ('rF   c                     | j         r8t          j        dt          j                    | j        z
   d| j                    t          j                    | j        z
  | j        k    r	d| _        d S d S )NzTime elapsed = r   T)r$   r%   r&   r   r   r   r   r   s    r9   finite_timezSHGO.finite_time  s}    9 	.L -49;;+B - -"l- - . . .IKK$)#44#D 54rF   c                 4   |                                   | j        r8t          j        d| j                    t          j        d| j                    | j        | j        S | j        dk    r| j        | j        k    rd| _        n| j        | j        z
  t          | j                  z  }| j        | j        k    rHd| _        t          |          d| j        z  k    r&t          j
        d| j         d| j         d	
           || j        k    rd| _        | j        S )z
        Stop the algorithm if the final function value is known

        Specify in options (with ``self.f_min_true = options['f_min']``)
        and the tolerance with ``f_tol = options['f_tol']``
        zLowest function evaluation = zSpecified minimum = N        Trf   z&A much lower value than expected f* = z was found f_lowest =    )
stacklevel)r)   r$   r%   r&   r+   r   r   r   abswarningswarn)rr   pes     r9   finite_precisionzSHGO.finite_precision  s=    	!!!9 	CLHHHIIILAAABBB= ## ?c!!}
**#' -$/1S5I5IIB}//#' r77a$*n,,M@ @ @04@ @#$   
 TZ#' rF   c                    | j         j        dk    rdS | j         j        | j        z
  | _        | j         j        | _        | j        | j        k    rd| _        | j        r%t          j        d| j         d| j         d           | j        S )zV
        Stop the algorithm if homology group rank did not grow in iteration.
        r   NTzCurrent homology growth = z  (minimum growth = ))	r'   sizer   hgrdr   r   r$   r%   r&   r   s    r9   finite_homology_growthzSHGO.finite_homology_growth  s     8=AFHMDH,	8=9$$#D9 	@L ?di ? ?/3|? ? ? @ @ @rF   c                    | j         |                                  | j        |                                  | j        |                                  | j        |                                  | j        |                                  | j	        | 
                                 | j        |                                  | j        S )zt
        Various stopping criteria ran every iteration

        Returns
        -------
        stop : bool
        )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   s    r9   r   zSHGO.stopping_criteria  s     <#""$$$:!""$$$;"OO:!NN<#?&!!###<#'')))rF   c                     |                                   | j        r| j        s|                                  | xj        dz  c_        d S Nr   )r   r   r#   r   r   r   s    r9   r   zSHGO.iterate  sT     # 	#% #  """ 	1rF   c                    | j         rt          j        d           | j        =| j                                         | j        j                                        | _        n4| j        	                    | j                   | xj        | j        z  c_        | j         rt          j        d           t          | j        j                  dk    rY| j        j        D ]L}| j        j        |         }|                                }|j        D ]}|                    |j                  }M| j        j                                         | j         rt          j        d           | j        j        j        | _        dS )z
        Iterate a subdivision of the complex

        Note: called with ``self.iterate_complex()`` after class initiation
        z<Constructing and refining simplicial complex graph structureNRTriangulation completed, evaluating all constraints and objective function values.r   Evaluations completed.)r$   r%   r&   r   r   
refine_allr   r   r2   refiner    r'   r(   r   starnnunionprocess_poolsr1   r0   )rr   xlvv_nears       r9   r   zSHGO.iterate_hypercube  s]    9 	&L % & & &6>G   !WY^^--DNNGNN46"""NNdf$NN9 	;L : ; ; ; tx  1$$hn 0 0GIbM 0 0A#\\!$//FF0 		!!!9 	3L1222 ').rF   c                    | xj         | j        z  c_         |                     | j                   | j        rLt          j        d| j                    t          j        d| j                     t          j        d           | j        dk     rt          j	        | j
        d          | _        | j                                        | _        g }t          | j                  D ]3\  }}|dk    r(|                    | j        |dz
  |dz                       4t          j        |          } t!          d	d
dg          | j
        |          | _        i | _        nP| j
        j        d         | j        dz   k    r|                     | j                   | j
        j        d         | _        | j        rt          j        d           t-          | d	          r/| j                            | j        j        | j        j                   | j        rt          j        d           | j        j                                         | j        rt          j        d           | j        j        j        | _        | j         | _        dS )z
        Build a complex of Delaunay triangulated points

        Note: called with ``self.iterate_complex()`` after class initiation
        )r   z	self.n = z
self.nc = zRConstructing and refining simplicial complex graph structure from sampling points.rf   r   axisr   Tripoints	simplices)r   r   r   N)r   r   sampled_surfacer   r$   r%   r&   rg   r|   argsortC
Ind_sortedflatten	enumerater   r}   r   r  r  r   delaunay_triangulationr   hasattrr   vf_to_vvr  r   r   r1   r0   r2   )rr   trisindind_ss       r9   r   zSHGO.iterate_delaunay,  sf    	46d.CDDD 9 	<L-TV--...L/dg//000L ; < < < 8a<< ja888DO"o5577DOD'88 B B
U77KKaa @AAA8D>>DAz%(K)@AA$&$OODHDKKv|AA--++$*+===aDJ9 	GL F G G G 4 	BGTX_dh.@AAA 9 	;L : ; ; ; 		!!!9 	3L1222 ').rF   c                    g | _         | j        j        j        D ]}d}t	          | j        j                  dk    rM| j        j        D ]@}t          j        t          j	        |          t          j	        |          k              rd}A|rr| j        j        |         
                                rM| j        rt          j        d           t          j        d| j        j        |         j         d           t          j        d| j        j        |         j         d           t          j        d           | j        j        |         | j         vr*| j                             | j        j        |                    | j        rzt          j        d	           t          j        d           | j        j        |         j        D ]&}t          j        d
|j         d|j                    't          j        d           g | _        g | _        i | _        | j         D ]a}| j                            |j                   | j                            |j                   |j        | j        t-          |j                  <   bt          j	        | j                  | _        t          j	        | j                  | _        |                                  | j        S )z7
        Returns the indexes of all minimizers
        Fr   Tz<============================================================zv.x = z is minimizerzv.f = z==============================z
Neighbors:zx = z || f = )r   r   r   r   r    r'   r(   r|   allr}   	minimiserr$   r%   r&   r   r   r   r   r/   minimizer_pool_Fr   X_min_cacher   sort_min_pool)rr   r/   in_LMCxlmivnr   s         r9   r   zSHGO.minimizerse  s    ! 	+ 	+AF48#$$q(( H, & &DvbhqkkRXd^^;<< &!% wy|%%'' +9 +L***L!I$')A,*:!I!I!IJJJL!G$')A,.!G!G!GHHHL***79Q<t':::'..twy|<<<9 +L...L***"gilo B B%@BD%@%@"$%@%@AAAAL*** "
$ 	1 	1AJae$$$!((----.SDU15\\** ")> ? ?Xdj))
 	zrF   Fc                 H   |                      | j        d         | j        d                   }|                     d           | j        s|                                  |r|dz  }|dk    rd| _        nt          j        | j                  d         dk    rd| _        n}|                     |j	        | j                   | j
        dddf         }|                      | j        dddf         | j        d                   }|                     |           | j        d| _        dS )a;  
        This processing method can optionally minimise only the best candidate
        solutions in the minimiser pool

        Parameters
        ----------
        force_iter : int
                     Number of starting minimizers to process (can be specified
                     globally or locally)

        r   r  r   TNF)r   r   r   trim_min_poolr   r   r|   r   g_topographr/   ZSs)rr   
force_iter
lres_f_min
ind_xmin_ls       r9   r   zSHGO.minimise_pool  s4    ]]4:a=d6I!6L]MM
 	1" 	+""$$$  a
??'+D$x
##A&!++#' 
 Z\4:666 2Jtwr111u~t7J27NOOJ z***5 " 	+: !rF   c                     t          j        | j                  | _        t          j        | j                  | j                 | _        t          j        | j                  | j                 | _        d S rA   )r|   r  r  	ind_f_minr}   r   r   s    r9   r  zSHGO.sort_min_pool  sV    D$9:: ht':;;DNK ")> ? ?N!rF   c                     t          j        | j        |d          | _        t          j        | j        |          | _        t          j        | j        |          | _        d S )Nr   r   )r|   deleter   r  r   )rr   trim_inds     r9   r  zSHGO.trim_min_pool  sO    Ytz8!<<<
 "	$*? J J i(;XFFrF   c                 H   t          j        |g          }t          j                            ||d          | _        t          j        | j        d          | _        || j                 d         | _        | j	        | j                 | _	        | j	        d         | _	        | j        S )a  
        Returns the topographical vector stemming from the specified value
        ``x_min`` for the current feasible set ``X_min`` with True boolean
        values indicating positive entries and False values indicating
        negative entries.

        	euclideanr  r   r   )
r|   r}   r   distancecdistYr  r  r  r   )rr   x_minr   s      r9   r  zSHGO.g_topograph  s     %!!!''ukBBDF,,,-""1$&9"1!4wrF   c                    d | j         D             }|j        D ]x}t          |j                  D ]a\  }}||j        |         k     r|||         d         k    r|||         d<   ||j        |         k    r|||         d         k     r|||         d<   by| j        r3t          j        d|j                    t          j        d|            |S )aM  
        Construct locally (approximately) convex bounds

        Parameters
        ----------
        v_min : Vertex object
                The minimizer vertex

        Returns
        -------
        cbounds : list of lists
            List of size dimension with length-2 list of bounds for each
            dimension.

        c                 .    g | ]}|d          |d         gS r   r   r   rC   x_b_is     r9   
<listcomp>z1SHGO.construct_lcb_simplicial.<locals>.<listcomp>  %    AAAEE!HeAh'AAArF   r   r   zcbounds found for v_min.x_a = z
cbounds = )r7   r   r	  r   r$   r%   r&   )rr   v_mincboundsr  ix_is         r9   construct_lcb_simplicialzSHGO.construct_lcb_simplicial  s      BAT[AAA( 	( 	(B#BF++ ( (3%)A,&&S71:a=-@-@$'GAJqM %)A,&&S71:a=-@-@$'GAJqM( 9 	1LE%)EEFFFL/g//000rF   c                 (    d | j         D             }|S )aL  
        Construct locally (approximately) convex bounds

        Parameters
        ----------
        v_min : Vertex object
                The minimizer vertex

        Returns
        -------
        cbounds : list of lists
            List of size dimension with length-2 list of bounds for each
            dimension.
        c                 .    g | ]}|d          |d         gS r0  r   r1  s     r9   r3  z/SHGO.construct_lcb_delaunay.<locals>.<listcomp>  r4  rF   r7   )rr   r5  r  r6  s       r9   construct_lcb_delaunayzSHGO.construct_lcb_delaunay  s     BAT[AAArF   c                    | j         r!t          j        d| j        j                    | j        |         j        9t          j        d| j        |         j                    | j        |         j        S | j        t          j        d| d           | j         rt          j        d| d           | j        dk    rt          |          }| j	        t          |                   }t          |          }| 
                    | j        j        |                   }d	| j        v r)|| j        d	<   t          j        | j        d	                    nI|                     ||
          }d	| j        v r)|| j        d	<   t          j        | j        d	                    | j         r<d	| j        v r3t          j        d           t          j        | j        d	                    t!          | j        |fi | j        }| j         rt          j        d|            | j        xj        |j        z  c_        d|v r| j        xj        |j        z  c_        d|v r| j        xj        |j        z  c_        	 |j        d         |_        n# t4          t6          f$ r
 |j         Y nw xY w| j        |          | j                            |||           |S )a  
        This function is used to calculate the local minima using the specified
        sampling point as a starting value.

        Parameters
        ----------
        x_min : vector of floats
            Current starting point to minimize.

        Returns
        -------
        lres : OptimizeResult
            The local optimization result represented as a `OptimizeResult`
            object.
        zVertex minimiser maps = NzFound self.LMC[x_min].lres = z#Callback for minimizer starting at :zStarting minimization at z...r   r7   r  zbounds in kwarg:zlres = njevnhevr   r<  )r$   r%   r&   r'   v_mapslresr   r   r   r  r9  r   r   r   r   r=  r   r6   r,   r   r1   r   r@  r   rA  r-   
IndexErrorrz   add_res)rr   r-  r  x_min_tx_min_t_normg_boundsrC  s          r9   r   zSHGO.minimize$  s   " 9 	GLEDHOEEFFF8E?+L 3 HUO03 3 4 4 48E?''=$LGuGGGHHH9 	AL?U???@@@<//EllG+E'NN;L ..L44TWY|5LMMH4///2:%h/T28<=== 225c2BBH4///2:%h/T28<===9 	:T%:::L+,,,L.x8999 	5BBD,ABB9 	+L)4))*** 	$)#T>>HNNdi'NNT>>HNNdi'NN	x{DHHI& 	 	 	HHHH	 	X666s   &I9 9JJc                    | j                                         }|d         | j        _        |d         | j        _        |d         | j        _        |d         | j        _        | j        | j        j        z   | j        _	        | j        S )A
        Sort results and build the global return object
        r   funlr/   r-   )
r'   sort_cache_resultr,   r   rK  r/   r-   r0   r   r1   )rr   resultss     r9   r   zSHGO.sort_resultp  sh    
 (,,..dmS\
u~ $(.0xrF   Failed to convergec                 T    d| _         d| j        _        d g| _        || j        _        d S )NTF)r#   r,   r5   r   r4   )rr   r   s     r9   r*   zSHGO.fail_routine  s-    ! V
rF   c                    | j         rt          j        d           |                     | j        | j                   t          | j        j                  dk    r<t          j
        | j        t          j        | j        j                  f          | _        |s| j        |                                  |                                  | j        | _        dS )a  
        Sample the function surface.

        There are 2 modes, if ``infty_cons_sampl`` is True then the sampled
        points that are generated outside the feasible domain will be
        assigned an ``inf`` value in accordance with SHGO rules.
        This guarantees convergence and usually requires less objective
        function evaluations at the computational costs of more Delaunay
        triangulation points.

        If ``infty_cons_sampl`` is False, then the infeasible points are
        discarded and only a subspace of the sampled points are used. This
        comes at the cost of the loss of guaranteed convergence and usually
        requires more objective function evaluations.
        zGenerating sampling pointsr   N)r$   r%   r&   r   r   rg   r    r'   r(   r|   vstackr  r}   r   sampling_subspacesorted_samplesr2   )rr   r   s     r9   r  zSHGO.sampled_surface  s    " 9 	7L5666dgtx(((tx  1$$Y1A(B(BCDDDF 	){&&&((( 	 rF   c                    | j         dk    r|                     ||          | _        n|                     ||          | _        t          t	          | j                            D ][}| j        dd|f         | j        |         d         | j        |         d         z
  z  | j        |         d         z   | j        dd|f<   \| j        S )zu
        Generates uniform sampling points in a hypercube and scales the points
        to the bound limits.
        r   Nr   )r2   r   r  ranger    r7   )rr   r   rg   r7  s       r9   r   zSHGO.sampling_custom  s     >Q++As33DFF++As33DFs4;''(( 	1 	1A F111a4L![^A.Q1BBD"k!nQ/0DF111a4LL vrF   c                 B    t           j                  D ]\  t          j         fd j        D             t
                    } j        |          _         j        j        dk    r1d j        _         j	        rt          j         j        j                   dS )z7Find subspace of feasible points from g_func definitionc           	      d    g | ],}t          j         |gj                 R  d k              -S )r   )r|   r  r   )rC   x_Cgr  rr   s     r9   r3  z*SHGO.sampling_subspace.<locals>.<listcomp>  sA    LLLc#1C 0111S899LLLrF   )dtyper   zJNo sampling point found within the feasible set. Increasing sampling size.N)r	  r   r|   r}   r  boolr   r,   r4   r$   r%   r&   )rr   feasiblerY  r  s   ` @@r9   rR  zSHGO.sampling_subspace  s      ,, 	3 	3FC
 xLLLLLLTVLLL  H VH%DFv{a%.  9 3L!1222#	3 	3rF   c                     t          j        | j        d          | _        | j        | j                 | _        | j        | j        fS )z*Find indexes of the sorted sampling pointsr   r   )r|   r  r  r  Xsr   s    r9   rS  zSHGO.sorted_samples  s9    *TV!444&)''rF   r   c                    t          | d          r3| j        r,| j                            | j        |d d d f                    n	 t          j        | j        | j                  | _        n# t
          j        $ rw t          t          j
                    d                   d d         dk    rAt          j        d           d| _        t          j        | j        | j                  | _        n Y nw xY w| j        S )Nr  )incrementalr      QH6239a   QH6239 Qhull precision error detected, this usually occurs when no bounds are specified, Qhull can only run with handling cocircular/cospherical points and in this case incremental mode is switched off. The performance of shgo will be reduced in this mode.F)r  r   r  
add_pointsr  r   Delaunay
QhullErrorrB   sysexc_infor%   warning)rr   r   s     r9   r
  zSHGO.delaunay_triangulation  s!   4 	D$: 	 Huvvqqqy 12222"+DF8<8N. . . %   s|~~a())"1"-99O %D E E E .3D*&/040F H  H  HDHH 	 H  xs   %A+ +BC10C1)	r   NNNNNNr   r   )FrA   )rN  )r   )#__name__
__module____qualname__r   r   r   r   r"   r   r)   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r9  r=  r   r   r*   r  r   rR  rS  r
  r   rF   r9   r!   r!     s5       BF=AEFB B B BJ=/ =/ =/~  5 5 5
! ! !<H H H6! ! !(          $ $ $$ $ $"  "  " H           0	 	 	- - -^6 6 6r0 0 0h2 2 2 2h      &     D   (I I I IX  "   ! ! ! !B  $3 3 3,( ( (     rF   r!   c                       e Zd Zd ZdS )LMapc                 L    || _         d | _        d | _        d | _        g | _        d S rA   )r   r   rC  r   lbounds)rr   r   s     r9   r   zLMap.__init__  s)    	
rF   N)ri  rj  rk  r   r   rF   r9   rm  rm    s#            rF   rm  c                   (    e Zd Zd Zd ZddZd ZdS )r   c                     i | _         g | _        g | _        t                      | _        g | _        g | _        d| _        d S )Nr   )r   rB  r(   r_   xl_maps_setf_mapslbound_mapsr   r   s    r9   r   zLMapCache.__init__  s?    
 55			rF   c                 
   	 t           j                            |          }n# t          $ r Y nw xY wt	          |          }	 | j        |         S # t          $ r) t          |          }|| j        |<   | j        |         cY S w xY wrA   )r|   ndarraytolistrz   r   r   r{   rm  )rr   r   xvals      r9   __getitem__zLMapCache.__getitem__  s    	
!!!$$AA 	 	 	D	!HH	!:a=  	! 	! 	!77D DJqM:a=   		!s   " 
//A 0BBNc                 b   t           j                            |          }t          |          }|j        | j        |         _        || j        |         _        |j        | j        |         _	        || j        |         _
        | xj        dz  c_        | j                            |           | j                            |j                   | j                            t          |j                             | j                            |j                   | j                            |           d S r   )r|   rv  rw  r   r/   r   r   rC  r-   r   ro  r   rB  r   r(   rr  addrs  rt  )rr   r   rC  r7   s       r9   rE  zLMapCache.add_res  s    Ja  !HH F
1!
1"h
1 &
1 			Q		 	1DF###U46]]+++48$$$'''''rF   c                 L   i }t          j        | j                  | _        t          j        | j                  | _        t          j        | j                  }| j        |         |d<   t          j        | j                  | _        | j        |         |d<   |d         j        |d<   | j        |d                  |d<   | j        |d                  |d<   t           j                            | j                  | _        t           j                            | j                  | _        |S )rJ  r   rK  r   r/   r-   )r|   r}   r(   rs  r  Trv  rw  )rr   rM  
ind_sorteds      r9   rL  zLMapCache.sort_cache_result(  s     x--ht{++ Z,,
 Z0ht{+++j1!&/+ |JqM2Z]3z((66j''44rF   rA   )ri  rj  rk  r   ry  rE  rL  r   rF   r9   r   r     sU        	 	 	! ! !( ( ( ($    rF   r   )r   Nr   r   NNNr   )__doc__collectionsr   r   r%   r   rf  numpyr|   scipyr   scipy.optimizer   r   r   scipy.optimize._optimizer   scipy.optimize._constraintsr	   scipy.optimize._minimizer
   scipy._lib._utilr   !scipy.optimize._shgo_lib._complexr   __all__r   r!   rm  r   r   rF   r9   <module>r     s   B B " " " " " "    



           ; ; ; ; ; ; ; ; ; ; / / / / / / 9 9 9 9 9 9 < < < < < < - - - - - - 5 5 5 5 5 5( GK9EO O O O O OdH H H H H H H HV        D D D D D D D D D DrF   