a
    aH                     @   s   d Z ddlZddlmZmZmZmZ ddlmZ ddl	m
Z
mZmZmZ ddlmZ ddlmZ d	d
gZddd	ZdddZG dd
 d
eZdS )zR
Functions
---------
.. autosummary::
   :toctree: generated/

    fmin_l_bfgs_b

    N)arrayasarrayfloat64zeros   )_lbfgsb)
MemoizeJacOptimizeResult_check_unknown_options_prepare_scalar_function)old_bound_to_new)LinearOperatorfmin_l_bfgs_bLbfgsInvHessProduct 
       cAh㈵>:0yE>:     c                 C   s   |r| }d}n |du r&t | }|j}n| }|}|du r:|
}||
||ttj ||	||||d
}t||f|||d|}|d |d |d |d |d d	}|d
 }|d }|||fS )a  
    Minimize a function func using the L-BFGS-B algorithm.

    Parameters
    ----------
    func : callable f(x,*args)
        Function to minimize.
    x0 : ndarray
        Initial guess.
    fprime : callable fprime(x,*args), optional
        The gradient of `func`. If None, then `func` returns the function
        value and the gradient (``f, g = func(x, *args)``), unless
        `approx_grad` is True in which case `func` returns only ``f``.
    args : sequence, optional
        Arguments to pass to `func` and `fprime`.
    approx_grad : bool, optional
        Whether to approximate the gradient numerically (in which case
        `func` returns only the function value).
    bounds : list, optional
        ``(min, max)`` pairs for each element in ``x``, defining
        the bounds on that parameter. Use None or +-inf for one of ``min`` or
        ``max`` when there is no bound in that direction.
    m : int, optional
        The maximum number of variable metric corrections
        used to define the limited memory matrix. (The limited memory BFGS
        method does not store the full hessian but uses this many terms in an
        approximation to it.)
    factr : float, optional
        The iteration stops when
        ``(f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr * eps``,
        where ``eps`` is the machine precision, which is automatically
        generated by the code. Typical values for `factr` are: 1e12 for
        low accuracy; 1e7 for moderate accuracy; 10.0 for extremely
        high accuracy. See Notes for relationship to `ftol`, which is exposed
        (instead of `factr`) by the `scipy.optimize.minimize` interface to
        L-BFGS-B.
    pgtol : float, optional
        The iteration will stop when
        ``max{|proj g_i | i = 1, ..., n} <= pgtol``
        where ``pg_i`` is the i-th component of the projected gradient.
    epsilon : float, optional
        Step size used when `approx_grad` is True, for numerically
        calculating the gradient
    iprint : int, optional
        Controls the frequency of output. ``iprint < 0`` means no output;
        ``iprint = 0``    print only one line at the last iteration;
        ``0 < iprint < 99`` print also f and ``|proj g|`` every iprint iterations;
        ``iprint = 99``   print details of every iteration except n-vectors;
        ``iprint = 100``  print also the changes of active set and final x;
        ``iprint > 100``  print details of every iteration including x and g.
    disp : int, optional
        If zero, then no output. If a positive number, then this over-rides
        `iprint` (i.e., `iprint` gets the value of `disp`).
    maxfun : int, optional
        Maximum number of function evaluations.
    maxiter : int, optional
        Maximum number of iterations.
    callback : callable, optional
        Called after each iteration, as ``callback(xk)``, where ``xk`` is the
        current parameter vector.
    maxls : int, optional
        Maximum number of line search steps (per iteration). Default is 20.

    Returns
    -------
    x : array_like
        Estimated position of the minimum.
    f : float
        Value of `func` at the minimum.
    d : dict
        Information dictionary.

        * d['warnflag'] is

          - 0 if converged,
          - 1 if too many function evaluations or too many iterations,
          - 2 if stopped for another reason, given in d['task']

        * d['grad'] is the gradient at the minimum (should be 0 ish)
        * d['funcalls'] is the number of function calls made.
        * d['nit'] is the number of iterations.

    See also
    --------
    minimize: Interface to minimization algorithms for multivariate
        functions. See the 'L-BFGS-B' `method` in particular. Note that the
        `ftol` option is made available via that interface, while `factr` is
        provided via this interface, where `factr` is the factor multiplying
        the default machine floating-point precision to arrive at `ftol`:
        ``ftol = factr * numpy.finfo(float).eps``.

    Notes
    -----
    License of L-BFGS-B (FORTRAN code):

    The version included here (in fortran code) is 3.0
    (released April 25, 2011). It was written by Ciyou Zhu, Richard Byrd,
    and Jorge Nocedal <nocedal@ece.nwu.edu>. It carries the following
    condition for use:

    This software is freely available, but we expect that all publications
    describing work using this software, or all commercial products using it,
    quote at least one of the references given below. This software is released
    under the BSD License.

    References
    ----------
    * R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound
      Constrained Optimization, (1995), SIAM Journal on Scientific and
      Statistical Computing, 16, 5, pp. 1190-1208.
    * C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B,
      FORTRAN routines for large scale bound constrained optimization (1997),
      ACM Transactions on Mathematical Software, 23, 4, pp. 550 - 560.
    * J.L. Morales and J. Nocedal. L-BFGS-B: Remark on Algorithm 778: L-BFGS-B,
      FORTRAN routines for large scale bound constrained optimization (2011),
      ACM Transactions on Mathematical Software, 38, 1.

    N)
