
    S_f4                     X    d dl ZddlmZm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_haltc           	         t        |      }t        j                  g || }t        j                  |D cg c]  }|j                   c} }t        j
                  |t        j                        rt        j                  n|}|d| ||d }}|D 	cg c]  }	|	j                  |d      d    }}	|D 	cg c]  }	t        j                   | |	g|         }
}	|d   j                  }|
d   j                  |re|| dfd
} t        j                  |      }|D 	cg c]  }	t        j                  |	|       }}	|D cg c]  }t        j                  ||       }}d}|d	|j                          }|
D cg c]  }|j                  |k(   }}t        j                  |      st        |      t        j                  |
D cg c]  }|j                   c}|gz    }|s/t        j
                  |t        j                         st        d
      |D 	cg c]  }	|	j                  |d      d    }}	|
D cg c]  }|j                  |d      d    }
}|D 	cg c]  }	|	j#                          }}	|
D cg c]  }|j#                          }
}|D cg c]  }|j%                          }}| ||
|||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`.
    NF)copy r   )shapefuncc                V    dt              t        |      z
  z  } || |   g|i |S )N)r   )len)xr   r   argskwargsifshapes         Hlib/python3.12/site-packages/scipy/_lib/_elementwise_iterative_method.pyr   z_initialize.<locals>.funcY   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`, z3Abscissae and function output must be real numbers.T)r   npbroadcast_arraysresult_typedtype
issubdtypeintegerfloat64astypeasarrayr   broadcast_shapesbroadcast_tolowerall
ValueErrorfloatingravelflatten)r   xsr   
complex_okpreserve_shapenxxasxaxatr   fsr   argmessagefshapes_equalxfatr   s                    @r   _initializer6      s   ^ 
RB 


)r
)D
)C
..c22882
3Cc2::6"**CC3BxRSB13	4A!((3U(
#B
'	4B	4.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66,!!
 >>b1QWW1SE9;DbmmD"++>NOO13	4A!((4d(
#B
'	4B	413	4A!((4d(
#B
'	4B	4  	 !'')	 B	 	 !'')	 B	 %)*cCKKM*D*Rud**O 3 
5	1 5< 2 2 
5	4 
!	 *sG   J6J;5#K K K
:KKK8KK#8K(K-c                    d}t        t        j                  |            }t        j                  |      }|D ci c]  \  }}|t        j                  ||       }}}t        j                  |t
              |d<   t        j                  |t              |d<   t        j                  |t               |d<   t        j                  |t               |d<   t        |      }|| _	        t        | ||||	|      }|t        | ||||||      }t        ||      rd}| j                  |k  r|j                  r|s|r ||       }| j                  r| j                  d	   j                  |j                  k7  rxt        j                  |j                  t        j                         }| j                  D cg c].  }t        j"                  |t%        ||j                  d             0 c}| _	        |j&                  }|r|j)                  |d
z         } ||g| j                   }t        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}n9|j                  d	k(  rn) |
|        | j                  |k  r|j                  r|s|r|rt.        nt0        | j2                  dd t        | ||||||      S c c}}w 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.

    F)r   successstatusnitnfevNTr   )r   r   r   )intr   prodarangezerosboolfull_EINPROGRESSr   r   _check_termination_prepare_resultr   r:   sizendimint64expand_dimstupler   reshaper    r;   
_ECALLBACK	_ECONVERRr9   )workcallbackr   maxiterr   r   r   pre_func_evalpost_func_evalcheck_terminationpost_termination_checkcustomize_resultres_work_pairsr+   cb_terminate
n_elementsactiver   jres_dictrestempr   dimsr1   x_shaper3   s                              r   _loopr_   y   s   F L RWWU^$JYYz"FAOPA288Je44PHP((:T:HY\:HXhhz5HUOxx
#6HV
h
CDIc>6 1>CF tS.&%/A$Xt4L
((W
\j$991**aff4 99QVV2884D$(II/  U4	?-CD /DI ''		%%-(ATYYJJq&		'"A		'"A		!&&A+Q1772;6	q!T"A#D#~v$5~G "4nfe#3^ED(48#;;!t$I ((W
\jL $0ZYDKKN4nfe+^= =q Q2/s   "M43Mc                 H    ||       }t        j                  |      rt        | |||||       |r||   }| }||   }|s^| j                         D ])  \  }}	t	        |	t         j
                        r|	|   n|	| |<   + | j                  D 
cg c]  }
|
|   	 c}
| _        |S c c}
w )N)r   any_update_activeitems
isinstancendarrayr   )rM   r[   rU   rX   rR   r+   stopproceedkeyvalr1   s              r   rC   rC      s    
 T"D	vvd| 	tS.&$O<D% JJL QS,6sBJJ,GCLSS	Q15;#W;DIM <s   	Bc                 $   |D ci c]  \  }}|| |    }}}| j                   dk(  |d<   ||r]t        j                  |      }	d|	|<   |	|z  }	|j                         D ]*  \  }
}t        j                  |      dkD  r||	   n|||
   |	<   , y ||   }	|j                         D ]*  \  }
}t        j                  |      dkD  r||   n|||
   |	<   , y |j                         D ])  \  }
}|rt        j
                  |      s||   }|||
   |<   + y c c}}w )Nr   r8   r   )r9   r   
zeros_likerc   rE   isscalar)rM   r[   rU   rX   maskr+   key1key2update_dictactive_maskrh   ri   s               r   rb   rb     s<   
 7EE
d4d#EKE![[A-K	---K"#K%,K'--/ 3S=?WWS\A=M[)9.1 C%3 !,K'--/ OS57WWS\A5ED	3C%O $))+ 	#HCbkk#&6&k"CHV	#! Fs   Dc                    |j                         }t        | |||d |        |||      }|j                         D ]!  \  }}t        j                  ||      d   ||<   # dg|D 	
cg c]  \  }	}
|		 c}
}	z   |d<   t        di |S c c}
}	w )Nr   r8   _order_keys)r   rb   rc   r   rJ   r   )rM   r[   rU   rX   r   rT   r+   rh   ri   r   rY   s              r   rD   rD   3  s    
 ((*C4nfdNKS%(EIIK .S::c5)"-C.#n'Eda'EEC (Fs   %B)FN)F)numpyr   _utilr   r   	_ESIGNERRrL   
_EVALUEERRrK   _ECONVERGEDrB   r6   r_   rC   rb   rD   r   r   r   <module>ry      sN     9		

^+F <AA=H6#6r   