
    (phoY                         S r SSKrSSKJr  SSKJrJrJr  SSK	J
r
  SSKJrJrJrJr  SSKJr  S	 r " S
 S5      r " S S5      r " S S5      r " S S5      rS rS rS rS rS rg)z$Constraints definition for minimize.    N   )BFGS)VectorFunctionLinearVectorFunctionIdentityVectorFunction)OptimizeWarning)warncatch_warningssimplefilterfilterwarnings)issparsec                 d    [        U [        R                  5      (       a  U R                  5       $ U $ N)
isinstancenpndarrayitem)xs    N/var/www/html/venv/lib/python3.13/site-packages/scipy/optimize/_constraints.py_arr_to_scalarr      s%     "!RZZ0016687a7    c                   (    \ rS rSrSr   SS jrSrg)NonlinearConstraint   a  Nonlinear constraint on the variables.

The constraint has the general inequality form::

    lb <= fun(x) <= ub

Here the vector of independent variables x is passed as ndarray of shape
(n,) and ``fun`` returns a vector with m components.

It is possible to use equal bounds to represent an equality constraint or
infinite bounds to represent a one-sided constraint.

Parameters
----------
fun : callable
    The function defining the constraint.
    The signature is ``fun(x) -> array_like, shape (m,)``.
lb, ub : array_like
    Lower and upper bounds on the constraint. Each array must have the
    shape (m,) or be a scalar, in the latter case a bound will be the same
    for all components of the constraint. Use ``np.inf`` with an
    appropriate sign to specify a one-sided constraint.
    Set components of `lb` and `ub` equal to represent an equality
    constraint. Note that you can mix constraints of different types:
    interval, one-sided or equality, by setting different components of
    `lb` and `ub` as  necessary.
jac : {callable,  '2-point', '3-point', 'cs'}, optional
    Method of computing the Jacobian matrix (an m-by-n matrix,
    where element (i, j) is the partial derivative of f[i] with
    respect to x[j]).  The keywords {'2-point', '3-point',
    'cs'} select a finite difference scheme for the numerical estimation.
    A callable must have the following signature::

        jac(x) -> {ndarray, sparse matrix}, shape (m, n)

    Default is '2-point'.
hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy, None}, optional
    Method for computing the Hessian matrix. The keywords
    {'2-point', '3-point', 'cs'} select a finite difference scheme for
    numerical  estimation.  Alternatively, objects implementing
    `HessianUpdateStrategy` interface can be used to approximate the
    Hessian. Currently available implementations are:

    - `BFGS` (default option)
    - `SR1`

    A callable must return the Hessian matrix of ``dot(fun, v)`` and
    must have the following signature:
    ``hess(x, v) -> {LinearOperator, sparse matrix, array_like}, shape (n, n)``.
    Here ``v`` is ndarray with shape (m,) containing Lagrange multipliers.
keep_feasible : array_like of bool, optional
    Whether to keep the constraint components feasible throughout
    iterations. A single value set this property for all components.
    Default is False. Has no effect for equality constraints.
finite_diff_rel_step: None or array_like, optional
    Relative step size for the finite difference approximation. Default is
    None, which will select a reasonable value automatically depending
    on a finite difference scheme.
finite_diff_jac_sparsity: {None, array_like, sparse matrix}, optional
    Defines the sparsity structure of the Jacobian matrix for finite
    difference estimation, its shape must be (m, n). If the Jacobian has
    only few non-zero elements in *each* row, providing the sparsity
    structure will greatly speed up the computations. A zero entry means
    that a corresponding element in the Jacobian is identically zero.
    If provided, forces the use of 'lsmr' trust-region solver.
    If None (default) then dense differencing will be used.

Notes
-----
Finite difference schemes {'2-point', '3-point', 'cs'} may be used for
approximating either the Jacobian or the Hessian. We, however, do not allow
its use for approximating both simultaneously. Hence whenever the Jacobian
is estimated via finite-differences, we require the Hessian to be estimated
using one of the quasi-Newton strategies.

