
    Ug3J                     ,   d Z ddgZddlZddlmZ ddlmZmZmZm	Z	m
Z
mZmZmZmZmZ ddlmZmZmZmZmZ dd	lmZ dd
lmZmZ ddlmZmZ dZ e ee          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fdZ$d Z%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)
zerosarraylinalgappendconcatenatefinfosqrtvstackisfinite
atleast_1d   )OptimizeResult_check_unknown_options_prepare_scalar_function_clip_x_for_func_check_clip_x)approx_derivative)old_bound_to_new_arr_to_scalar)
atleast_ndarray_namespacez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        W/var/www/surfInsights/venv3-11/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 )a/  
    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 )ineqr3   Nr(   r6   s     r&   r9   zfmin_slsqp.<locals>.<genexpr>   s-      LLq6!T::LLLLLLr'   r2   )r4   r5   r%   r   r;   )r%   boundsconstraintsr"   r5   nitstatusmessage)tuple_minimize_slsqp)r#   x0eqconsf_eqconsieqcons	f_ieqconsr<   fprimefprime_eqconsfprime_ieqconsr   iteraccr-   r.   full_outputr$   r0   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                   EFG t          |           |dz
  }|}|
E|	sd}t          |          }t          |d|          }|j        }|                    |j        d          r|j        }|                    |                    ||          d          G|t          |          dk    rt          j
         t          j
        fFnt          |          Ft          j        GFd         Fd                   Gt          |t                    r|f}ddd}t          |          D ]\  }}	 |d	                                         }|dvrt#          d
|d	         z            n_# t$          $ r}t%          d|z            |d}~wt&          $ r}t'          d          |d}~wt(          $ r}t'          d          |d}~ww xY wd|vrt#          d|z            |                    d          }|EFfd} ||d                   }||xx         |d         ||                    dd          dfz  cc<   dddddddddddd}t-          t/          t          Gfd |d!         D                                 }t-          t/          t          Gfd"|d#         D                                 }||z   }t1          d|g                                          }t          G          }|dz   }||z
  |z   |z   } d$|z  |z   |dz   z  ||z
  dz   | d%z   z  z   d%| z  z   || z   ||z
  z  z   d%|z  z   |z   |dz   |z  d%z  z   d%|z  z   d$|z  z   d$|z  z   dz   }!| }"t5          |!          }#t5          |"          }$|t          |          dk    rvt          j        |t8          &          }%t          j        |t8          &          }&|%                    t          j                   |&                    t          j                   n#t1          d' |D             t8                    }'|'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   |("                                r/t#          d+d,#                    d- |(D                       z            |'dddf         |'dddf         }&}%tI          |'           })t          j        |%|)dddf         <   t          j        |&|)dddf         <   tK          | G||
