a
    ijB                     @   s,  d Z ddlZddlZddlZddlZddlmZmZmZm	Z	m
Z
mZmZ ddlZddlZG dd dejZG dd dejZejdejd	ejd
ejdiZejddG dd dZG dd dejZG dd deZdde ddddddejdddfejeejgejf ee	ej  eeejejgejf  eeeeeee eee f ee
 eeee gdf  e!eejee f dddZ"d&eejgejf ejejej#e eeej  eeje f dddZ$d'eejgejf ejejejej#e eeej  ee
 ee% e d 
d!d"Z&d(ejeej#ee
 d#d$d%Z'dS ))z5Nonlinear Least Squares minimization with box bounds.    N)CallableListOptionalSequenceTextIOTupleUnionc                   @   s   e Zd ZdZdZdZdZdS )	Verbosityr            N)__name__
__module____qualname__SILENTZFINALITERFULLITER r   r   O/home/ghrups/robot-bench/.venv/lib64/python3.9/site-packages/mujoco/minimize.pyr	      s   r	   c                   @   s,   e Zd Ze Ze Ze Ze ZdS )StatusN)	r   r   r   enumautoFACTORIZATION_FAILEDNO_IMPROVEMENTMAX_ITERDX_TOLr   r   r   r   r   "   s   r   zfactorization failed.zinsufficient reduction.zmaximum iterations reached.znorm(dx) < tol.T)frozenc                   @   sp   e Zd ZU dZejed< ejed< ejed< ejed< dZe	ej ed< dZ
e	ej ed< dZe	ej ed	< dS )
IterLoga"  Log of a single iteration of the non-linear least-squares solver.

  Attributes:
    candidate: Value of the decision variable at the beginning this iteration.
    objective: Value of the objective at the candidate.
    reduction: Reduction of the objective during this iteration.
    regularizer: Value of the regularizer used for this iteration.
    residual: Optional value of the residual at the candidate.
    jacobian: Optional value of the Jacobian at the candidate.
    step: Optional change in decision variable during this iteration.
  	candidate	objective	reductionregularizerNresidualjacobianstep)r   r   r   __doc__npndarray__annotations__float64r"   r   r#   r$   r   r   r   r   r   1   s   




r   c                   @   sD   e Zd ZdZejejejdddZ	ejejejdddZ
dS )	Normah  Abstract interface for norm functions, measuring the magnitude of vectors.

  Key Concepts:

  * Norm Value: The value of the norm for a given input vector.
  * Gradient and Hessian: The gradient (first derivative) and Hessian (second
    derivative) of the norm function with respect to the input vector.

  Subclasses Must Implement:

  * `value(self, r: np.ndarray)`: Computes and returns the norm value for the
     input vector `r`.
  * `grad_hess(self, r: np.ndarray, proj: np.ndarray)`: Computes and returns
     both  the gradient and Hessian of the norm at `r`, projected onto `proj`.
     The reason we ask the user to perform the projection themselves is that
     norm Hessians are often large and sparse, and the "sandwich" projection
     operator `proj.T @ hess @ proj` can be computed efficiently by taking the
     specific norm structure into account.
  )rreturnc                 C   s   dS )z@Returns the value of the norm at the input vector `y = norm(r)`.Nr   selfr+   r   r   r   value]   s    z
Norm.valuer+   projc                 C   s   dS )aZ  Computes the projected gradient and Hessian of the norm at `r`.

    Args:
        r: A NumPy column vector (nr x 1).
        proj: A pre-computed projection matrix (nr x nx).

    Returns:
        A tuple containing:
            * Projected gradient: proj.T @ (d_norm/d_r).
            * Projected Hessian: proj.T @ (d^2_norm/d_r^2) @ proj.
    Nr   )r.   r+   r1   r   r   r   	grad_hessb   s    zNorm.grad_hessN)r   r   r   r%   abcabstractmethodr&   r'   r)   r/   r2   r   r   r   r   r*   H   s
   r*   c                   @   s4   e Zd ZdZejdddZejejdddZdS )		Quadraticz%Implementation of the quadratic norm.)r+   c                 C   s   d|j |   S )z"Returns the quadratic norm of `r`.      ?)Titemr-   r   r   r   r/   u   s    zQuadratic.valuer0   c                 C   s   |j | }|j | }||fS )aJ  Computes the projected gradient and Hessian of the quadratic norm at `r`.

    Args:
        r: A NumPy column vector (nr x 1).
        proj: A pre-computed projection matrix (nr x nx).

    Returns:
        A tuple containing:
            * Projected gradient: `proj.T @ r`.
            * Projected Hessian: `proj.T @ proj`.
    )r7   )r.   r+   r1   gradhessr   r   r   r2   y   s    

