U
    Ä@·fV  ã                   @   sÐ   d Z ddlZddlmZ ddlmZmZmZ ddl	m
Z
 ddlmZmZmZ ddlmZ dd	lmZ d
d„ ZG dd„ dƒZG dd„ dƒZG dd„ dƒZG dd„ dƒZdd„ Zdd„ Zdd„ Zdd„ Zdd„ ZdS )z$Constraints definition for minimize.é    Né   )ÚBFGS)ÚVectorFunctionÚLinearVectorFunctionÚIdentityVectorFunction)ÚOptimizeWarning)ÚwarnÚcatch_warningsÚsimplefilter)Úsuppress_warnings)Úissparsec                 C   s   t | tjƒr|  ¡ S | S ©N)Ú
isinstanceÚnpZndarrayÚitem©Úx© r   ú?/tmp/pip-unpacked-wheel-w7avvj8p/scipy/optimize/_constraints.pyÚ_arr_to_scalar   s    r   c                   @   s&   e Zd ZdZdeƒ dddfdd„ZdS )ÚNonlinearConstrainta  Nonlinear constraint on the variables.

    The constraint has the general inequality form::

        lb <= fun(x) <= ub

    Here the vector of independent variables x is passed as ndarray of shape
    (n,) and ``fun`` returns a vector with m components.

    It is possible to use equal bounds to represent an equality constraint or
    infinite bounds to represent a one-sided constraint.

    Parameters
    ----------
    fun : callable
        The function defining the constraint.
        The signature is ``fun(x) -> array_like, shape (m,)``.
    lb, ub : array_like
        Lower and upper bounds on the constraint. Each array must have the
        shape (m,) or be a scalar, in the latter case a bound will be the same
        for all components of the constraint. Use ``np.inf`` with an
        appropriate sign to specify a one-sided constraint.
        Set components of `lb` and `ub` equal to represent an equality
        constraint. Note that you can mix constraints of different types:
        interval, one-sided or equality, by setting different components of
        `lb` and `ub` as  necessary.
    jac : {callable,  '2-point', '3-point', 'cs'}, optional
        Method of computing the Jacobian matrix (an m-by-n matrix,
        where element (i, j) is the partial derivative of f[i] with
        respect to x[j]).  The keywords {'2-point', '3-point',
        'cs'} select a finite difference scheme for the numerical estimation.
        A callable must have the following signature:
        ``jac(x) -> {ndarray, sparse matrix}, shape (m, n)``.
        Default is '2-point'.
    hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy, None}, optional
        Method for computing the Hessian matrix. The keywords
        {'2-point', '3-point', 'cs'} select a finite difference scheme for
        numerical  estimation.  Alternatively, objects implementing
        `HessianUpdateStrategy` interface can be used to approximate the
        Hessian. Currently available implementations are:

            - `BFGS` (default option)
            - `SR1`

        A callable must return the Hessian matrix of ``dot(fun, v)`` and
        must have the following signature:
        ``hess(x, v) -> {LinearOperator, sparse matrix, array_like}, shape (n, n)``.
        Here ``v`` is ndarray with shape (m,) containing Lagrange multipliers.
    keep_feasible : array_like of bool, optional
        Whether to keep the constraint components feasible throughout
        iterations. A single value set this property for all components.
        Default is False. Has no effect for equality constraints.
    finite_diff_rel_step: None or array_like, optional
        Relative step size for the finite difference approximation. Default is
        None, which will select a reasonable value automatically depending
        on a finite difference scheme.
    finite_diff_jac_sparsity: {None, array_like, sparse matrix}, optional
        Defines the sparsity structure of the Jacobian matrix for finite
        difference estimation, its shape must be (m, n). If the Jacobian has
        only few non-zero elements in *each* row, providing the sparsity
        structure will greatly speed up the computations. A zero entry means
        that a corresponding element in the Jacobian is identically zero.
        If provided, forces the use of 'lsmr' trust-region solver.
        If None (default) then dense differencing will be used.

    Notes
    -----
    Finite difference schemes {'2-point', '3-point', 'cs'} may be used for
    approximating either the Jacobian or the Hessian. We, however, do not allow
    its use for approximating both simultaneously. Hence whenever the Jacobian
    is estimated via finite-differences, we require the Hessian to be estimated
    using one of the quasi-Newton strategies.

    The scheme 'cs' is potentially the most accurate, but requires the function
    to correctly handles complex inputs and be analytically continuable to the
    complex plane. The scheme '3-point' is more accurate than '2-point' but
    requires twice as many operations.

    Examples
    --------
    Constrain ``x[0] < sin(x[1]) + 1.9``

    >>> from scipy.optimize import NonlinearConstraint
    >>> import numpy as np
    >>> con = lambda x: x[0] - np.sin(x[1])
    >>> nlc = NonlinearConstraint(con, -np.inf, 1.9)

    ú2-pointFNc	           	      C   s4   || _ || _|| _|| _|| _|| _|| _|| _d S r   )ÚfunÚlbÚubÚfinite_diff_rel_stepÚfinite_diff_jac_sparsityÚjacÚhessÚkeep_feasible)	Úselfr   r   r   r   r   r   r   r   r   r   r   Ú__init__k   s    zNonlinearConstraint.__init__)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r!   r   r   r   r   r      s   X þr   c                   @   s6   e Zd ZdZdd„ Zej ejdfdd„Zdd„ Zd	S )
