o
    h;                     @   s~   d dl Z d dlZddlmZmZ ddlmZmZ dZ	dZ
dZdZd	Zd ZdZdddZ	
dddZdd Zdd Zdd ZdS )    N   )_RichResult_call_callback_maybe_halt)array_namespacexp_sizeFc                    s  t |}du rt| njg | R  }jdd |D  dr.djn|d| ||d } fdd|D } fdd|D }|d j|d j|rd	fd
d
t	fdd|D }fdd D  d}	|durd|	
  }	fdd|D }
t|
st|	jdd |D g  |sdstdfdd|D }fdd|D }fdd|D }fdd|D }fdd D  || fS )a  Initialize abscissa, function, and args arrays for elementwise function

    Parameters
    ----------
    func : callable
        An elementwise function with signature

            func(x: ndarray, *args) -> ndarray

        where each element of ``x`` is a finite real and ``args`` is a tuple,
        which may contain an arbitrary number of arrays that are broadcastable
        with ``x``.
    xs : tuple of arrays
        Finite real abscissa arrays. Must be broadcastable.
    args : tuple, optional
        Additional positional arguments to be passed to `func`.
    preserve_shape : bool, default:False
        When ``preserve_shape=False`` (default), `func` may be passed
        arguments of any shape; `_scalar_optimization_loop` is permitted
        to reshape and compress arguments at will. When
        ``preserve_shape=False``, arguments passed to `func` must have shape
        `shape` or ``shape + (n,)``, where ``n`` is any integer.
    xp : namespace
        Namespace of array arguments in `xs`.

    Returns
    -------
    xs, fs, args : tuple of arrays
        Broadcasted, writeable, 1D abscissa and function value arrays (or
        NumPy floats, if appropriate). The dtypes of the `xs` and `fs` are
        `xfat`; the dtype of the `args` are unchanged.
    shape : tuple of ints
        Original shape of broadcasted arrays.
    xfat : NumPy dtype
        Result dtype of abscissae, function values, and args determined using
        `np.result_type`, except integer types are promoted to `np.float64`.

    Raises
    ------
    ValueError
        If the result dtype is not that of a real scalar

    Notes
    -----
    Useful for initializing the input of SciPy functions that accept
    an elementwise callable, abscissae, and arguments; e.g.
    `scipy.optimize._chandrupatla`.
    Nc                 S      g | ]}|j qS  dtype).0xar   r   \/var/www/vscode/kcb/lib/python3.10/site-packages/scipy/_lib/_elementwise_iterative_method.py
