
    Џkh:                         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y)    N   )_RichResult_call_callback_maybe_halt)array_namespacexp_sizexp_result_typec           	         t        |      }|t        | n|}t        |d|d} |j                  g || }|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 )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xpdtyper   )shapefuncc                V    dt              t        |      z
  z  } || |   g|i |S )N)r   )len)xr   r   argskwargsifshapes         d/var/www/teggl/fontify/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.)r   copyr	   )r   )r   r   r   broadcast_arraysasarrayr   npbroadcast_shapesbroadcast_tolowerall
ValueErrorresult_typer   isdtypereshape)r   xsr   
complex_okpreserve_shaper   nxxatxasr   fsr   argmessagefshapes_equalxfatr   s                    @r   _initializer7      s   b 
RB!#"	B "Tb
9C
"


)r
)D
)C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..I 
0	1 5< 2 2 
<	; 
,	+JsB   I'II*I  I%I*I/=I4I9=I>*Jc           
         |t        d      d}t        j                  |      }|j                  |      }|D ci c]  \  }}||j	                  ||       }}}|j	                  ||j
                        |d<   |j                  ||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t-        j.                  | j0                        dd j3                  |rt4        nt6              | _        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`. 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.Fr   successstatusnitnfevTr   )r   r   r   r	   )NotImplementedErrormathprodarangezerosboolfullr!   _EINPROGRESSint32r   r   _check_termination_prepare_resultr   r;   r   ndimr   appendr*   r<   xpxatr:   set
_ECALLBACK	_ECONVERR)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   _looprb      sI   R 
z!"455L 5!JYYz"FAOPA288Je844PHP((:RWW(=HYRZZ-ERXXVHX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 &&%a(,,<ZYWDK4nfe+^RA Aw Qs   M7c           	      8    ||       }|j                  |      r{t        | ||||||       |r||   }| }||   }|sY| j                         D ]$  \  }	}
|	dv rt        |
dd      dkD  r|
|   n|
| |	<   & | j                  D cg c]  }||   	 c}| _        |S c c}w )N>   nr   rH   r   )any_update_activeitemsgetattrr   )rO   r]   rW   rZ   rT   r-   r   stopproceedkeyvalr2   s               r   rF   rF     s    
 T"D	vvd| 	tS.&$PRS<D% JJL QS-',3C,Ca,GCLSS		Q
 26;#W;DIM <s   Bc                    |D ci c]  \  }}|| |    }	}}| j                   dk(  |	d<   ||r|j                  |      }
t        j                  |
      |   j	                  d      }
|
|z  }
|	j                         D ]I  \  }}t        |dd      dkD  r||
   n|}t        j                  ||         |
   j	                  |      ||<   K y ||   }
|	j                         D ]I  \  }}t        |dd      dkD  r||   n|}t        j                  ||         |
   j	                  |      ||<   K y |	j                         D ]I  \  }}|rt        |dd      dkD  r||   }t        j                  ||         |   j	                  |      ||<   K y c c}}w )Nr   r9   TrH   )r:   
zeros_likerJ   rK   rL   rg   rh   )rO   r]   rW   rZ   maskr-   r   key1key2update_dictactive_maskrk   rl   s                r   rf   rf   .  s   
 7EE
d4d#EKE![[A-K	---K&&-f599$?K%,K'--/ BS*1#vq*AA*Ec+&366#c(+K8<<SACB !,K'--/ BS#*3#:Q#>c$iC66#c(+K8<<SACB $))+ 	9HC'#vq"9A"=&kvvc#h'/33C8CH	9# Fs   F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   rf   rg   r*   rH   r   )rO   r]   rW   rZ   r   rV   r-   r   rk   rl   r^   r   r[   s                r   rG   rG   J  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)FNN)F)r>   numpyr"   _utilr   r   
_array_apir   r   r   scipy._lib.array_api_extra_libarray_api_extrarJ   	_ESIGNERRrN   
_EVALUEERRrM   
_EINPUTERR_ECONVERGEDrD   r7   rb   rF   rf   rG   ru   r   r   <module>r      sd      9 @ @ ( (		


`/J @EMA`<98r   