
    Yh;]                     h   d Z ddgZddlZddlmZ ddlmZ ddl	m
Z
mZmZmZmZ dd	lmZ dd
lmZmZ ddlmZ ddlmZ ddlmZ dZ ej         ej        ej                  j                  Z d Z!dddddddddddddde dfdZ"dddddddde dddfdZ#dedede$de%de%f
dZ&dedede$de%de%f
dZ'dS )a  
This module implements the Sequential Least Squares Programming optimization
algorithm (SLSQP), originally developed by Dieter Kraft.
See http://www.netlib.org/toms/733

Functions
---------
.. autosummary::
   :toctree: generated/

    approx_jacobian
    fmin_slsqp

approx_jacobian
fmin_slsqp    N   )slsqp)norm)OptimizeResult_check_unknown_options_prepare_scalar_function_clip_x_for_func_check_clip_x)approx_derivative)old_bound_to_new_arr_to_scalar)array_namespace)array_api_extra)NDArrayzrestructuredtext enc                 R    t          || d||          }t          j        |          S )a  
    Approximate the Jacobian matrix of a callable function.

    Parameters
    ----------
    x : array_like
        The state vector at which to compute the Jacobian matrix.
    func : callable f(x,*args)
        The vector-valued function.
    epsilon : float
        The perturbation used to determine the partial derivatives.
    args : sequence
        Additional arguments passed to func.

    Returns
    -------
    An array of dimensions ``(lenf, lenx)`` where ``lenf`` is the length
    of the outputs of `func`, and ``lenx`` is the number of elements in
    `x`.

    Notes
    -----
    The approximation is done using forward differences.

    2-point)methodabs_stepargs)r   np
atleast_2d)xfuncepsilonr   jacs        j/var/www/tools.fuzzalab.pt/emblema-extractor/venv/lib/python3.11/site-packages/scipy/optimize/_slsqp_py.pyr   r   #   s5    6 D!I!%' ' 'C =     d   gư>c                 Z  
 ||}||||dk    ||d}d}|t          
