
    sg9                     t    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
Z	 ddZd Zd Zd Zy)    N   )_RichResult_call_callback_maybe_halt)array_namespacesizec           	         t        |      }t        | } |j                  g || } |j                  |D cg c]  }|j                   c} }	|j                  |	d      r|j                  d      j                  n|	}	|d| ||d }}|D 
cg c]  }
|j                  |
|	       }}
|D 
cg c]  }
|j                   | |
g|        }}
|d   j                  }|d   j                  |r]|| dfd
} t        j                  |      }|D 
cg c]  }
|j                  |
|       }}
|D cg c]  }|j                  ||       }}d}|d	|j                          }|D cg c]  }|j                  |k(   }}t        |      st        |       |j                  |D cg c]  }|j                   c}|	gz    }|s|j                  |d
      st        d      |D 
cg c]  }
|j                  |
|d       }}
|D cg c]  }|j                  ||d       }}|D 
cg c]  }
|j                  |
d       }}
|D cg c]  }|j                  |d       }}|D cg c]%  }|j                  |j                  |d      d      ' }}| ||||||fS c c}w c c}
w c c}
w c c}
w c c}w c c}w c c}w c c}
w c c}w c c}
w c c}w c c}w )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.

    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`.
    integralg      ?Ndtyper   )shapefuncc                V    dt              t        |      z
  z  } || |   g|i |S )N)r   )len)xr   r   argskwargsifshapes         [/var/www/html/venv/lib/python3.12/site-packages/scipy/_lib/_elementwise_iterative_method.pyr   z_initialize.<locals>.func]   s3    c&kCJ./A!.t.v..    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`, zreal floatingz3Abscissae and function output must be real numbers.T)r   copyr   )r   )r   r   broadcast_arraysresult_typer   isdtypeasarrayr   npbroadcast_shapesbroadcast_tolowerall
ValueErrorreshape)r   xsr   
complex_okpreserve_shapenxxpxasxaxatr   fsr   argmessagefshapes_equalxfatr   s                     @r   _initializer7      s   ^ 
RB	"	B "


)r
)D
)C
"..c22882
3C"$**S*"="**R.

3C3BxRSB,.	/q"**Qc*
"	/B	/.0	1"**T!^d^
$	1B	1qEKKEU[[F!&T 	/ ##FE2134Abooa'447;<U+<<DG!1'--/1BC.01AGGu$1L1|!!
 2>>b1QWW1SE9;Dbjj?NOO8:	;1"**Qd*
.	;B	;8:	;1"**Qd*
.	;B	; )+	+1"**Q
	+B	+(*	+1"**Q
	+B	+EIJcBJJrzz#Dz159JDJRudB..O 3 
0	1 5< 2 2 
<	; 
,	+JsG   JJ-J!J&0J+&J0$J5"J:J?$KK	"*Kc           
         |t        d      d}t        j                  |      }|j                  |      }|D ci c]  \  }}||j	                  ||       }}}|j	                  ||j
                        |d<   |j                  |t        |j                        |d<   |j	                  ||j                        |d<   |j	                  ||j                        |d<   t        |      }|| _
        t        | ||||	||      }| t        | |||||||      }t        ||      rd	}| j                  |k  rt        |      r|s|r ||       }| j                  r| j                  d
   j                   |j                   k7  rfg }| j                  D ]N  }|j                   |j                   z
  }|j"                  d|z  z   }|j%                  |j'                  ||             P || _
        |j"                  }|r|j'                  ||dz         } ||g| j                   }|j)                  ||      }|r$|j'                  ||      }|j'                  ||      }| xj*                  |j                   dk(  rdn|j"                  d   z  c_         ||||        | xj                  dz  c_        t        | ||||	||      }|!t        | |||||||      }t        ||      rd	}n7t        |      d
