
    Ti:                         d dl Z d dlZddlmZmZ ddlmZmZm	Z	 d dl
mc 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dS )    N   )_RichResult_call_callback_maybe_halt)array_namespacexp_sizexp_result_typeFc                 F    t          |          }	t          | nt          |dd j        g |R  }|d|         ||d         c}fd|D             } fd|D             }|d         j        |d         j        |r< dfd
 t          j                  fd	|D             }fd
D             d}	|d|	                                 }	fd|D             }
t          |
          st          |	           j
        d |D             gz    |s%                    d          st          d          fd|D             }fd|D             }fd|D             }fd|D             }f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`.
    NT)force_floatingxpc                 >    g | ]}                     |           S dtypeasarray).0xxatr   s     /var/www/development/aibuddy-work/election-extract/venv/lib/python3.11/site-packages/scipy/_lib/_elementwise_iterative_method.py
<listcomp>z_initialize.<locals>.<listcomp>Y   s)    	/	/	/q"**Qc*
"
"	/	/	/    c                 H    g | ]}                      |gR            S  r   )r   r   argsfuncr   s     r   r   z_initialize.<locals>.<listcomp>Z   s3    	1	1	1"**TT!^d^^^
$
$	1	1	1r   r   )shaper    c                l    dt                    t          |          z
  z  } || |         g|R i |S )N)r   )len)r   r!   r    r   kwargsifshapes         r   r    z_initialize.<locals>.func`   sB    c&kkCJJ./A4!.t...v...r   c                 <    g | ]}                     |          S r   broadcast_to)r   r   r!   r   s     r   r   z_initialize.<locals>.<listcomp>d   s'    444Abooa''444r   c                 <    g | ]}                     |          S r   r(   )r   argr!   r   s     r   r   z_initialize.<locals>.<listcomp>e   s'    <<<U++<<<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                 &    g | ]}|j         k    S r   )r!   )r   fr!   s     r   r   z_initialize.<locals>.<listcomp>k   s     111AGu$111r   c                     g | ]	}|j         
S r   r   )r   r-   s     r   r   z_initialize.<locals>.<listcomp>r   s    111QW111r   zreal floatingz3Abscissae and function output must be real numbers.c                 @    g | ]}                     |d           S T)r   copyr   )r   r   xfatr   s     r   r   z_initialize.<locals>.<listcomp>u   +    	;	;	;1"**Qd*
.
.	;	;	;r   c                 @    g | ]}                     |d           S r0   r   )r   r-   r2   r   s     r   r   z_initialize.<locals>.<listcomp>v   r3   r   c                 <    g | ]}                     |d           S r	   reshape)r   r   r   s     r   r   z_initialize.<locals>.<listcomp>z   '    	+	+	+1"**Q

	+	+	+r   c                 <    g | ]}                     |d           S r6   r8   )r   r-   r   s     r   r   z_initialize.<locals>.<listcomp>{   r:   r   c                 f    g | ]-}                                         |d           d          .S )T)r1   r7   )r9   r   )r   r+   r   s     r   r   z_initialize.<locals>.<listcomp>|   s7    JJJcBJJrzz#Dz11599JJJr   )r#   r   r   broadcast_arraysr!   npbroadcast_shapeslowerall
