
    (phز                     ,   S r SSKrSSKrSSKJr  SSKJ	r	  SSK
Jr  SSKJrJrJr  SSKJr  SrSr SSKrSS	KJr  SS
KJr   SSKr  SS jr   SS jrS rS r S r!S r"S r#S r$SS jr%S r&    SS jr'g! \ a    Sr NBf = f! \ a    Sr NKf = f)a  Interior-point method for linear programming

The *interior-point* method uses the primal-dual path following algorithm
outlined in [1]_. This algorithm supports sparse constraint matrices and
is typically faster than the simplex methods, especially for large, sparse
problems. Note, however, that the solution returned may be slightly less
accurate than those of the simplex methods and will not, in general,
correspond with a vertex of the polytope defined by the constraints.

    .. versionadded:: 1.0.0

References
----------
.. [1] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
       optimizer for linear programming: an implementation of the
       homogeneous algorithm." High performance optimization. Springer US,
       2000. 197-232.
    N)warn)LinAlgError   )OptimizeWarningOptimizeResult_check_unknown_options)
_postsolveT)cholesky)analyzeFc                   ^ ^  U(       a  U(       a
  SU 4S jjnU$ U(       a2   [         R                  R                  T 5        [         R                  nU$ [
        (       a(  U(       a!  [        R                  R                  T 5      nU$ [        R                  R                  T US9R                  n U$ U(       a  U 4S jnU$ U(       a'  [        R                  R                  T 5      mU4S jnU$ U4U 4S jjn U$ ! [         a6    [	        T 5      [         l        [         R                  R                  T 5         Nf = f! [         a    e [         a     gf = f)a  
Given solver options, return a handle to the appropriate linear system
solver.

Parameters
----------
M : 2-D array
    As defined in [4] Equation 8.31
sparse : bool (default = False)
    True if the system to be solved is sparse. This is typically set
    True when the original ``A_ub`` and ``A_eq`` arrays are sparse.
lstsq : bool (default = False)
    True if the system is ill-conditioned and/or (nearly) singular and
    thus a more robust least-squares solver is desired. This is sometimes
    needed as the solution is approached.
sym_pos : bool (default = True)
    True if the system matrix is symmetric positive definite
    Sometimes this needs to be set false as the solution is approached,
    even when the system should be symmetric positive definite, due to
    numerical difficulties.
cholesky : bool (default = True)
    True if the system is to be solved by Cholesky, rather than LU,
    decomposition. This is typically faster unless the problem is very
    small or prone to numerical difficulties.
permc_spec : str (default = 'MMD_AT_PLUS_A')
    Sparsity preservation strategy used by SuperLU. Acceptable values are:

    - ``NATURAL``: natural ordering.
    - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
    - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
    - ``COLAMD``: approximate minimum degree column ordering.

    See SuperLU documentation.

Returns
-------
solve : function
    Handle to the appropriate solver function

c                 J   > [         R                  R                  TU 5      S   $ Nr   )spslinalglsqrrsym_posMs     M/var/www/html/venv/lib/python3.13/site-packages/scipy/optimize/_linprog_ip.pysolve_get_solver.<locals>.solveW   s    ::??1a033    )
permc_specc                 J   > [         R                  R                  TU 5      S   $ r   )spr   lstsq)r   r   s    r   r   r   j   s    99??1a033r   c                 D   > [         R                  R                  TU 5      $ N)r   r   	cho_solve)r   Ls    r   r   r   o   s    99..q!44r   c                    > U(       a  [         R                  R                  TU SS9$ [         R                  R                  TU 5      $ )Npos)assume_a)r   r   r   r   s     r   r   r   t   s4    !yyq!eDD!yyq!44r   NF)_get_solvercholmod_factorcholesky_inplace	Exceptioncholmod_analyzehas_umfpackr   r   
factorizedsplur   r   
cho_factorKeyboardInterrupt)r   sparser   r   r
   r   r   r!   s   `      @r   r&   r&   *   s;   T,4T LQ C  ..??B $22@ L= ;7JJ11!4E: L7  JJOOA*OEKKE6 L1 4. L+ II((+5$ L &- 5 5 LG ! C1@1CK...??BC>   sW   D? D? C< D? 1D? (D? 3D? ,D? 0	D? <=D<9D? ;D<<D? ?EEc                    U R                   S   S:X  a  Su  pp[        U5      nX-  U R                  U5      -
  nX&-  U R                  R                  U5      -
  U-
  nUR                  U5      UR	                  5       R                  U5      -
  U-   nUR                  U5      Xg-  -   US-   -  nX5-  nU
(       a?  U R                  [
        R                  " USSS9R                  U R                  5      5      nO.U R                  UR                  SS5      U R                  -  5      n[        UXXU5      nU(       a  SOSnSnSu  nnnnnUU::  Ga  U	" U5      U-  n U	" U5      U-  n!U	" U5      U-  n"UU-  X5-  -
  n#UU-  Xg-  -
  n$US:X  aP  U(       a9  SU-
  U-  U-  X5-  -
  US-  U-  U-  -
  n#SU-
  U-  U-  Xg-  -
  US-  U-  U-  -
  n$OU#UU-  -  n#U$UU-  -  n$S	n%U%(       d   [        UXUU5      u  n&n'[        UU U!SU-  U#-  -
  U U5      u  n(n)[        R                  " [        R                  " U&5      5      (       d/  [        R                  " [        R                  " U'5      5      (       a  [        eS
n%U%(       d  M  U"SU-  U$-  -   UR                  W(5      * UR                  W)5      -   -
  SU-  U-  UR                  W&5      * UR                  W'5      -   -   -  nU(U&U-  -   nU)U'U-  -   n+SU-  U#UU-  -
  -  nSU-  U$UU-  -
  -  n[%        UUUUUUUUS5	      nU(       a  SnOSn,SU-
  S-  ['        U,SU-
  5      -  nUS-  nUU::  a  GM  UW+UUU4$ ! [        [        [        4 ag  n*U(       a  S	n[!        S["        SS9  O4U(       a  S	n[!        S["        SS9  OU(       d  S
n[!        S["        SS9  OU*e[        UXUUU5      n Sn*A*GNVSn*A*ff = f)a  
Given standard form problem defined by ``A``, ``b``, and ``c``;
current variable estimates ``x``, ``y``, ``z``, ``tau``, and ``kappa``;
algorithmic parameters ``gamma and ``eta;
and options ``sparse``, ``lstsq``, ``sym_pos``, ``cholesky``, ``pc``
(predictor-corrector), and ``ip`` (initial point improvement),
get the search direction for increments to the variable estimates.

Parameters
----------
As defined in [4], except:
sparse : bool
    True if the system to be solved is sparse. This is typically set
    True when the original ``A_ub`` and ``A_eq`` arrays are sparse.
lstsq : bool
    True if the system is ill-conditioned and/or (nearly) singular and
    thus a more robust least-squares solver is desired. This is sometimes
    needed as the solution is approached.
sym_pos : bool
    True if the system matrix is symmetric positive definite
    Sometimes this needs to be set false as the solution is approached,
    even when the system should be symmetric positive definite, due to
    numerical difficulties.
cholesky : bool
    True if the system is to be solved by Cholesky, rather than LU,
    decomposition. This is typically faster unless the problem is very
    small or prone to numerical difficulties.
pc : bool
    True if the predictor-corrector method of Mehrota is to be used. This
    is almost always (if not always) beneficial. Even though it requires
    the solution of an additional linear system, the factorization
    is typically (implicitly) reused so solution is efficient, and the
    number of algorithm iterations is typically reduced.
ip : bool
    True if the improved initial point suggestion due to [4] section 4.3
    is desired. It's unclear whether this is beneficial.
permc_spec : str (default = 'MMD_AT_PLUS_A')
    (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos =
    True``.) A matrix is factorized in each iteration of the algorithm.
    This option specifies how to permute the columns of the matrix for
    sparsity preservation. Acceptable values are:

    - ``NATURAL``: natural ordering.
    - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
    - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
    - ``COLAMD``: approximate minimum degree column ordering.

    This option can impact the convergence of the
    interior point algorithm; test different values to determine which
    performs best for your problem. For more information, refer to
    ``scipy.sparse.linalg.splu``.

Returns
-------
Search directions as defined in [4]

References
----------
.. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
       optimizer for linear programming: an implementation of the
       homogeneous algorithm." High performance optimization. Springer US,
       2000. 197-232.

r   )FFTFr   csc)format)r   r   r   r   r      FTzSolving system with option 'cholesky':True failed. It is normal for this to happen occasionally, especially as the solution is approached. However, if you see this frequently, consider setting option 'cholesky' to False.   
stacklevelzSolving system with option 'sym_pos':True failed. It is normal for this to happen occasionally, especially as the solution is approached. However, if you see this frequently, consider setting option 'sym_pos' to False.aU  Solving system with option 'sym_pos':False failed. This may happen occasionally, especially as the solution is approached. However, if you see this frequently, your problem may be numerically challenging. If you cannot improve the formulation, consider setting 'lstsq' to True. Consider also setting `presolve` to True, if it is not already.N
   皙?)shapelendotT	transposer   diagsreshaper&   
_sym_solvenpanyisnanr   
ValueError	TypeErrorr   r   	_get_stepmin)-Abcxyztaukappagammaetar0   r   r   r
   pcipr   n_xr_Pr_Dr_GmuDinvr   r   n_correctionsialphad_xd_zd_taud_kapparhatprhatdrhatgrhatxsrhattksolvedpquved_ybeta1s-                                                r   
_get_deltarp      sB   F 	wwqzQ ,E(w
a&C 'AEE!H
C
'ACCGGAJ

"C
%%(Q[[]&&q)
)E
1C
%%(S[
 S1W	-B 5DEE#))D!E266qss;<EE$,,r1%+,6'ZHE
 AM	A&3#E3UG
}
E
S E
S E
S  ae#ck)6u9-2% "'(S.3"67u9-2K 1Hu$w./
 #)#%'/) .:!$a71!$5#$q5F"2,3495B166"((1+&&"&&!*=*=%% &b !c'F**quuQxi!%%(.BCc'E/aeeAhYq%9:<!e)m!e)m 1u!c')*c'Veem34 !S!S#ueWaHEEYNSU%<<E	QK }
N S%((s  Y7 %: $HG
 (A7 #GF
 (A7  ED (A	7 G#Avg$,j:I%:s   $BM O*AOOc                     X1R                  X-  5      -   nU" U5      nXR                  R                  U5      U-
  -  nXv4$ )a8  
An implementation of [4] equation 8.31 and 8.32

References
----------
.. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
       optimizer for linear programming: an implementation of the
       homogeneous algorithm." High performance optimization. Springer US,
       2000. 197-232.

)r=   r>   )r[   rJ   r1r2r   r   rl   rk   s           r   rB   rB   M  s?     	UU49AaA
R A4Kr   c	                    US:  n	US:  n
[         R                  " U	5      (       a!  U[         R                  " X	   X   * -  5      -  OSnUS:  a  X-  U* -  OSn[         R                  " U
5      (       a!  U[         R                  " X*   X:   * -  5      -  OSnUS:  a  X-  U* -  OSn[         R                  " SXX/5      nU$ )a/  
An implementation of [4] equation 8.21

References
----------
.. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
       optimizer for linear programming: an implementation of the
       homogeneous algorithm." High performance optimization. Springer US,
       2000. 197-232.

r   r   )rC   rD   rI   )rM   r_   rO   r`   rP   ra   rQ   rb   alpha0i_xi_zalpha_x	alpha_taualpha_zalpha_kappar^   s                   r   rH   rH   a  s      'C
'C57VVC[[frvvafy011aG).v%I57VVC[[frvvafy011aG/6{&.G8+KFFAw7@AELr   c                     / SQnX   $ )a  
Given problem status code, return a more detailed message.

Parameters
----------
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

Returns
-------
message : str
    A string descriptor of the exit status of the optimization.

)%Optimization terminated successfully.z?The iteration limit was reached before the algorithm converged.zTThe algorithm terminated successfully and determined that the problem is infeasible.zSThe algorithm terminated successfully and determined that the problem is unbounded.a  Numerical difficulties were encountered before the problem converged. Please check your problem formulation for errors, independence of linear equality constraints, and reasonable scaling and matrix condition numbers. If you continue to encounter this error, please submit a bug report. )statusmessagess     r   _get_messager   {  s    ,	  r   c                 R    X
U-  -   n X:U-  -   nX*U-  -   nXJU	-  -   nXU-  -   nXX#U4$ )a.  
An implementation of [4] Equation 8.9

References
----------
.. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
       optimizer for linear programming: an implementation of the
       homogeneous algorithm." High performance optimization. Springer US,
       2000. 197-232.

r~   )rM   rN   rO   rP   rQ   r_   rn   r`   ra   rb   r^   s              r   _do_stepr     sJ     	
CKA

C	CKAGO#E	CKAr   c                     U u  p[         R                  " U5      n[         R                  " U5      n[         R                  " U5      nSnSnX4XVU4$ )a/  
Return the starting point from [4] 4.4

References
----------
.. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
       optimizer for linear programming: an implementation of the
       homogeneous algorithm." High performance optimization. Springer US,
       2000. 197-232.

r   )rC   oneszeros)r;   mnx0y0z0tau0kappa0s           r   _get_blind_startr     sI     DA	B	!B	BDF2V##r   c	                   ^ ^^ [        T R                  5      u  ppnU U4S jnU U4S jnUU4S jnS nTR                  XG-  5      U-   nS nU" X5      nU" XU5      nU" XU5      nU" XX5      nU" TR                  R                  U5      TR                  R                  U5      -
  5      UU" TR                  R                  U5      5      -   -  nU" U" XG5      5      [	        SU" U5      5      -  nU" U" XVU5      5      [	        SU" U5      5      -  nU" U" XEU5      5      [	        SU" U5      5      -  nU" XGXh5      U-  nUUUUUU4$ )ag  
Implementation of several equations from [4] used as indicators of
the status of optimization.

References
----------
.. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
       optimizer for linear programming: an implementation of the
       homogeneous algorithm." High performance optimization. Springer US,
       2000. 197-232.

c                 2   > TU-  TR                  U 5      -
  $ r   r=   )rM   rP   rJ   rK   s     r   r_p_indicators.<locals>.r_p  s    3wq!!r   c                 L   > TU-  TR                   R                  U 5      -
  U-
  $ r   )r>   r=   )rN   rO   rP   rJ   rL   s      r   r_d_indicators.<locals>.r_d  s#    3w#a''r   c                 P   > UTR                  U 5      -   TR                  U5      -
  $ r   r   )rM   rN   rQ   rK   rL   s      r   r_g_indicators.<locals>.r_g  s#    quuQx!%%(**r   c                 p    U R                  U5      [        R                   " X5      -   [        U 5      S-   -  $ Nr   )r=   rC   r<   )rM   rP   rO   rQ   s       r   rZ   _indicators.<locals>.mu  s+    a266#--#a&1*==r   c                 @    [         R                  R                  U 5      $ r   )rC   r   norm)as    r   r   _indicators.<locals>.norm  s    yy~~a  r   r   )r   r;   r=   r>   max)rJ   rK   rL   c0rM   rN   rO   rP   rQ   r   r   r   r   r   r   r   r   rZ   objr   r_p0r_d0r_g0mu_0rho_Arho_prho_drho_grho_mus   ```                          r   _indicatorsr     s=     08BBf"(+> %%.2
C! r=DrtDrvDb#Daccggaj()S4
3C-CDEQAtDz 22EQ3 3q$t*#55EQ5!"SDJ%77E!D(F%vs22r   c                    U(       a  [        SSSSSS5        Sn[        UR                  [        U 5      [        U5      [        U5      [        U[        5      (       a  UO
[        U5      [        U5      [        U5      5      5        g)	a  
Print indicators of optimization status to the console.

Parameters
----------
rho_p : float
    The (normalized) primal feasibility, see [4] 4.5
rho_d : float
    The (normalized) dual feasibility, see [4] 4.5
rho_g : float
    The (normalized) duality gap, see [4] 4.5
alpha : float
    The step size, see [4] 4.3
rho_mu : float
    The (normalized) path parameter, see [4] 4.5
obj : float
    The objective function value of the current iterate
header : bool
    True if a header is to be printed

References
----------
.. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
       optimizer for linear programming: an implementation of the
       homogeneous algorithm." High performance optimization. Springer US,
       2000. 197-232.

zPrimal Feasibility zDual Feasibility   zDuality Gap        zStep            zPath Parameter     zObjective          z<{0:<20.13}{1:<20.13}{2:<20.13}{3:<17.13}{4:<20.13}{5:<20.13}N)printr3   float
isinstancestr)r   r   r   r^   r   r   headerfmts           r   _display_iterr     st    : ### ##	% IC	#**eeeE3''U5\fc
 r   c                 2   Sn[        U R                  5      u  nnnnnU(       a  UOSn[        XX#UUUUU5	      u  nnnnnnUU:  =(       d    UU:  =(       d    UU:  nU(       a  [        UUUSUUSS9  Ub2  [	        UU-  U5      u  nn n!n"[        UU U!U"USSSSSS.
5      n#U" U#5        Sn$S	n%U	(       a  [        R                  " U 5      n U(       Ga  US-  nU(       a  Sn&S
 n'O+U(       a  SOU[        R                  " UU-  5      -  n&U&4S jn' [        XUUUUUUU&U'XXXU5      u  n(n)n*n+n,U(       aH  Sn-[        UUUUUU(U)U*U+U,U-5      u  nnnnnSUUS:  '   SUUS:  '   [        SU5      n[        SU5      nSnO/[        UU(UU*UU+UU,U5	      n-[        UUUUUU(U)U*U+U,U-5      u  nnnnn [        XX#UUUUU5	      u  nnnnnnUU:  =(       d    UU:  =(       d    UU:  nU(       a  [        UUUU-UU5        Ub2  [	        UU-  U5      u  nn n!n"[        UU U!U"USSSSSS.
5      n#U" U#5        UU:  =(       a*    UU:  =(       a    UU:  =(       a    UU[        SU5      -  :  n.UU:  =(       a    UU['        SU5      -  :  n/U.(       d  U/(       a4  UR)                  5       R+                  U5      U:  a  Sn$OSn$[%        U$5      n%OUU:  a  Sn$[%        U$5      n%O
U(       a  GM  UU-  n0U0U$U%U4$ ! [        [        [         ["        4 a    Sn$[%        U$5      n% M5  f = f)a  
Solve a linear programming problem in standard form:

Minimize::

    c @ x

Subject to::

    A @ x == b
        x >= 0

using the interior point method of [4].

Parameters
----------
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 RHS of each equality constraint
    (row) in ``A`` (for standard form problem).
c : 1-D array
    Coefficients of the linear objective function to be minimized (for
    standard form problem).
c0 : float
    Constant term in objective function due to fixed (and eliminated)
    variables. (Purely for display.)
alpha0 : float
    The maximal step size for Mehrota's predictor-corrector search
    direction; see :math:`\beta_3`of [4] Table 8.1
beta : float
    The desired reduction of the path parameter :math:`\mu` (see  [6]_)
maxiter : int
    The maximum number of iterations of the algorithm.
disp : bool
    Set to ``True`` if indicators of optimization status are to be printed
    to the console each iteration.
tol : float
    Termination tolerance; see [4]_ Section 4.5.
sparse : bool
    Set to ``True`` if the problem is to be treated as sparse. However,
    the inputs ``A_eq`` and ``A_ub`` should nonetheless be provided as
    (dense) arrays rather than sparse matrices.
lstsq : bool
    Set to ``True`` if the problem is expected to be very poorly
    conditioned. This should always be left as ``False`` unless severe
    numerical difficulties are frequently encountered, and a better option
    would be to improve the formulation of the problem.
sym_pos : bool
    Leave ``True`` if the problem is expected to yield a well conditioned
    symmetric positive definite normal equation matrix (almost always).
cholesky : bool
    Set to ``True`` if the normal equations are to be solved by explicit
    Cholesky decomposition followed by explicit forward/backward
    substitution. This is typically faster for moderate, dense problems
    that are numerically well-behaved.
pc : bool
    Leave ``True`` if the predictor-corrector method of Mehrota is to be
    used. This is almost always (if not always) beneficial.
ip : bool
    Set to ``True`` if the improved initial point suggestion due to [4]_
    Section 4.3 is desired. It's unclear whether this is beneficial.
permc_spec : str (default = 'MMD_AT_PLUS_A')
    (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos =
    True``.) A matrix is factorized in each iteration of the algorithm.
    This option specifies how to permute the columns of the matrix for
    sparsity preservation. Acceptable values are:

    - ``NATURAL``: natural ordering.
    - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
    - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
    - ``COLAMD``: approximate minimum degree column ordering.

    This option can impact the convergence of the
    interior point algorithm; test different values to determine which
    performs best for your problem. For more information, refer to
    ``scipy.sparse.linalg.splu``.
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 only when an algorithm has completed successfully,
            so this is always False as the callback function is called
            only while the algorithm is still iterating.
        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. This is always
            1 for the interior-point method because it has only one phase.
        status : int
            For revised simplex, this is always 0 because if a different
            status is detected, the algorithm terminates.
        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.

Returns
-------
x_hat : float
    Solution vector (for standard form 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

message : str
    A string descriptor of the exit status of the optimization.
iteration : int
    The number of iterations taken to solve the problem

References
----------
.. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
       optimizer for linear programming: an implementation of the
       homogeneous algorithm." High performance optimization. Springer US,
       2000. 197-232.
.. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear
       Programming based on Newton's Method." Unpublished Course Notes,
       March 2004. Available 2/25/2017 at:
       https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf

r   F-T)r   r    )
rM   funslackconnitphasecompleter   messagesuccessr}   c                     gr   r~   gs    r   rS   _ip_hsd.<locals>.eta  s    r   c                     SU -
  $ r   r~   r   s    r   rS   r     s    1ur   g      ?   r5      )r   r;   r   r   r	   r   r   
csc_matrixrC   meanrp   r   r   rH   r   FloatingPointErrorrF   ZeroDivisionErrorr   rI   r?   r=   )1rJ   rK   rL   r   ru   betamaxiterdisptolr0   r   r   r
   rT   rU   r   callbackpostsolve_args	iterationrM   rN   rO   rP   rQ   r   r   r   r   r   r   gox_or   r   r   resr   r   rR   rS   r_   rn   r`   ra   rb   r^   inf1inf2x_hats1                                                    r   _ip_hsdr   *  s   b I +1773Aq!S% uB /:	aQ1c5/*+E5%		2	2us{BeUE3DI)!C%@S%3sU%(Q*/1)+? @ 	F5GNN1
Q	E AA!6E  "	,6aAq#ueSw"*-F)Cc5'  &.q!S%c'0#1ae !a%!a%!SkAu "!S!S#"'A '/q!S%c3w'O#1ae 3>!Aq#u3./ueUFCS[6ECK653;%ufcB#-ae^#D CeS s3),Y.3q-/E"C DC SM    cAuG A|9cC5M&9 94{{}  #c)"6*G'!F"6*Gm "p GE&'9,,W /-/ 	
 F"6*G	s   A+K+ <.K+ +'LLc                    [        U5        U(       d  Uc*  U(       a#  [        (       d  U(       a  [        S[        SS9  SnU(       a  U(       a  [        S[        SS9  U(       a  U(       a  [        S[        SS9  SnUR	                  5       U;  a   [        S	[        U5      -   S
-   [        SS9  SnU(       d  U(       a  [        S5      eU=(       d    USL =(       a    U=(       a    U(       + n[        X#XXXhX{XUUUUUU5      u  nnnnUUUU4$ )a)  
Minimize a linear objective function subject to linear
equality and non-negativity constraints using the interior point method
of [4]_. 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
    Callback function to be executed once per iteration.
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 (default = 1000)
    The maximum number of iterations of the algorithm.
tol : float (default = 1e-8)
    Termination tolerance to be used for all termination criteria;
    see [4]_ Section 4.5.
disp : bool (default = False)
    Set to ``True`` if indicators of optimization status are to be printed
    to the console each iteration.
alpha0 : float (default = 0.99995)
    The maximal step size for Mehrota's predictor-corrector search
    direction; see :math:`\beta_{3}` of [4]_ Table 8.1.
beta : float (default = 0.1)
    The desired reduction of the path parameter :math:`\mu` (see [6]_)
    when Mehrota's predictor-corrector is not in use (uncommon).
sparse : bool (default = False)
    Set to ``True`` if the problem is to be treated as sparse after
    presolve. If either ``A_eq`` or ``A_ub`` is a sparse matrix,
    this option will automatically be set ``True``, and the problem
    will be treated as sparse even during presolve. If your constraint
    matrices contain mostly zeros and the problem is not very small (less
    than about 100 constraints or variables), consider setting ``True``
    or providing ``A_eq`` and ``A_ub`` as sparse matrices.
lstsq : bool (default = False)
    Set to ``True`` if the problem is expected to be very poorly
    conditioned. This should always be left ``False`` unless severe
    numerical difficulties are encountered. Leave this at the default
    unless you receive a warning message suggesting otherwise.
sym_pos : bool (default = True)
    Leave ``True`` if the problem is expected to yield a well conditioned
    symmetric positive definite normal equation matrix
    (almost always). Leave this at the default unless you receive
    a warning message suggesting otherwise.
cholesky : bool (default = True)
    Set to ``True`` if the normal equations are to be solved by explicit
    Cholesky decomposition followed by explicit forward/backward
    substitution. This is typically faster for problems
    that are numerically well-behaved.
pc : bool (default = True)
    Leave ``True`` if the predictor-corrector method of Mehrota is to be
    used. This is almost always (if not always) beneficial.
ip : bool (default = False)
    Set to ``True`` if the improved initial point suggestion due to [4]_
    Section 4.3 is desired. Whether this is beneficial or not
    depends on the problem.
permc_spec : str (default = 'MMD_AT_PLUS_A')
    (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos =
    True``, and no SuiteSparse.)
    A matrix is factorized in each iteration of the algorithm.
    This option specifies how to permute the columns of the matrix for
    sparsity preservation. Acceptable values are:

    - ``NATURAL``: natural ordering.
    - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
    - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
    - ``COLAMD``: approximate minimum degree column ordering.

    This option can impact the convergence of the
    interior point algorithm; test different values to determine which
    performs best for your problem. For more information, refer to
    ``scipy.sparse.linalg.splu``.
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.

Notes
-----
This method implements the algorithm outlined in [4]_ with ideas from [8]_
and a structure inspired by the simpler methods of [6]_.

The primal-dual path following method begins with initial 'guesses' of
the primal and dual variables of the standard form problem and iteratively
attempts to solve the (nonlinear) Karush-Kuhn-Tucker conditions for the
problem with a gradually reduced logarithmic barrier term added to the
objective. This particular implementation uses a homogeneous self-dual
formulation, which provides certificates of infeasibility or unboundedness
where applicable.

The default initial point for the primal and dual variables is that
defined in [4]_ Section 4.4 Equation 8.22. Optionally (by setting initial
point option ``ip=True``), an alternate (potentially improved) starting
point can be calculated according to the additional recommendations of
[4]_ Section 4.4.

A search direction is calculated using the predictor-corrector method
(single correction) proposed by Mehrota and detailed in [4]_ Section 4.1.
(A potential improvement would be to implement the method of multiple
corrections described in [4]_ Section 4.2.) In practice, this is
accomplished by solving the normal equations, [4]_ Section 5.1 Equations
8.31 and 8.32, derived from the Newton equations [4]_ Section 5 Equations
8.25 (compare to [4]_ Section 4 Equations 8.6-8.8). The advantage of
solving the normal equations rather than 8.25 directly is that the
matrices involved are symmetric positive definite, so Cholesky
decomposition can be used rather than the more expensive LU factorization.

With default options, the solver used to perform the factorization depends
on third-party software availability and the conditioning of the problem.

For dense problems, solvers are tried in the following order:

1. ``scipy.linalg.cho_factor``

2. ``scipy.linalg.solve`` with option ``sym_pos=True``

3. ``scipy.linalg.solve`` with option ``sym_pos=False``

4. ``scipy.linalg.lstsq``

For sparse problems:

1. ``sksparse.cholmod.cholesky`` (if scikit-sparse and SuiteSparse are installed)

2. ``scipy.sparse.linalg.factorized``
    (if scikit-umfpack and SuiteSparse are installed)

3. ``scipy.sparse.linalg.splu`` (which uses SuperLU distributed with SciPy)

4. ``scipy.sparse.linalg.lsqr``

If the solver fails for any reason, successively more robust (but slower)
solvers are attempted in the order indicated. Attempting, failing, and
re-starting factorization can be time consuming, so if the problem is
numerically challenging, options can be set to  bypass solvers that are
failing. Setting ``cholesky=False`` skips to solver 2,
``sym_pos=False`` skips to solver 3, and ``lstsq=True`` skips
to solver 4 for both sparse and dense problems.

Potential improvements for combating issues associated with dense
columns in otherwise sparse problems are outlined in [4]_ Section 5.3 and
[10]_ Section 4.1-4.2; the latter also discusses the alleviation of
accuracy issues associated with the substitution approach to free
variables.

After calculating the search direction, the maximum possible step size
that does not activate the non-negativity constraints is calculated, and
the smaller of this step size and unity is applied (as in [4]_ Section
4.1.) [4]_ Section 4.3 suggests improvements for choosing the step size.

The new point is tested according to the termination conditions of [4]_
Section 4.5. The same tolerance, which can be set using the ``tol`` option,
is used for all checks. (A potential improvement would be to expose
the different tolerances to be set independently.) If optimality,
unboundedness, or infeasibility is detected, the solve procedure
terminates; otherwise it repeats.

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.


References
----------
.. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
       optimizer for linear programming: an implementation of the
       homogeneous algorithm." High performance optimization. Springer US,
       2000. 197-232.
.. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear
       Programming based on Newton's Method." Unpublished Course Notes,
       March 2004. Available 2/25/2017 at
       https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf
.. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear
       programming." Mathematical Programming 71.2 (1995): 221-245.
.. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
       programming." Athena Scientific 1 (1997): 997.
.. [10] Andersen, Erling D., et al. Implementation of interior point methods
        for large scale linear programming. HEC/Universite de Geneve, 1996.

NzPSparse cholesky is only available with scikit-sparse. Setting `cholesky = False`r   r7   FzEOption combination 'sparse':True and 'lstsq':True is not recommended.zvInvalid option combination 'lstsq':True and 'cholesky':True; option 'cholesky' has no effect when 'lstsq' is set True.)NATURALMMD_ATAMMD_AT_PLUS_ACOLAMDzInvalid permc_spec option: 'zc'. Acceptable values are 'NATURAL', 'MMD_ATA', 'MMD_AT_PLUS_A', and 'COLAMD'. Reverting to default.r   zInvalid option combination 'sym_pos':False and 'cholesky':True: Cholesky decomposition is only possible for symmetric positive definite matrices.)r   has_cholmodr   r   upperr   rF   r   )rL   r   rJ   rK   r   r   r   r   r   ru   r   r0   r   r   r
   rT   rU   r   unknown_optionsvalid_permc_specrM   r   r   r   s                           r   _linprog_ipr   5  s)   J ?+ 	H$& . Q0 % #	,  $ 	,
 I!11+c*o= A3 3 	, %
 x89 	9
 GH,FFYH$+A!,33,1H,.J,:	%<!Avw	 fgy((r   )FFTTr   )FFTTTFr   r%   )i  g:0yE>FgSt$?r:   FFTNTFr   )(__doc__numpyrC   scipyr   scipy.sparser0   r   warningsr   scipy.linalgr   	_optimizer   r   r   _linprog_utilr	   r+   r   sksparsesksparse.cholmodr
   cholmodr   r*   ImportErrorscikits.umfpackscikitsr&   rp   rB   rH   r   r   r   r   r   r   r   r~   r   r   <module>r      s   (     $ N N %4;
 7;*9Wt AFEJ)F)R(4"J($*.3b-`H-V JNIN9>*q)g  K  Ks#   A: B :BBBB