L i ddlmZddlmZddlZddlZddlmZm Z m Z m Z ddl m Z ddlmZmZddlmZmZdd lmZGd d ZGd d ZGddZGddZGddZy))suppress) signatureN)BoundsLinearConstraintNonlinearConstraintOptimizeResult)PreparedConstraint) PRINT_OPTIONSBARRIER)CallbackSuccessget_arrays_tol)exact_1d_arrayc<eZdZdZdZdZedZedZy)ObjectiveFunctionz) Real-valued objective function. c|r3| t|sJt|tsJt|tsJ||_||_||_d|_y)a Initialize the objective function. Parameters ---------- fun : {callable, None} Function to evaluate, or None. ``fun(x, *args) -> float`` where ``x`` is an array with shape (n,) and `args` is a tuple. verbose : bool Whether to print the function evaluations. debug : bool Whether to make debugging tests during the execution. *args : tuple Additional arguments to be passed to the function. Nr)callable isinstancebool_fun_verbose_args_n_eval)selffunverbosedebugargss _/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/_lib/cobyqa/problem.py__init__zObjectiveFunction.__init__sT& ;(3- //gt, ,,eT* **    ctj|t}|jd}|Sttj|j|g|j }|xj dz c_|jrAtjdit5t|jd|d|ddd|S|S#1swY|SxYw)a Evaluate the objective function. Parameters ---------- x : array_like, shape (n,) Point at which the objective function is evaluated. Returns ------- float Function value at `x`. dtypeNr () = ) nparrayfloatrsqueezerrr printoptionsr printname)rxfs r__call__zObjectiveFunction.__call__6s HHQe $ 99 A bjj1!:tzz!:;r?r@r rArJrLr]r[rar(r!rrCrCnsEG4    !")Gr!rCceZdZdZdZedZedZedZedZ edZ edZ d Z d Z y ) LinearConstraintszK Linear constraints ``a_ub @ x <= b_ub`` and ``a_eq @ x == b_eq``. c |r=t|tsJ|D]}t|trJt|tsJt j d|f|_t j d|_t j d|f|_t j d|_ |D]|}t j|j|jz t|j|jk}t j|ryt j|j |j"|f|_t j$|j&d|j||j|zzf|_ t j(|rt j|j*|j"||j"| f|_t j$|j,|j||j| f|_d|j*t j.|j*<d|j t j.|j <t j.|j,t j0|j,z}t j.|j&}|j*|ddf|_|j,||_|j |ddf|_|j&||_ |Dcgc]8}|j"j2st5|t j6|:c}|_ycc}w)a2 Initialize the linear constraints. Parameters ---------- constraints : list of LinearConstraint Linear constraints. n : int Number of variables. debug : bool Whether to make debugging tests during the execution. r?r%N)rlistrrr)empty_a_ub_b_ub_a_eq_b_eqabsrGrEranyvstacka_eqA concatenateb_eqrMa_ubb_ubrKisinfrRr rQrS) r constraintsnr constraint is_equalityundef_ubundef_eqcs rr zLinearConstraints.__init__s k40 00) @ !*.>??? @eT* **XXq!f% XXa[ XXq!f% XXa[ % J&& - z}}=>Kvvk"YY :<< 3L'MN ^^ &MM+6(mmK89  66+&YY " k\2#{l33  ^^ " {l3# |44 1 B*- "((499%&), "((499%&88DII&$)))<<88DII&YYy!|, YYy) YYy!|, YYy) 7B 23acchh q"''!* -  s N  !N c|jS)z Left-hand side matrix of the linear inequality constraints. Returns ------- `numpy.ndarray`, shape (m, n) Left-hand side matrix of the linear inequality constraints. )rhr6s rrszLinearConstraints.a_ubzzr!c|jS)z Right-hand side vector of the linear inequality constraints. Returns ------- `numpy.ndarray`, shape (m, n) Right-hand side vector of the linear inequality constraints. )rir6s rrtzLinearConstraints.b_ub#r~r!c|jS)z Left-hand side matrix of the linear equality constraints. Returns ------- `numpy.ndarray`, shape (m, n) Left-hand side matrix of the linear equality constraints. )rjr6s rrozLinearConstraints.a_eq/r~r!c|jS)z Right-hand side vector of the linear equality constraints. Returns ------- `numpy.ndarray`, shape (m, n) Right-hand side vector of the linear equality constraints. )rkr6s rrrzLinearConstraints.b_eq;r~r!c.|jjSz Number of linear inequality constraints. Returns ------- int Number of linear inequality constraints. )rtrRr6s rm_ubzLinearConstraints.m_ubGyy~~r!c.|jjSz Number of linear equality constraints. Returns ------- int Number of linear equality constraints. )rrrRr6s rm_eqzLinearConstraints.m_eqSrr!cNtj|j|dS)rYr%initialr)maxr[r\s rr]zLinearConstraints.maxcv_svvdnnQ'55r!ct|jr>TXX"Fr2<<?"FG Gxx|#GsA'N)r<r>r?r@r rArsrtrorrrrr]r[r(r!rrcrcsB H            6 r!rcc\eZdZdZdZdZedZedZedZ d dZ d d Z y) NonlinearConstraintszI Nonlinear constraints ``c_ub(x) <= 0`` and ``c_eq(x) == b_eq``. c|rOt|tsJ|D]}t|trJt|tsJt|tsJ||_g|_||_d|_d|_dx|_ |_ y)aA Initialize the nonlinear constraints. Parameters ---------- constraints : list Nonlinear constraints. verbose : bool Whether to print the function evaluations. debug : bool Whether to make debugging tests during the execution. N) rrfrr _constraintsrSr_map_ub_map_eq_m_ub_m_eq)rrvrrrxs rr zNonlinearConstraints.__init__zs k40 00) C !*.ABBB Cgt, ,,eT* **'   "&& TZr!c  t|js8dx|_|_t j gt j gfSt j |t }t|jsg|_g|_ d|_d|_|jD]~}t|js2tj|}d|_ d|_ t||}n t||}d|j_|jj#|t j$|jj&}|j(d|j(d}}t+||}t j,||z |k} |jj#|| |jj#|| |xjt j.| z c_|xjt j.| z c_g} g} t1|jD]\} }|jj|} |j2rpt j4d it65t9t:5|j| jj<}t?|d|d| d d d d d d |j| }|j| }| |}t|r|j(d|}|j(d|}|tj@ kD}||||z }| j#||tj@k}||||z }| j#|| |}t|r-d |j(d||j(d|zz}||z}| j#||jrt jB| } nt j g} |jrt jB| } nt j g} | jD|_| jD|_| | fS#1swYxYw#1swYxYw) a Calculates the residual (slack) for the constraints. Parameters ---------- x : array_like, shape (n,) Point at which the constraints are evaluated. Returns ------- `numpy.ndarray`, shape (m_nonlinear_ub,) Nonlinear inequality constraint slack values. `numpy.ndarray`, shape (m_nonlinear_eq,) Nonlinear equality constraint slack values. rr#c|Srr()x0s rz/NonlinearConstraints.__call__..srr!cy)Nr%r()rvs rrz/NonlinearConstraints.__call__..sr!Tr r&r'Nrer()#rrrrr)r*r+rSrrrjaccopyhessr r f_updatedappendarangerPrTrrlrO enumeraterr-r rr=r<r.rIrqrR)rr0rxr|ridxrErGarr_tolryc_ubc_eqivalfun_nameeq_idxub_idxub_valrJrL finite_xl_v finite_xueq_valmidpoints rr2zNonlinearConstraints.__call__s 4$$%&' 'DJ88B<"- - HHQe $488}DLDLDJDJ"// =  / *-A)AE.AF+Aq1B+J:B$( #ii)1ryy|B(R0 ffR"Wo8  ##C $45 ##C $56 b..{;;  b.. |<< 7 =:txx( EAr&&**Q-C}}__5}5:!.1:#'#4#4Q#7#;#;#D#D !A3d3%89:: \\!_F\\!_F[F6{YYq\&)YYq\&)"&&L  ]VI%66 BK I&I6 B[F6{"))A,v"61f9M"MN(" KK A D ::>>$'D88B>$'D88Bs)(vv NN1gwN ?  r!ctj|jDcgc]}|j|c}Scc}wr)r)rqrSr[)rr0rrrs rr[zNonlinearConstraints.violationVs+~~B2r||ABCCBs=NN) r<r>r?r@r r2rArrr7r]r[r(r!rrrusZ':jX**   0Dr!rc:eZdZdZdZddZedZedZedZ edZ edZ ed Z ed Z ed Zed Zed ZedZedZedZedZedZedZdZddZddZdZy)Problemz Optimization problem. c  | rt|tsJt|tsJt|tsJt|tsJt|t sJt|t sJt| t sJt| tsJ| r| dkDsJt| tsJ| dkDsJt| t sJ||_||_ ||_ |t|s td||_ t|d}|j} |j j| k7rt#d| d|j$j&d| k7rt#d| d t)|j |j*}|j |j*kt-j.|j |j*z |kz|_d |j |j0|j*|j0zz|_t-j4|j2|j |j0|j*|j0|_||_tt9|j |j0|j*|j0|_|j:j=||j0|_|j@|jBdd|j0f|j2zz }ttE|j$dd|j0ft,jF |jH|j$dd|j0f|j2zz tE|jBdd|j0f||g|jJ| |_ |xr|j:jLxrzt-jNt-jP|j:j xr<t-jNt-jP|j:j*}|rd |j:j*|j:j z z|_)d |j:j*|j:j zz|_*tt9t-jV|jJ t-jV|jJ|_|jj@|jjB|jTzz }ttE|jj$t-jX|jRzt,jF |jjH|jj$|jTzz tE|jjBt-jX|jRz||g|jJ| |_ |j>|jTz |jRz |_nHt-jV|jJ|_)t-jZ|jJ|_*||_.| |_/g|_0g|_1g|_2| |_3| |_4g|_5g|_6g|_7y) aY Initialize the nonlinear problem. The problem is preprocessed to remove all the variables that are fixed by the bound constraints. Parameters ---------- obj : ObjectiveFunction Objective function. x0 : array_like, shape (n,) Initial guess. bounds : BoundConstraints Bound constraints. linear : LinearConstraints Linear constraints. nonlinear : NonlinearConstraints Nonlinear constraints. callback : {callable, None} Callback function. feasibility_tol : float Tolerance on the constraint violation. scale : bool Whether to scale the problem according to the bounds. store_history : bool Whether to store the function evaluations. history_size : int Maximum number of function evaluations to store. filter_size : int Maximum number of points in the filter. debug : bool Whether to make debugging tests during the execution. rNz)The callback must be a callable function.z#The initial guess must be a vector.zThe bounds must have z elements.r z@The left-hand side matrices of the linear constraints must have z columns.re)8rrrCrcrr+rint_obj_linear _nonlinearr TypeError _callbackrrRrJrrsshaperrLr)rl _fixed_idx _fixed_valr` _orig_boundsr_boundsra_x0rrrorrIrtrwrNrMisfinite_scaling_factor_scaling_shiftrQdiagzeros_feasibility_tol _filter_size _fun_filter _maxcv_filter _x_filter_store_history _history_size _fun_history_maxcv_history _x_history)robjrrTlinear nonlinearcallbackfeasibility_tolscale store_history history_size filter_sizerrwtolrrs rr zProblem.__init___s` c#45 55f&67 77f&78 88i)=> >>ou5 55eT* **mT2 22lC0 00#a'''k3/ //? "?eT* **  #  H% KLL!B E F GG 99>>Q 4QCzBC C ;;  Q 1 $s)%  VYY 2!99 1 FF699vyy( )C /  IIdoo &4??)C C '' OO IIdoo & IIdoo & #' 699doo-. 4??:J0K L  <<''DOO+;(<={{V[[DOO);t>|tj|<t>|tj|<tAtCt>t> tjDtjF|t>t> }tjDtjF|t>t> }||fS#t:$r }t<|d}~wwxYw) a Evaluate the objective and nonlinear constraint functions. Parameters ---------- x : array_like, shape (n,) Point at which the functions are evaluated. penalty : float, optional Penalty parameter used to select the point in the filter to forward to the callback function. Returns ------- float Objective function value. `numpy.ndarray`, shape (m_nonlinear_ub,) Nonlinear inequality constraint function values. `numpy.ndarray`, shape (m_nonlinear_eq,) Nonlinear equality constraint function values. Raises ------ `cobyqa.utils.CallbackSuccess` If the callback function raises a ``StopIteration``. r#rc3K|]:\}}tj|xr|kxstj|<ywrr)rK).0 fun_filter maxcv_filter maxcv_vals r z#Problem.__call__..7sK -J $- ,*88L)* AAc3K|]:\}}tj|xr|kxstj|<ywrr)rrrfun_vals rrz#Problem.__call__..AsK -J &)j((88J'( rc3<K|]\}}|kxs|kywrr()rrrrrs rrz#Problem.__call__..Ks/ ,J *$@ L(@@ sNintermediate_result)r0r)r)$r)rZr+build_xrrr]rrrrrrrpoprKrrMziprrrangerrr best_evalset parametersr StopIterationr r rminmaximumminimum)rr0penaltyx_fullrr include_pointk remove_pointsigx_bestfun_best_rexcrrs @@rr2zProblem.__call__ s6 JJq &a))F#??62JJq'73       $ $W -    & &y 1 OO " "1 %4$$%(:(::!!%%a(##''*##A& 88G )!4 0 01Q6M XXg  14$$&&1  MXXi  14$$&&1  M  03$$&&1 M     # #G ,    % %i 0 NN ! !! $ 3t//014b"= *88G$#%88D,<,,>q,A#BL!1!1!!45?88D$6$6q$9:?"d&6&6q&99?%););A)>> !  $$((+&&**1-NN&&q) *$4##$t'8'88  $$Q'""&&q)""1% >> %DNN+C /&*nnW&=#!f-s~~&+@*AA*8 $+' NN7JNKNN6* 88G G%,!"%,!"c'7+gX6**RZZ9G8D**RZZ9G8D((! /%3. /sA0W W$WW$c.|jjS)zt Number of variables. Returns ------- int Number of variables. )rrRr6s rrwz Problem.nsww||r!c.|jjS)z Number of variables in the original problem (with fixed variables). Returns ------- int Number of variables in the original problem (with fixed variables). )rrRr6s rn_origzProblem.n_origs###r!c|jS)z Initial guess. Returns ------- `numpy.ndarray`, shape (n,) Initial guess. )rr6s rrz Problem.x0rVr!c.|jjSr4)rr7r6s rr7zProblem.n_evalsyyr!c.|jjS)r:)rr/r6s rrzProblem.fun_namerr!c|jS)z} Bound constraints. Returns ------- BoundConstraints Bound constraints. )rr6s rrTzProblem.boundsr8r!c|jS)z Linear constraints. Returns ------- LinearConstraints Linear constraints. )rr6s rrzProblem.linearr8r!c.|jjS)z Number of bound constraints. Returns ------- int Number of bound constraints. )rTrPr6s rm_boundszProblem.m_boundss{{}}r!c.|jjSr)rrr6s r m_linear_ubzProblem.m_linear_ub{{r!c.|jjSr)rrr6s r m_linear_eqzProblem.m_linear_eqrr!c.|jjS)a  Number of nonlinear inequality constraints. Returns ------- int Number of nonlinear inequality constraints. Raises ------ ValueError If the number of nonlinear inequality constraints is not known. )rrr6s rm_nonlinear_ubzProblem.m_nonlinear_ub###r!c.|jjS)a Number of nonlinear equality constraints. Returns ------- int Number of nonlinear equality constraints. Raises ------ ValueError If the number of nonlinear equality constraints is not known. )rrr6s rm_nonlinear_eqzProblem.m_nonlinear_eqrr!cLtj|jtS)z History of objective function evaluations. Returns ------- `numpy.ndarray`, shape (n_eval,) History of objective function evaluations. r#)r)r*rr+r6s r fun_historyzProblem.fun_history(sxx))77r!cLtj|jtS)z History of maximum constraint violations. Returns ------- `numpy.ndarray`, shape (n_eval,) History of maximum constraint violations. r#)r)r*rr+r6s r maxcv_historyzProblem.maxcv_history4sxx++599r!c |jdkDs|jdkDry|jdkDs|jdkDry|jdkDryy#t $rYywxYw)z Type of the problem. The problem can be either 'unconstrained', 'bound-constrained', 'linearly constrained', or 'nonlinearly constrained'. Returns ------- str Type of the problem. rznonlinearly constrainedzlinearly constrainedzbound-constrained unconstrained)rr rrrrr6s rtypez Problem.type@si -""Q&$*=*=*A0!!A%)9)9A)=-"*& - -  -sAAA AAc |jdk(S)z Whether the problem is a feasibility problem. Returns ------- bool Whether the problem is a feasibility problem. r;)rr6s ris_feasibilityzProblem.is_feasibility^s}}""r!ctj|j}|j||j<||j z|j z||j<|jj|S)a0 Build the full vector of variables from the reduced vector. Parameters ---------- x : array_like, shape (n,) Reduced vector of variables. Returns ------- `numpy.ndarray`, shape (n_orig,) Full vector of variables. ) r)rgrrrrrrra)rr0rs rrzProblem.build_xjsi$++&"&//t$%(<(<$<&*&9&9%:   ((00r!Nc|j|||}tj|rtj|dSyr)r[r)rOr)rr0rrr[s rr]z Problem.maxcv~s:(NN1gwNG  I &66)S1 1r!cg}|jjs,|jj|}|j|t |j j r,|j j|}|j|t |jj r.|jj|||}|j|t |rtj|Syr) rTrNr[rrrrSrr)rq)rr0rrr[blcnlcs rr[zProblem.violations {{&& %%a(A   Q  t{{ &&q)B   R t"" #//++Aw@C   S ! y>>>), , r!ct|jdk(r||jtj|j}tj|j }tj|j }tj|}tj|r||jk}tj|rtjtj||sn||tj||kz}tj|dkDr||tj||kz}tj|d}ntj|rtj|d}ntj |tj"} |||||zz| |<tjtj| r2|tj|k} tj| d}n| tj| k} tj| dkDr| |tj|| kz} tj| dkDr| |tj|| kz} tj| d}ngtjtj|s1|tj|k}tj|d}nt|dz }|j$j'||ddf||||fS)a Return the best point in the filter and the corresponding objective and nonlinear constraint function evaluations. Parameters ---------- penalty : float Penalty parameter Returns ------- `numpy.ndarray`, shape (n,) Best point. float Corresponding objective function value. float Corresponding maximum constraint violation. rr rN)rrrr)r*rrrrmrrMrKnanminrOr flatnonzero full_likenanrTra) rrrrx_filter finite_idx feasible_idx fun_min_idxr merit_filter min_maxcv_idx merit_min_idxs rrzProblem.best_evals, t A % MXXd../ xx 2 23 88DNN+[[. 66* '4+@+@@Lvvl#BFFL12-+"))J|,D"EE ##K014<266$[14$KNN;/3 %NN<04 "||J? z*W|J7O-OOZ(66"((<01%1BIIl4K$KM}5b9A%1BIIl4K$KM'' 6:%(7:* '' 6:%rvv&}58* }5b9A,- % *(==K{+B/AJ!#A KK  A / qM O  r!)r%r)r<r>r?r@r r2rArwrrr7rrTrrrrrr r"r$r'r)rr]r[rr(r!rrrZsjiVB)H   $ $                      $$ $$  8 8 : :--: # #1(4- h r!r) contextlibrinspectrrnumpyr)scipy.optimizerrrrscipy.optimize._constraintsr settingsr r utilsr rrrrCrcrrr(r!rrCso  ;-2!WWt]G]G@ddNbDbDJv  v  r!