ÚLinearConstrainta~  Linear constraint on the variables.

    The constraint has the general inequality form::

        lb <= A.dot(x) <= ub

    Here the vector of independent variables x is passed as ndarray of shape
    (n,) and the matrix A has shape (m, n).

    It is possible to use equal bounds to represent an equality constraint or
    infinite bounds to represent a one-sided constraint.

    Parameters
    ----------
    A : {array_like, sparse matrix}, shape (m, n)
        Matrix defining the constraint.
    lb, ub : array_like, optional
        Lower and upper limits on the constraint. Each array must have the
        shape (m,) or be a scalar, in the latter case a bound will be the same
        for all components of the constraint. Use ``np.inf`` with an
        appropriate sign to specify a one-sided constraint.
        Set components of `lb` and `ub` equal to represent an equality
        constraint. Note that you can mix constraints of different types:
        interval, one-sided or equality, by setting different components of
        `lb` and `ub` as  necessary. Defaults to ``lb = -np.inf``
        and ``ub = np.inf`` (no limits).
    keep_feasible : array_like of bool, optional
        Whether to keep the constraint components feasible throughout
        iterations. A single value set this property for all components.
        Default is False. Has no effect for equality constraints.
    c                 C   s‚   | j jdkrd}t|ƒ‚zD| j jdd… }t | j|¡| _t | j|¡| _t | j|¡| _W n  tk
r|   d}t|ƒ‚Y nX d S )Né   z%`A` must have exactly two dimensions.r   r   zM`lb`, `ub`, and `keep_feasible` must be broadcastable to shape `A.shape[0:1]`)	ÚAÚndimÚ
ValueErrorÚshaper   Úbroadcast_tor   r   r   )r    Úmessager+   r   r   r   Ú_input_validation˜   s    z"LinearConstraint._input_validationFc              	   C   s„   t |ƒs8tƒ " tdƒ t |¡ tj¡| _W 5 Q R X n|| _t |¡ tj¡| _	t |¡ tj¡| _
t |¡ t¡| _|  ¡  d S )NÚerror)r   r	   r
   r   Ú
atleast_2dÚastypeZfloat64r(   Ú
atleast_1dr   r   Úboolr   r.   )r    r(   r   r   r   r   r   r   r!   §   s     zLinearConstraint.__init__c                 C   s    | j | | j | j| j |  fS )a	  
        Calculate the residual between the constraint function and the limits

        For a linear constraint of the form::

            lb <= A@x <= ub

        the lower and upper residuals between ``A@x`` and the limits are values
        ``sl`` and ``sb`` such that::

            lb + sl == A@x == ub - sb

        When all elements of ``sl`` and ``sb`` are positive, all elements of
        the constraint are satisfied; a negative element in ``sl`` or ``sb``
        indicates that the corresponding element of the constraint is not
        satisfied.

        Parameters
        ----------
        x: array_like
            Vector of independent variables

        Returns
        -------
        sl, sb : array-like
            The lower and upper residuals
        )r(   r   r   ©r    r   r   r   r   Úresidual¸   s    zLinearConstraint.residualN)	r"   r#   r$   r%   r.   r   Úinfr!   r5   r   r   r   r   r&   x   s   r&   c                   @   s>   e Zd ZdZdd„ Zej ejdfdd„Zdd„ Zd	d
