3

6^K                 @   sT  d Z ddlmZmZmZ ddgZddlZddlm	Z	 ddlm
Z
mZmZmZmZmZmZmZmZmZmZmZmZ dd	lmZmZmZ d
ZeeejZdd Zf df df dddf dddddedfddZ f ddf ddddedf
ddZ!e"dkrPdddddgfddZ#ee gd egd gj$Z%ddge%dddf< d1ddZ&d2ddZ'd3ddZ(d4d d!Z)d"e&e'd5d#d$e(e)d6d#fZ*e+d%j,d&d' e+d( e e#ed7dge%dd)d*dd \Z-Z.e+d+ e!e#ed8dgfd,e%id-d)iZ/e+d.j,d&d' e+d( e e#ed9dge&e'e(e)dd)d/dd \Z-Z.e+d+ e!e#ed:dgfd0e*id-d)iZ/dS );a  
This module implements the Sequential Least SQuares Programming optimization
algorithm (SLSQP), originally developed by Dieter Kraft.
See http://www.netlib.org/toms/733

Functions
---------
.. autosummary::
   :toctree: generated/

    approx_jacobian
    fmin_slsqp

    )divisionprint_functionabsolute_importapprox_jacobian
fmin_slsqpN)slsqp)zerosarraylinalgappendasfarrayconcatenatefinfosqrtvstackexpinfisfinite
atleast_1d   )wrap_functionOptimizeResult_check_unknown_optionszrestructuredtext enc       	      G   s   t | }t||f|  }tt|t|g}tt|}xBtt|D ]2}|||< ||| f|  | | ||< d||< qHW |j S )a  
    Approximate the Jacobian matrix of a callable function.

    Parameters
    ----------
    x : array_like
        The state vector at which to compute the Jacobian matrix.
    func : callable f(x,*args)
        The vector-valued function.
    epsilon : float
        The perturbation used to determine the partial derivatives.
    args : sequence
        Additional arguments passed to func.

    Returns
    -------
    An array of dimensions ``(lenf, lenx)`` where ``lenf`` is the length
    of the outputs of `func`, and ``lenx`` is the number of elements in
    `x`.

    Notes
    -----
    The approximation is done using forward differences.

    g        )r   r   r   lenrangeZ	transpose)	xfuncepsilonargsx0f0jacZdxi r#   5/tmp/pip-build-vw4w4j08/scipy/scipy/optimize/slsqp.pyr      s    d   gư>c                s   |dk	r|}||||dk||d}f }|t  fdd|D 7 }|t  fdd|D 7 }|rr|d|| df7 }|r|d	||	 df7 }t| | f|||d
|}|r|d |d |d |d |d fS |d S dS )a6  
    Minimize a function using Sequential Least SQuares Programming

    Python interface function for the SLSQP Optimization subroutine
    originally implemented by Dieter Kraft.

    Parameters
    ----------
    func : callable f(x,*args)
        Objective function.  Must return a scalar.
    x0 : 1-D ndarray of float
        Initial guess for the independent variable(s).
    eqcons : list, optional
        A list of functions of length n such that
        eqcons[j](x,*args) == 0.0 in a successfully optimized
        problem.
    f_eqcons : callable f(x,*args), optional
        Returns a 1-D array in which each element must equal 0.0 in a
        successfully optimized problem.  If f_eqcons is specified,
        eqcons is ignored.
    ieqcons : list, optional
        A list of functions of length n such that
        ieqcons[j](x,*args) >= 0.0 in a successfully optimized
        problem.
    f_ieqcons : callable f(x,*args), optional
        Returns a 1-D ndarray in which each element must be greater or
        equal to 0.0 in a successfully optimized problem.  If
        f_ieqcons is specified, ieqcons is ignored.
    bounds : list, optional
        A list of tuples specifying the lower and upper bound
        for each independent variable [(xl0, xu0),(xl1, xu1),...]
        Infinite values will be interpreted as large floating values.
    fprime : callable `f(x,*args)`, optional
        A function that evaluates the partial derivatives of func.
    fprime_eqcons : callable `f(x,*args)`, optional
        A function of the form `f(x, *args)` that returns the m by n
        array of equality constraint normals.  If not provided,
        the normals will be approximated. The array returned by
        fprime_eqcons should be sized as ( len(eqcons), len(x0) ).
    fprime_ieqcons : callable `f(x,*args)`, optional
        A function of the form `f(x, *args)` that returns the m by n
        array of inequality constraint normals.  If not provided,
        the normals will be approximated. The array returned by
        fprime_ieqcons should be sized as ( len(ieqcons), len(x0) ).
    args : sequence, optional
        Additional arguments passed to func and fprime.
    iter : int, optional
        The maximum number of iterations.
    acc : float, optional
        Requested accuracy.
    iprint : int, optional
        The verbosity of fmin_slsqp :

        * iprint <= 0 : Silent operation
        * iprint == 1 : Print summary upon completion (default)
        * iprint >= 2 : Print status of each iterate and summary
    disp : int, optional
        Over-rides the iprint interface (preferred).
    full_output : bool, optional
        If False, return only the minimizer of func (default).
        Otherwise, output final objective function and summary
        information.
    epsilon : float, optional
        The step size for finite-difference derivative estimates.
    callback : callable, optional
        Called after each iteration, as ``callback(x)``, where ``x`` is the
        current parameter vector.

    Returns
    -------
    out : ndarray of float
        The final minimizer of func.
    fx : ndarray of float, if full_output is true
        The final value of the objective function.
    its : int, if full_output is true
        The number of iterations.
    imode : int, if full_output is true
        The exit mode from the optimizer (see below).
    smode : string, if full_output is true
        Message describing the exit mode from the optimizer.

    See also
    --------
    minimize: Interface to minimization algorithms for multivariate
        functions. See the 'SLSQP' `method` in particular.

    Notes
    -----
    Exit modes are defined as follows ::

        -1 : Gradient evaluation required (g & a)
         0 : Optimization terminated successfully.
         1 : Function evaluation required (f & c)
         2 : More equality constraints than independent variables
         3 : More than 3*n iterations in LSQ subproblem
         4 : Inequality constraints incompatible
         5 : Singular matrix E in LSQ subproblem
         6 : Singular matrix C in LSQ subproblem
         7 : Rank-deficient equality constraint subproblem HFTI
         8 : Positive directional derivative for linesearch
         9 : Iteration limit exceeded

    Examples
    --------
    Examples are given :ref:`in the tutorial <tutorial-sqlsp>`.

    Nr   )maxiterftoliprintdispepscallbackc             3   s   | ]}d | dV  qdS )eq)typefunr   Nr#   ).0c)r   r#   r$   	<genexpr>   s    zfmin_slsqp.<locals>.<genexpr>c             3   s   | ]}d | dV  qdS )ineq)r-   r.   r   Nr#   )r/   r0   )r   r#   r$   r1      s    r,   )r-   r.   r!   r   r2   )r!   boundsconstraintsr   r.   nitstatusmessage)tuple_minimize_slsqp)r   r   Zeqconsf_eqconsZieqcons	f_ieqconsr3   fprimefprime_eqconsfprime_ieqconsr   iteraccr(   r)   full_outputr   r+   optsconsresr#   )r   r$   r   E   s,    p"Fc       F   0      s  t | |}|}|}|
 |	s d}t|tr0|f}f f d}xt|D ]\}}y|d j }W nT tk