The scheme 'cs' is potentially the most accurate, but requires the function
to correctly handles complex inputs and be analytically continuable to the
complex plane. The scheme '3-point' is more accurate than '2-point' but
requires twice as many operations.

Examples
--------
Constrain ``x[0] < sin(x[1]) + 1.9``

>>> from scipy.optimize import NonlinearConstraint
>>> import numpy as np
>>> con = lambda x: x[0] - np.sin(x[1])
>>> nlc = NonlinearConstraint(con, -np.inf, 1.9)

Nc	                 ~    Uc
  [        5       nXl        X l        X0l        Xpl        Xl        X@l        XPl        X`l        g r   )	r   funlbubfinite_diff_rel_stepfinite_diff_jac_sparsityjachesskeep_feasible)	selfr   r   r   r!   r"   r#   r   r    s	            r   __init__NonlinearConstraint.__init__l   s;     <6D$8!(@%	*r   )r    r   r   r"   r!   r#   r   r   )2-pointNFNN)__name__
__module____qualname____firstlineno____doc__r%   __static_attributes__ r   r   r   r      s    Yt 9=;?*.+r   r   c                   ^    \ rS rSrSrS r\R                  * \R                  S4S jrS r	Sr
g)	LinearConstraint{   a&  Linear constraint on the variables.

The constraint has the general inequality form::

    lb <= A.dot(x) <= ub

Here the vector of independent variables x is passed as ndarray of shape
(n,) and the matrix A has shape (m, n).

It is possible to use equal bounds to represent an equality constraint or
infinite bounds to represent a one-sided constraint.

Parameters
----------
A : {array_like, sparse matrix}, shape (m, n)
    Matrix defining the constraint.
lb, ub : dense array_like, optional
    Lower and upper limits on the constraint. Each array must have the
    shape (m,) or be a scalar, in the latter case a bound will be the same
    for all components of the constraint. Use ``np.inf`` with an
    appropriate sign to specify a one-sided constraint.
    Set components of `lb` and `ub` equal to represent an equality
    constraint. Note that you can mix constraints of different types:
    interval, one-sided or equality, by setting different components of
    `lb` and `ub` as  necessary. Defaults to ``lb = -np.inf``
    and ``ub = np.inf`` (no limits).
keep_feasible : dense array_like of bool, optional
    Whether to keep the constraint components feasible throughout
    iterations. A single value set this property for all components.
    Default is False. Has no effect for equality constraints.
c                    U R                   R                  S:w  a  Sn[        U5      e U R                   R                  SS n[        R
                  " U R                  U5      U l        [        R
                  " U R                  U5      U l        [        R
                  " U R                  U5      U l        g ! [         a    Sn[        U5      ef = f)N   z%`A` must have exactly two dimensions.r   r   zM`lb`, `ub`, and `keep_feasible` must be broadcastable to shape `A.shape[0:1]`)	Andim
ValueErrorshaper   broadcast_tor   r   r#   )r$   messager7   s      r   _input_validation"LinearConstraint._input_validation   s    66;;!=GW%%	&FFLL1%Eoodggu5DGoodggu5DG!#1C1CU!KD 	&1GW%%	&s   BB5 5CFc                    [        U5      (       dW  [        5          [        S5        [        R                  " U5      R                  [        R                  5      U l        S S S 5        OXl        [        U5      (       d  [        U5      (       a  [        S5      e[        R                  " U5      R                  [        R                  5      U l
        [        R                  " U5      R                  [        R                  5      U l        [        U5      (       a  [        S5      e[        R                  " U5      R                  [        5      U l        U R                  5         g ! , (       d  f       GN= f)Nerrorz'Constraint limits must be dense arrays.&`keep_feasible` must be a dense array.)r   r
   r   r   
atleast_2dastypefloat64r4   r6   
atleast_1dr   r   boolr#   r:   )r$   r4   r   r   r#   s        r   r%   LinearConstraint.__init__   s    {{  !W%q)00< "! FB<<8B<<FGG--#**2::6--#**2::6M""EFF]]=9@@F  "!s   AE##
E2c                 r    U R                   U-  U R                  -
  U R                  U R                   U-  -
  4$ )aq  
Calculate the residual between the constraint function and the limits

For a linear constraint of the form::

    lb <= A@x <= ub

the lower and upper residuals between ``A@x`` and the limits are values
``sl`` and ``sb`` such that::

    lb + sl == A@x == ub - sb

When all elements of ``sl`` and ``sb`` are positive, all elements of
the constraint are satisfied; a negative element in ``sl`` or ``sb``
indicates that the corresponding element of the constraint is not
satisfied.

Parameters
----------
x: array_like
    Vector of independent variables

Returns
-------
sl, sb : array-like
    The lower and upper residuals
)r4   r   r   r$   r   s     r   residualLinearConstraint.residual   s1    8 vvax$''!477TVVAX#555r   )r4   r#   r   r   N)r(   r)   r*   r+   r,   r:   r   infr%   rG   r-   r.   r   r   r0   r0   {   s)    >& !ffWu !,6r   r0   c                   d    \ rS rSrSrS r\R                  * \R                  S4S jrS r	S r
Srg	)
Bounds   a  Bounds constraint on the variables.

The constraint has the general inequality form::

    lb <= x <= ub

It is possible to use equal bounds to represent an equality constraint or
infinite bounds to represent a one-sided constraint.

Parameters
----------
lb, ub : dense array_like, optional
    Lower and upper bounds on independent variables. `lb`, `ub`, and
    `keep_feasible` must be the same shape or broadcastable.
    Set components of `lb` and `ub` equal
    to fix a variable. Use ``np.inf`` with an appropriate sign to disable
    bounds on all or some variables. Note that you can mix constraints of
    different types: interval, one-sided or equality, by setting different
    components of `lb` and `ub` as necessary. Defaults to ``lb = -np.inf``
    and ``ub = np.inf`` (no bounds).
keep_feasible : dense array_like of bool, optional
    Whether to keep the constraint components feasible throughout
    iterations. Must be broadcastable with `lb` and `ub`.
    Default is False. Has no effect for equality constraints.
c                      [         R                  " U R                  U R                  U R                  5      nUu  U l        U l        U l        g ! [
         a    Sn[        U5      ef = f)Nz6`lb`, `ub`, and `keep_feasible` must be broadcastable.)r   broadcast_arraysr   r   r#   r6   )r$   resr9   s      r   r:   Bounds._input_validation   s[    	&%%dggtww8J8JKC360DGTWd0 	&NGW%%	&s   AA A&Fc                 x   [        U5      (       d  [        U5      (       a  [        S5      e[        R                  " U5      U l        [        R                  " U5      U l        [        U5      (       a  [        S5      e[        R                  " U5      R                  [        5      U l        U R                  5         g )Nz,Lower and upper bounds must be dense arrays.r>   )
r   r6   r   rB   r   r   r@   rC   r#   r:   )r$   r   r   r#   s       r   r%   Bounds.__init__  s~    B<<8B<<KLL--#--#M""EFF]]=9@@F r   c                     [        U 5      R                   SU R                  < SU R                  < 3n[        R
                  " U R                  5      (       a  SU R                  < S3nX-   $ SnX-   $ )N(z, z, keep_feasible=))typer(   r   r   r   anyr#   )r$   startends      r   __repr__Bounds.__repr__  sn    :&&'q2dgg[A66$$$%%$T%7%7$:!<C { C{r   c                 <    XR                   -
  U R                  U-
  4$ )aW  Calculate the residual (slack) between the input and the bounds

For a bound constraint of the form::

    lb <= x <= ub

the lower and upper residuals between `x` and the bounds are values
``sl`` and ``sb`` such that::

    lb + sl == x == ub - sb

When all elements of ``sl`` and ``sb`` are positive, all elements of
``x`` lie within the bounds; a negative element in ``sl`` or ``sb``
indicates that the corresponding element of ``x`` is out of bounds.

Parameters
----------
x: array_like
    Vector of independent variables

Returns
-------
sl, sb : array-like
    The lower and upper residuals
)r   r   rF   s     r   rG   Bounds.residual  s    4 77{DGGaK''r   )r#   r   r   N)r(   r)   r*   r+   r,   r:   r   rI   r%   rZ   rG   r-   r.   r   r   rK   rK      s.    2& 66'bffE 	!(r   rK   c                   Z    \ rS rSrSrS\R                  * \R                  44S jrS rSr	g)PreparedConstrainti1  a  Constraint prepared from a user defined constraint.

On creation it will check whether a constraint definition is valid and
the initial point is feasible. If created successfully, it will contain
the attributes listed below.

Parameters
----------
constraint : {NonlinearConstraint, LinearConstraint`, Bounds}
    Constraint to check and prepare.
