a
    ¯ïaÜê  ã                   @   sŠ   d 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
 ddlmZ dgZdd
d„ZG dd„ dƒZG dd„ dƒZG dd„ dƒZdS )z=
shgo: The simplicial homology global optimisation algorithm
é    N)Úspatial)ÚOptimizeResultÚminimize)ÚComplexÚshgo© é   Ú
simplicialc
                 C   s¤   t | |||||||||	d
}
|
 ¡  |
js8|
jr8tdƒ t|
jjƒdkrˆ|
 ¡  d|
_|
j	d 
|
j¡d |
j|
j_|
j|
j_|
j|
j_|
jsžd|
j_d|
j_|
jS )aF  
    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
        Bounds for variables.  ``(min, max)`` pairs for each element in ``x``,
        defining the lower and upper bounds for the optimizing argument of
        `func`. It is required to have ``len(bounds) == len(x)``.
        ``len(bounds)`` is used to determine the number of parameters in ``x``.
        Use ``None`` for one of min or max when there is no bound in that
        direction. By default bounds are ``(None, None)``.
    args : tuple, optional
        Any additional fixed parameters needed to completely specify the
        objective function.
    constraints : dict or sequence of dict, optional
        Constraints definition.
        Function(s) ``R**n`` in the form::

            g(x) >= 0 applied as g : R^n -> R^m
            h(x) == 0 applied as h : R^n -> R^p

        Each constraint is defined in a dictionary with fields:

            type : str
                Constraint type: 'eq' for equality, 'ineq' for inequality.
            fun : callable
                The function defining the constraint.
            jac : callable, optional
                The Jacobian of `fun` (only for SLSQP).
            args : sequence, optional
                Extra arguments to be passed to the function and Jacobian.

        Equality constraint means that the constraint function result is to
        be zero whereas inequality means that it is to be non-negative.
        Note that COBYLA only supports inequality constraints.

        .. note::

           Only the COBYLA and SLSQP 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).

    n : int, optional
        Number of sampling points used in the construction of the simplicial
        complex. Note that this argument is only used for ``sobol`` and other
        arbitrary `sampling_methods`. In case of ``sobol``, it must be a
        power of 2: ``n=2**m``, and the argument will automatically be
        converted to the next higher power of 2. Default is 100 for
        ``sampling_method='simplicial'`` and 128 for
        ``sampling_method='sobol'``.
    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, the default is ``SLSQP``.
            * 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
            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 : bool
            Specify True if the objective function contains symmetric variables.
            The search space (and therefore performance) is decreased by O(n!).

        * 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.minmize` 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.minmize`
            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 False then only the
            final minimizer pool will be run. Defaults to False.
        * 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`.

    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`` or ``COBYLA`` 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] Hoch, 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.

    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)

    >>> 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, 20)

    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, iters=3, constraints=cons)
    >>> res
         fun: 29.894378159142136
        funl: array([29.89437816])
     message: 'Optimization terminated successfully.'
        nfev: 114
         nit: 3
       nlfev: 35
       nlhev: 0
       nljev: 5
     success: True
           x: array([6.35521569e-01, 1.13700270e-13, 3.12701881e-01, 5.17765506e-02])
          xl: array([[6.35521569e-01, 1.13700270e-13, 3.12701881e-01, 5.17765506e-02]])

    >>> 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_methodz/Successfully completed construction of complex.r   TzEFailed to find a feasible minimizer point. Lowest sampling point = {})Úmesz%Optimization terminated successfully.)ÚSHGOÚconstruct_complexÚbreak_routineÚdispÚprintÚlenÚLMCÚxl_mapsÚfind_lowest_vertexÚfail_routineÚformatÚf_lowestÚresÚfunÚx_lowestÚxÚfnÚnfevÚmessageÚsuccess)ÚfuncÚboundsr
   r   r   r   r   r   r   r   Zshcr   r   úd/Users/vegardjervell/Documents/master/model/venv/lib/python3.9/site-packages/scipy/optimize/_shgo.pyr      s2       ýÿ


c                   @   sV  e Zd ZdUdd„Zdd„ Zdd	„ Zd
d„ Zdd„ Zdd„ Zdd„ Z	dd„ Z
dd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zd d!„ Zd"d#„ ZdVd%d&„Zd'd(„ Zd)d*„ Zd+d,„ Zd-d.„ ZdWd/d0„ZdXd1d2„Zd3d4„ ZdYd6d7„ZdZd8d9„Zd:d;„ Zd<d=„ Zd>d?„ Zd@dA„ Z dBdC„ Z!dDdE„ Z"dFdG„ Z#dHdI„ Z$dJdK„ Z%d[dMdN„Z&e'dOdP„ ƒZ(dQdR„ Z)dSdT„ Z*dS )\r   r   NÚsobolc                    s$  ddl m} g d¢}t|
tƒr:|
|vr:td d |¡¡ƒ‚|ˆ _|ˆ _|ˆ _	|ˆ _
t |t¡}t |¡d ˆ _t |¡ }d||d d …df df< d||d d …df df< |d d …df |d d …df k}| ¡ rðtd	 d d
d„ |D ƒ¡¡ƒ‚|ˆ _|d ur®|ˆ _g ˆ _g ˆ _t|ƒtur4t|ƒtur4|f}|D ]Z}|d dkr8ˆ j |d ¡ zˆ j |d ¡ W n  tyŽ   ˆ j d¡ Y n0 q8tˆ jƒˆ _tˆ jƒˆ _nd ˆ _d ˆ _ˆ j	dˆ ji ˆ j
dœˆ _|d urêˆ j |¡ nddiˆ jd< ˆ jd dv r&|d ur&d|vr&|d us2ˆ jd ur>ˆ jˆ jd< |	d urTˆ  |	¡ nHd ˆ _dˆ _d ˆ _d ˆ _ d ˆ _!d ˆ _"d ˆ _d ˆ _#dˆ _$dˆ _%dˆ _&dˆ _'g d¢ˆ _(g d¢g g dgdgg d¢ddgddgdgg d ¢dd!gg d¢g d¢dd!gd"œ}ˆ jd }ˆ  j(|| )¡  7  _(d#d$„ }|ˆ jˆ j(ƒ |ˆ jd ˆ j(dg ƒ dˆ _*dˆ _+|ˆ _,dˆ _-|ˆ _.|ˆ _/dˆ _0dˆ _1dˆ _2dˆ _3ˆ j,d u rŽdˆ _,ˆ j.d u r¸d%ˆ _.|
d&kr°d'ˆ _.ˆ j.ˆ _/ˆ jd u rôˆ j d u rôˆ j!d u rôˆ j#d u rôˆ jd u súd ˆ _,|
d(krˆ j4ˆ _5ˆ j6ˆ _7|
ˆ _8nÂ|
d)v s2t|
tƒsÞˆ j9ˆ _5ˆ j:ˆ _7|
d)v rÊ|
d&krœt;d*t <t =ˆ j.¡¡ ƒˆ _.ˆ j.ˆ _/d&ˆ _8|j>ˆ jdtj? @¡ d+ˆ _An d,ˆ _8|jBˆ jdtj? @¡ d+ˆ _A‡ fd-d.„}
nd/ˆ _8ˆ jCˆ _D|
ˆ _Edˆ _Fdˆ _Gg ˆ _HtIƒ ˆ _JtKƒ ˆ _Ldˆ jL_Mdˆ jL_Ndˆ jL_Odˆ jL_Pd S )0Nr   )Úqmc)Úhaltonr*   r	   z4Unknown sampling_method specified. Valid methods: {}z, gšd~ÅQÊgšd~ÅQJr   zError: lb > ub in bounds {}.c                 s   s   | ]}t |ƒV  qd S ©N)Ústr)Ú.0Úbr   r   r)   Ú	<genexpr>Þ  ó    z SHGO.__init__.<locals>.<genexpr>ÚtypeZineqr    r
   r   ÚSLSQP)r
   Úmethodr(   r   r   Zftolgê-™—q=r   r5   )r4   ZCOBYLAr   FT)r    Zx0r
   r   r   r5   )ÚjacÚhessÚhesspr(   r   r6   )r6   r7   r8   r(   )r6   r(   r   r7   )Z_customznelder-meadZpowellZcgZbfgsz	newton-cgzl-bfgs-bZtncZcobylaZslsqpZdoglegz	trust-ncgztrust-krylovztrust-exactc                 S   s*   t | ƒ}|t |ƒ D ]}|  |d¡ qdS )z8Remove keys from dictionary if not in goodkeys - inplaceN)ÚsetÚpop)Ú
dictionaryZgoodkeysZexistingkeysÚkeyr   r   r)   Ú_restrict_to_keysA  s    z(SHGO.__init__.<locals>._restrict_to_keyséd   r*   é€   r	   )r,   r*   é   )ÚdZscrambleÚseedr,   c                    s   ˆ j  | ¡S r-   )Ú
qmc_engineÚrandom)r   rA   ©Úselfr   r)   Ú<lambda>}  r2   zSHGO.__init__.<locals>.<lambda>Zcustom)QZscipy.statsr+   Ú
isinstancer.   Ú
ValueErrorr   Újoinr'   r(   r
   r   ÚnpÚarrayÚfloatÚshapeÚdimÚisfiniteÚanyZmin_consÚg_consÚg_argsr3   ÚtupleÚlistÚappendÚKeyErrorr   ÚupdateÚinit_optionsÚ
f_min_trueÚminimize_every_iterÚmaxiterÚmaxfevÚmaxevÚmaxtimeÚminhgrdÚsymmetryÚ
local_iterÚinfty_cons_samplr   Úmin_solver_argsÚlowerÚstop_globalr   r   Ú
iters_doner   ÚncÚn_prcÚ	n_sampledr#   ÚhgrÚiterate_hypercubeÚiterate_complexÚsimplex_minimizersÚ
minimizersr   Úiterate_delaunayÚdelaunay_complex_minimisersÚintÚceilÚlog2ZSobolrD   ZRandomStaterC   ZHaltonÚsampling_customÚsamplingÚsampling_functionÚstop_l_iterZstop_complex_iterÚminimizer_poolÚ	LMapCacher   r   r   r$   ÚnlfevÚnljevÚnlhev)rF   r'   r(   r
   r   r   r   r   r   r   r   r+   ÚmethodsZaboundZinfindZbnderrZconsZsolver_argsr5   r=   r   rE   r)   Ú__init__¿  s6   ÿ ÿ
ÿü
ÿþýü

ò


ÿ
ÿþþ

ÿ


ÿ

ÿzSHGO.__init__c                 C   sÎ   | j d  |¡ | dd¡| _| dd¡| _| dd¡| _| dd¡| _t ¡ | _| dd¡| _	d	|v r‚|d	 | _
| d
d¡| _nd| _
| dd¡| _d|v | _| 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   r[   Fr\   Nr]   r^   r_   Úf_minÚf_tolg-Cëâ6?r`   ra   rb   Zinfty_constraintsTr   )r   rX   Úgetr[   r\   r]   r^   ÚtimeÚinitr_   rZ   r   r`   ra   rb   rc   r   )rF   r   r   r   r)   rY   —  s     


zSHGO.init_optionsc                 C   sT   | j rtdƒ | js.| jrq.|  ¡  |  ¡  q| jsB| jsB|  ¡  | jd | 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 generationr   N)r   r   rf   r   ÚiterateÚstopping_criteriar[   Úfind_minimarg   r   ZnitrE   r   r   r)   r   Ì  s    

zSHGO.construct_complexc                 C   sL   |   ¡  t| jƒdkr@|  | j¡ |  ¡  | jj| _| jj	| _
n|  ¡  dS )zŒ
        Construct the minimizer pool, map the minimizers to local minima
        and sort the results into a global return object.
        r   N)ro   r   ÚX_minÚminimise_poolrb   Úsort_resultr   r    r   r"   r!   r   rE   r   r   r)   r‡   è  s    
zSHGO.find_minimac                 C   sÂ   | j dkrptj| _| jjjD ]8}| jj| j| jk r| jj| j| _| jj| j| _	q| jtjkr¾d | _d | _	nN| j
dkrˆd | _d | _	n6tj| jdd| _| j| jd  | _| j| jd  | _	d S )Nr	   r   éÿÿÿÿ©Zaxis)r   rK   Úinfr   ÚHCÚVÚcacheÚfÚx_ar!   r#   ÚargsortÚFZf_IÚC)rF   r"   r   r   r)   r   ü  s    

zSHGO.find_lowest_vertexc                 C   sF   | j d ur | j| j d kr d| _| jd ur@| j| jd kr@d| _| jS )Nr   T)r   rg   rf   r\   rE   r   r   r)   Úfinite_iterations  s    

zSHGO.finite_iterationsc                 C   s   | j | jkrd| _| jS ©NT)r#   r]   rf   rE   r   r   r)   Ú
finite_fev  s    zSHGO.finite_fevc                 C   s   | j | jkrd| _d S r—   )rj   r^   rf   rE   r   r   r)   Ú	finite_ev"  s    zSHGO.finite_evc                 C   s   t   ¡ | j | jkrd| _d S r—   )rƒ   r„   r_   rf   rE   r   r   r)   Úfinite_time'  s    zSHGO.finite_timec                 C   s¶   t | jjƒdkr|  ¡  | jdkr@| jdkr°| j| jkr°d| _np| j| j t| jƒ }| j| jkr d| _t|ƒd| j kr t	 
dd | j¡ d d | j¡ ¡ || 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']``
        r   ç        Tr@   z%A much lower value than expected f* =z {} thanz the was found f_lowest =z{} )r   r   r   r   r   rZ   r   rf   ÚabsÚwarningsÚwarnr   )rF   Úper   r   r)   Úfinite_precision+  s(    


ÿþ
ý
zSHGO.finite_precisionc                 C   sB   | j jdkrd S | j j| j | _| j j| _| j| jkr<d| _| jS )Nr   T)r   Úsizerk   Zhgrdr`   rf   rE   r   r   r)   Úfinite_homology_growthJ  s    
zSHGO.finite_homology_growthc                 C   s‚   | j dur|  ¡  | jdur$|  ¡  | jdur6|  ¡  | jdurH|  ¡  | jdurZ|  ¡  | j	durl|  
¡  | jdur~|  ¡  dS )zt
        Various stopping criteria ran every iteration

        Returns
        -------
        stop : bool
        N)r\   r–   r   r]   r˜   r^   r™   r_   rš   rZ   r    r`   r¢   rE   r   r   r)   r†   T  s    






zSHGO.stopping_criteriac                 C   s.   |   ¡  | jr| js|  ¡  |  jd7  _d S ©Nr   )rm   r[   r   r‡   rg   rE   r   r   r)   r…   k  s
    zSHGO.iteratec                 C   sV   | j dkr0t| j| j| j| j| j| j| jƒ| _	n
| j	 
¡  | j	jj| _| j	jj| _ dS )zƒ
        Iterate a subdivision of the complex

        Note: called with ``self.iterate_complex()`` after class initiation
        r   N)rj   r   rO   r'   r
   ra   r(   rR   rS   rŽ   Zsplit_generationr   r$   r#   r¡   rE   r   r   r)   rl   v  s    
þ
zSHGO.iterate_hypercubec                 C   s*   | j | jd |  j| j7  _| j| _dS )zŽ
        Build a complex of Delaunay triangulated points

        Note: called with ``self.iterate_complex()`` after class initiation
        )rc   N)Úsampled_surfacerc   rh   r   rj   rE   r   r   r)   rp   Š  s    zSHGO.iterate_delaunayc                 C   s`  g | _ | jjjD ]Ö}| jj|  ¡ r| jrrt d¡ t d | jj| j	¡¡ t d | jj| j