r|   td| Y nN tk
r   tdY n4 tk
r   tdY nX |dDkrtd	|d  d
|krtd| |j	d}|dkr
 fdd}||d
 }||  |d
 ||j	df df7  < qDW dEdddddddddddddddd d!d"d#d$d%i}t
| |\}} |rt
||\}}nt
t|  f\}}t|j tttfd&d'|d D }tttfd(d'|d D }|| }td|gj }t}|d }|| | | }d| | |d  || d |d   d|  || ||   d|  | |d | d  d|  d|  d|  d } |}!t| }"t|!}#|dkst|dkrtj|td)}$tj|td)}%|$jtj |%jtj nt|t}&|&jd |krtd*tjd+d,& |&dddf |&dddf k}'W dQ R X |'j rxtd-d.jd/d0 |'D  |&dddf |&dddf  }$}%t|& }(tj|$|(dddf < tj|%|(dddf < tj|$})tj|) |$|) tj |)< tj|%})tj|) tj  |%|) |)< tdt!}*t|t}t|t!}+d},tdt}-tdt}.tdt}/tdt}0tdt}1tdt}2tdt}3tdt}4tdt}5tdt}6tdt!}7tdt!}8tdt!}9tdt!}:tdt!};tdt!}tdt!}<tdt!}=|dkr
t"d1dF  x2|*dks"|*dkr| }>yttj#|>}>W n" ttfk
r^   td6Y nX |d rt$fd7d'|d D }?ntd}?|d rt$fd8d'|d D }@ntd}@t$|?|@f}A|*dks|*dGkrt%|d9}B|d rt&fd:d'|d D }Cnt||f}C|d rBt&fd;d'|d D }Dnt||f}D|dkrft||f}Ent&|C|Df}Et$|Et|dgfd}Et'|||$|%|>|A|B|E||+|*|"|#|-|.|/|0|1|2|3|4|5|6|7|8|9|:|;||<|=  |dk	r|+|,kr|tj( |dkr"|+|,kr"t"d<|+|d |>t)j*|Bf  t+|*dkr2P t!|+},qW |dkrt"|t!|* d= t,|* d>  t"d?|> t"d@|+ t"dA|d  t"dB|d  t-|>|BddH t!|+|d |d t!|*|t!|* |*dkdC	S )Ia  
    Minimize a scalar function of one or more variables using Sequential
    Least SQuares Programming (SLSQP).

    Options
    -------
    ftol : float
        Precision goal for the value of f in the stopping criterion.
    eps : float
        Step size used for numerical approximation of the Jacobian.
    disp : bool
        Set to True to print convergence messages. If False,
        `verbosity` is ignored and set to 0.
    maxiter : int
        Maximum number of iterations.

    r   )r,   r2   r-   z"Constraint %d has no type defined.z/Constraints must be defined using a dictionary.z#Constraint's type must be a string.r,   r2   zUnknown constraint type '%s'.r.   z&Constraint %d has no function defined.r!   Nc                s    fdd}|S )Nc                s   t |  f| S )N)r   )r   r   )r   r.   r#   r$   cjac  s    z3_minimize_slsqp.<locals>.cjac_factory.<locals>.cjacr#   )r.   rE   )r   )r.   r$   cjac_factory  s    z%_minimize_slsqp.<locals>.cjac_factoryr   )r.   r!   r   r   z$Gradient evaluation required (g & a)z%Optimization terminated successfully.z$Function evaluation required (f & c)   z4More equality constraints than independent variables   z*More than 3*n iterations in LSQ subproblem   z#Inequality constraints incompatible   z#Singular matrix E in LSQ subproblem   z#Singular matrix C in LSQ subproblem   z2Rank-deficient equality constraint subproblem HFTI   z.Positive directional derivative for linesearch	   zIteration limit exceededc                s&   g | ]}t |d   f|d  qS )r.   r   )r   )r/   r0   )r   r#   r$   
