L iqYdZddlmZmZmZmZddlZddlm Z m Z m Z ddl m Z ddlmZddlmZd ZGd d ZGd d ZGddZGddZdZdZdZdZdZy)z$Constraints definition for minimize.)warncatch_warnings simplefilterfilterwarningsN)VectorFunctionLinearVectorFunctionIdentityVectorFunction)BFGS)OptimizeWarning)issparsecZt|tjr|jS|SN) isinstancenpndarrayitem)xs a/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/optimize/_constraints.py_arr_to_scalarrs""!RZZ016687a7ceZdZdZ ddZy)NonlinearConstraintaNonlinear 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 array}, 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 array, 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 array}, 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 | t}||_||_||_||_||_||_||_||_yr) r funlbubfinite_diff_rel_stepfinite_diff_jac_sparsityjachess keep_feasible) selfrrrr r!r"rrs r__init__zNonlinearConstraint.__init__psK <6D$8!(@% *r)2-pointNFNN)__name__ __module__ __qualname____doc__r$rrrrsYt9=;?*. +rrcTeZdZdZdZej ej dfdZdZy)LinearConstraintaLinear 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 array}, 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|jjdk7r d}t| |jjdd}t j |j ||_t j |j||_t j |j||_y#t$rd}t|wxYw)Nz%`A` must have exactly two dimensions.rrzM`lb`, `ub`, and `keep_feasible` must be broadcastable to shape `A.shape[0:1]`) Andim ValueErrorshaper broadcast_torrr")r#messager2s r_input_validationz"LinearConstraint._input_validations 66;;! =GW% % &FFLL1%Eoodggu5DGoodggu5DG!#1C1CU!KD  &1GW% % &s BB11CFct|sVt5tdtj|j tj |_dddn||_t|s t|r tdtj|j tj |_ tj|j tj |_ t|r tdtj|j t|_ |jy#1swYxYw)Nerrorz'Constraint limits must be dense arrays.&`keep_feasible` must be a dense array.)r rrr atleast_2dastypefloat64r/r1 atleast_1drrboolr"r5)r#r/rrr"s rr$zLinearConstraint.__init__s{  ! =W%q)00< = =DF B<8B<FG G--#**2::6--#**2::6 M "EF F]]=9@@F   = =s AE  Ecr|j|z|jz |j|j|zz fS)a  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 )r/rrr#rs rresidualzLinearConstraint.residuals18vvax$''!477TVVAX#555rN) r&r'r(r)r5rinfr$r@r*rrr,r,s)> &!ffWu!,6rr,cZeZdZdZdZej ej dfdZdZdZ y)Boundsa\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 tj|j|j|j}|\|_|_|_y#t $rd}t |wxYw)Nz6`lb`, `ub`, and `keep_feasible` must be broadcastable.)rbroadcast_arraysrrr"r1)r#resr4s rr5zBounds._input_validations[ &%%dggtww8J8JKC36 0DGTWd0 &NGW% % &s A A A$FcTt|s t|r tdtj||_tj||_t|r tdtj|j t|_|jy)Nz,Lower and upper bounds must be dense arrays.r8) r r1rr<rrr:r=r"r5)r#rrr"s rr$zBounds.__init__sw B<8B<KL L--#--# M "EF F]]=9@@F  rct|jd|jd|j}t j |j rd|j d}||zSd}||zS)N(z, z, keep_feasible=))typer&rrranyr")r#startends r__repr__zBounds.__repr__so:&&'q 2dgg[A 66$$$ %$T%7%7$:!||jz |j|z fS)aCalculate 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 )rrr?s rr@zBounds.residuals4477{DGGaK''rN) r&r'r(r)r5rrAr$rOr@r*rrrCrCs.2&66'bffE !(rrCcPeZdZdZdej ej ffdZdZy)PreparedConstraintaConstraint 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 t|trEt|j||j|j |j |j||}nPt|trt|j||}n(t|tr t||}n td|j}tj |j"t$}tj |j&t$}tj |j(t*} tj,||}tj,||}tj,| |} | j.|fk7r td| ||k7z} |j0} tj2| | || kstj2| | || kDr td||_||f|_| |_y)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.)rrrrr r!rrr,r r/rCr r1mrasarrayrfloatrr"r=r3r2frLbounds) r# constraintx0sparse_jacobianfinite_diff_boundsrrUrrr"maskf0s rr$zPreparedConstraint.__init__Ws j"5 6 !+!+!@!@!+!D!D!3_ FC  $4 5&z||RIC  F +(_=CIJ J EE ZZ U 3 ZZ U 3 :#;#;4H __R # __R # q9   1$ &AB Bb) UU 66"T(RX% &"&&DBtH1D*E,- -2h *rc`t5tddt|jjt j |}dddt j |jdz d}t j ||jdz d}||zS#1swYZxYw)aZHow 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_gradNrr)rr UserWarningrrrVmaximumrY)r#rev excess_lb excess_ubs r violationzPreparedConstraint.violation~s  - 8\; ?bjjm,B  -JJt{{1~2A6 JJrDKKN2A6 9$$ - -s AB$$B-)r&r'r(r)rrAr$rhr*rrrRrR5s* B8<&(ffWbff$5%+N%rrRcNtj||}tj||}|Dcgc]#}|tj kDr t|nd%}}|Dcgc]"}|tjkr t|nd$}}t t ||Scc}wcc}w)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)rr3rArWlistzip)rrnrs rnew_bounds_to_oldrms Q B Q B57 8a266'k%(t + 8B 846 7qa"&&j%(d * 7B 7 B  9 7s (B'B"c Rt|\}}tj|Dcgc])}|tt |ntj +c}}tj|Dcgc](}|tt |ntj *c}}||fScc}wcc}w)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. )rkrarrayrWrrA)rYrrrs rold_bound_to_newrps&\FB  01}5*+266'I  !B  01}5*+"&&H  !B r6M   s .B'-B$c,tj||jt}tj||jt}tj||}tj ||<tj||<||fS)z6Remove bounds which are not asked to be kept feasible.)rresizer:rWrA)rrr"n_vars strict_lb strict_ubs r strict_boundsrvsu "f%,,U3I "f%,,U3IIImV4M!#I}n "I}n i rc t|tr|j2|j&t|jt r |j rtdtd|j t|jr |jnednbtj|j rtdtd|j t r j! fd fdt#|}|j$\k(tj&tj( k7tj&tj(k7 tj*tj( k(tj(k(}tj|rtdtdg}tjr fd }d |d g}fd }||d d<g}tj,tj, zr% fd}d|d g} fd} | |d d<||z} t/| dkDrtdtd| S)zU 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.funs66!Q< rcSrr*r|s rr z"new_constraint_to_old..jacsHrzSAt least one constraint is unbounded above and below. Such constraints are ignored.cltj|j}|z Sr)rroflatten)ryri_eqrs rf_eqz#new_constraint_to_old..f_eqs1Q ((*AT7RX% %req)rKrc|}t|r|j}tj|}|ddfSr)r toarrayrr9)rdyrr s rj_eqz#new_constraint_to_old..j_eqs:VB<B]]2&$'{"rrr ctjz}tj|j}|z |d| z |d|Sr)rzerosror) rry_allr i_bound_above i_bound_belowr n_bound_above n_bound_belowrs rf_ineqz%new_constraint_to_old..f_ineqso67AHHSV$,,.E %m 4r-7H HAn} "' "6M9J"J KAmn Hrineqctjztf}|}t|r|j }tj |}||dddf<| |dddf<|Sr)rrlenr rr9) rrdy_allrrr rrr[s rj_ineqz%new_constraint_to_old..j_ineqsXX}}M>1$%)/ )>(>=>1$% rrzEquality 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. )rrrrr!r r"rr rcallabler rrLr/r rrRrY logical_xorrA logical_andsumr)conr[pcon i_unboundedceqrrcineqrrold_constraintsr/rrrrr rrrrs ` @@@@@@@@@@rnew_constraint_to_oldrs+#*+  ( ( 4((4sxx.!! /!Q 0 gg CGG ''CC 66### $ O Q 0 EE A; A   c2 &D [[FB 8DNN2"&&=$7MNN2<6M..wbff =K vvk (  , C vvd| &T*+ ? # !CF5M EFF=)MFF=)M}$   !01 ?  %E!HUOEkO ?a =  , rc dj}|dvrtdddd vrtd|d d }|d k(rd }nt j }d}dvrdfd}dvrfd}nd }dvrd}t||||S#t$r}td|d|d}~wt$r}td|d}~wt$r}td |d}~wwxYw)zU Converts old-style constraint dictionaries to new-style constraint objects. rK)rrzUnknown constraint type 'z'.z Constraint z has no type defined.Nz/Constraints must be a sequence of dictionaries.z#Constraint's type must be a string.rz has no function defined.rrr%argscd|gS)Nrr*rrrs rrz"old_constraint_to_new..funLs3u:a'$' 'rr cd|gS)Nr r*rs rr z"old_constraint_to_new..jacOs!s5z!+d++r)lowerr1KeyError TypeErrorAttributeErrorrrAr) icrctypeerrr rrs ` @rold_constraint_to_newr.s) JF !!#  &8V RHI I C;rd*CDEE B }  VV C }6{ ( C< ,%j C<e*C sBC 00C GRD(=>?QF  =   F=>AEFs/B C B++ C 7 C C  CC )r)warningsrrrrnumpyr_differentiable_functionsrr r _hessian_update_strategyr _optimizer scipy._lib._sparser rrr,rCrRrmrprvrrr*rrrsz*GG+&'8 g+g+Ta6a6HO(O(db%b%J$* `F(1r