L iBdZddlZddlZddlmZmZddlmZddl m Z ddl m Z m Z mZmZmZddlmZmZmZd Zd Zd Z d d Zy)a^HiGHS Linear Optimization Methods Interface to HiGHS linear optimization software. https://highs.dev/ .. versionadded:: 1.5.0 References ---------- .. [1] Q. Huangfu and J.A.J. Hall. "Parallelizing the dual revised simplex method." Mathematical Programming Computation, 10 (1), 119-142, 2018. DOI: 10.1007/s12532-017-0130-5 N)OptimizeWarningOptimizeResult)warn)_highs_wrapper) kHighsInfHighsDebugLevelObjSenseHighsModelStatussimplex_constants) csc_arrayvstackissparsectiddtjdtjdtjdtjdtj dtj dtjdtjdtjdtjdtjdtjdtjdtjd tjd }d }|j!||\}}| t#|nd}|d |d |d}||fS)zCConverts HiGHS status number/message to SciPy status number/messageN)z%HiGHS did not provide a status code. )r)r)rz&Optimization terminated successfully. )rzTime limit reached. )rzIteration limit reached. )rzThe problem is infeasible. )zThe problem is unbounded. )rz(The problem is unbounded or infeasible. )rz*The HiGHS status code was not recognized. z(HiGHS Status z: ))r kNotset kLoadError kModelErrorkPresolveError kSolveErrorkPostsolveError kModelEmptykObjectiveBoundkObjectiveTargetkOptimal kTimeLimitkIterationLimit kInfeasible kUnboundedkUnboundedOrInfeasiblegetint) highs_status highs_messagescipy_statuses_messages unrecognized scipy_status scipy_messagehstats c/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/optimize/_linprog_highs.py_highs_to_scipy_status_messager/"sF :F  'F ##WF $$g F '' F $$g F (('F $$gF (('F ))7F !!#PF ##%@F ((*JF $$&HF ##%FF //2E!F$EL##L,? L-!-!9C tE%%eWB}oQ@M  &&ctj|}tjd5tj||tz||<ddd|S#1swY|SxYw)Nignoreinvalid)npisinferrstatesignr)xinfss r. _replace_infr;@sP 88A;D X &-''!D'"9,$- H- Hs #AA#c @ ||jS#t$r||cYSt$rptjt }|j |j}td|d|dt|jd|d td||cYSwxYw)NzOption z is z, but only values in z are allowed. Using default: .r stacklevel) lowerAttributeErrorKeyErrorinspect signature_linprog_highs parametersdefaultrsetkeysr)option option_strchoicessig default_strs r._convert_to_highs_enumrOHs $v||~&& v $/nnZ088  wzl$vh.CGLLN#$$A}A ,{##$sBA5BBc  | rd| d} t| tdt| dtjj tjj tjjtjjdd}|\}}}}}}}}|jj\}}tjd 5tj| tjz}ddd|}|}|}tj|f}tj||f}t!|s t!|rt#||f}ntj"||f}t%|}id |d t&j(d |d|dt*j,d|d|d|d| d|d|d|dtj.j0d|d|d| } | j3| t5|}t5|}t5|}t5|}|tj6|dk(rtj8d}ntj:|}t=||j>|j@|jB|||||jEtjF| }!d|!vrH|!d}"tj:|"tI|d}#tj:|"dtI|}"nd\}"}#d|!vr|!d}$tj:|$dtI|}%tj:|$tI|d}&tj:|!ddddf}'tj:|!ddddf}(n d\}%}&d\}'}(|!jKd d})|!jKd!d}*tM|)|*\}+} |!d"},|,|"|#tO|"|%d#tO|#|&d#tO|,dn|,|z |(d#tO|,dn||,z |'d#|!jKd$|+|!d tPjRk(| |!jKd%dxs|!jKd&d|!jKd'd( }-tjT|,rG|E|-j3|!jKd)d|!jKd*d+|!jKd,d+d-|-S#1swYxYw).a Solve the following linear programming problem using one of the HiGHS solvers: User-facing documentation is in _linprog_doc.py. Parameters ---------- lp : _LPProblem A ``scipy.optimize._linprog_util._LPProblem`` ``namedtuple``. solver : "ipm" or "simplex" or None Which HiGHS solver to use. If ``None``, "simplex" will be used. Options ------- maxiter : int The maximum number of iterations to perform in either phase. For ``solver='ipm'``, this does not include the number of crossover iterations. Default is the largest possible value for an ``int`` on the platform. disp : bool Set to ``True`` if indicators of optimization status are to be printed to the console each iteration; default ``False``. time_limit : float The maximum time in seconds allotted to solve the problem; default is the largest possible value for a ``double`` on the platform. presolve : bool Presolve attempts to identify trivial infeasibilities, identify trivial unboundedness, and simplify the problem before sending it to the main solver. It is generally recommended to keep the default setting ``True``; set to ``False`` if presolve is to be disabled. dual_feasibility_tolerance : double Dual feasibility tolerance. Default is 1e-07. The minimum of this and ``primal_feasibility_tolerance`` is used for the feasibility tolerance when ``solver='ipm'``. primal_feasibility_tolerance : double Primal feasibility tolerance. Default is 1e-07. The minimum of this and ``dual_feasibility_tolerance`` is used for the feasibility tolerance when ``solver='ipm'``. ipm_optimality_tolerance : double Optimality tolerance for ``solver='ipm'``. Default is 1e-08. Minimum possible value is 1e-12 and must be smaller than the largest possible value for a ``double`` on the platform. simplex_dual_edge_weight_strategy : str (default: None) Strategy for simplex dual edge weights. The default, ``None``, automatically selects one of the following. ``'dantzig'`` uses Dantzig's original strategy of choosing the most negative reduced cost. ``'devex'`` uses the strategy described in [15]_. ``steepest`` uses the exact steepest edge strategy as described in [16]_. ``'steepest-devex'`` begins with the exact steepest edge strategy until the computation is too costly or inexact and then switches to the devex method. Currently, using ``None`` always selects ``'steepest-devex'``, but this may change as new options become available. mip_max_nodes : int The maximum number of nodes allotted to solve the problem; default is the largest possible value for a ``HighsInt`` on the platform. Ignored if not using the MIP solver. unknown_options : dict Optional arguments not used by this particular solver. If ``unknown_options`` is non-empty, a warning is issued listing all unused options. Returns ------- sol : dict A dictionary consisting of the fields: x : 1D array The values of the decision variables that minimizes the objective function while satisfying the constraints. fun : float The optimal value of the objective function ``c @ x``. slack : 1D array The (nominally positive) values of the slack, ``b_ub - A_ub @ x``. con : 1D array The (nominally zero) residuals of the equality constraints, ``b_eq - A_eq @ x``. success : bool ``True`` when the algorithm succeeds in finding an optimal solution. status : int An integer representing the exit status of the algorithm. ``0`` : Optimization terminated successfully. ``1`` : Iteration or time limit reached. ``2`` : Problem appears to be infeasible. ``3`` : Problem appears to be unbounded. ``4`` : The HiGHS solver ran into a problem. message : str A string descriptor of the exit status of the algorithm. nit : int The total number of iterations performed. For ``solver='simplex'``, this includes iterations in all phases. For ``solver='ipm'``, this does not include crossover iterations. crossover_nit : int The number of primal/dual pushes performed during the crossover routine for ``solver='ipm'``. This is ``0`` for ``solver='simplex'``. ineqlin : OptimizeResult Solution and sensitivity information corresponding to the inequality constraints, `b_ub`. A dictionary consisting of the fields: residual : np.ndnarray The (nominally positive) values of the slack variables, ``b_ub - A_ub @ x``. This quantity is also commonly referred to as "slack". marginals : np.ndarray The sensitivity (partial derivative) of the objective function with respect to the right-hand side of the inequality constraints, `b_ub`. eqlin : OptimizeResult Solution and sensitivity information corresponding to the equality constraints, `b_eq`. A dictionary consisting of the fields: residual : np.ndarray The (nominally zero) residuals of the equality constraints, ``b_eq - A_eq @ x``. marginals : np.ndarray The sensitivity (partial derivative) of the objective function with respect to the right-hand side of the equality constraints, `b_eq`. lower, upper : OptimizeResult Solution and sensitivity information corresponding to the lower and upper bounds on decision variables, `bounds`. residual : np.ndarray The (nominally positive) values of the quantity ``x - lb`` (lower) or ``ub - x`` (upper). marginals : np.ndarray The sensitivity (partial derivative) of the objective function with respect to the lower and upper `bounds`. mip_node_count : int The number of subproblems or "nodes" solved by the MILP solver. Only present when `integrality` is not `None`. mip_dual_bound : float The MILP solver's final estimate of the lower bound on the optimal solution. Only present when `integrality` is not `None`. mip_gap : float The difference between the final objective function value and the final dual bound, scaled by the final objective function value. Only present when `integrality` is not `None`. Notes ----- The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain `marginals`, or partial derivatives of the objective function with respect to the right-hand side of each constraint. These partial derivatives are also referred to as "Lagrange multipliers", "dual values", and "shadow prices". The sign convention of `marginals` is opposite that of Lagrange multipliers produced by many nonlinear solvers. References ---------- .. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code." Mathematical programming 5.1 (1973): 1-28. .. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge simplex algorithm." Mathematical Programming 12.1 (1977): 361-371. zUnrecognized options detected: z). These will be passed to HiGHS verbatim.rr>!simplex_dual_edge_weight_strategyN)dantzigdevexzsteepest-devexsteepestN)rLr2r3presolvesensesolver time_limithighs_debug_leveldual_feasibility_toleranceipm_optimality_tolerancelog_to_console mip_max_nodes output_flagprimal_feasibility_tolerancesimplex_strategyipm_iteration_limitsimplex_iteration_limit mip_rel_gaprslack)NNlambda marg_bndsrstatusmessager9)residual marginalsfun simplex_nitipm_nit crossover_nit) r9rdconineqlineqlinr@upperrkrgsuccessrhnitrnmip_node_countmip_dual_boundgmip_gap)rurvrw)+rrrOs_cSimplexEdgeWeightStrategy!kSimplexEdgeWeightStrategyDantzigkSimplexEdgeWeightStrategyDevex kSimplexEdgeWeightStrategyChoose&kSimplexEdgeWeightStrategySteepestEdgeTcopyr5r7 ones_likeinf concatenaterrr r kMinimizer kHighsDebugLevelNoneSimplexStrategykSimplexStrategyDualupdater;sumemptyarrayrindptrindicesdataastypeuint8lenr%r/rr rany).lprWrXrUdispmaxiterrZr_r[rQrcr]unknown_optionsrh&simplex_dual_edge_weight_strategy_enumcA_ubb_ubA_eqb_eqboundsx0 integralitylbublhs_ubrhs_ublhs_eqrhs_eqlhsrhsAoptionsresrdrolamda marg_ineqlin marg_eqlin marg_upper marg_lowerr'r(rgr9sols. r.rErEYsJ4_4EF== Wo!4.D)+..PP..NN..OO..UU .*:<6AtT4vr; XX]]_FB X &,,,t$$RVV+, F F F ..&&) *C ..&&) *C~$ D$<  IItTl #! AH## & j  _AA  %&@  #$< $  t '(D , 2 C//DD w "7!" {#G& NN?# s C s C b B b Bbff[1Q6hhqk hh{+ AHHaiicR!3!3BHH!=w HC #~G hhuSYZ()zD *+ s3H xxjs4y 12 XXeCIJ/0 XXc+.q!t45 XXc+.q!t45 #- j!+ J 778T*LGGIt,M4\5BDOFG CA$ (& #&$ ##$94!b&&$ ##$94"q&&$''%.(m'7'@'@@''-+Dswwy!/DGGO41 C6 vvay[, !gg&6:!gg&6<wwy#.  Jc,,s (S  S) NTFNNNNNNN)__doc__rCnumpyr5 _optimizerrwarningsr_highspy._highs_wrapperr_highspy._corerr r r r rx scipy.sparser rrr/r;rOrEr0r.rs\ 6354 '< $":>'+.204,059#!%Mr0