<listcomp>8  s   z#_minimize_slsqp.<locals>.<listcomp>c                s&   g | ]}t |d   f|d  qS )r.   r   )r   )r/   r0   )r   r#   r$   rO   :  s   )ZdtypezDSLSQP Error: the length of bounds is not compatible with that of x0.ignore)invalidz"SLSQP Error: lb > ub in bounds %s.z, c             s   s   | ]}t |V  qd S )N)str)r/   br#   r#   r$   r1   ]  s    z"_minimize_slsqp.<locals>.<genexpr>z%5s %5s %16s %16sNITFCOBJFUNGNORMz'Objective function must return a scalarc                s&   g | ]}t |d   f|d  qS )r.   r   )r   )r/   con)r   r#   r$   rO     s   c                s&   g | ]}t |d   f|d  qS )r.   r   )r   )r/   rX   )r   r#   r$   rO     s   g        c                s"   g | ]}|d   f|d  qS )r!   r   r#   )r/   rX   )r   r#   r$   rO     s   c                s"   g | ]}|d   f|d  qS )r!   r   r#   )r/   rX   )r   r#   r$   rO     s   z%5i %5i % 16.6E % 16.6Ez    (Exit mode )z#            Current function value:z            Iterations:z!            Function evaluations:z!            Gradient evaluations:)	r   r.   r!   r5   ZnfevZnjevr6   r7   success)r,   r2   )rT   rU   rV   rW   r[   r[   ).r   
isinstancedict	enumeratelowerKeyError	TypeErrorAttributeError
ValueErrorgetr   r   r   flattensummapr   r	   maxr   npemptyfloatfillnanshape
IndexErrorZerrstateanyjoinr   Zclipr   intprintZasarrayr   r   r   r   copyr
   ZnormabsrR   r   )Fr   r   r   r!   r3   r4   r&   r'   r(   r)   r*   r+   Zunknown_optionsr<   r?   r@   rC   ZicrX   ctyperE   rF   Z
exit_modesZfevalZgevalZmeqZmieqmZlanZn1ZmineqZlen_wZlen_jwwZjwZxlZxubndsZbnderrZinfbndZ
have_boundmodeZmajiterZmajiter_prevalphar    Zgsh1h2h3h4tt0ZtolZiexactZinconsZiresetZitermxlineZn2Zn3ZfxZc_eqZc_ieqr0   gZa_eqZa_ieqar#   )r   r   r$   r9      s6   



x
*
"
































 

r9   __main__rI   rG   c             C   sd   t | d |d | d d  |d | d d   |d | d  | d   |d | d   |d   S )z Objective function r   rG   r   rH   rI   )r   )r   rr#   r#   r$   r.     s    
Nr.   g?g?c             C   s   t | d d | d  | gS )z Equality constraint r   rG   r   )r	   )r   rS   r#   r#   r$   feqcon  s    r   c             C   s   t d| d  dggS )z! Jacobian of equality constraint rG   r   r   )r	   )r   rS   r#   r#   r$   jeqcon  s    r   
   c             C   s   t | d | d  | gS )z Inequality constraint r   r   )r	   )r   r0   r#   r#   r$   fieqcon  s    r   c             C   s   t ddggS )z# Jacobian of Inequality constraint r   )r	   )r   r0   r#   r#   r$   jieqcon  s    r   r,   )r-   r.   r!   r   r2   z Bounds constraints H   -z * fmin_slsqpT)r3   r)   rA   z * _minimize_slsqpr3   r)   z% Equality and inequality constraints )r:   r=   r;   r>   r)   rA   r4   )r   )r   )r   )r   )r   )r   r[   r[   r[   r[   )0__doc__
__future__r   r   r   __all__Znumpyri   Zscipy.optimize._slsqpr   r   r	   r
   r   r   r   r   r   r   r   r   r   r   optimizer   r   r   Z__docformat__rk   r*   Z_epsilonr   r   r9   __name__r.   Trz   r   r   r   r   rC   rs   centerr   frD   r#   r#   r#   r$   <module>   s^   <&   




