o
    4Biq\                     @   s   d dl Zd dlmZ ddlmZmZ ddlm	Z	 d dl
mZ d dlmZmZ dZG dd	 d	ZG d
d dZG dd dZG dd deZdS )    N   )approx_derivativegroup_columns)HessianUpdateStrategy)LinearOperator)
atleast_ndarray_namespace)z2-pointz3-pointcsc                   @   sT   e Zd ZdZ	dddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd ZdS )ScalarFunctiona  Scalar function and its derivatives.

    This class defines a scalar function F: R^n->R and methods for
    computing or approximating its first and second derivatives.

    Parameters
    ----------
    fun : callable
        evaluates the scalar function. Must be of the form ``fun(x, *args)``,
        where ``x`` is the argument in the form of a 1-D array and ``args`` is
        a tuple of any additional fixed parameters needed to completely specify
        the function. Should return a scalar.
    x0 : array-like
        Provides an initial set of variables for evaluating fun. Array of real
        elements of size (n,), where 'n' is the number of independent
        variables.
    args : tuple, optional
        Any additional fixed parameters needed to completely specify the scalar
        function.
    grad : {callable, '2-point', '3-point', 'cs'}
        Method for computing the gradient vector.
        If it is a callable, it should be a function that returns the gradient
        vector:

            ``grad(x, *args) -> array_like, shape (n,)``

        where ``x`` is an array with shape (n,) and ``args`` is a tuple with
        the fixed parameters.
        Alternatively, the keywords  {'2-point', '3-point', 'cs'} can be used
        to select a finite difference scheme for numerical estimation of the
        gradient with a relative step size. These finite difference schemes
        obey any specified `bounds`.
    hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy}
        Method for computing the Hessian matrix. If it is callable, it should
        return the  Hessian matrix:

            ``hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n)``

        where x is a (n,) ndarray and `args` is a tuple with the fixed
        parameters. Alternatively, the keywords {'2-point', '3-point', 'cs'}
        select a finite difference scheme for numerical estimation. Or, objects
        implementing `HessianUpdateStrategy` interface can be used to
        approximate the Hessian.
        Whenever the gradient is estimated via finite-differences, the Hessian
        cannot be estimated with options {'2-point', '3-point', 'cs'} and needs
        to be estimated using one of the quasi-Newton strategies.
    finite_diff_rel_step : None or array_like
        Relative step size to use. The absolute step size is computed as
        ``h = finite_diff_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 then finite_diff_rel_step is selected
        automatically,
    finite_diff_bounds : tuple of array_like
        Lower and upper bounds on independent variables. Defaults to no bounds,
        (-np.inf, np.inf). Each bound must match the size of `x0` or be a
        scalar, in the latter case the bound will be the same for all
        variables. Use it to limit the range of function evaluation.
    epsilon : None or array_like, optional
        Absolute step size to use, possibly adjusted to fit into the bounds.
        For ``method='3-point'`` the sign of `epsilon` is ignored. By default
        relative steps are used, only if ``epsilon is not None`` are absolute
        steps used.

    Notes
    -----
    This class implements a memoization logic. There are methods `fun`,
    `grad`, hess` and corresponding attributes `f`, `g` and `H`. The following
    things should be considered:

        1. Use only public methods `fun`, `grad` and `hess`.
        2. After one of the methods is called, the corresponding attribute
           will be set. However, a subsequent call with a different argument
           of *any* of the methods may overwrite the attribute.
    Nc	                    s  t stvrtdt dt s%tv s%tts%tdt dtv r1tv r1tdt| _}	t|d|	d}
|	j}|		|
j
drL|
j
}|	|
|_|_jj_d_d_d_d	_d	_d	_d _tj_i tv rd
< |d< |d< |d< tv rd
< |d< |d< dd<  fddfdd}|_  t rȇ fddfdd}ntv rԇfdd}|_  t r7t|g R  _d_ jd7  _t !jr fddt "j_n"tjt#r fddn fddt$t%j_fdd}n4tv rKfdd}|  d_n ttrk_j&jd  d_d _'d _(fd!d}|_)ttr{fd"d#}nfd$d#}|_*d S )%Nz)`grad` must be either callable or one of .z@`hess` must be either callable, HessianUpdateStrategy or one of zWhenever the gradient is estimated via finite-differences, we require the Hessian to be estimated using one of the quasi-Newton strategies.r   ndimxpreal floatingr   Fmethodrel_stepabs_stepboundsTas_linear_operatorc              
      s    j d7  _ t| g R  }t|s4z	t| }W n ttfy3 } ztd|d }~ww |jk r?| _	|_|S )Nr   z@The user-provided objective function must return a scalar value.)
nfevnpcopyisscalarasarrayitem	TypeError
ValueError	_lowest_f	_lowest_x)xfxe)argsfunself h/var/www/html/Trade-python/venv/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.pyfun_wrapped   s"   

z,ScalarFunction.__init__.<locals>.fun_wrappedc                          j _d S Nr   fr%   r'   r$   r%   r&   
update_fun      z+ScalarFunction.__init__.<locals>.update_func                    s*    j d7  _ tt| g R  S Nr   )ngevr   
atleast_1dr   r   )r"   gradr$   r%   r&   grad_wrapped      z-ScalarFunction.__init__.<locals>.grad_wrappedc                      r(   r)   )r   gr%   )r4   r$   r%   r&   update_grad   r.   z,ScalarFunction.__init__.<locals>.update_gradc                      s6       jd7  _tjfdji _d S )Nr   f0)_update_funr0   r   r   r+   r6   r%   finite_diff_optionsr'   r$   r%   r&   r7      s
   c                    s*    j d7  _ tt| g R  S r/   )nhevsps
csr_matrixr   r   r2   r"   hessr$   r%   r&   hess_wrapped   r5   z-ScalarFunction.__init__.<locals>.hess_wrappedc                    s$    j d7  _ t| g R  S r/   )r<   r   r   r2   r?   r%   r&   rA         c                    s0    j d7  _ ttt| g R  S r/   )r<   r   
atleast_2dr   r   r2   r?   r%   r&   rA      s   "c                      r(   r)   )r   Hr%   rA   r$   r%   r&   update_hess   r.   z,ScalarFunction.__init__.<locals>.update_hessc                      s*      tjfdji _jS Nr8   )_update_gradr   r   r6   rD   r%   )r;   r4   r$   r%   r&   rF      s
   r@   c                      s*        j j j  j j  d S r)   )rH   rD   updater   x_prevr6   g_prevr%   r$   r%   r&   rF      s   "c                    X        j _ j _t| d jd} j| j _d _	d _
d _   d S Nr   r   F)rH   r   rJ   r6   rK   r   r   astypex_dtype	f_updated	g_updated	H_updated_update_hessr   _xrL   r%   r&   update_x   s   z)ScalarFunction.__init__.<locals>.update_xc                    8   t | d jd} j| j _d _d _d _d S rN   )r   r   rO   rP   r   rQ   rR   rS   rU   rL   r%   r&   rW      s
   
)+callable
FD_METHODSr   
isinstancer   r   r   r   float64isdtypedtyperO   r   rP   sizenr   r0   r<   rQ   rR   rS   r   r   infr   _update_fun_implr9   _update_grad_implrH   r   rD   r=   issparser>   r   rC   r   
initializerJ   rK   _update_hess_impl_update_x_impl)r$   r#   x0r"   r3   r@   finite_diff_rel_stepfinite_diff_boundsepsilonr   rV   _dtyper-   r7   rF   rW   r%   )	r"   r;   r#   r'   r3   r4   r@   rA   r$   r&   __init__W   s   




zScalarFunction.__init__c                 C      | j s|   d| _ d S d S NTrQ   rb   rL   r%   r%   r&   r9        
zScalarFunction._update_func                 C   rn   ro   )rR   rc   rL   r%   r%   r&   rH   	  rq   zScalarFunction._update_gradc                 C   rn   ro   rS   rf   rL   r%   r%   r&   rT     rq   zScalarFunction._update_hessc                 C   &   t || js| | |   | jS r)   )r   array_equalr   rg   r9   r+   r$   r   r%   r%   r&   r#        
zScalarFunction.func                 C   rs   r)   )r   rt   r   rg   rH   r6   ru   r%   r%   r&   r3     rv   zScalarFunction.gradc                 C   rs   r)   )r   rt   r   rg   rT   rD   ru   r%   r%   r&   r@     rv   zScalarFunction.hessc                 C   s4   t || js| | |   |   | j| jfS r)   )r   rt   r   rg   r9   rH   r+   r6   ru   r%   r%   r&   fun_and_grad%  s
   
zScalarFunction.fun_and_gradr)   )__name__
__module____qualname____doc__rm   r9   rH   rT   r#   r3   r@   rw   r%   r%   r%   r&   r
      s    K
 .r
   c                   @   sX   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd ZdS )VectorFunctiona  Vector function and its derivatives.

    This class defines a vector function F: R^n->R^m and methods for
    computing or approximating its first and second derivatives.

    Notes
    -----
    This class implements a memoization logic. There are methods `fun`,
    `jac`, hess` and corresponding attributes `f`, `J` and `H`. The following
    things should be considered:

        1. Use only public methods `fun`, `jac` and `hess`.
        2. After one of the methods is called, the corresponding attribute
           will be set. However, a subsequent call with a different argument
           of *any* of the methods may overwrite the attribute.
    c	                    s  t stvrtdt dt s%tv s%tts%tdt dtv r1tv r1tdt| _}	t|d|	d}