„ Z	dS )ÚBoundsaP  Bounds constraint on the variables.

    The constraint has the general inequality form::

        lb <= x <= ub

    It is possible to use equal bounds to represent an equality constraint or
    infinite bounds to represent a one-sided constraint.

    Parameters
    ----------
    lb, ub : array_like, optional
        Lower and upper bounds on independent variables. `lb`, `ub`, and
        `keep_feasible` must be the same shape or broadcastable.
        Set components of `lb` and `ub` equal
        to fix a variable. Use ``np.inf`` with an appropriate sign to disable
        bounds on all or some variables. Note that you can mix constraints of
        different types: interval, one-sided or equality, by setting different
        components of `lb` and `ub` as necessary. Defaults to ``lb = -np.inf``
        and ``ub = np.inf`` (no bounds).
    keep_feasible : array_like of bool, optional
        Whether to keep the constraint components feasible throughout
        iterations. Must be broadcastable with `lb` and `ub`.
        Default is False. Has no effect for equality constraints.
    c                 C   sN   z(t  | j| j| j¡}|\| _| _| _W n  tk
rH   d}t|ƒ‚Y nX d S )Nz6`lb`, `ub`, and `keep_feasible` must be broadcastable.)r   Zbroadcast_arraysr   r   r   r*   )r    Úresr-   r   r   r   r.   ñ   s    zBounds._input_validationFc                 C   s6   t  |¡| _t  |¡| _t  |¡ t¡| _|  ¡  d S r   )r   r2   r   r   r1   r3   r   r.   )r    r   r   r   r   r   r   r!   ù   s    zBounds.__init__c                 C   sF   t | ƒj› d| j›d| j›}t | j¡r:d| j›d}nd}|| S )Nú(z, z, keep_feasible=ú))Útyper"   r   r   r   Úanyr   )r    ÚstartÚendr   r   r   Ú__repr__ÿ   s
    zBounds.__repr__c                 C   s   || j  | j| fS )aß  Calculate the residual (slack) between the input and the bounds

        For a bound constraint of the form::

            lb <= x <= ub

        the lower and upper residuals between `x` and the bounds are values
        ``sl`` and ``sb`` such that::

            lb + sl == x == ub - sb

        When all elements of ``sl`` and ``sb`` are positive, all elements of
        ``x`` lie within the bounds; a negative element in ``sl`` or ``sb``
        indicates that the corresponding element of ``x`` is out of bounds.

        Parameters
        ----------
        x: array_like
            Vector of independent variables

        Returns
        -------
        sl, sb : array-like
            The lower and upper residuals
        )r   r   r4   r   r   r   r5     s    zBounds.residualN)
