U
    Gvf/<                     @   sv   d Z ddlZddlmZmZmZmZ ddlm	Z	m
Z
 dddd	gZdddZdd Zdd Zdd ZG dd	 d	e
ZdS )z2Nearly exact trust-region optimization subproblem.    N)normget_lapack_funcssolve_triangular	cho_solve   )_minimize_trust_regionBaseQuadraticSubproblem_minimize_trustregion_exact estimate_smallest_singular_valuesingular_leading_submatrixIterativeSubproblem c                 K   s<   |dkrt dt|s t dt| |f|||td|S )a  
    Minimization of scalar function of one or more variables using
    a nearly exact trust-region algorithm.

    Options
    -------
    initial_tr_radius : float
        Initial trust-region radius.
    max_tr_radius : float
        Maximum value of the trust-region radius. No steps that are longer
        than this value will be proposed.
    eta : float
        Trust region related acceptance stringency for proposed steps.
    gtol : float
        Gradient norm must be less than ``gtol`` before successful
        termination.
    Nz9Jacobian is required for trust region exact minimization.z?Hessian matrix is required for trust region exact minimization.)argsjachessZ
subproblem)
ValueErrorcallabler   r   )funZx0r   r   r   Ztrust_region_optionsr   r   E/tmp/pip-unpacked-wheel-96ln3f52/scipy/optimize/_trustregion_exact.pyr	      s    c                 C   sX  t | } | j\}}||kr$tdt |}t |}t|D ]}d||  | j||f  }d||  | j||f  }||d d | j|d d|f |  }||d d | j|d d|f |  }	t|t	|d t|t	|	d kr|||< |||d d< q@|||< |	||d d< q@t
| |}
t	|
}t	|}|| }|
| }||fS )aZ  Given upper triangular matrix ``U`` estimate the smallest singular
    value and the correspondent right singular vector in O(n**2) operations.

    Parameters
    ----------
    U : ndarray
        Square upper triangular matrix.

    Returns
    -------
    s_min : float
        Estimated smallest singular value of the provided matrix.
    z_min : ndarray
        Estimatied right singular vector.

    Notes
    -----
    The procedure is based on [1]_ and is done in two steps. First, it finds
    a vector ``e`` with components selected from {+1, -1} such that the
    solution ``w`` from the system ``U.T w = e`` is as large as possible.
    Next it estimate ``U v = w``. The smallest singular value is close
    to ``norm(w)/norm(v)`` and the right singular vector is close
    to ``v/norm(v)``.

    The estimation will be better more ill-conditioned is the matrix.

    References
    ----------
    .. [1] Cline, A. K., Moler, C. B., Stewart, G. W., Wilkinson, J. H.
           An estimate for the condition number of a matrix.  1979.
           SIAM Journal on Numerical Analysis, 16(2), 368-375.
    z.A square triangular matrix should be provided.r   N)npZ
atleast_2dshaper   zerosemptyrangeTabsr   r   )UmnpwkZwpZwmppZpmvv_normw_norms_minz_minr   r   r   r
   ,   s,    "



**&
c                 C   sT   t | }t |}t jt | dd}t || | }t || | }||fS )a  
    Given a square matrix ``H`` compute upper
    and lower bounds for its eigenvalues (Gregoshgorin Bounds).
    Defined ref. [1].

    References
    ----------
    .. [1] Conn, A. R., Gould, N. I., & Toint, P. L.
           Trust region methods. 2000. Siam. pp. 19.
    r   )Zaxis)r   Zdiagr   summinmax)HZH_diagZ
H_diag_absZ
H_row_sumsZlbZubr   r   r   gershgorin_bounds{   s    

r-   c                 C   s   t |d|d |d f d | |d |d f  }t| }t |}d||d < |dkrt|d|d d|d f |d|d |d f  |d|d < ||fS )a  
    Compute term that makes the leading ``k`` by ``k``
    submatrix from ``A`` singular.

    Parameters
    ----------
    A : ndarray
        Symmetric matrix that is not positive definite.
    U : ndarray
        Upper triangular matrix resulting of an incomplete
        Cholesky decomposition of matrix ``A``.
    k : int
        Positive integer such that the leading k by k submatrix from
        `A` is the first non-positive definite leading submatrix.

    Returns
    -------
    delta : float
        Amount that should be added to the element (k, k) of the
        leading k by k submatrix of ``A`` to make it singular.
    v : ndarray
        A vector such that ``v.T B v = 0``. Where B is the matrix A after
        ``delta`` is added to its element (k, k).
    Nr      )r   r)   lenr   r   )Ar   r"   deltar   r$   r   r   r   r      s    6