dispiprintmaxcorftolgtolepsmaxfunmaxitercallbackmaxls)argsjacboundsr#   messagenfevnitstatus)ZgradtaskZfuncallsr'   warnflagfunx)r   Z
derivativenpfinfofloatr   _minimize_lbfgsb)funcx0Zfprimer"   Zapprox_gradr$   mfactrpgtolepsilonr   r   r   r   r    r!   r+   r#   optsresdfr,   r   r   e/Users/vegardjervell/Documents/master/model/venv/lib/python3.9/site-packages/scipy/optimize/lbfgsb.pyr   0   sB    }    #>c           2      K   s  t | |}|}|ttj }t| }|j\}|du rFdg| }t||krZt	ddd |D }t
|}|d |d k rt	dt||d |d }|dur|dkrd	}n|}t| ||||	||d
}|j}tjjj}t||}t|t}t|t}ddddd}td|D ]N}|| \}}|dur>|||< d}|durT|||< d}|||f ||< q|dkszt	dt|t} tdt}!t|ft}"td| | d|  d| |  d|  t}#td| |}$tdd}%tdd}&td|}'td|}(tdt})d|%dd< d}*t|| ||||!|"|||#|$|%||&|'|(|)| |% }+|+drf|| \}!}"nb|+dr|*d7 }*|dur|t|  |*|krd|%dd< n|j|
krd|%dd< nq̐q|% d }+|+drd},n |j|
ks|*|krd},nd},|#d||  ||}-|#|| d| |  ||}.|(d }/t|/|}0t|-d|0 |.d|0 }1|+  }+t!|!|"|j|j"|*|,|+| |,dk|1d
S ) a
  
    Minimize a scalar function of one or more variables using the L-BFGS-B
    algorithm.

    Options
    -------
    disp : None or int
        If `disp is None` (the default), then the supplied version of `iprint`
        is used. If `disp is not None`, then it overrides the supplied version
        of `iprint` with the behaviour you outlined.
    maxcor : int
        The maximum number of variable metric corrections used to
        define the limited memory matrix. (The limited memory BFGS
        method does not store the full hessian but uses this many terms
        in an approximation to it.)
    ftol : float
        The iteration stops when ``(f^k -
        f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= ftol``.
    gtol : float
        The iteration will stop when ``max{|proj g_i | i = 1, ..., n}
        <= gtol`` where ``pg_i`` is the i-th component of the
        projected gradient.
    eps : float or ndarray
        If `jac is None` the absolute step size used for numerical
        approximation of the jacobian via forward differences.
    maxfun : int
        Maximum number of function evaluations.
    maxiter : int
        Maximum number of iterations.
    iprint : int, optional
        Controls the frequency of output. ``iprint < 0`` means no output;
        ``iprint = 0``    print only one line at the last iteration;
        ``0 < iprint < 99`` print also f and ``|proj g|`` every iprint iterations;
        ``iprint = 99``   print details of every iteration except n-vectors;
        ``iprint = 100``  print also the changes of active set and final x;
        ``iprint > 100``  print details of every iteration including x and g.
    callback : callable, optional
        Called after each iteration, as ``callback(xk)``, where ``xk`` is the
        current parameter vector.
    maxls : int, optional
        Maximum number of line search steps (per iteration). Default is 20.
    finite_diff_rel_step : None or array_like, optional
        If `jac in ['2-point', '3-point', 'cs']` the relative step size to
        use for numerical approximation of the jacobian. The absolute step
        size is computed as ``h = rel_step * sign(x0) * max(1, abs(x0))``,
        possibly adjusted to fit into the bounds. For ``method='3-point'``
        the sign of `h` is ignored. If None (default) then step is selected
        automatically.

    Notes
    -----
    The option `ftol` is exposed via the `scipy.optimize.minimize` interface,
    but calling `scipy.optimize.fmin_l_bfgs_b` directly exposes `factr`. The
    relationship between the two is ``ftol = factr * numpy.finfo(float).eps``.
    I.e., `factr` multiplies the default machine floating-point precision to
    arrive at `ftol`.

    NNNz length of x0 != length of boundsc                 S   s6   g | ].\}}|t j krd n||t jkr,d n|fqS )N)r-   inf).0lur   r   r;   