<listcomp>V       z_initialize.<locals>.<listcomp>integralg      ?c                    s   g | ]	}j | d qS r   asarrayr   x)xatxpr   r   r   Y       c                    s"   g | ]} |g R  qS r   r   r   )argsfuncr   r   r   r   Z      " r   )shaper   c                   s.   dt  t |  }|| | g|R i |S )N)r   )len)r   r!   r   r   kwargsi)fshaper   r   r   `   s   z_initialize.<locals>.funcc                       g | ]} | qS r   broadcast_tor   r!   r   r   r   r   d       c                    r&   r   r'   r   argr)   r   r   r   e   r*   zpThe shape of the array returned by `func` must be the same as the broadcasted shape of `x` and all other `args`.zWhen `preserve_shape=False`, c                    s   g | ]}|j  kqS r   r!   r   fr-   r   r   r   k   s    c                 S   r   r   r   r.   r   r   r   r   r   r   zreal floatingz3Abscissae and function output must be real numbers.c                       g | ]
}j | d dqS T)r   copyr   r   xfatr   r   r   r   u       c                    r0   r1   r   r.   r3   r   r   r   v   r5   c                       g | ]}  |d qS r   reshaper   r   r   r   r   z   r*   c                    r6   r7   r9   r.   r;   r   r   r   {   r*   c                    s"   g | ]}   j|d ddqS )T)r2   r8   )r:   r   r+   r;   r   r   r   |   r    )r"   r   broadcast_arraysresult_typeisdtyper   r   r!   npbroadcast_shapeslowerall
ValueError)r   xsr   
complex_okpreserve_shaper   nxxasfsmessageshapes_equalr   )r   r%   r   r!   r   r4   r   r   _initialize   s<   1

rL   c              	      s  du rt dd}t|} fdd|D }jjd|d< jtj	d|d< jj	d|d	< jj	d|d
< t
|}|| _t| ||||	|}|durrt| ||||||}t||rrd}| j|k r<t|r<|s<r<|| }| jr| jd j|jkrg }| jD ]}|j|j }|jd|  }||| q|| _|j}|r||d }||g| jR  }j| d}|r߈||}||}|  j|jdkrdn|jd 7  _||||  |  jd7  _t| ||||	|}|dur t| ||||||}t||r d}nt|dkr(n|
|  | j|k r<t|r<|s<s|rAtnt| jdd< t| ||||||S )a  Main loop of a vectorized scalar optimization algorithm

    Parameters
    ----------
    work : _RichResult
        All variables that need to be retained between iterations. Must
        contain attributes `nit`, `nfev`, and `success`. All arrays are
        subject to being "compressed" if `preserve_shape is False`; nest
        arrays that should not be compressed inside another object (e.g.
        `dict` or `_RichResult`).
    callback : callable
        User-specified callback function
    shape : tuple of ints
        The shape of all output arrays
    maxiter :
        Maximum number of iterations of the algorithm
    func : callable
        The user-specified callable that is being optimized or solved
    args : tuple
        Additional positional arguments to be passed to `func`.
    dtype : NumPy dtype
        The common dtype of all abscissae and function values
    pre_func_eval : callable
        A function that accepts `work` and returns `x`, the active elements
        of `x` at which `func` will be evaluated. May modify attributes
        of `work` with any algorithmic steps that need to happen
         at the beginning of an iteration, before `func` is evaluated,
    post_func_eval : callable
        A function that accepts `x`, `func(x)`, and `work`. May modify
        attributes of `work` with any algorithmic steps that need to happen
         in the middle of an iteration, after `func` is evaluated but before
         the termination check.
    check_termination : callable
        A function that accepts `work` and returns `stop`, a boolean array
        indicating which of the active elements have met a termination
        condition.
    post_termination_check : callable
        A function that accepts `work`. May modify `work` with any algorithmic
        steps that need to happen after the termination check and before the
        end of the iteration.
    customize_result : callable
        A function that accepts `res` and `shape` and returns `shape`. May
        modify `res` (in-place) according to preferences (e.g. rearrange
        elements between attributes) and modify `shape` if needed.
    res_work_pairs : list of (str, str)
        Identifies correspondence between attributes of `res` and attributes
        of `work`; i.e., attributes of active elements of `work` will be
        copied to the appropriate indices of `res` when appropriate. The order
        determines the order in which _RichResult attributes will be
        pretty-printed.
    preserve_shape : bool, default: False
        Whether to compress the attributes of `work` (to avoid unnecessary
        computation on elements that have already converged).

    Returns
    -------
    res : _RichResult
        The final result object

    Notes
    -----
    Besides providing structure, this framework provides several important
    services for a vectorized optimization algorithm.

    - It handles common tasks involving iteration count, function evaluation
      count, a user-specified callback, and associated termination conditions.
    - It compresses the attributes of `work` to eliminate unnecessary
      computation on elements that have already converged.

    NzMust provide xp.Fc                    s    i | ]\}}|j  d qS r   )zerosr   r$   jr   
n_elementsr   r   r   
<dictcomp>   s     z_loop.<locals>.<dictcomp>r   successstatusnitnfevTr   )r   r8   r   r   )NotImplementedErrormathprodarangerM   boolfullr   _EINPROGRESSint32r   r   _check_termination_prepare_resultr   rU   r   ndimr!   appendr:   rV   
_ECALLBACK	_ECONVERRrT   )workcallbackr!   maxiterr   r   r   pre_func_evalpost_func_evalcheck_terminationpost_termination_checkcustomize_resultres_work_pairsr   rF   cb_terminateactiveres_dictrestempr   r,   
n_new_dims	new_shapex_shaper/   r   rP   r   _loop   sv   I



"
"

 )rv   c           
         s   || }| |rSt| |||||| |r|| }|  |  }|sS|  D ]!\}}	|dkr/q&z|	  | |< W q& tttfyG   |	| |< Y q&w  fdd| jD | _|S )Nr   c                    s   g | ]}|  qS r   r   r+   proceedr   r   r   -      z&_check_termination.<locals>.<listcomp>)any_update_activeitems
IndexError	TypeErrorKeyErrorr   )
re   rq   rm   ro   rj   rF   r   stopkeyvalr   rw   r   r_     s$   
r_   c                    s6   fdd|D } j dk|d< |d uru|rJ||}d||< ||@ }| D ] \}	}
z
|
| ||	 |< W q' tttfyG   |
||	 |< Y q'w d S || }| D ] \}	}
z
|
| ||	 |< W qR tttfyr   |
||	 |< Y qRw d S | D ]\}	}
|rz|
| }
W n tttfy   Y nw |
||	 |< qyd S )Nc                    s   i | ]	\}}| | qS r   r   )r   key1key2re   r   r   rR   7  r   z"_update_active.<locals>.<dictcomp>r   rS   r   )rT   
zeros_liker|   r}   r~   r   )re   rq   rm   ro   maskrF   r   update_dictactive_maskr   r   r   r   r   r{   2  s>   
r{   c                 C   s   |  }t| |||d || |||}| D ]\}}	||	|}
|
jdkr*|
d n|
||< qdgdd |D  |d< tdi |S )Nr   r   rS   c                 S   s   g | ]\}}|qS r   r   rN   r   r   r   r   d  ry   z#_prepare_result.<locals>.<listcomp>_order_keys)r2   r{   r|   r:   ra   r   )re   rq   rm   ro   r!   rl   rF   r   r   r   rr   r   r   r   r`   U  s   
r`   )FNN)F)rX   numpyr?   _utilr   r   
_array_apir   r   	_ESIGNERRrd   
_EVALUEERRrc   
_EINPUTERR_ECONVERGEDr]   rL   rv   r_   r{   r`   r   r   r   r   <module>   s$   
f
 "#