
    4[gٲ                         d Z ddlZddlZddlmZ ddlm	Z	 ddl
mZ ddlmZmZmZ ddlmZ dZdZ	 ddlZdd	lmZ dd
lmZ 	 ddlZ	 	 ddZ	 	 	 ddZd Zd Z d Z!d Z"d Z#d Z$ddZ%d Z&	 	 	 	 ddZ'y# e$ r dZY =w xY w# e$ r dZY Ew xY w)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                 `    	 |r|rd fd	}|S |r2	 t         j                  j                          t         j                  }|S t
        r#|r!t        j                  j                         }|S t        j                  j                   |      j                  }	 |S |r fd}|S |r&t        j                  j                         fd}|S |f fd	}	 |S # t        $ r6 t	               t         _        t         j                  j                          Y w xY w# t        $ r  t        $ r Y yw xY w)ae  
    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    t         j                  j                  |       d   S Nr   )spslinalglsqrrsym_posMs     U/var/www/html/bid-api/venv/lib/python3.12/site-packages/scipy/optimize/_linprog_ip.pysolvez_get_solver.<locals>.solveW   s    ::??1a033    )
permc_specc                 J    t         j                  j                  |       d   S r   )spr   lstsq)r   r   s    r   r   z_get_solver.<locals>.solvej   s    99??1a033r   c                 D    t         j                  j                  |       S N)r   r   	cho_solve)r   Ls    r   r   z_get_solver.<locals>.solveo   s    99..q!44r   c                     |r"t         j                  j                  | d      S t         j                  j                  |       S )Npos)assume_a)r   r   r   r   s     r   r   z_get_solver.<locals>.solvet   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%   *   s4   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 LG ! C1@1CK...??BC>   sV   
D D C D 'D -+D D $&D D <DD DD D-,D-c                 V   | j                   d   dk(  rd\  }
}}}t        |      }||z  | j                  |      z
  }||z  | j                  j                  |      z
  |z
  }|j                  |      |j	                         j                  |      z
  |z   }|j                  |      ||z  z   |dz   z  }||z  }|
rA| j                  t        j                  |dd      j                  | j                              }n.| j                  |j                  dd      | j                  z        }t        ||
||||      }|rdnd}d}d\  }}}}}||k  r |	|      |z  }  |	|      |z  }! |	|      |z  }"||z  ||z  z
  }#||z  ||z  z
  }$|dk(  rM|r;d|z
  |z  |z  ||z  z
  |dz  |z  |z  z
  }#d|z
  |z  |z  ||z  z
  |dz  |z  |z  z
  }$n|#||z  z  }#|$||z  z  }$d	}%|%s	 t        || |||      \  }&}'t        || |!d|z  |#z  z
  | |      \  }(})t        j                  t        j                  |&            s(t        j                  t        j                  |'            rt        d
}%|%s|"d|z  |$z  z   |j                  (       |j                  )      z   z
  d|z  |z  |j                  &       |j                  '      z   z   z  }|(|&|z  z   }|)|'|z  z   }+d|z  |#||z  z
  z  }d|z  |$||z  z
  z  }t%        ||||||||d	      }|rd}nd},d|z
  dz  t'        |,d|z
        z  }|dz  }||k  r|+|||fS # t        t        t        f$ rb}*|rd	}t!        dt"        d       n0|rd	}t!        dt"        d       n|sd
}t!        dt"        d       n|*t        ||
||||      }Y d}*~*Cd}*~*ww xY w)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etar/   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_deltaro      sV   F 	wwqzQ ,E(w
a&C c'AEE!H
C
c'ACCGGAJ

"C
%%(Q[[]&&q)
)E
1C
%%(S5[
 S1W	-B q5DEE#))D!E266qss;<EE$,,r1%+,65'8ZHE
 AM	A&3#E3UG
}
E
S E
S E
S  a!e#cEk)6u9-2a% "'(S.3"67u9-2%K 1Hu$w./
 #)#%'/) .:!$1a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#Avug$,j:I%:s   BL2 2N(AN##N(c                     ||j                  | |z        z   } ||      }| |j                  j                  |      |z
  z  }||fS )aX  
    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=   )rZ   rI   r1r2r   r   rk   rj   s           r   rA   rA   M  sG     	QUU4"9AaA