zQuadratic.grad_hessN)r   r   r   r%   r&   r'   r/   r2   r   r   r   r   r5   r   s   r5   gư>g    חAg&$?d   F)x0r"   boundsr#   normepsmu_minmu_max	mu_factortolmax_iterverboseoutputiter_callbackcheck_derivativesr,   c           <         s$  t   }t|j}d}tj}d}| j}| tj	|df}t
|df}t
|df}t
||d f}t|}td}d}g }d}d}d}d} dkrtd fdd} fd	d
} |du rdnt|}|durt|dkrtd|d j|ks|d j|krtdtt|d rHtt|d sPtdt|d |d k sptd|d 	|d|d< |d 	|d|d< tj||d |d |d tt|stdt   }!||}"|"}#|t   |! 7 }|d7 }|"jtjkrtdt|
D ]}|tjkr. q||"}$t   }!|du rrt|||"|||\}%}|t   |! 7 }nH|||"}%|t   |! 7 }|d7 }|dkr|rt|||"|%||||}|dkr|rt|tst|"||| ||"|%\}&}'|du rdn
|d | }(|du rdn
|d | })d}*d}+|*dk r4d},|,st||d|'|t|  |&|(|)}-|-dkrxd},n"||krtj}qn| |\}}q>|tjkrq4|| }t   }!||}#|t   |! 7 }|d7 }||#}.|$|. }+|+||&j|    }*|*dk r0||kr$tj}q4| |\}}q0|tjkrF q|&j| d|j |' |    }/d}0|/dkr|tj jkr|/dkrt!d|d n|/dk rt!d|d n|+|/ }0tj"#|}1|tj$jkr2|dkrt%|ntj& }2d|dd|$dd|2d d!|0d"d#|1d"d$|+d"}3t!|3|d t'||$|+|d%}4|tj(jkrbt)j*|4|"|%|d&}4|+|4 |dur~|| |1|	k rtj,} q|0d'kr|||\}}n|0d(k r| |\}}|}|#}"q||"}5td}6t'||5|6|d%}4|+|4 |dur|| |tj jkrd)| d*}3|3t-| 7 }3|3d+|5d,d-|d.7 }3|dkrh|3d/|d.7 }3t!|3|d t   | }7|7dkrd0| |7 }8|7dkrdnd1}9|7dkrd2nd3}:d4|9|7 d5|: }3|3d6|8d5d77 }3|dkrd0| |7 };|3d8|;d5d77 }3t!|3|d |	| j.|fS )9a  Nonlinear Least Squares minimization with box bounds.

  Args:
    x0: Initial guess
    residual: Vectorized function returning the residual for 1 or more points.
    bounds: Optional pair of lower and upper bounds on the solution.
    jacobian: Optional function that returns Jacobian of the residual at a given
      point and residual. If not given, `residual` will be finite-differenced.
    norm: Norm object returning norm scalar or its projected gradient and
      Hessian. See Norm class for detailed documentation.
    eps: Perurbation used for automatic finite-differencing.
    mu_min: Minimum value of the regularizer.
    mu_max: Maximum value of the regularizer.
    mu_factor: Factor for increasing or decreasing the regularizer.
    tol: Termination tolerance on the step size.
    max_iter: Maximum number of iterations.
    verbose: Verbosity level.
    output: Optional file or StringIO to which to print messages.
    iter_callback: Optional iteration callback, takes trace argument.
    check_derivatives: Compare user-defined Jacobian and norm against fin-diff.

  Returns:
    x: best solution found
    trace: sequence of solution iterates.
  g{Gz?r   r
              zmu_factor must be > 1.c                    s8   d  d|  }| | k r dn| | } |d7 }| |fS )Nr
   r   rJ   r   )mun_reducZdmurB   r@   r   r   decrease_mu   s    z"least_squares.<locals>.decrease_muc                    s   t  |  } d}| |fS )Nr   )max)rK   rL   rM   r   r   increase_mu   s    z"least_squares.<locals>.increase_muNr   zbounds must have 2 elements.z%bounds must have the same size as x0.zbounds must be finite.z)bounds[0] must be smaller than bounds[1].)outzx0 must be finite.z-residual function must return float64 arrays.FTr6   z-Zero expected reduction: exact minimum found?filez.Negative expected reduction: should not occur.ziter: z<3dz  y: z<9.4gz  log10mu: z>4.1fz	  ratio: z<7.2gz  dx: z  reduction: )r   r   r    r!   )r"   r#   r$   g      ?g      ?zTerminated after z iterations: z y: <.4gz, Residual evals: dz, Jacobian evals: r;   i  smsztotal time z<.1fz of which residual %z
 Jacobian )/timer	   r/   r   r   sizeZastyper&   r)   ZreshapeZzeros
