L i`hdZddlZddlmZddlmZmZmZddl m Z d dZ d dZ d d Z dd Z dd Zy)aSimplex method for linear programming The *simplex* method uses a traditional, full-tableau implementation of Dantzig's simplex algorithm [1]_, [2]_ (*not* the Nelder-Mead simplex). This algorithm is included for backwards compatibility and educational purposes. .. versionadded:: 0.15.0 Warnings -------- The simplex method may encounter numerical difficulties when pivot values are close to the specified tolerance. If encountered try remove any redundant constraints, change the pivot strategy to Bland's rule or increase the tolerance value. Alternatively, more robust methods maybe be used. See :ref:`'interior-point' ` and :ref:`'revised simplex' `. References ---------- .. [1] Dantzig, George B., Linear programming and extensions. Rand Corporation Research Study Princeton Univ. Press, Princeton, NJ, 1963 .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to Mathematical Programming", McGraw-Hill, Chapter 4. N)warn)OptimizeResultOptimizeWarning_check_unknown_options) _postsolvectjj|dddf| k\|dddfd}|jdk(rdtjfS|rMdtj tj tj|jddfSdtjj ||jk(ddfS)a5 Given a linear programming simplex tableau, determine the column of the variable to enter the basis. Parameters ---------- T : 2-D array A 2-D array representing the simplex tableau, T, corresponding to the linear programming problem. It should have the form: [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]], [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]], . . . [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]], [c[0], c[1], ..., c[n_total], 0]] for a Phase 2 problem, or the form: [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]], [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]], . . . [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]], [c[0], c[1], ..., c[n_total], 0], [c'[0], c'[1], ..., c'[n_total], 0]] for a Phase 1 problem (a problem in which a basic feasible solution is sought prior to maximizing the actual objective. ``T`` is modified in place by ``_solve_simplex``. tol : float Elements in the objective row larger than -tol will not be considered for pivoting. Nominally this value is zero, but numerical issues cause a tolerance about zero to be necessary. bland : bool If True, use Bland's rule for selection of the column (select the first column with a negative coefficient in the objective row, regardless of magnitude). Returns ------- status: bool True if a suitable pivot column was found, otherwise False. A return of False indicates that the linear programming simplex algorithm is complete. col: int The index of the column of the pivot element. If status is False, col will be returned as nan. NFcopyrT) npma masked_wherecountnannonzero logical_not atleast_1dmaskmin)Ttolblandrs e/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/optimize/_linprog_simplex.py _pivot_colr%sh   Ab#2#gJ3$."crc'   GB xxzQbff} RZZr}}RWW/E FGJ1MMM rRVVX~.q1!4 44c|dk(rd}nd}tjj|d| |f|k|d| |fd}|jdk(rdtjfStjj|d| |f|k|d| dfd}||z } tjj | | j k(d} |r.d| tjtj|| fSd| dfS) a Given a linear programming simplex tableau, determine the row for the pivot operation. Parameters ---------- T : 2-D array A 2-D array representing the simplex tableau, T, corresponding to the linear programming problem. It should have the form: [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]], [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]], . . . [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]], [c[0], c[1], ..., c[n_total], 0]] for a Phase 2 problem, or the form: [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]], [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]], . . . [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]], [c[0], c[1], ..., c[n_total], 0], [c'[0], c'[1], ..., c'[n_total], 0]] for a Phase 1 problem (a Problem in which a basic feasible solution is sought prior to maximizing the actual objective. ``T`` is modified in place by ``_solve_simplex``. basis : array A list of the current basic variables. pivcol : int The index of the pivot column. phase : int The phase of the simplex algorithm (1 or 2). tol : float Elements in the pivot column smaller than tol will not be considered for pivoting. Nominally this value is zero, but numerical issues cause a tolerance about zero to be necessary. bland : bool If True, use Bland's rule for selection of the row (if more than one row can be used, choose the one with the lowest variable index). Returns ------- status: bool True if a suitable pivot row was found, otherwise False. A return of False indicates that the linear programming problem is unbounded. row: int The index of the row of the pivot element. If status is False, row will be returned as nan. rNFr rr T) r rrrrrrargmintake) rbasispivcolphaserrkrmbqmin_rowss r _pivot_rowr(bs p z     Acrc6kNc11SqbS&[>  NB xxzQbff}   Acrc6kNc11SqbS"W:E  JB RAuu}}Q!%%'\*1-H Xbiix(@ABBB ! rc|||<|||f}|||z ||<t|jdD]}||k7s |||||||fzz ||< tj||ddrd|dd|dd}t |t d y y ) a Pivot the simplex tableau inplace on the element given by (pivrow, pivol). The entering variable corresponds to the column given by pivcol forcing the variable basis[pivrow] to leave the basis. Parameters ---------- T : 2-D array A 2-D array representing the simplex tableau, T, corresponding to the linear programming problem. It should have the form: [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]], [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]], . . . [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]], [c[0], c[1], ..., c[n_total], 0]] for a Phase 2 problem, or the form: [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]], [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]], . . . [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]], [c[0], c[1], ..., c[n_total], 0], [c'[0], c'[1], ..., c'[n_total], 0]] for a Phase 1 problem (a problem in which a basic feasible solution is sought prior to maximizing the actual objective. ``T`` is modified in place by ``_solve_simplex``. basis : 1-D array An array of the indices of the basic variables, such that basis[i] contains the column corresponding to the basic variable for row i. Basis is modified in place by _apply_pivot. pivrow : int Row index of the pivot. pivcol : int Column index of the pivot. rg@)atolrtolz.The pivot operation produces a pivot value of:z .1ez=, which is only slightly greater than the specified tolerancez. This may lead to issues regarding the numerical stability of the simplex method. Removing redundant constraints, changing the pivot strategy via Bland's rule or increasing the tolerance may help reduce the issue.) stacklevelN)rangeshaper iscloserr)rr!pivrowr"rpivvalirowmessages r _apply_pivotr5sVE&M vv~ F& F"AfIaggaj!< 6>g& AdFlO ;;AdG<  zz&#AC0= 0 Parameters ---------- T : 2-D array A 2-D array representing the simplex tableau, T, corresponding to the linear programming problem. It should have the form: [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]], [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]], . . . [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]], [c[0], c[1], ..., c[n_total], 0]] for a Phase 2 problem, or the form: [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]], [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]], . . . [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]], [c[0], c[1], ..., c[n_total], 0], [c'[0], c'[1], ..., c'[n_total], 0]] for a Phase 1 problem (a problem in which a basic feasible solution is sought prior to maximizing the actual objective. ``T`` is modified in place by ``_solve_simplex``. n : int The number of true variables in the problem. basis : 1-D array An array of the indices of the basic variables, such that basis[i] contains the column corresponding to the basic variable for row i. Basis is modified in place by _solve_simplex callback : callable, optional If a callback function is provided, it will be called within each iteration of the algorithm. The callback must accept a `scipy.optimize.OptimizeResult` consisting of the following fields: x : 1-D array Current solution vector fun : float Current value of the objective function success : bool True only when a phase has completed successfully. This will be False for most iterations. slack : 1-D array The values of the slack variables. Each slack variable corresponds to an inequality constraint. If the slack is zero, the corresponding constraint is active. con : 1-D array The (nominally zero) residuals of the equality constraints, that is, ``b - A_eq @ x`` phase : int The phase of the optimization being executed. In phase 1 a basic feasible solution is sought and the T has an additional row representing an alternate objective function. status : int An integer representing the exit status of the optimization:: 0 : Optimization terminated successfully 1 : Iteration limit reached 2 : Problem appears to be infeasible 3 : Problem appears to be unbounded 4 : Serious numerical difficulties encountered nit : int The number of iterations performed. message : str A string descriptor of the exit status of the optimization. postsolve_args : tuple Data needed by _postsolve to convert the solution to the standard-form problem into the solution to the original problem. maxiter : int The maximum number of iterations to perform before aborting the optimization. tol : float The tolerance which determines when a solution is "close enough" to zero in Phase 1 to be considered a basic feasible solution or close enough to positive to serve as an optimal solution. phase : int The phase of the optimization being executed. In phase 1 a basic feasible solution is sought and the T has an additional row representing an alternate objective function. bland : bool If True, choose pivots using Bland's rule [3]_. In problems which fail to converge due to cycling, using Bland's rule can provide convergence at the expense of a less optimal path about the simplex. nit0 : int The initial iteration number used to keep an accurate iteration total in a two-phase problem. Returns ------- nit : int The number of iterations. Used to keep an accurate iteration total in the two-phase problem. status : int An integer representing the exit status of the optimization:: 0 : Optimization terminated successfully 1 : Iteration limit reached 2 : Problem appears to be infeasible 3 : Problem appears to be unbounded 4 : Serious numerical difficulties encountered rFrrz1Argument 'phase' to _solve_simplex must be 1 or 2N)dtypeTr ) xfunslackconstatusr4nitsuccessr#complete)r/ ValueErrorr.sizeabslenr5r emptyfloat64maxrrr(rr)rnr!callbackpostsolve_argsmaxiterrr#rnit0r?r>r4rAmrowr1col non_zero_rowr"solution pivcol_found pivrow_foundr:r;r<r=ress r_solve_simplexrVsv C FGH z GGAJqL ! GGAJqLLMM z',EJJ&77s*qwwqzA~57 F+0a+@:C"1VS[>2S8 :L:< 1$%aQvvs;q  5!9~88AGGAJN"**=88C QE"1I0BC"$**.)!S%8 fVVFVVFFH$.asE#R L&  HQK"#BQBF)HU2AY ! A!+>" AsE3! "!Q;38$ " C SMg~Qvvs;qWX ;w7:s !I $Ic t| d} dddddd} |j\} }tj|d}||xxdzcc<||xxdzcc<tj| |z}|j }tj |tj| |d d tjff}tj |tj| |f}|jd  }d||<tj|||f}t|| |||||d | \}} |}t|d |kr#|d dd d f}tj||d }n+d} dt|d dd|dt|d dd| | <| dk(rt|| |||||d| | \}} tj| |z}|d | df||d | <|d |}|| | | t|fS)a Minimize a linear objective function subject to linear equality and non-negativity constraints using the two phase simplex method. Linear programming is intended to solve problems of the following form: Minimize:: c @ x Subject to:: A @ x == b x >= 0 User-facing documentation is in _linprog_doc.py. Parameters ---------- c : 1-D array Coefficients of the linear objective function to be minimized. c0 : float Constant term in objective function due to fixed (and eliminated) variables. (Purely for display.) A : 2-D array 2-D array such that ``A @ x``, gives the values of the equality constraints at ``x``. b : 1-D array 1-D array of values representing the right hand side of each equality constraint (row) in ``A``. callback : callable, optional If a callback function is provided, it will be called within each iteration of the algorithm. The callback function must accept a single `scipy.optimize.OptimizeResult` consisting of the following fields: x : 1-D array Current solution vector fun : float Current value of the objective function success : bool True when an algorithm has completed successfully. slack : 1-D array The values of the slack variables. Each slack variable corresponds to an inequality constraint. If the slack is zero, the corresponding constraint is active. con : 1-D array The (nominally zero) residuals of the equality constraints, that is, ``b - A_eq @ x`` phase : int The phase of the algorithm being executed. status : int An integer representing the status of the optimization:: 0 : Algorithm proceeding nominally 1 : Iteration limit reached 2 : Problem appears to be infeasible 3 : Problem appears to be unbounded 4 : Serious numerical difficulties encountered nit : int The number of iterations performed. message : str A string descriptor of the exit status of the optimization. postsolve_args : tuple Data needed by _postsolve to convert the solution to the standard-form problem into the solution to the original problem. Options ------- maxiter : int The maximum number of iterations to perform. disp : bool If True, print exit status message to sys.stdout tol : float The tolerance which determines when a solution is "close enough" to zero in Phase 1 to be considered a basic feasible solution or close enough to positive to serve as an optimal solution. bland : bool If True, use Bland's anti-cycling rule [3]_ to choose pivots to prevent cycling. If False, choose pivots which should lead to a converged solution more quickly. The latter method is subject to cycling (non-convergence) in rare instances. 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 ------- x : 1-D array Solution vector. status : int An integer representing the exit status of the optimization:: 0 : Optimization terminated successfully 1 : Iteration limit reached 2 : Problem appears to be infeasible 3 : Problem appears to be unbounded 4 : Serious numerical difficulties encountered message : str A string descriptor of the exit status of the optimization. iteration : int The number of iterations taken to solve the problem. References ---------- .. [1] Dantzig, George B., Linear programming and extensions. Rand Corporation Research Study Princeton Univ. Press, Princeton, NJ, 1963 .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to Mathematical Programming", McGraw-Hill, Chapter 4. .. [3] Bland, Robert G. New finite pivoting rules for the simplex method. Mathematics of Operations Research (2), 1977: pp. 103-107. Notes ----- The expected problem formulation differs between the top level ``linprog`` module and the method specific solvers. The method specific solvers expect a problem in standard form: Minimize:: c @ x Subject to:: A @ x == b x >= 0 Whereas the top level ``linprog`` module expects a problem of form: Minimize:: c @ x Subject to:: A_ub @ x <= b_ub A_eq @ x == b_eq lb <= x <= ub where ``lb = 0`` and ``ub = None`` unless set in ``bounds``. The original problem contains equality, upper-bound and variable constraints whereas the method specific solver requires equality constraints and variable non-negativity. ``linprog`` module converts the original problem to standard form by converting the simple bounds to upper bound constraints, introducing non-negative slack variables for inequality constraints, and expressing unbounded variables as the difference between two non-negative variables. rz%Optimization terminated successfully.zIteration limit reached.z>Optimization failed. Unable to find a feasible starting point.z9Optimization failed. The problem appears to be unbounded.z1Optimization failed. Singular matrix encountered.)rrrr9r N)axisr)rJrKrLrr#r)r r rzmPhase 1 of the simplex method failed to find a feasible solution. The pseudo-objective function evaluates to z.1ez) which exceeds the required tolerance of z for a solution to be considered 'close enough' to zero to be a basic solution. Consider increasing the tolerance to be greater than zH. If this tolerance is unacceptably large the problem may be infeasible.)rJrKrLrr#rrM)rr/r lessaranger hstackeyenewaxiszerossumvstackrVrDdeleteint)cc0AbrJrKrLrdisprunknown_optionsr>messagesrIrNis_negative_constraintavr!row_constraints row_objectiverow_pseudo_objectivernit1nit2rRr:s r_linprog_simplexrrs>v?+ F:-&NF HH 77DAq WWQ]## 1 B GGIEiiBFF1IqBJJ/? @AOIIq"((1+r23M+//Q/77  ?M3GHIA!!Q1?*1s!(-$LD& D 1V9~ crc1fI IIaQ  D1V9~c"#77:eF)rs)rsrFr)rtrsFF)__doc__numpyr warningsr _optimizerrr _linprog_utilrrr(r5rVrrrrr{sI<NN%:5zDN<5@GHK^@Ea2r