R Aa4Kr   c	                 r   |dk  }	|dk  }
t        j                  |	      r"|t        j                  | |	   ||	    z        z  nd}|dk  r	||z  | z  nd}t        j                  |
      r"|t        j                  ||
   ||
    z        z  nd}|dk  r	||z  | z  nd}t        j                  d||||g      }|S )aO  
    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   )rB   rC   rH   )rL   r^   rN   r_   rO   r`   rP   ra   alpha0i_xi_zalpha_x	alpha_taualpha_zalpha_kappar]   s                   r   rG   rG   a  s      'C
'C57VVC[frvvafCy011aG).v%I57VVC[frvvafCy011aG/6{&5.G8+KFFAw	7K@AELr   c                     g d}||    S )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    ,	  Fr   c                 `    | |
|z  z   } ||
|z  z   }||
|z  z   }||
|	z  z   }||
|z  z   }| ||||fS )aN  
    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}   )rL   rM   rN   rO   rP   r^   rm   r_   r`   ra   r]   s              r   _do_stepr     sX     	
ECKA

C	ECKAEGO#E	ECKAaCr   c                     | \  }}t        j                  |      }t        j                  |      }t        j                  |      }d}d}|||||fS )aO  
    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   )rB   oneszeros)r:   mnx0y0z0tau0kappa0s           r   _get_blind_startr     sO     DAq	B	!B	BDFr2tV##r   c	                     t         j                        \  }	}
}}} fd} fd}fd}d }j                  ||z        |z   }d } ||	|      } ||
||      } ||	|
|      } ||	|||      } |j                  j                  |      j                  j                  |      z
        | |j                  j                  |            z   z  } | |||            t	        d ||            z  } | ||||            t	        d ||            z  } | ||||            t	        d ||            z  } |||||      |z  }||||||fS )a  
    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    |z  j                  |       z
  S r   r<   )rL   rO   rI   rJ   s     r   r_pz_indicators.<locals>.r_p  s    3wq!!r   c                 L    |z  j                   j                  |       z
  |z
  S r   )r=   r<   )rM   rN   rO   rI   rK   s      r   r_dz_indicators.<locals>.r_d  s#    3w#a''r   c                 P    |j                  |       z   j                  |      z
  S r   r   )rL   rM   rP   rJ   rK   s      r   r_gz_indicators.<locals>.r_g  s#    quuQx!%%(**r   c                 p    | j                  |      t        j                   ||      z   t        |       dz   z  S Nr   )r<   rB   r;   )rL   rO   rN   rP   s       r   rY   z_indicators.<locals>.mu  s-    a266#u--#a&1*==r   c                 @    t         j                  j                  |       S r   )rB   r   norm)as    r   r   z_indicators.<locals>.norm  s    yy~~a  r   r   )r   r:   r<   r=   max)rI   rJ   rK   c0rL   rM   rN   rO   rP   r   r   r   r   r   r   r   r   rY   objr   r_p0r_d0r_g0mu_0rho_Arho_prho_drho_grho_mus   ```                          r   _indicatorsr     sW     08BBf"(+> %%C.2
C! r4=Dr2tDr2vDb$F#Daccggaj()S4
3C-CDEQAtDz 22EQ3 3q$t*#55EQ5!"SDJ%77E35!D(F%vs22r   c                     |rt        dddddd       d}t        |j                  t        |       t        |      t        |      t        |t              r|n
t        |      t        |      t        |                   y)	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)printr2   float
isinstancestr)r   r   r   r]   r   r   headerfmts           r   _display_iterr     sq    : ### ##	% IC	#**eeeE3'U5\fc
 r   c                 t   d}t        | j                        \  }}}}}|r|nd}t        | ||||||||	      \  }}}}}}||kD  xs ||kD  xs ||kD  }|rt        |||d||d       |2t	        ||z  |      \  }} }!}"t        || |!|"|dddddd
      }# ||#       d}$d	}%|	rt        j                  |       } |r|dz  }|rd}&d
 }'n$|rdn|t        j                  ||z        z  }&|&fd}'	 t        | ||||||||&|'|	|