¡¡ t d¡ | jj| | j vr˜| j  | jj| ¡ | jrt d¡ t d¡ | jj| jD ]}t d |j|j
¡¡ qÀt d¡ qg | _g | _i | _| j D ]4}| j |j	¡ | j |j
¡ |j| jt|j	ƒ< q t | j¡| _t | j¡| _|  ¡  | jS )z7
        Returns the indexes of all minimizers
        z<============================================================zv.x = {} is minimizerzv.f = {} is minimizerz==============================z
Neighbors:zx = {} || f = {})ry   rŽ   r   r   Z	minimiserr   ÚloggingÚinfor   r’   r‘   rV   Únnr"   Úminimizer_pool_Frˆ   ÚX_min_cacherT   rK   rL   Úsort_min_pool)rF   r"   ÚvnÚvr   r   r)   rn   •  s:    
ÿ



zSHGO.simplex_minimizersFc                 C   s   | j | jd | jd d}|  d¡ |r.|| _| js| jdurf|j| j t| jƒ | j	krfd| _q| jdurª| j
rˆt d | j¡¡ |  jd8  _| jdkrªd| _qt | j¡d dkrÈd| _q|  |j| j¡ | jdd…df }|   | jddd…f | jd ¡}|  |¡ q.d| _dS )	a;  
        This processing method can optionally minimise only the best candidate
        solutions in the minimizer pool

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

        r   ©ÚindNTz)SHGO.iters in function minimise_pool = {}r   r‹   F)r   rˆ   ry   Útrim_min_poolrb   rx   rZ   r    rœ   r   r   r¥   r¦   r   rK   rN   Úg_topographr"   ÚZÚSs)rF   Z