fd|D                       z  }|t          
fd|D                       z  }|r|d||
dfz  }|r|d	||	
dfz  }t          | |
f|||d
|}|r%|d         |d         |d         |d         |d         fS |d         S )aC  
    Minimize a function using Sequential Least Squares Programming

    Python interface function for the SLSQP Optimization subroutine
    originally implemented by Dieter Kraft.

    Parameters
    ----------
    func : callable f(x,*args)
        Objective function.  Must return a scalar.
    x0 : 1-D ndarray of float
        Initial guess for the independent variable(s).
    eqcons : list, optional
        A list of functions of length n such that
        eqcons[j](x,*args) == 0.0 in a successfully optimized
        problem.
    f_eqcons : callable f(x,*args), optional
        Returns a 1-D array in which each element must equal 0.0 in a
        successfully optimized problem. If f_eqcons is specified,
        eqcons is ignored.
    ieqcons : list, optional
        A list of functions of length n such that
        ieqcons[j](x,*args) >= 0.0 in a successfully optimized
        problem.
    f_ieqcons : callable f(x,*args), optional
        Returns a 1-D ndarray in which each element must be greater or
        equal to 0.0 in a successfully optimized problem. If
        f_ieqcons is specified, ieqcons is ignored.
    bounds : list, optional
        A list of tuples specifying the lower and upper bound
        for each independent variable [(xl0, xu0),(xl1, xu1),...]
        Infinite values will be interpreted as large floating values.
    fprime : callable ``f(x,*args)``, optional
        A function that evaluates the partial derivatives of func.
    fprime_eqcons : callable ``f(x,*args)``, optional
        A function of the form ``f(x, *args)`` that returns the m by n
        array of equality constraint normals. If not provided,
        the normals will be approximated. The array returned by
        fprime_eqcons should be sized as ( len(eqcons), len(x0) ).
    fprime_ieqcons : callable ``f(x,*args)``, optional
        A function of the form ``f(x, *args)`` that returns the m by n
        array of inequality constraint normals. If not provided,
        the normals will be approximated. The array returned by
        fprime_ieqcons should be sized as ( len(ieqcons), len(x0) ).
    args : sequence, optional
        Additional arguments passed to func and fprime.
    iter : int, optional
        The maximum number of iterations.
    acc : float, optional
        Requested accuracy.
    iprint : int, optional
        The verbosity of fmin_slsqp :

        * iprint <= 0 : Silent operation
        * iprint == 1 : Print summary upon completion (default)
        * iprint >= 2 : Print status of each iterate and summary
    disp : int, optional
        Overrides the iprint interface (preferred).
    full_output : bool, optional
        If False, return only the minimizer of func (default).
        Otherwise, output final objective function and summary
        information.
    epsilon : float, optional
        The step size for finite-difference derivative estimates.
    callback : callable, optional
        Called after each iteration, as ``callback(x)``, where ``x`` is the
        current parameter vector.

    Returns
    -------
    out : ndarray of float
        The final minimizer of func.
    fx : ndarray of float, if full_output is true
        The final value of the objective function.
    its : int, if full_output is true
        The number of iterations.
    imode : int, if full_output is true
        The exit mode from the optimizer (see below).
    smode : string, if full_output is true
        Message describing the exit mode from the optimizer.

    See also
    --------
    minimize: Interface to minimization algorithms for multivariate
        functions. See the 'SLSQP' `method` in particular.

    Notes
    -----
    Exit modes are defined as follows:

    - ``-1`` : Gradient evaluation required (g & a)
    - ``0`` : Optimization terminated successfully
    - ``1`` : Function evaluation required (f & c)
    - ``2`` : More equality constraints than independent variables
    - ``3`` : More than 3*n iterations in LSQ subproblem
    - ``4`` : Inequality constraints incompatible
    - ``5`` : Singular matrix E in LSQ subproblem
    - ``6`` : Singular matrix C in LSQ subproblem
    - ``7`` : Rank-deficient equality constraint subproblem HFTI
    - ``8`` : Positive directional derivative for linesearch
    - ``9`` : Iteration limit reached

    Examples
    --------
    Examples are given :ref:`in the tutorial <tutorial-sqlsp>`.

    Nr   )maxiterftoliprintdispepscallbackr    c              3   $   K   | ]
}d |dV  dS )eqtypefunr   Nr    .0cr   s     r   	<genexpr>zfmin_slsqp.<locals>.<genexpr>   s-      IIQ4488IIIIIIr   c              3   $   K   | ]
}d |dV  dS )ineqr+   Nr    r.   s     r   r1   zfmin_slsqp.<locals>.<genexpr>   s-      LLq6!T::LLLLLLr   r*   )r,   r-   r   r   r3   )r   boundsconstraintsr   r-   nitstatusmessage)tuple_minimize_slsqp)r   x0eqconsf_eqconsieqcons	f_ieqconsr4   fprimefprime_eqconsfprime_ieqconsr   iteraccr%   r&   full_outputr   r(   optsconsress             `          r   r   r   E   sF   ` aK " "D D 	EIIII&IIIIIIDELLLLGLLLLLLD  #$x    # 	# #&>    # 	# $D 4fV&*4 4.24 4C 3xUSZXINN3xr   Fc                   012 t          |           |}|
0|	sd}t          |          }t          j        |                    |          d|          }|j        }|                    |j        d          r|j        }|                    |	                    ||          d          2|t          |          dk    rt          j         t          j        f1nt          |          1t          j        21d         1d                   2t          |t                     r|f}ddd}t#          |          D ]\  }}	 |d	                                         }|dvrt'          d
|d	          d          n`# t(          $ r}t)          d| d          |d}~wt*          $ r}t+          d          |d}~wt,          $ r}t+          d          |d}~ww xY wd|vrt'          d| d          |                    d          }|01fd} ||d                   }||xx         |d         ||                    dd          dfz  cc<   ddddddddddd d!}t1          t3          t          2fd"|d#         D                                 }t1          t3          t          2fd$|d%         D                                 }||z   }t          2          }|t          |          dk    rvt          j        |t6          &          }t          j        |t6          &          }|                    t          j                   |                    t          j                   nRt          j        d' |D             t6                    } | j        d         |k    rtA          d(          t          j!        d)*          5  | dddf         | dddf         k    }!ddd           n# 1 swxY w Y   |!"                                r0t'          d+d,#                    d- |!D                        d.          | dddf         $                                | dddf         $                                }}t          j%        |            }"t          j        ||"dddf         <   t          j        ||"dddf         <   tM          | 2||
1|/          }#tO          |#j(        1          }$tO          |#j)        1          }%i d0|d1d2d3d2d4d2d5d2d6d2d7d2d8d2d9d2d:d2d;d<|z  d=dd>dd?dd@ddA|dBd||d|dC}&|dDk    rtU          dEdFdGdHdFdGdIdJdGdKdJ           t          j+        tY          |dD|z  z   dDz   d          gt          j-        &          }'||dz   z  dDz  dL|z  |z  z   |dM|z  z   dNz   |z  z
  dO|z  z   dP|z  |z  z   dQ|z  z   ||z  z   dRz   }(|dk    r|(dD|z  |dz   z  z  }(t          j+        tY          |(d          t          j        &          }) |$2          }* |%2          }+t          j+        tY          d|dD|z  z   dDz             gt          j        &          },t          j+        tY          d|          |gt          j        dST          }-t          j+        tY          d|          gt          j        &          }.t]          |-2|||           t_          |.2|||           d}/	 ta          |&|*|+|-|.2|,|||)|'           |&dV         dk    r(|#(                    2          }*t_          |.2|||           |&dV         dk    r(|#)                    2          }+t]          |-2|||           |&d@         |/k    r[| |t          j$        2                     |dDk    r6tU          |&d@         dWdG|#j1        dWdG|*dXdGte          |+          dX           tg          |&dV                   dk    rn
|&d@         }/|dk    rxtU          ||&dV                  dY|&dV          dZz              tU          d[|*           tU          d\|&d@                    tU          d]|#j1                   tU          d^|#j4                   tk          2|*|+|&d@         |#j1        |#j4        |&dV         ||&dV                  |&dV         dk    |,d|         _
  
        S )`a  
    Minimize a scalar function of one or more variables using Sequential
    Least Squares Programming (SLSQP).

    Parameters
    ----------
    ftol : float
        Precision target for the value of f in the stopping criterion. This value
        controls the final accuracy for checking various optimality conditions;
        gradient of the lagrangian and absolute sum of the constraint violations
        should be lower than ``ftol``. Similarly, computed step size and the
        objective function changes are checked against this value. Default is 1e-6.
    eps : float
        Step size used for numerical approximation of the Jacobian.
    disp : bool
        Set to True to print convergence messages. If False,
        `verbosity` is ignored and set to 0.
    maxiter : int
        Maximum number of iterations.
    finite_diff_rel_step : None or array_like, optional
        If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
        use for numerical approximation of `jac`. The absolute step
        size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
        possibly adjusted to fit into the bounds. For ``method='3-point'``
        the sign of `h` is ignored. If None (default) then step is selected
        automatically.
    workers : int, map-like callable, optional
        A map-like callable, such as `multiprocessing.Pool.map` for evaluating
        any numerical differentiation in parallel.
        This evaluation is carried out as ``workers(fun, iterable)``.

        .. versionadded:: 1.16.0

    Returns
    -------
    res : OptimizeResult
        The optimization result represented as an `OptimizeResult` object.
        In this dict-like object the following fields are of particular importance:
        ``x`` the solution array, ``success`` a Boolean flag indicating if the
        optimizer exited successfully, ``message`` which describes the reason for
        termination, and ``multipliers`` which contains the Karush-Kuhn-Tucker
        (KKT) multipliers for the QP approximation used in solving the original
        nonlinear problem. See ``Notes`` below. See also `OptimizeResult` for a
        description of other attributes.

    Notes
    -----
    The KKT multipliers are returned in the ``OptimizeResult.multipliers``
    attribute as a NumPy array. Denoting the dimension of the equality constraints
    with ``meq``, and of inequality constraints with ``mineq``, then the returned
    array slice ``m[:meq]`` contains the multipliers for the equality constraints,
    and the remaining ``m[meq:meq + mineq]`` contains the multipliers for the 
    inequality constraints. The multipliers corresponding to bound inequalities 
    are not returned. See [1]_ pp. 321 or [2]_ for an explanation of how to interpret
    these multipliers. The internal QP problem is solved using the methods given
    in [3]_ Chapter 25.

    Note that if new-style `NonlinearConstraint` or `LinearConstraint` were
    used, then ``minimize`` converts them first to old-style constraint dicts.
    It is possible for a single new-style constraint to simultaneously contain
    both inequality and equality constraints. This means that if there is mixing
    within a single constraint, then the returned list of multipliers will have
    a different length than the original new-style constraints.

    References
    ----------
    .. [1] Nocedal, J., and S J Wright, 2006, "Numerical Optimization", Springer,
       New York.
    .. [2] Kraft, D., "A software package for sequential quadratic programming",
       1988, Tech. Rep. DFVLR-FB 88-28, DLR German Aerospace Center, Germany.
    .. [3] Lawson, C. L., and R. J. Hanson, 1995, "Solving Least Squares Problems",
       SIAM, Philadelphia, PA.

    r   r   )ndimxpzreal floatingNr    )r*   r3   r,   zUnknown constraint type 'z'.zConstraint z has no type defined.z/Constraints must be defined using a dictionary.z#Constraint's type must be a string.r-   z has no function defined.r   c                       fd}|S )Nc                     t          |           } dv rt          | |          S t          | d|          S )N)r   z3-pointcs)r   r   rel_stepr4   r   )r   r   r   r4   )r   r   )r   r   r   finite_diff_rel_stepr-   r   