ValueErrorlistlenallisfiniteZclipZdtyperangejacobian_fdcheck_jacobian
isinstancer5   
check_normr2   mujocoZ	mju_boxQPeyer   r7   r8   r   r   printlinalgr>   r   log10infr   r   dataclassesreplaceappendr   _STATUS_MESSAGEshape)<r<   r"   r=   r#   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   Zt_start_totalZ	armijo_c1statusinxZxnewZdxZscratchrK   rL   tracen_resZn_jacZt_resZt_jacrN   rP   Zt_startr+   Zrnewyjacr9   r:   ZdlowerZdupperZarmijor    ZfactorizableZn_freeZynewZexpected_reductionZreduction_ratioZdx_normZlogmumessagelogZyfinalredZ
time_totalZ	r_percentZ
time_scaleZ
time_unitsZjac_percentr   rM   r   least_squares   s4   *



 ,








"














r|   )r"   rt   r+   r?   rv   r=   r,   c                 C   sx   |j }|du r|t| }n,d|d |d   }t||k| | }|t| }	| |	}
|
| | }||| fS )a  Finite-difference Jacobian of a residual function.

  Args:
    residual: vectorized function that returns the residual of a vector array.
    x: point at which to evaluate the Jacobian.
    r: residual at x.
    eps: finite-difference step size.
    n_res: number or residual evaluations so far.
    bounds: optional pair of lower and upper bounds.

  Returns:
    jac: Jacobian of the residual at x.
    n_res: updated number of residual evaluations (add x.size).
  Nr6   r
   r   )r[   r&   ZoneswhereflattenZdiag)r"   rt   r+   r?   rv   r=   rs   Zeps_vecmidxhZrhrx   r   r   r   rb     s    rb   Jacobian)
r"   rt   r+   rx   r?   rv   r=   rF   namer,   c	                 C   s~   t | |||||\}	}t| t|	  d }
t||	 |
 }t|dkrftd| dtd| d|d |S )aC  Check user-provided Jacobian against internal finite-differencing.

  Args:
    residual: vectorized function that returns the residual of a vector array.
    x: point at which the r and jac were evaluated.
    r: residual at x.
    jac: Jacobian at x.
    eps: finite-difference step size.
    n_res: number or residual evaluations so far.
    bounds: optional pair of lower and upper bounds.
    output: Optional file or StringIO to which to print messages.
    name: Optional name of the function being tested.

  Returns:
    n_res: updated number of residual evaluations.
  g:0yE>gh㈵>zUser-provided zC does not match finite-differences to a relative tolerance of 1e-5.z matches finite-differences.rS   )rb   r&   abssumanyr\   rh   )r"   rt   r+   rx   r?   rv   r=   rF   r   Zjac_fddenomZrel_diffr   r   r   rc     s     
rc   )r+   r>   r?   rF   c           
   
      s   t | }t | j |  \}}t ||jsBtdt 	t j
|dk rzt t j
|}td|dfdd}t|| ||j|dd|d	  fd	d
}	t|	| |||dd|d	 dS )a3  Check user-provided norm against internal finite-differencing.

  Args:
    r: residual vector.
    norm: Norm function returning either the norm scalar or its gradient and
      Gauss-Newton Hessian.
    eps: finite-difference step size.
    output: Optional file or StringIO to which to print messages.
  z,User-provided norm Hessian is not symmetric.r   zKUser-provided norm Hessian is not positive definite. Minimum eigenvalue is rU   c                    s(    fddt  jd D }t|S )Nc                    s0   g | ](}t  d d ||d f qS )Nr
   )r&   
atleast_2dr/   .0rr   )r>   vr   r   
<listcomp>  s   z0check_norm.<locals>.norm_vec.<locals>.<listcomp>r
   ra   rp   r&   Zhstack)r   Znorms)r>   r   r   norm_vec  s    zcheck_norm.<locals>.norm_vecNznorm gradientc                    s*    fddt  jd D }t|S )Nc              	      s0   g | ](} d d ||d f  d qS )Nr
   r   )r2   r   )rg   r>   r   r   r   r     s   z0check_norm.<locals>.grad_vec.<locals>.<listcomp>r
   r   )r   Z	gradientsrg   r>   r   r   grad_vec  s    zcheck_norm.<locals>.grad_vecznorm Hessian)r&   r   r/   rg   r[   r2   Zallcloser7   r\   r   ri   Zeigvalsminrc   )
r+   r>   r?   rF   rs   Zn_gZn_hZh_minr   r   r   r   r   re     s     re   )N)NNr   )N)(r%   r3   rl   r   rZ   typingr   r   r   r   r   r   r   rf   numpyr&   Enumr	   r   r   r   r   r   ro   	dataclassr   ABCr*   r5   r   r'   floatintboolr|   r)   rb   strrc   re   r   r   r   r   <module>   s   $
*
   )   + 