r"   r#   r$   r%   r.   r   r6   r!   r?   r5   r   r   r   r   r7   ×   s
   r7   c                   @   s0   e Zd ZdZdej ejffdd„Zdd„ ZdS )ÚPreparedConstrainta€  Constraint prepared from a user defined constraint.

    On creation it will check whether a constraint definition is valid and
    the initial point is feasible. If created successfully, it will contain
    the attributes listed below.

    Parameters
    ----------
    constraint : {NonlinearConstraint, LinearConstraint`, Bounds}
        Constraint to check and prepare.
    x0 : array_like
        Initial vector of independent variables.
    sparse_jacobian : bool or None, optional
        If bool, then the Jacobian of the constraint will be converted
        to the corresponded format if necessary. If None (default), such
        conversion is not made.
    finite_diff_bounds : 2-tuple, optional
        Lower and upper bounds on the independent variables for the finite
        difference approximation, if applicable. Defaults to no bounds.

    Attributes
    ----------
    fun : {VectorFunction, LinearVectorFunction, IdentityVectorFunction}
        Function defining the constraint wrapped by one of the convenience
        classes.
    bounds : 2-tuple
        Contains lower and upper bounds for the constraints --- lb and ub.
        These are converted to ndarray and have a size equal to the number of
        the constraints.
    keep_feasible : ndarray
         Array indicating which components must be kept feasible with a size
         equal to the number of the constraints.
    Nc              	   C   s6  t |tƒr,t|j||j|j|j|j||ƒ}n8t |tƒrFt	|j
||ƒ}nt |tƒr\t||ƒ}ntdƒ‚|j}tj|jtd}tj|jtd}tj|jtd}	t ||¡}t ||¡}t |	|¡}	|	j|fkrÒtdƒ‚|	||k@ }
|j}t ||
 ||
 k ¡st ||
 ||
 k¡rtdƒ‚|| _||f| _|	| _d S )Nz*`constraint` of an unknown type is passed.)Zdtypez"`keep_feasible` has a wrong shape.z_`x0` is infeasible with respect to some inequality constraint with `keep_feasible` set to True.)r   r   r   r   r   r   r   r   r&   r   r(   r7   r   r*   Úmr   Úasarrayr   Úfloatr   r   r3   r,   r+   Úfr<   Úbounds)r    Ú
constraintÚx0Zsparse_jacobianZfinite_diff_boundsr   rA   r   r   r   ÚmaskZf0r   r   r   r!   F  s<    
  ü

0
zPreparedConstraint.__init__c              	   C   sb   t ƒ "}| t¡ | j t |¡¡}W 5 Q R X t | jd | d¡}t || jd  d¡}|| S )aZ  How much the constraint is exceeded by.

        Parameters
        ----------
        x : array-like
            Vector of independent variables

        Returns
        -------
        excess : array-like
            How much the constraint is exceeded by, for each of the
            constraints specified by `PreparedConstraint.fun`.
        r   r   )r   ÚfilterÚUserWarningr   r   rB   ÚmaximumrE   )r    r   ÚsupZevZ	excess_lbZ	excess_ubr   r   r   Ú	violationm  s    
zPreparedConstraint.violation)r"   r#   r$   r%   r   r6   r!   rM   r   r   r   r   r@   $  s
   !ÿ
'r@   c                 C   sB   t  | |¡} t  ||¡}dd„ | D ƒ} dd„ |D ƒ}tt| |ƒƒS )a.  Convert the new bounds representation to the old one.

    The new representation is a tuple (lb, ub) and the old one is a list
    containing n tuples, ith containing lower and upper bound on a ith
    variable.
    If any of the entries in lb/ub are -np.inf/np.inf they are replaced by
    None.
    c                 S   s$   g | ]}|t j krt|ƒnd ‘qS r   ©r   r6   rC   ©Ú.0r   r   r   r   Ú
<listcomp>‘  s     z%new_bounds_to_old.<locals>.<listcomp>c                 S   s"   g | ]}|t jk rt|ƒnd ‘qS r   rN   rO   r   r   r   rQ   ’  s     )r   r,   ÚlistÚzip)r   r   Únr   r   r   Únew_bounds_to_old…  s
    	rU   c                 C   s<   t | Ž \}}t dd„ |D ƒ¡}t dd„ |D ƒ¡}||fS )a.  Convert the old bounds representation to the new one.

    The new representation is a tuple (lb, ub) and the old one is a list
    containing n tuples, ith containing lower and upper bound on a ith
    variable.
    If any of the entries in lb/ub are None they are replaced by
    -np.inf/np.inf.
    c                 S   s(   g | ] }|d k	rt t|ƒƒntj ‘qS r   ©rC   r   r   r6   rO   r   r   r   rQ   ¤  s   ÿz$old_bound_to_new.<locals>.<listcomp>c                 S   s&   g | ]}|d k	rt t|ƒƒntj‘qS r   rV   rO   r   r   r   rQ   ¦  s   ÿ)rS   r   Úarray)rE   r   r   r   r   r   Úold_bound_to_new—  s    	
ÿ
ÿrX   c                 C   sR   t  | |¡ t¡}t  ||¡ t¡}t  ||¡}t j || < t j|| < ||fS )z6Remove bounds which are not asked to be kept feasible.)r   Úresizer1   rC   r6   )r   r   r   Zn_varsZ	strict_lbZ	strict_ubr   r   r   Ústrict_bounds¬  s    rZ   c                    sô  t | tƒrX| jdk	s0| jdk	s0t | jtƒr0| jr:tdtƒ | j	‰t
| jƒrR| j‰qœd‰nDt | j¡rntdtƒ | j‰ tˆ ƒr„ˆ  ¡ ‰ ‡ fdd„‰‡ fdd„‰t| ˆ
ƒ}|j\‰‰	ˆˆ	k‰t ˆtj kˆ¡‰t ˆ	tjkˆ¡‰t ˆtj kˆ	tjk¡}t |¡rtdtƒ g }t ˆ¡r^‡‡‡fdd	„}d
|dœg}ˆdk	r^‡‡fdd„}||d d< g }t ˆ¡‰t ˆ¡‰ˆˆ rÐ‡‡‡‡‡‡‡	fdd„}d|dœg}ˆdk	rÐ‡‡‡‡‡‡
fdd„}	|	|d d< || }
t|
ƒdkrðtdtƒ |
S )zU
    Converts new-style constraint objects to old-style constraint dictionaries.
    Nz}Constraint options `finite_diff_jac_sparsity`, `finite_diff_rel_step`, `keep_feasible`, and `hess`are ignored by this method.z<Constraint option `keep_feasible` is ignored by this method.c                    s   t  ˆ | ¡S r   )r   Údotr   ©r(   r   r   Ú<lambda>Ñ  ó    z'new_constraint_to_old.<locals>.<lambda>c                    s   ˆ S r   r   r   r\   r   r   r]   Ò  r^   zSAt least one constraint is unbounded above and below. Such constraints are ignored.c                    s"   t  ˆ | ƒ¡ ¡ }|ˆ ˆˆ  S r   )r   rW   Úflatten)r   Úy)r   Úi_eqr   r   r   Úf_eqä  s    z#new_constraint_to_old.<locals>.f_eqÚeq)r;   r   c                    s2   ˆ| ƒ}t |ƒr| ¡ }t |¡}|ˆ d d …f S r   )r   Útoarrayr   r0   )r   Údy)ra   r   r   r   Új_eqê  s
    
z#new_constraint_to_old.<locals>.j_eqr   r   c                    sV   t  ˆˆ ¡}t  ˆ | ƒ¡ ¡ }|ˆ ˆˆ  |d ˆ…< |ˆ ˆˆ   |ˆd …< |S r   )r   ÚzerosrW   r_   )r   r`   Zy_all)r   Úi_bound_aboveÚi_bound_belowr   Ún_bound_aboveÚn_bound_belowr   r   r   Úf_ineqö  s
    z%new_constraint_to_old.<locals>.f_ineqÚineqc                    sn   t  ˆˆ tˆƒf¡}ˆ| ƒ}t|ƒr.| ¡ }t  |¡}|ˆ |d ˆ…d d …f< |ˆ   |ˆd …d d …f< |S r   )r   rg   Úlenr   rd   r0   )r   re   Zdy_all)rh   ri   r   rj   rk   rG   r   r   Új_ineqÿ  s    