|	j}|		|
j
drL|
j
}|	|
|_|_jj_d_d_d_d	_d	_d	_i  tv r d
< | d< |d urt|}||f d< | d< tj_tv r d
< | d< d d< tj_tv rtv rtdfddfdd}|_|  tj_jj_t r=j_d_ jd7  _|s|d u rt !jrfddt "j_d_#n)t !jr$fddj$ _d	_#nfddt%j_d	_#fdd}nctv rt&jfdji _d_|sb|d u rut !jru fdd}t "j_d_#n+t !jr fdd}j$ _d	_#n fdd}t%j_d	_#|_'t rjj_(d_ jd7  _t !j(rЇfddt "j(_(n tj(t)r߇fd dnfd!dt%t*j(_(fd"d#}n:tv rfd$d% fd&d#}|  d_n ttr2_(j(+jd' d_d _,d _-fd(d#}|_.ttrBfd)d*}nfd+d*}|_/d S ),Nz(`jac` must be either callable or one of r   z?`hess` must be either callable,HessianUpdateStrategy or one of zWhenever the Jacobian is estimated via finite-differences, we require the Hessian to be estimated using one of the quasi-Newton strategies.r   r   r   r   Fr   r   sparsityr   Tr   c                        j d7  _ t | S r/   )r   r   r1   r2   )r#   r$   r%   r&   r'   w     z,VectorFunction.__init__.<locals>.fun_wrappedc                      r(   r)   r*   r%   r,   r%   r&   r-   {  r.   z+VectorFunction.__init__.<locals>.update_func                    r~   r/   )njevr=   r>   r2   jacr$   r%   r&   jac_wrapped  r   z,VectorFunction.__init__.<locals>.jac_wrappedc                    s    j d7  _  |  S r/   )r   toarrayr2   r   r%   r&   r     s   c                    r~   r/   )r   r   rC   r2   r   r%   r&   r     r   c                      r(   r)   )r   Jr%   )r   r$   r%   r&   
update_jac  r.   z+VectorFunction.__init__.<locals>.update_jacr8   c                      .      ttjfdji _d S rG   )r9   r=   r>   r   r   r+   r   r%   r:   r%   r&   r        
c                      s,      tjfdji  _d S rG   )r9   r   r   r+   r   r   r%   r:   r%   r&   r     s   c                      r   rG   )r9   r   rC   r   r   r+   r   r%   r:   r%   r&   r     r   c                    s    j d7  _ t | |S r/   )r<   r=   r>   r   vr@   r$   r%   r&   rA     s   z-VectorFunction.__init__.<locals>.hess_wrappedc                    s    j d7  _  | |S r/   )r<   r   r   r%   r&   rA     s   
c                    s$    j d7  _ tt | |S r/   )r<   r   rC   r   r   r   r%   r&   rA     rB   c                      s    j j_d S r)   )r   r   rD   r%   rE   r%   r&   rF     s   z,VectorFunction.__init__.<locals>.update_hessc                    s    | j |S r)   )Tdotr   )r   r%   r&   	jac_dot_v  r.   z*VectorFunction.__init__.<locals>.jac_dot_vc                      s8      tjfjjjjfd _d S )N)r8   r"   )_update_jacr   r   r   r   r   r   rD   r%   )r;   r   r$   r%   r&   rF     s   
r@   c                     sb        jd ur- jd ur/ j j }  jj j jj j } j	| | d S d S d S r)   )
r   rJ   J_prevr   r   r   r   r   rD   rI   )delta_xdelta_grL   r%   r&   rF     s    c                    rM   rN   )r   r   rJ   r   r   r   r   rO   rP   rQ   	J_updatedrS   rT   rU   rL   r%   r&   rW     s   z)VectorFunction.__init__.<locals>.update_xc                    rX   rN   )r   r   rO   rP   r   rQ   r   rS   rU   rL   r%   r&   rW     s
   
)0rY   rZ   r   r[   r   r   r   r   r\   r]   r^   rO   r   rP   r_   r`   r   r   r<   rQ   r   rS   r   r   r   x_diffrb   
zeros_liker+   r   mr   r=   rd   r>   sparse_jacobianr   rC   r   _update_jac_implrD   r   r   re   rJ   r   rf   rg   )r$   r#   rh   r   r@   ri   finite_diff_jac_sparsityrj   r   r   rV   rl   sparsity_groupsr-   r   rF   rW   r%   )	r;   r#   r'   r@   rA   r   r   r   r$   r&   rm   >  s   






	
zVectorFunction.__init__c                 C   s"   t || js|| _d| _d S d S )NF)r   rt   r   rS   )r$   r   r%   r%   r&   	_update_v  s   
zVectorFunction._update_vc                 C   s    t || js| | d S d S r)   )r   rt   r   rg   ru   r%   r%   r&   	_update_x  s   zVectorFunction._update_xc                 C   rn   ro   rp   rL   r%   r%   r&   r9     rq   zVectorFunction._update_func                 C   rn   ro   )r   r   rL   r%   r%   r&   r     rq   zVectorFunction._update_jacc                 C   rn   ro   rr   rL   r%   r%   r&   rT   $  rq   zVectorFunction._update_hessc                 C      |  | |   | jS r)   )r   r9   r+   ru   r%   r%   r&   r#   )     
zVectorFunction.func                 C   r   r)   )r   r   r   ru   r%   r%   r&   r   .  r   zVectorFunction.jacc                 C   s"   |  | | | |   | jS r)   )r   r   rT   rD   r$   r   r   r%   r%   r&   r@   3  s   

zVectorFunction.hessN)rx   ry   rz   r{   rm   r   r   r9   r   rT   r#   r   r@   r%   r%   r%   r&   r|   -  s     Tr|   c                   @   s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )LinearVectorFunctionzLinear vector function and its derivatives.

    Defines a linear function F = A x, where x is N-D vector and
    A is m-by-n matrix. The Jacobian is constant and equals to A. The Hessian
    is identically zero and it is returned as a csr matrix.
    c                 C   s   |s|d u rt |rt || _d| _nt |r#| | _d| _ntt|| _d| _| jj	\| _
| _t| | _}t|d|d}|j}||jdrR|j}|||| _|| _| j| j| _d| _tj| j
td| _t | j| jf| _d S )NTFr   r   r   )r^   )r=   rd   r>   r   r   r   r   rC   r   shaper   r`   r   r   r   r\   r]   r^   rO   r   rP   r   r+   rQ   zerosfloatr   rD   )r$   Arh   r   r   rV   rl   r%   r%   r&   rm   B  s(   

zLinearVectorFunction.__init__c                 C   s>   t || jst|d| jd}| j|| j| _d| _d S d S rN   )r   rt   r   r   r   rO   rP   rQ   )r$   r   rV   r%   r%   r&   r   `  s
   
zLinearVectorFunction._update_xc                 C   s*   |  | | js| j|| _d| _| jS ro   )r   rQ   r   r   r+   ru   r%   r%   r&   r#   f  s
   
zLinearVectorFunction.func                 C   s   |  | | jS r)   )r   r   ru   r%   r%   r&   r   m  s   
zLinearVectorFunction.jacc                 C   s   |  | || _| jS r)   )r   r   rD   r   r%   r%   r&   r@   q  s   
zLinearVectorFunction.hessN)	rx   ry   rz   r{   rm   r   r#   r   r@   r%   r%   r%   r&   r   ;  s    r   c                       s    e Zd ZdZ fddZ  ZS )IdentityVectorFunctionzIdentity vector function and its derivatives.

    The Jacobian is the identity matrix, returned as a dense array when
    `sparse_jacobian=False` and as a csr matrix otherwise. The Hessian is
    identically zero and it is returned as a csr matrix.
    c                    sJ   t |}|s
|d u rtj|dd}d}nt|}d}t ||| d S )Ncsr)formatTF)lenr=   eyer   superrm   )r$   rh   r   r`   r   	__class__r%   r&   rm   ~  s   
zIdentityVectorFunction.__init__)rx   ry   rz   r{   rm   __classcell__r%   r%   r   r&   r   w  s    r   )numpyr   scipy.sparsesparser=   _numdiffr   r   _hessian_update_strategyr   scipy.sparse.linalgr   scipy._lib._array_apir   r   rZ   r
   r|   r   r   r%   r%   r%   r&   <module>   s      #  <