<listcomp>      z$_minimize_lbfgsb.<locals>.<listcomp>r   r   z@LBFGSB - one of the lower bounds is greater than an upper bound.r   )r#   r"   r6   r$   finite_diff_rel_step      )r=   )r   N)r   r   )Nr   zmaxls must be positive.g                 ZS60   ,      STARTs   FGs   NEW_Xz+STOP: TOTAL NO. of ITERATIONS REACHED LIMITz4STOP: TOTAL NO. of f AND g EVALUATIONS EXCEEDS LIMIT    s   CONV   )
r+   r#   r&   Znjevr'   r(   r%   r,   successhess_inv)#r
   r-   r.   r/   r   r   Zravelshapelen
ValueErrorr   anyZclipr   Zfun_and_gradr   typesZintvardtyper   r   ranger   Zsetulbtobytes
startswithcopyr&   stripreshapeminr   decoder	   Zngev)2r+   r2   r"   r#   r$   r   r   r   r   r   r   r   r   r    r!   rD   Zunknown_optionsr3   r5   r4   nZ
new_boundsZsfZfunc_and_gradZfortran_intZnbdZlow_bndZ	upper_bndZ
bounds_mapir@   rA   r,   r:   gwaZiwar)   ZcsaveZlsaveZisaveZdsaveZn_iterationsZtask_strr*   syZn_bfgs_updatesn_corrsrQ   r   r   r;   r0      s    ?









.






 


r0   c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )r   aM  Linear operator for the L-BFGS approximate inverse Hessian.

    This operator computes the product of a vector with the approximate inverse
    of the Hessian of the objective function, using the L-BFGS limited
    memory approximation to the inverse Hessian, accumulated during the
    optimization.

    Objects of this class implement the ``scipy.sparse.linalg.LinearOperator``
    interface.

    Parameters
    ----------
    sk : array_like, shape=(n_corr, n)
        Array of `n_corr` most recent updates to the solution vector.
        (See [1]).
    yk : array_like, shape=(n_corr, n)
        Array of `n_corr` most recent updates to the gradient. (See [1]).

    References
    ----------
    .. [1] Nocedal, Jorge. "Updating quasi-Newton matrices with limited
       storage." Mathematics of computation 35.151 (1980): 773-782.

    c                    sh   |j |j ks|jdkrtd|j \}}t jtj||fd || _|| _|| _	dt
d|| | _dS )zConstruct the operator.rE   z0sk and yk must have matching shape, (n_corrs, n))rW   rR   r   zij,ij->iN)rR   ndimrT   super__init__r-   r   skykrf   Zeinsumrho)selfrj   rk   rf   r`   	__class__r   r;   ri     s    
zLbfgsInvHessProduct.__init__c                 C   s   | j | j| j| jf\}}}}tj|| jdd}|jdkrP|jd dkrP|	d}t
|}t|d ddD ]4}|| t|| | ||< ||| ||   }qj|}	t|D ]4}|| t|| |	 }
|	|| || |
   }	q|	S )aE  Efficient matrix-vector multiply with the BFGS matrices.

        This calculation is described in Section (4) of [1].

        Parameters
        ----------
        x : ndarray
            An array with shape (n,) or (n,1).

        Returns
        -------
        y : ndarray
            The matrix-vector product

        T)rW   r[   rE   r   r   )rj   rk   rf   rl   r-   r   rW   rg   rR   r]   emptyrX   dot)rm   r,   rd   re   rf   rl   qalphara   rbetar   r   r;   _matvec  s    

zLbfgsInvHessProduct._matvecc           
      C   s   | j | j| j| jf\}}}}tj| jd| ji}|}t|D ]}||| ddtj	f || tj	ddf  ||   }||| ddtj	f || tj	ddf  ||   }	t
|t
||	|| || ddtj	f  || tj	ddf   }q<|S )zReturn a dense array representation of this operator.

        Returns
        -------
        arr : ndarray, shape=(n, n)
            An array with the same shape and containing
            the same data represented by this `LinearOperator`.

        rW   N)rj   rk   rf   rl   r-   ZeyerR   rW   rX   Znewaxisrq   )
rm   rd   re   rf   rl   IZHkra   A1A2r   r   r;   todense  s    
88.zLbfgsInvHessProduct.todense)__name__
__module____qualname____doc__ri   rv   rz   __classcell__r   r   rn   r;   r     s   ")Nr   r   Nr   r   r   r   r   r   r   NNr   )r   NNNr   r<   r   r   r   r   r   Nr   N)r~   Znumpyr-   r   r   r   r    r   optimizer   r	   r
   r   _constraintsr   Zscipy.sparse.linalgr   __all__r   r0   r   r   r   r   r;   <module>   s.   #      
 #     
 A