Dc                       sB   e Zd ZdZdZeejZ	d fdd	Z
dd	 Zd
d Z  ZS )r   a  Quadratic subproblem solved by nearly exact iterative method.

    Notes
    -----
    This subproblem solver was based on [1]_, [2]_ and [3]_,
    which implement similar algorithms. The algorithm is basically
    that of [1]_ but ideas from [2]_ and [3]_ were also used.

    References
    ----------
    .. [1] A.R. Conn, N.I. Gould, and P.L. Toint, "Trust region methods",
           Siam, pp. 169-200, 2000.
    .. [2] J. Nocedal and  S. Wright, "Numerical optimization",
           Springer Science & Business Media. pp. 83-91, 2006.
    .. [3] J.J. More and D.C. Sorensen, "Computing a trust region step",
           SIAM Journal on Scientific and Statistical Computing, vol. 4(3),
           pp. 553-572, 1983.
    g{Gz?N皙?皙?c                    s   t  |||| d| _d | _d| _|| _|| _td| jf\| _	t
| j| _t| j\| _| _t| jtj| _t| jd| _| j| j | j | _d S )Nr   r   )ZpotrfZfro)super__init__previous_tr_radius	lambda_lbniterk_easyk_hardr   r   choleskyr/   	dimensionr-   hess_gershgorin_lbhess_gershgorin_ubr   r   ZInfhess_infhess_froEPSCLOSE_TO_ZERO)selfxr   r   r   Zhesspr9   r:   	__class__r   r   r5      s    zIterativeSubproblem.__init__c                 C   s   t d| j| t| j | j| j }t dt| j  | j| t| j| j| j }|| j	k rjt | j
|}|dkrxd}n"t t|| || j||   }|||fS )zGiven a trust radius, return a good initial guess for
        the damping factor, the lower bound and the upper bound.
        The values were chosen accordingly to the guidelines on
        section 7.3.8 (p. 192) from [1]_.
        r   )r+   jac_magr*   r=   r@   r?   r   Zdiagonalr>   r6   r7   r   sqrtUPDATE_COEFF)rC   	tr_radius	lambda_ubr7   Zlambda_initialr   r   r   _initial_values   s$    
z#IterativeSubproblem._initial_valuesc                 C   s4  |  |\}}}| j}d}d}d| _|r.d}n*| j|t|  }| j|dddd\}	}
|  jd7  _|
dkr| j| jkrt	|	df| j
 }t|}||kr|dkrd}qt|	|dd}t|}|| d ||  | }|| }||k rt|	\}}| |||\}}t||gtd	}t|t||}|d |d  |||d    }|| jkrn||| 7 }q|}t|||d  }| j|t|  }| j|dddd\}}
|
dkr|}d}n,t||}tt|| || j||   }n(t|| | }|| jkrq|}|}q$|
dkr| j| jkr|dkrNt|}d}qt|	\}}|}|d |d  | j| |d  kr|| }q|}t|||d  }tt|| || j||   }q$t||	|
\}}t|}t||||d   }tt|| || j||   }q$|| _|| _|| _||fS )
zSolve quadratic subproblemTFr   )lowerZoverwrite_acleanr   r   )Ztransr.   )key)rL   r<   r8   r   r   Zeyer;   rG   rB   r   r   r   r   r
   Zget_boundaries_intersectionsr*   r   dotr:   r+   rH   rI   r9   r   r   r7   lambda_currentr6   )rC   rJ   rQ   r7   rK   r   Zhits_boundaryZalready_factorizedr,   r   infor    Zp_normr!   r&   Zdelta_lambdaZ
lambda_newr'   r(   tatbZstep_lenZquadratic_termZrelative_errorcr1   r$   r%   r   r   r   solve  s    

 




$zIterativeSubproblem.solve)Nr2   r3   )__name__
__module____qualname____doc__rI   r   ZfinfofloatZepsrA   r5   rL   rV   __classcell__r   r   rE   r   r      s       ))r   NN)rZ   Znumpyr   Zscipy.linalgr   r   r   r   Z_trustregionr   r   __all__r	   r
   r-   r   r   r   r   r   r   <module>   s   
O*