k(  rn( |
|        | j                  |k  rt        |      r|s|r|rt,        nt.        | j0                  dd t        | |||||||      S c c}}w )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`
    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.

    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.Fr   successstatusnitnfevTr   )r   r   r   r   )NotImplementedErrormathprodarangezerosboolfull_EINPROGRESSint32r   r   _check_termination_prepare_resultr   r;   xp_sizendimr   appendr(   r!   r<   
_ECALLBACK	_ECONVERRr:   )workcallbackr   maxiterr   r   r   pre_func_evalpost_func_evalcheck_terminationpost_termination_checkcustomize_resultres_work_pairsr-   r+   cb_terminate
n_elementsactiver   jres_dictrestempr   r2   
n_new_dims	new_shapex_shaper4   s                                r   _loopr`   }   s)   F 
z!"455L 5!JYYz"FAOPA288Je844PHP((:RWW(=HY\JHXhhzh:HUOxx
"((x;HV
h
CDIc>6 1>2GF tS.&%/E$Xt4L
((W
*$991**aff4 Dyy 8VVchh.
IIZ7	BJJsI678 DI''

1uu}.ATYYJJqJ&

1g&A

1g&A		!&&A+Q1772;6	q!T"A#D#~v$5~rK "4nfe#3^RID(48#6?at$O ((W
*R $0ZYDKKN4nfe+^RA Aw Qs   Mc           	      V    ||       }|j                  |      rkt        | ||||||       |r||   }| }||   }|sI| j                         D ]  \  }	}
|	dk(  r	 |
|   | |	<    | j                  D cg c]  }||   	 c}| _        |S # t        t        t
        f$ r |
| |	<   Y Vw xY wc c}w )Nr   )any_update_activeitems
IndexError	TypeErrorKeyErrorr   )rM   r[   rU   rX   rR   r+   r-   stopproceedkeyvalr2   s               r   rF   rF     s    
 T"D	vvd| 	tS.&$PRS<D% JJL $S &=$ #GDI$ 26;#W;DIM	 #Ix8 $ #DI$;s   B1B&B#"B#c                 L   |D ci c]  \  }}|| |    }	}}| j                   dk(  |	d<   |l|r@|j                  |      }
d|
|<   |
|z  }
|	j                         D ]  \  }}	 ||
   ||   |
<    y ||   }
|	j                         D ]  \  }}	 ||   ||   |
<    y |	j                         D ]  \  }}|r	 ||   }|||   |<    y c c}}w # t        t        t
        f$ r |||   |
<   Y w xY w# t        t        t
        f$ r |||   |
<   Y w xY w# t        t        t
        f$ r Y kw xY w)Nr   r9   r   )r:   
zeros_likerd   re   rf   rg   )rM   r[   rU   rX   maskr+   r-   key1key2update_dictactive_maskrj   rk   s                r   rc   rc   )  s   
 7EE
d4d#EKE![[A-K	---K"#K%,K'--/ 0S0,/,<CH[)0 !,K'--/ 0S0,/ICH[)0 $))+ 	#HCf+C  #CHV	#+ F #Ix8 0,/CH[)0 #Ix8 0,/CH[)0 #Ix8 s;   C!CC*2DC'&C'*D	D	D#"D#c           	      6   |j                         }t        | |||d ||        |||      }|j                         D ]0  \  }}	|j                  |	|      }
|
j                  dk(  r|
d   n|
||<   2 dg|D cg c]  \  }}|	 c}}z   |d<   t        di |S c c}}w )Nr    r9   _order_keys)r   rc   rd   r(   rI   r   )rM   r[   rU   rX   r   rT   r+   r-   rj   rk   r\   r   rY   s                r   rG   rG   L  s    
 ((*C4nfdNBOS%(EIIK 8Szz#u%#yyA~484C8
 $n'Eda'EEC (Fs   5B)FN)F)r>   numpyr"   _utilr   r   
_array_apir   r   rH   	_ESIGNERRrL   
_EVALUEERRrK   
_EINPUTERR_ECONVERGEDrD   r7   r`   rF   rc   rG   rt   r   r   <module>r}      s]      9 8		


_/H @EGATD #Fr   