F.          }*tM          |*j'        F          }+tM          |*j(        F          },t1          dtR                    }-t1          |t8                    }t1          |tR                    }.d}/t1          dt8                    }0t1          dt8                    }1t1          dt8                    }2t1          dt8                    }3t1          dt8                    }4t1          dt8                    }5t1          dt8                    }6t1          dt8                    }7t1          dt8                    }8t1          dt8                    }9t1          dtR                    }:t1          dtR                    };t1          dtR                    }<t1          dtR                    }=t1          dtR                    }>t1          dtR                    }t1          dtR                    }?t1          dtR                    }@|d%k    rtU          d/d0z              |+G          }AtW           |,G          d1          }BtY          G|          }Ct[          G||||||          }D	 t]          g ||G|%|&|A|C|B|D||.|-|#|$|0|1|2|3|4|5|6|7|8|9|:|;|<|=|>||?|@R   |-dk    r |+G          }AtY          G|          }C|-dk    r.tW           |,G          d1          }Bt[          G||||||          }D|.|/k    rR| |t          j/        G                     |d%k    r-tU          d2|.|*j0        |Atc          j2        |B          fz             tg          |-          dk    rntS          |.          }/|dk    rtU          |tS          |-                   d3z   ti          |-          z   d4z              tU          d5|A           tU          d6|.           tU          d7|*j0                   tU          d8|*j5                   tm          G|A|Bdd         tS          |.          |*j0        |*j5        tS          |-          |tS          |-                   |-dk    9	  	        S ):a  
    Minimize a scalar function of one or more variables using Sequential
    Least Squares Programming (SLSQP).

    Options
    -------
    ftol : float
        Precision goal for the value of f in the stopping criterion.
    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.
    r   r   )ndimxpzreal floatingNr(   )r2   r;   r4   zUnknown constraint type '%s'.z"Constraint %d has no type defined.z/Constraints must be defined using a dictionary.z#Constraint's type must be a string.r5   z&Constraint %d 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_stepr<   r   )r   r   r   r<   )r   r   )r"   r   r$   finite_diff_rel_stepr5   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(   )r5   r[   r$   rY   r%   rZ   s   ` r&   cjac_factoryz%_minimize_slsqp.<locals>.cjac_factory*  sA    
D 
D 
D 
D 
D 
D 
D 
D 
D r'   r   )r5   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)rT   r   r                        	   c           	      T    g | ]$}t           |d          g|d         R            %S r5   r   r   r7   r8   r"   s     r&   
<listcomp>z#_minimize_slsqp.<locals>.<listcomp>M  sK     # # # #81U8A#:&	#:#:#:;; # # #r'   r2   c           	      T    g | ]$}t           |d          g|d         R            %S rf   rg   rh   s     r&   ri   z#_minimize_slsqp.<locals>.<listcomp>O  sK     & & & $HAeHQ$;6$;$;$;<< & & &r'   r;   r^   r]   )dtypec                 P    g | ]#\  }}t          |          t          |          f$S r(   )r   )r7   lus      r&   ri   z#_minimize_slsqp.<locals>.<listcomp>h  sA     , , , 1a &a((.*;*;< , , ,r'   zDSLSQP Error: the length of bounds is not compatible with that of x0.ignore)invalidz"SLSQP Error: lb > ub in bounds %s.z, c              3   4   K   | ]}t          |          V  d S )N)str)r7   bs     r&   r9   z"_minimize_slsqp.<locals>.<genexpr>s  s(      &>&>!s1vv&>&>&>&>&>&>r'   )r%   r   r$   rY   r<   z%5s %5s %16s %16s)NITFCOBJFUNGNORMg        z%5i %5i % 16.6E % 16.6Ez    (Exit mode )z#            Current function value:z            Iterations:z!            Function evaluations:z!            Gradient evaluations:)	r"   r5   r%   r>   nfevnjevr?   r@   success)7r   r   r   float64isdtyperk   reshapeastypelenr    infr   clip
isinstancedict	enumeratelower
ValueErrorKeyError	TypeErrorAttributeErrorgetsummapr   maxr   emptyfloatfillnanshape
IndexErrorerrstateanyjoinr   r   r   r5   gradintprintr	   _eval_constraint_eval_con_normalsr   copyry   r   normabsrr   ngevr   )Hr#   rC   r   r%   r<   r=   r+   r,   r-   r.   r/   r0   rY   unknown_optionsrK   rL   rS   rk   rO   icconctypeer[   r\   
exit_modesmeqmieqmlann1mineqlen_wlen_jwwjwxlxubndsbnderrinfbndsfwrapped_funwrapped_gradmodemajitermajiter_prevalphaf0gsh1h2h3h4tt0toliexactinconsiresetitermxlinen2n3fxgr8   ar$   rZ   r"   sH      `        `                                                        @@@r&   rB   rB      s/   8 ?+++Q;D
CG  
		B	BQ2	&	&	&BJE	zz"(O,, 


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

%f--
 	:a=*Q-00A +t$$ &"ob!!D[)) +9 +9C	PK%%''E N** !@3v;!NOOO +  	M 	M 	M?"DEE1L 	2 	2 	2 * + +012 	J 	J 	JABBI	J EJKKK 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	1v				BAA 
QBGbL2ErT!VbdORVAXa001U7:BuHr#v;NNeqS!Ga<(*+A#.01!467d;=>?EFeA	vB ~V))Xau%%%Xau%%%

 , ,$*, , ,-24 4:a=A ; < < < [*** 	- 	-!!!Q$Z$qqq!t*,F	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- ::<< 	@A!YY&>&>v&>&>&>>>? @ @ @aaadT!!!Q$ZB 4..66!!!Q$<66!!!Q$< 
"$ss7K)3
5 
5 
5B
 #26:66K#BGZ88L C==D
U

CD#GL !UOOE	q%B	q%B	q%B	q%B	q%B	q%BaA	q%B
5//C1c]]F1c]]F1c]]F1c]]FC==D	q#B	q#B	q#B {{!$DDEEE
 
QB||A$$AD!!A!T2q!S$77A$ 	a 	 	a 	 	R 	 	Q 	 	1 	c 	7 	D 	! 	R 					!#	%'	)+	-.	02	47			$	&,	.2	 	 	 	 	 	 	
 199QB D))A2::||A,,A!!T2q!S$??A\!!#$$$ {{/7BG35v{1~~3G G H H H t99>>7||;$@ {{jT#&77#d))CcIJJJ3R888'111127;;;127;;;A21SbS6s7||!wRWSYY",SYY"7$!)N N N NsB   )E  
F<*E==F<
FF<'F77F<Q22Q69Q6c                     |d         r"t           fd|d         D                       }nt          d          }|d         r"t           fd|d         D                       }nt          d          }t          ||f          }|S )Nr2   c           	      T    g | ]$}t           |d          g|d         R            %S rf   rg   r7   r   r"   s     r&   ri   z$_eval_constraint.<locals>.<listcomp>  sK     3 3 3 # 'zs5z!'Bc&k'B'B'BCC 3 3 3r'   r   r;   c           	      T    g | ]$}t           |d          g|d         R            %S rf   rg   r   s     r&   ri   z$_eval_constraint.<locals>.<listcomp>  sK     6 6 6!$ (
E
1(Cs6{(C(C(CDD 6 6 6r'   )r
   r   )r"   rO   c_eqc_ieqr8   s   `    r&   r   r     s    Dz  3 3 3 3'+Dz3 3 3 4 4 QxxF|  6 6 6 6(,V6 6 6 7 7 a 	T5M""AHr'   c                     |d         r"t           fd|d         D                       }nt          ||f          }|d         r"t           fd|d         D                       }nt          ||f          }|dk    rt          ||f          }	nt          ||f          }	t          |	t          |dg          fd          }	|	S )Nr2   c                 :    g | ]} |d          g|d         R  S r%   r   r(   r   s     r&   ri   z%_eval_con_normals.<locals>.<listcomp>  sC     . . . "s5z!2c&k222 . . .r'   r;   c                 :    g | ]} |d          g|d         R  S r   r(   r   s     r&   ri   z%_eval_con_normals.<locals>.<listcomp>  sC     1 1 1 #E
13s6{333 1 1 1r'   r   r   )r   r   r
   )
r"   rO   r   r   r   r   r   a_eqa_ieqr   s
   `         r&   r   r     s   Dz  . . . ."&t*. . . / / c1XF| ! 1 1 1 1#'<1 1 1 2 2 tQi   	Avv2q'NND%=!!Qr1g'++AHr'   )'__doc____all__numpyr    scipy.optimize._slsqpr   r   r   r   r	   r
   r   r   r   r   r   	_optimizer   r   r   r   r   _numdiffr   _constraintsr   r   scipy._lib._array_apir   r   __docformat__r   r/   _epsilonr   r   rB   r   r   r(   r'   r&   <module>r      s    l
+     ' ' ' ' ' '7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7' ' ' ' ' ' ' ' ' ' ' ' ' ' ( ' ' ' ' ' : : : : : : : : = = = = = = = = &4e !!  D !#T2T"#6d8	O O O Od $&4 "fQU 4d|N |N |N |N~  &    r'   