new_boundss     r   cjacz3_minimize_slsqp.<locals>.cjac_factory.<locals>.cjac]  sr    %a44A:::0a$:N8B D  D  D D  1a	:A8B D  D  D Dr   r    )r-   rS   r   rQ   r   rR   s   ` r   cjac_factoryz%_minimize_slsqp.<locals>.cjac_factory\  sA    
D 
D 
D 
D 
D 
D 
D 
D 
D r   r   )r-   r   r   z$Gradient evaluation required (g & a)z$Optimization terminated successfullyz$Function evaluation required (f & c)z4More equality constraints than independent variablesz*More than 3*n iterations in LSQ subproblemz#Inequality constraints incompatiblez#Singular matrix E in LSQ subproblemz#Singular matrix C in LSQ subproblemz2Rank-deficient equality constraint subproblem HFTIz.Positive directional derivative for linesearchzIteration limit reached)rL   r   r                        	   c           	      ^    g | ])}t          j         |d          g|d         R            *S r-   r   r   
atleast_1dr/   r0   r   s     r   
<listcomp>z#_minimize_slsqp.<locals>.<listcomp>  sM     # # # hahq&=1V9&=&=&=>> # # #r   r*   c           	      ^    g | ])}t          j         |d          g|d         R            *S r^   r_   ra   s     r   rb   z#_minimize_slsqp.<locals>.<listcomp>  sM     & & & xqx'>AfI'>'>'>?? & & &r   r3   )dtypec                 P    g | ]#\  }}t          |          t          |          f$S r    )r   )r/   loups      r   rb   z#_minimize_slsqp.<locals>.<listcomp>  sA     . . ."2r ),,nR.@.@A . . .r   zDSLSQP Error: the length of bounds is not compatible with that of x0.ignore)invalidzSLSQP Error: lb > ub in bounds z, c              3   4   K   | ]}t          |          V  d S )N)str)r/   bs     r   r1   z"_minimize_slsqp.<locals>.<genexpr>  s(      )A)AQ#a&&)A)A)A)A)A)Ar   .)r   r   r   rQ   r4   workersrD   alphag        f0gsh1h2h3h4tt0tolg      $@exactinconsistentresetrC   itermaxline)mmeqmodenrU   NITz>5 FCOBJFUNz>16GNORMrV   rX   rZ   r\   r[   #      F)rd   orderTr   5dz16.6Ez    (Exit mode )z#            Current function value:z            Iterations:z!            Function evaluations:z!            Gradient evaluations:)
r   r-   r   r6   nfevnjevr7   r8   successmultipliers)6r	   r   xpx
atleast_ndasarrayfloat64isdtyperd   reshapeastypelenr   infr   clip
isinstancedict	enumeratelower
ValueErrorKeyError	TypeErrorAttributeErrorgetsummapemptyfloatfillnanarrayshape
IndexErrorerrstateanyjoincopyisfiniter
   r   r-   gradprintzerosmaxint32_eval_con_normals_eval_constraintr   r   lanormabsngevr   )3r   r;   r   r   r4   r5   r#   r$   r%   r&   r'   r(   rQ   rn   unknown_optionsrD   rK   rd   rG   icconctypeerS   rT   
exit_modesr   mieqr~   r   xlxubndsbnderrinfbndsfwrapped_funwrapped_grad
state_dictindicesbuffer_sizebufferfxgmultCd	iter_prevr   rR   r   s3      `        `                                   @@@r   r:   r:      s*   ^ ?+++
CG  
		B	

2Q2	6	6	6BJE	zz"(O,, 


299R'',,A ~V))vgrv&

%f--
 	:a=*Q-00A +t$$ &"ob!!D[)) +9 +9C	NK%%''E N** !LS[!L!L!LMMM +  	K 	K 	KBBBBCCJ 	2 	2 	2 * + +012 	J 	J 	JABBI	J H2HHHIII wwu~~<         <E
++D 	UE
 $!$!4!46 6 9 	9 =<<LB;;;JF/
1 
1J c# # # # #Dz# # # $ $ % %Cs3 & & & &V& & & ' ' ( (D 	d
AAA ~V))Xau%%%Xau%%%

x . .&,. . ./46 6:a=A ; < < < [*** 	- 	-!!!Q$Z$qqq!t*,F	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- ::<< 	F E $		)A)A&)A)A)A A AE E E F F Faaad""DAJOO$5$5B +d###66!!!Q$<66!!!Q$< 
"$ss7K)3W
F 
F 
FB
 #26:66K#BGZ88L.s 	c 	c	
 	c 	c 	c 	c 	S 	c 	tCx 	 	 	 	  	7!" 	#$ +  J2 {{BBBDBBBhBBBWBBBCCC hA!GaK++,BH===G 	
1Q3
QqSUa!A#gk3..14qs1u<r!tCc#gMPRR 
 qyyqsAE{"Xc+q))<<<F
 
QBQA 8SA!GaK(()<<<D 	#a))Qrz===A
#a))BJ///AaD!S)))Q4C(((I'j"aAq$BHHHf""BQ4C000f##

AaD!S111f	))#$$$ {{F+> 6 6> 6 656 6$*1II56 6 7 7 7 z&!""a''v&	5': {{z&)*-Tz&?Q-T-T-TT	
 	
 	
 	3R888'F);<<<127;;;127;;;

6 2rw&!:j6H+IF#q(tBQBx   sB   <E44
G>FGF//G<GG:O!!O%(O%r   r   rG   r~   r   c                    |dk    rd S |dk    rod}|d         D ]d}t          j         |d         |g|d         R                                            }|| ||t          |          z   <   |t          |          z  }e||k    ro|}|d         D ]d}t          j         |d         |g|d         R                                            }|| ||t          |          z   <   |t          |          z  }ed S )Nr   r*   r-   r   r3   )r   r`   ravelr   )r   r   rG   r~   r   rowr   temps           r   r   r   0  s   Avv Qww: 	 	C=UA!<F!<!<!<==CCEED%)Ac#D		/!"3t99CC3ww< 	 	C=UA!<F!<!<!<==CCEED%)Ac#D		/!"3t99CC
Fr   r   c                    |dk    rd S |dk    r]d}|d         D ]R}t          j         |d         |g|d         R            }|| |||j        d         z   d d f<   ||j        d         z  }S||k    r]|}|d         D ]R}t          j         |d         |g|d         R            }|| |||j        d         z   d d f<   ||j        d         z  }Sd S )Nr   r*   r   r   r3   )r   r   r   )r   r   rG   r~   r   r   r   r   s           r   r   r   I  s   Avv
Qww: 	! 	!C=UA!<F!<!<!<==D,0Ac#
1%%qqq()4:a= CC3ww< 	! 	!C=UA!<F!<!<!<==D,0Ac#
1%%qqq()4:a= CC
Fr   )(__doc____all__numpyr   	_slsqplibr   scipy.linalgr   r   	_optimizer   r	   r
   r   r   _numdiffr   _constraintsr   r   scipy._lib._array_apir   
scipy._libr   r   numpy.typingr   __docformat__sqrtfinfor   r'   _epsilonr   r   r:   r   intr   r   r    r   r   <module>r      s    l
+           ' ' ' ' ' '' ' ' ' ' ' ' ' ' ' ' ' ' ' ( ' ' ' ' ' : : : : : : : : 1 1 1 1 1 1 - - - - - -            %27828BJ''+,,  D !#T2T"#6d8	O O O Od $&4 "fQU 4d 	V V V Vr
 G 4 C c    2 W D S s      r   