|||||      \  }(})}*}+},|rHd}-t        ||||||(|)|*|+|,|-      \  }}}}}d||dk  <   d||dk  <   t        d|      }t        d|      }d}n.t        ||(||*||+||,|	      }-t        ||||||(|)|*|+|,|-      \  }}}}}t        | ||||||||	      \  }}}}}}||kD  xs ||kD  xs ||kD  }|rt        ||||-||       |2t	        ||z  |      \  }} }!}"t        || |!|"|dddddd
      }# ||#       ||k  xr  ||k  xr ||k  xr ||t        d|      z  k  }.||k  xr ||t'        d|      z  k  }/|.s|/r3|j)                         j+                  |      |kD  rd}$nd}$t%        |$      }%n||k\  rd}$t%        |$      }%n|r||z  }0|0|$|%|fS # t        t        t         t"        f$ r d}$t%        |$      }%Y 3w xY w)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    )
rL   funslackconnitphasecompleter~   messagesuccessr|   c                      yr   r}   gs    r   rR   z_ip_hsd.<locals>.eta  s    r   c                     d| z
  S r   r}   r   s    r   rR   z_ip_hsd.<locals>.eta  s    1ur   g      ?   r4      )r   r:   r   r   r	   r   r   
csc_matrixrB   meanro   r   r   rG   r   FloatingPointErrorrE   ZeroDivisionErrorr   rH   r>   r<   )1rI   rJ   rK   r   rt   betamaxiterdisptolr/   r   r   r
   rS   rT   r   callbackpostsolve_args	iterationrL   rM   rN   rO   rP   r   r   r   r   r   r   gox_or   r   r   resr~   r   rQ   rR   r^   rm   r_   r`   ra   r]   inf1inf2x_hats1                                                    r   _ip_hsdr   *  s   b I +1773Aq!S% uB /:	1aQ1c5/*+E5%		2	2us{BeUE3DI)!C%@S%3sU%(Q*/1)+? @ 	F5GNN1
Q	E AA!6E  "	,61aAq#ueSw"b*-F)Cc5'  &.q!S%c'0#1ae !a%!a%!SkAu "!S!S#"'A '/q!S%c3w'O#1ae 3>q!R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   )BJ &J76J7c                    t        |       |s||rt        s|rt        dt        d       d}|r|rt        dt        d       |r|rt        dt        d       d}|j	                         |vr#t        d	t        |      z   d
z   t        d       d}|s|rt        d      |xs |du xr |xr | }t        ||| ||	|
||||||||||||      \  }}}}||||fS )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 combatting 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   r6   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   rE   r   )rK   r   rI   rJ   r   r   r   r   r   rt   r   r/   r   r   r
   rS   rT   r   unknown_optionsvalid_permc_specrL   r~   r   r   s                           r   _linprog_ipr   5  s3   J ?+ 	H$& . Q0 % #	,  $ 	,
 I!11+c*o= A3 3 	, %
 x89 	9
 GH,FFYH$+Aq!R,3T3,17H,.J,:	%<!Avw	 fgy((r   )FFTTr   )FFTTTFr   r$   )i  g:0yE>FgSt$?r9   FFTNTFr   )(__doc__numpyrB   scipyr   scipy.sparser/   r   warningsr   scipy.linalgr   	_optimizer   r   r   _linprog_utilr	   r*   r   sksparsesksparse.cholmodr
   cholmodr   r)   ImportErrorscikits.umfpackscikitsr%   ro   rA   rG   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#   A6 B 6B ?B BB