z%new_constraint_to_old.<locals>.j_ineqr   zçEquality and inequality constraints are specified in the same element of the constraint list. For efficient use with this method, equality and inequality constraints should be specified in separate elements of the constraint list. )r   r   r   r   r   r   r   r   r   r   Úcallabler   r   r<   r(   r   rd   r@   rE   Úlogical_xorr6   Úlogical_andÚsumrn   )ÚconrG   ZpconZi_unboundedZceqrb   rf   Zcineqrl   ro   Zold_constraintsr   )r(   r   rh   ri   ra   r   r   rj   rk   r   rG   r   Únew_constraint_to_old¶  sp    

ÿ
þýþ
ÿ

ÿ




	ýru   c              
      s@  zˆd   ¡ }W n„ tk
r@ } ztd|  ƒ|‚W 5 d}~X Y nn tk
rj } ztdƒ|‚W 5 d}~X Y nD tk
r” } ztdƒ|‚W 5 d}~X Y nX |dkr®tdˆd  ƒ‚dˆkrÂtd	|  ƒ‚d
}|dkrÔd
}ntj}d}dˆkrˆd ‰ ‡ ‡fdd„}dˆkr2‡ ‡fdd„}nˆd }dˆkr2ˆd }t||||ƒS )zU
    Converts old-style constraint dictionaries to new-style constraint objects.
    r;   z"Constraint %d has no type defined.Nz/Constraints must be a sequence of dictionaries.z#Constraint's type must be a string.)rc   rm   zUnknown constraint type '%s'.r   z&Constraint %d has no function defined.r   rc   r   Úargsc                    s   ˆd | fˆ žŽ S )Nr   r   r   ©rv   rt   r   r   r]   2  r^   z'old_constraint_to_new.<locals>.<lambda>r   c                    s   ˆd | fˆ žŽ S )Nr   r   r   rw   r   r   r]   4  r^   )ÚlowerÚKeyErrorÚ	TypeErrorÚAttributeErrorr*   r   r6   r   )Zicrt   ÚctypeÚer   r   r   r   r   rw   r   Úold_constraint_to_new  s<    ÿþ


r~   )r%   Znumpyr   Z_hessian_update_strategyr   Z_differentiable_functionsr   r   r   Ú	_optimizer   Úwarningsr   r	   r
   Znumpy.testingr   Zscipy.sparser   r   r   r&   r7   r@   rU   rX   rZ   ru   r~   r   r   r   r   Ú<module>   s"   f_Ma
^