force_iterZ
lres_f_minZ
ind_xmin_lr   r   r)   r‰   Ã  sB    

ÿÿ
ÿÿ
 zSHGO.minimise_poolc                 C   s:   t  | j¡| _t  | j¡| j | _t  | j¡| j | _d S r-   )rK   r“   r¨   Z	ind_f_minrL   ry   rE   r   r   r)   rª     s    
ÿzSHGO.sort_min_poolc                 C   s8   t j| j|dd| _t  | j|¡| _t  | j|¡| _d S )Nr   rŒ   )rK   Údeleterˆ   r¨   ry   )rF   Ztrim_indr   r   r)   r¯   
  s    zSHGO.trim_min_poolc                 C   s`   t  |g¡}tj ||d¡| _t j| jd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.

        Z	euclideanr‹   rŒ   r   )
rK   rL   r   ZdistanceZcdistÚYr“   r±   r²   ry   )rF   Úx_minrˆ   r   r   r)   r°     s    zSHGO.g_topographc                 C   s°   dd„ | j D ƒ}|jD ]l}t|jƒD ]\\}}||j| k rV||| d krV||| d< ||j| kr$||| d k r$||| d< q$q| jr¬t d |j¡¡ t d |¡¡ |S )a@  
        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                 S   s   g | ]}|d  |d g‘qS ©r   r   r   ©r/   Zx_b_ir   r   r)   Ú
<listcomp>2  r2   z1SHGO.construct_lcb_simplicial.<locals>.<listcomp>r   r   z cbounds found for v_min.x_a = {}zcbounds = {})r(   r§   Ú	enumerater’   r   r¥   r¦   r   )rF   Úv_minÚcboundsr«   ÚiZx_ir   r   r)   Úconstruct_lcb_simplicial#  s    
zSHGO.construct_lcb_simplicialc                 C   s   dd„ | j D ƒ}|S )a?  
        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                 S   s   g | ]}|d  |d g‘qS r¶   r   r·   r   r   r)   r¸   R  r2   z/SHGO.construct_lcb_delaunay.<locals>.<listcomp>©r(   )rF   rº   r®   r»   r   r   r)   Úconstruct_lcb_delaunayD  s    zSHGO.construct_lcb_delaunayc              	   C   sÀ  | j rt d | jj¡¡ | j| jdur6| j| jS | jdurNtd |¡ƒ | j rbtd |¡ƒ | j	dkr²t
|ƒ}| jt
|ƒ }t
|ƒ}|  | jj| ¡}d| jv rÔ|| jd< n"| j||d}d| jv rÔ|| jd< | j rúd| jv rútdƒ t| jd ƒ t| j|fi | j¤Ž}| j r&td	 |¡ƒ | j j|j7  _d
|v rT| j j|j7  _d|v rp| j j|j7  _z|jd |_W n ttfyž   |j Y n0 | j|  | jj|||d |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&Callback for minimizer starting at {}:zStarting minimization at {}...r	   r(   r­   zbounds in kwarg:z	lres = {}ÚnjevÚnhevr   r¾   )r   r¥   r¦   r   r   Úv_mapsÚlresr   r   r   rT   r©   r½   rŽ   r   rd   r   r¿   r   r'   r   r{   r$   r|   rÀ   r}   rÁ   r    Ú
IndexErrorÚ	TypeErrorÚadd_res)rF   rµ   r®   Zx_min_tZx_min_t_normZg_boundsrÃ   r   r   r)   r   W  sP    
ÿÿ






zSHGO.minimizec                 C   sR   | j  ¡ }|d | j_|d | j_|d | j_|d | j_| j| jj | j_	| jS )úA
        Sort results and build the global return object
        ÚxlÚfunlr"   r    )
r   Úsort_cache_resultr   rÈ   rÉ   r"   r    r#   r{   r$   )rF   Úresultsr   r   r)   rŠ   ¥  s    
zSHGO.sort_resultúFailed to convergec                 C   s"   d| _ d| j_d g| _|| j_d S )NTF)r   r   r&   rˆ   r%   )rF   r   r   r   r)   r   ¶  s    zSHGO.fail_routinec                 C   sX   | j rtdƒ |  | j| j¡ | j| _|s<| jdur<|  ¡  |  ¡  |  	¡  | 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 pointsN)r   r   rv   rh   rO   r   rR   Úsampling_subspaceÚsorted_samplesÚfun_refrj   )rF   rc   r   r   r)   r¤   ¼  s    
zSHGO.sampled_surfacec                 C   sô   | j | jd kr¶| jdk rB| jr(tdƒ |  ¡  |  ¡  |  ¡  nZ| jrPtdƒ | jdkrh| jdd n| jd| j	d | j
jd	 | _	| jr”td
ƒ |  ¡  | jrðt d | j¡¡ n:| jrÄtdƒ d g| _z
| j W n tyî   g | _Y n0 d S )Nr@   zConstructing 1-D minimizer poolz-Constructing Gabrial graph and minimizer poolr   F)ÚgrowT)rÐ   ri   r   z0Triangulation completed, building minimizer poolz Minimizer pool = SHGO.X_min = {}z8Not enough sampling points found in the feasible domain.)r#   rO   r   r   Úax_subspaceÚsurface_topo_refÚminimizers_1Dr   Údelaunay_triangulationri   r•   rN   Údelaunay_minimizersr¥   r¦   r   rˆ   ry   ÚAttributeErrorrE   r   r   r)   rq   ß  s:    



ÿÿ
z SHGO.delaunay_complex_minimisersc                 C   sr   |   ||¡| _tt| jƒƒD ]N}| jdd…|f | j| d | j| d   | j| d  | jdd…|f< q| jS )zu
        Generates uniform sampling points in a hypercube and scales the points
        to the bound limits.
        Nr   r   )rw   r•   Úranger   r(   )rF   r   rO   r¼   r   r   r)   ru   	  s    ÿþzSHGO.sampling_customc                 C   sd   t | jƒD ]T\}}| j|| jjg| j| ¢R Ž dk | _| jjdkr
d| j_| jr
t	| jjƒ q
dS )z7Find subspace of feasible points from g_func definitionr›   r   zJNo sampling point found within the feasible set. Increasing sampling size.N)
r¹   rR   r•   ÚTrS   r¡   r   r%   r   r   )rF   r®   Úgr   r   r)   rÍ     s    &zSHGO.sampling_subspacec                 C   s,   t j| jdd| _| j| j | _| j| jfS )z*Find indexes of the sorted sampling pointsr   rŒ   )rK   r“   r•   Ú
Ind_sortedÚXsrE   r   r   r)   rÎ   %  s    zSHGO.sorted_samplesc                 C   st   g | _ g | _g | _t| jƒD ]R}| j  | jdd…|f ¡ | j | jdd…|f ¡ | j | jdd…|f ¡ qdS )zG
        Finds the subspace vectors along each component axis.
        N)	ZCiZXs_iÚIir×   rO   rV   r•   rÚ   rÛ   )rF   r¼   r   r   r)   rÑ   +  s    zSHGO.ax_subspacec                 C   s  d}| j dkr| j}| j }d}t t | j¡d ¡| _t| j t | j¡d ƒD ]¦}d}| jdur˜| jD ]0}|| j|dd…f g| j¢R Ž dk rfd} q˜qf|rÔ| j	| j|dd…f g| j¢R Ž | j|< |  j d7  _ qN| j
rNtj| j|< |  j d7  _ qN|r|dkr|| jd|…< | jS )zD
        Find the objective function output reference table
        Fr   TNr›   r   )r#   r”   rK   ZzerosrN   r•   r×   rR   r
   r'   rc   r   )rF   Zf_cache_boolZFtempZfn_oldr¼   Zeval_frÙ   r   r   r)   rÏ   7  s.    


$(
zSHGO.fun_refc                 C   sl   t j| jt  | j¡< t  | j¡| _| j| j | _t j| jdd| _t j| jddd… ddddd… | _	dS )zT
        Find the BD and FD finite differences along each component vector.
        r   rŒ   Nr‹   )
rK   r   r”   ÚisnanZ
nan_to_numrÚ   ZFtÚdiffÚFtpÚFtmrE   r   r   r)   rÒ   \  s
    zSHGO.surface_topo_refc                 C   sX  g | _ g | _t| jƒD ]}t| j| tt| j| ƒƒƒD ]\}}||kr:| j  |¡ q:| j | dkrŠ| j | jd d …|f d dk¡ q| j | | j	d krÈ| j | jd d …|f | j	d  dk ¡ q| jd d …|f | j |  dk}| j
d d …|f | j | d  dk}| j |o|¡ qt | j¡ ¡ r:d| _nd| _t | j¡ ¡ | _| jS )Nr   r   r@   TF)Z
Xi_ind_posÚXi_ind_topo_ir×   rO   ÚziprÜ   r   rV   rß   r#   rà   rK   rL   ÚallÚXi_ind_topo)rF   r®   r¼   r"   ZI_indZXi_ind_top_pZXi_ind_top_mr   r   r)   Úsample_topoj  s$    &$* $zSHGO.sample_topoc                 C   sp   g | _ t| jƒD ]}|  |¡}|r| j  |¡ q| j| j  | _|  ¡  t| j ƒdksd| j	| j  | _
ng | _
| j
S )ú7
        Returns the indices of all minimizers
        r   )ry   r×   r#   rå   rV   r”   r¨   rª   r   r•   rˆ   ©rF   r®   Zmin_boolr   r   r)   rÓ   Ž  s    
zSHGO.minimizers_1Dr   c                 C   sV   |st  | j¡| _n<t| dƒr>| j | j|d …d d …f ¡ nt j| jdd| _| jS )NÚTriT)Úincremental)r   ZDelaunayr•   rè   ÚhasattrZ
add_points)rF   rÐ   ri   r   r   r)   rÔ   ¥  s    
 zSHGO.delaunay_triangulationc                 C   s*   |j d |j d |  |j d | d  … S )zŒ
        Returns the indices of points connected to ``pindex`` on the Gabriel
        chain subgraph of the Delaunay triangulation.
        r   r   )Zvertex_neighbor_vertices)ZpindexZtriangr   r   r)   Úfind_neighbors_delaunay°  s
    ÿÿzSHGO.find_neighbors_delaunayc                 C   sV   g | _ |  || j¡}|D ]$}| j| | j| k }| j  |¡ qt | j ¡ ¡ | _| jS r-   )	rá   rë   rè   r”   rV   rK   rL   rã   rä   )rF   r®   ZG_indZg_iZrel_topo_boolr   r   r)   Úsample_delaunay_topoº  s    zSHGO.sample_delaunay_topoc                 C   sÊ   g | _ | jrHt d | j¡¡ t d | j¡¡ t d t | j	¡¡¡ t
| jƒD ]}|  |¡}|rR| j  |¡ qR| j| j  | _|  ¡  | jr t d | j ¡¡ t| j ƒdks¾| j	| j  | _ng | _| jS )ræ   zself.fn = {}zself.nc = {}znp.shape(self.C) = {}zself.minimizer_pool = {}r   )ry   r   r¥   r¦   r   r#   rh   rK   rN   r•   r×   rì   rV   r”   r¨   rª   r   rˆ   rç   r   r   r)   rÕ   Ê  s&    
ÿ
zSHGO.delaunay_minimizers)r   NNNNNNr*   )F)N)N)rÌ   )F)Fr   )+Ú__name__Ú
__module__Ú__qualname__r   rY   r   r‡   r   r–   r˜   r™   rš   r    r¢   r†   r…   rl   rp   rn   r‰   rª   r¯   r°   r½   r¿   r   rŠ   r   r¤   rq   ru   rÍ   rÎ   rÑ   rÏ   rÒ   rå   rÓ   rÔ   Ústaticmethodrë   rì   rÕ   r   r   r   r)   r   ¾  sX      þ
 Y5

.
?!

N

#*%$

	r   c                   @   s   e Zd Zdd„ ZdS )ÚLMapc                 C   s"   || _ d | _d | _d | _g | _d S r-   )r¬   Úx_lrÃ   r€   Úlbounds)rF   r¬   r   r   r)   r   è  s
    zLMap.__init__N)rí   rî   rï   r   r   r   r   r)   rñ   ç  s   rñ   c                   @   s.   e Zd Zdd„ Zdd„ Zd
dd„Zdd	„ ZdS )rz   c                 C   s(   i | _ g | _g | _g | _g | _d| _d S )Nr   )r   rÂ   r   Úf_mapsÚlbound_mapsr¡   rE   r   r   r)   r   ñ  s    zLMapCache.__init__c                 C   sT   t j |¡}t|ƒ}z| j| W S  tyN   t|ƒ}|| j|< | j|  Y S 0 d S r-   )rK   ÚndarrayÚtolistrT   r   rW   rñ   )rF   r¬   Zxvalr   r   r)   Ú__getitem__û  s    
zLMapCache.__getitem__Nc                 C   sŽ   t j |¡}t|ƒ}|j| j| _|| j| _|j| j| _	|| j| _
|  jd7  _| j |¡ | j |j¡ | j |j¡ | j |¡ d S r£   )rK   rö   r÷   rT   r"   r   rò   rÃ   r    r€   ró   r¡   rÂ   rV   r   rô   rõ   )rF   r¬   rÃ   r(   r   r   r)   rÆ     s    zLMapCache.add_resc                 C   s¬   i }t  | j¡| _t  | j¡| _t  | j¡}| j| |d< t  | j¡| _| j| |d< |d j|d< | j|d  |d< | j|d  |d< t j | j¡| _t j | j¡| _|S )rÇ   rÈ   rÉ   r   r"   r    )rK   rL   r   rô   r“   rØ   rö   r÷   )rF   rË   Z
ind_sortedr   r   r)   rÊ     s    zLMapCache.sort_cache_result)N)rí   rî   rï   r   rø   rÆ   rÊ   r   r   r   r)   rz   ð  s   

rz   )r   NNr   NNNr	   )Ú__doc__ZnumpyrK   rƒ   r¥   r   Zscipyr   Zscipy.optimizer   r   Z&scipy.optimize._shgo_lib.triangulationr   Ú__all__r   r   rñ   rz   r   r   r   r)   Ú<module>   s4      þ
   0        1	