x0 : array_like
    Initial vector of independent variables.
sparse_jacobian : bool or None, optional
    If bool, then the Jacobian of the constraint will be converted
    to the corresponded format if necessary. If None (default), such
    conversion is not made.
finite_diff_bounds : 2-tuple, optional
    Lower and upper bounds on the independent variables for the finite
    difference approximation, if applicable. Defaults to no bounds.

Attributes
----------
fun : {VectorFunction, LinearVectorFunction, IdentityVectorFunction}
    Function defining the constraint wrapped by one of the convenience
    classes.
bounds : 2-tuple
    Contains lower and upper bounds for the constraints --- lb and ub.
    These are converted to ndarray and have a size equal to the number of
    the constraints.
keep_feasible : ndarray
     Array indicating which components must be kept feasible with a size
     equal to the number of the constraints.
Nc           
         [        U[        5      (       aD  [        UR                  UUR                  UR
                  UR                  UR                  XC5      nOX[        U[        5      (       a  [        UR                  X#5      nO,[        U[        5      (       a  [        X#5      nO[        S5      eUR                  n[        R                   " UR"                  [$        S9n[        R                   " UR&                  [$        S9n[        R                   " UR(                  [*        S9n	[        R,                  " Xv5      n[        R,                  " X5      n[        R,                  " X5      n	U	R.                  U4:w  a  [        S5      eXU:g  -  n
UR0                  n[        R2                  " X   Xz   :  5      (       d"  [        R2                  " X   X   :  5      (       a  [        S5      eXPl        Xx4U l        Xl        g )Nz*`constraint` of an unknown type is passed.)dtypez"`keep_feasible` has a wrong shape.z_`x0` is infeasible with respect to some inequality constraint with `keep_feasible` set to True.)r   r   r   r   r!   r"   r   r    r0   r   r4   rK   r   r6   mr   asarrayr   floatr   r#   rC   r8   r7   frW   bounds)r$   
constraintx0sparse_jacobianfinite_diff_boundsr   rb   r   r   r#   maskf0s               r   r%   PreparedConstraint.__init__S  s   j"566 !+!+!@!@!+!D!D!3	FC
 
$455&z||RIC
F++(=CIJJEEZZ
U3ZZ
U3

:#;#;4H__R#__R#91$&ABBb)UU66"(RX%&&"&&BH1D*E*E , - - h*r   c                 l   [        5          [        SS[        5        U R                  R                  [        R
                  " U5      5      nSSS5        [        R                  " U R                  S   W-
  S5      n[        R                  " X R                  S   -
  S5      nX4-   $ ! , (       d  f       N_= f)a
  How much the constraint is exceeded by.

Parameters
----------
x : array-like
    Vector of independent variables

Returns
-------
excess : array-like
    How much the constraint is exceeded by, for each of the
    constraints specified by `PreparedConstraint.fun`.
ignore
delta_gradNr   r   )r
   r   UserWarningr   r   rc   maximumrf   )r$   r   ev	excess_lb	excess_ubs        r   	violationPreparedConstraint.violationz  s     
 8\;?bjjm,B  JJt{{1~2A6	JJrKKN2A6	$$ s   AB%%
B3)rf   r   r#   )
r(   r)   r*   r+   r,   r   rI   r%   rv   r-   r.   r   r   r_   r_   1  s*     B 8<&(ffWbff$5%+N%r   r_   c                 X   [         R                  " X5      n [         R                  " X5      nU  Vs/ s H$  o3[         R                  * :  a  [        U5      OSPM&     n nU Vs/ s H#  o3[         R                  :  a  [        U5      OSPM%     nn[	        [        X5      5      $ s  snf s  snf )a  Convert the new bounds representation to the old one.

The new representation is a tuple (lb, ub) and the old one is a list
containing n tuples, ith containing lower and upper bound on a ith
variable.
If any of the entries in lb/ub are -np.inf/np.inf they are replaced by
None.
N)r   r8   rI   rd   listzip)r   r   nr   s       r   new_bounds_to_oldr|     s     
	B		B57	8R266'k%(t
+RB	846	7Bq"&&j%(d
*BB	7B 
9	7s   +B""*B'c           
      b   [        U 6 u  p[        R                  " U Vs/ s H+  nUb  [        [	        U5      5      O[        R
                  * PM-     sn5      n[        R                  " U Vs/ s H*  nUb  [        [	        U5      5      O[        R
                  PM,     sn5      nX4$ s  snf s  snf )a  Convert the old bounds representation to the new one.

The new representation is a tuple (lb, ub) and the old one is a list
containing n tuples, ith containing lower and upper bound on a ith
variable.
If any of the entries in lb/ub are None they are replaced by
-np.inf/np.inf.
)rz   r   arrayrd   r   rI   )rf   r   r   r   s       r   old_bound_to_newr     s     &\FB 
 q 01}5*+266'I  
!B	 q 01}5*+"&&H  
!B 6M  s   2B',1B,c                 &   [         R                  " X5      R                  [        5      n[         R                  " X5      R                  [        5      n[         R                  " X#5      n[         R                  * XB) '   [         R                  XR) '   XE4$ )z6Remove bounds which are not asked to be kept feasible.)r   resizer@   rd   rI   )r   r   r#   n_vars	strict_lb	strict_ubs         r   strict_boundsr     si    		"%,,U3I		"%,,U3IIIm4M!#In "Inr   c                 `  ^^^^^^^^^^^ [        U [        5      (       a  U R                  c=  U R                  c0  [        U R                  [
        5      (       a  U R                  (       a  [        S[        SS9  U R                  m[        U R                  5      (       a  U R                  mOoSmOl[        R                  " U R                  5      (       a  [        S[        SS9  U R                  m[        T5      (       a  TR!                  5       mU4S jmU4S jm[#        U T5      nUR$                  u  mmTT:H  m[        R&                  " T[        R(                  * :g  T5      m[        R&                  " T[        R(                  :g  T5      m[        R*                  " T[        R(                  * :H  T[        R(                  :H  5      n[        R                  " U5      (       a  [        S[        SS9  / n[        R                  " T5      (       a  UUU4S	 jnS
US./nTb  UU4S jnXdS   S'   / n[        R,                  " T5      m[        R,                  " T5      mTT-   (       a'  UUUUUUU4S jnSUS./nTb  UUUUUU4S jn	XS   S'   XG-   n
[/        U
5      S:  a  [        S[        SS9  U
$ )zM
Converts new-style constraint objects to old-style constraint dictionaries.
Nz}Constraint options `finite_diff_jac_sparsity`, `finite_diff_rel_step`, `keep_feasible`, and `hess`are ignored by this method.   )
stacklevelz<Constraint option `keep_feasible` is ignored by this method.c                 2   > [         R                  " TU 5      $ r   )r   dotr   r4   s    r   r   "new_constraint_to_old.<locals>.fun  s    66!Q<r   c                    > T$ r   r.   r   s    r   r!   "new_constraint_to_old.<locals>.jac  s    Hr   zSAt least one constraint is unbounded above and below. Such constraints are ignored.c                 n   > [         R                  " T" U 5      5      R                  5       nUT   TT   -
  $ r   )r   r~   flatten)r   yr   i_eqr   s     r   f_eq#new_constraint_to_old.<locals>.f_eq  s1    Q ((*AT7RX%%r   eq)rV   r   c                    > T" U 5      n[        U5      (       a  UR                  5       n[        R                  " U5      nUTS S 24   $ r   )r   toarrayr   r?   )r   dyr   r!   s     r   j_eq#new_constraint_to_old.<locals>.j_eq  s<    VB<<B]]2&$'{"r   r   r!   c                    > [         R                  " TT-   5      n[         R                  " T" U 5      5      R                  5       nUT   TT   -
  US T& UT   T	T   -
  * UTS & U$ r   )r   zerosr~   r   )
r   r   y_allr   i_bound_abovei_bound_belowr   n_bound_aboven_bound_belowr   s
      r   f_ineq%new_constraint_to_old.<locals>.f_ineq  so    67AHHSV$,,.E %m 4r-7H HAn}"'"6M9J"J KAmnHr   ineqc                   > [         R                  " TT-   [        T5      45      nT" U 5      n[        U5      (       a  UR	                  5       n[         R
                  " U5      nUT   US T2S S 24'   UT   * UTS 2S S 24'   U$ r   )r   r   lenr   r   r?   )	r   r   dy_allr   r   r!   r   r   rh   s	      r   j_ineq%new_constraint_to_old.<locals>.j_ineq  s    XX}}<c"gFGQF###^^-Fv.(.}(=>M>1$%)/)>(>=>1$%	r   r   zEquality and inequality constraints are specified in the same element of the constraint list. For efficient use with this method, equality and inequality constraints should be specified in separate elements of the constraint list. )r   r   r    r   r"   r   r#   r	   r   r   callabler!   r   rW   r4   r   r   r_   rf   logical_xorrI   logical_andsumr   )conrh   pconi_unboundedceqr   r   cineqr   r   old_constraintsr4   r   r   r   r   r!   r   r   r   r   s    `         @@@@@@@@@@r   new_constraint_to_oldr     s8    #*++((4((4sxx..!! / !Q0
 ggCGG''CC 66###$$O Q0 EEA;;		A	 	
 c2&D[[FB8DNN2"&&=$7MNN2<6M..wbff=K	vvk (	, C	vvd||	& T*+?# !F5MEFF=)MFF=)M}$	 	 !01?  %!HUOkO
?a = 		,
 r   c                   ^^  TS   R                  5       nUS;  a  [        STS    S35      e S	T;  a  [        S
U -  5      eSnUS:X  a  SnO[
        R                  nSnST;   a  TS   mUU4S jnST;   a  UU4S jnOTS	   nST;   a  TS   n[        XtXV5      $ ! [         a  n[        SU -  5      UeSnAf[         a  n[        S5      UeSnAf[         a  n[        S5      UeSnAff = f)zM
Converts old-style constraint dictionaries to new-style constraint objects.
rV   )r   r   zUnknown constraint type 'z'.z"Constraint %d has no type defined.Nz/Constraints must be a sequence of dictionaries.z#Constraint's type must be a string.r   z&Constraint %d has no function defined.r   r   r'   argsc                    > TS   " U /TQ76 $ )Nr   r.   r   r   r   s    r   r   "old_constraint_to_new.<locals>.funH  s    u:a'$''r   r!   c                    > TS   " U /TQ76 $ )Nr!   r.   r   s    r   r!   "old_constraint_to_new.<locals>.jacK  s    5z!+d++r   )lowerr6   KeyError	TypeErrorAttributeErrorr   rI   r   )	icr   ctypeer   r   r!   r   r   s	    `      @r   old_constraint_to_newr   *  s#   
JF!!# &8VRHII 'CABFGG	
B}VV
C}6{	(C<, %jC<e*Cs00C  I;b@AqH =
	  F=>AEFs/   B 
C-'B66C-CC-C((C-)r,   numpyr   _hessian_update_strategyr   _differentiable_functionsr   r   r   	_optimizer   warningsr	   r
   r   r   scipy.sparser   r   r   r0   rK   r_   r|   r   r   r   r   r.   r   r   <module>r      sz    *  *B B & G G !8g+ g+Ta6 a6HO( O(db% b%J$* `F(1r   