ValueErrorresult_typeisdtype)r    xsr   
complex_okpreserve_shaper   nxxasfsmessageshapes_equalr&   r!   r   r2   s   ` `  `     @@@@r   _initializerM      s   b 
RB!#"		B "Tb
9
9
9C
"

)r
)D
)
)
)C3B3xRSSHB	/	/	/	/	/B	/	/	/B	1	1	1	1	1	1b	1	1	1BqEKEU[F =!&T 	/ 	/ 	/ 	/ 	/ 	/ 	/ #FE2244444444<<<<<t<<<DG!C'--//CC1111b111L| "!!!
 2>11b111SE9;D Pbjj?? PNOOO	;	;	;	;	;	;	;	;B	;	;	;	;	;	;	;	;B 
,	+	+	+	+	+	+B	+	+	+	+	+	+	+BJJJJTJJJDRudB..r   c           
         t          d          d}t          j        |                                        }fd|D             }                    j                  |d<                                           t                    j	                  |d<                       j	                  |d<                       j	                  |d	<   t          |          }|| _        t          | ||||	|          }|(t          | ||||||          }t          ||          rd
}| j        |k     rt!          |          r|sr ||           }| j        rs| j        d         j        |j        k    rXg }| j        D ]G}|j        |j        z
  }|j        d|z  z   }|                                        ||                     H|| _        |j        }|r                    ||dz             } ||g| j        R  }                    |          }|r,                    ||          }                    ||          }| xj        |j        dk    rdn|j        d         z  c_         ||||            | xj        dz  c_        t          | ||||	|          }|)t          | ||||||          }t          ||          rd
}n>t!          |          dk    rn* |
|            | j        |k     rt!          |          r|st-          j        | j                  dd                             |rt4          nt6                    | _        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                 F    i | ]\  }}|                                S r   )zeros)r   r%   jr   
n_elementsr   s      r   
<dictcomp>z_loop.<locals>.<dictcomp>   s/    PPPA288Je844PPPr   r   successstatusnitnfevTr   )r   r7   r   r	   )NotImplementedErrormathprodarangerP   boolfullr   _EINPROGRESSint32r   r   _check_termination_prepare_resultr   rV   r   ndimr!   appendr9   rW   xpxatrU   set
_ECALLBACK	_ECONVERR)workcallbackr!   maxiterr    r   r   pre_func_evalpost_func_evalcheck_terminationpost_termination_checkcustomize_resultres_work_pairsr   rG   cb_terminateactiveres_dictrestempr   r+   
n_new_dims	new_shapex_shaper-   rR   s         `      `            @r   _looprz      s   R 
z!"4555L 5!!JYYz""FPPPPPPPPPH((:RW(==HYRZZ-E-ERXVVHXhhzh::HUOxx
"(x;;HV
h

CDIc>6 1>2G GF tS.&%/E E$Xt44 	 L
(W



*
M$9 		1*af44 Dy 8 8Vch.
IZ7	BJJsI667777DI' 	/

1uu}..ADTYJJqJ&& 	'

1g&&A

1g&&A		!&A++QQ172;6		q!T"""A#D#~v$5~rK K "4nfe#3^RI ID(488 #6??at$$$O (W



*
R &%%aaa(,,<-VZZYWWDK4nfe+^RA A Ar   c           	      R  
  ||           }|                     |          rt          | ||||||           |r||         }| 
|
         }|sY|                                 D ],\  }}	|dv r
t          |	dd          dk    r|	
         n|	| |<   -
fd| j        D             | _        |S )N>   nr   rb   r   c                      g | ]
}|         S r   r   )r   r+   proceeds     r   r   z&_check_termination.<locals>.<listcomp>)  s    ;;;#W;;;r   )any_update_activeitemsgetattrr   )ri   ru   rq   rs   rn   rG   r   stopkeyvalr~   s             @r   r`   r`     s    
 T""D	vvd|| < 	tS.&$PRSSS 	 <D% 	< JJLL Q QS-'',3C,C,Ca,G,GCLLSS		;;;;;;;DIMr   c                      fd|D             } j         dk    |d<   |3|r|                    |          }t          j        |          |                             d          }||z  }|                                D ]Z\  }	}
t          |
dd          dk    r|
|         n|
}
t          j        ||	                   |                             |
          ||	<   [d S ||         }|                                D ]Z\  }	}
t          |
dd          dk    r|
|         n|
}
t          j        ||	                   |                             |
          ||	<   [d S |                                D ]Z\  }	}
|rt          |
dd          dk    r|
|         }
t          j        ||	                   |                             |
          ||	<   [d S )Nc                 (    i | ]\  }}||         S r   r   )r   key1key2ri   s      r   rS   z"_update_active.<locals>.<dictcomp>3  s#    EEE
d4dEEEr   r   rT   Trb   )rU   
zeros_likerd   re   rf   r   r   )ri   ru   rq   rs   maskrG   r   update_dictactive_maskr   r   s   `          r   r   r   .  s   
 FEEEnEEEK![A-K	 	B----K&--f599$??K%,K'--// B BS*1#vq*A*AA*E*Ec+&&36#c(++K8<<SAACB B !,K'--// B BS#*3#:#:Q#>#>c$iiC6#c(++K8<<SAACB B $))++ 	9 	9HC "'#vq"9"9A"="=&kvc#h''/33C88CHH	9 	9r   c           	      :   |                                 }t          | |||d ||            |||          }|                                D ]3\  }}	|                    |	|          }
|
j        dk    r|
d         n|
||<   4dgd |D             z   |d<   t          di |S )Nr   r   rT   c                     g | ]\  }}|S r   r   )r   r%   rQ   s      r   r   z#_prepare_result.<locals>.<listcomp>Y  s    'E'E'Eda'E'E'Er   _order_keys)r1   r   r   r9   rb   r   )ri   ru   rq   rs   r!   rp   rG   r   r   r   rv   s              r   ra   ra   J  s    
 ((**C4nfdNBOOOS%((EIIKK 8 8Szz#u%%#yA~~4884C#'E'En'E'E'EECr   )FNN)F)rY   numpyr>   _utilr   r   
_array_apir   r   r   scipy._lib.array_api_extra_libarray_api_extrard   	_ESIGNERRrh   
_EVALUEERRrg   
_EINPUTERR_ECONVERGEDr^   rM   rz   r`   r   ra   r   r   r   <module>r      s        9 9 9 9 9 9 9 9 @ @ @ @ @ @ @ @ @ @ ( ( ( ( ( ( ( ( (		


`/ `/ `/ `/J @EMA MA MA MA`  <9 9 98    r   