11import builtins
22import collections .abc
33import functools
4+ import inspect
45import re
56import sys
67import warnings
@@ -2303,170 +2304,170 @@ def _get_vectorize_dtype(dtype):
23032304
23042305@set_module ('numpy' )
23052306class vectorize :
2306- """
2307- vectorize(pyfunc=np._NoValue, otypes=None, doc=None, excluded=None,
2308- cache=False, signature=None)
2309-
2310- Returns an object that acts like pyfunc, but takes arrays as input.
2311-
2312- Define a vectorized function which takes a nested sequence of objects or
2313- numpy arrays as inputs and returns a single numpy array or a tuple of numpy
2314- arrays. The vectorized function evaluates `pyfunc` over successive tuples
2315- of the input arrays like the python map function, except it uses the
2316- broadcasting rules of numpy.
2317-
2318- The data type of the output of `vectorized` is determined by calling
2319- the function with the first element of the input. This can be avoided
2320- by specifying the `otypes` argument.
2321-
2322- Parameters
2323- ----------
2324- pyfunc : callable, optional
2325- A python function or method.
2326- Can be omitted to produce a decorator with keyword arguments.
2327- otypes : str or list of dtypes, optional
2328- The output data type. It must be specified as either a string of
2329- typecode characters or a list of data type specifiers. There should
2330- be one data type specifier for each output.
2331- doc : str, optional
2332- The docstring for the function. If None, the docstring will be the
2333- ``pyfunc.__doc__``.
2334- excluded : set, optional
2335- Set of strings or integers representing the positional or keyword
2336- arguments for which the function will not be vectorized. These will be
2337- passed directly to `pyfunc` unmodified.
2338-
2339- cache : bool, optional
2340- If neither `otypes` nor `signature` are provided, and `cache` is ``True``, then
2341- cache the number of outputs.
2342-
2343- signature : string, optional
2344- Generalized universal function signature, e.g., ``(m,n),(n)->(m)`` for
2345- vectorized matrix-vector multiplication. If provided, ``pyfunc`` will
2346- be called with (and expected to return) arrays with shapes given by the
2347- size of corresponding core dimensions. By default, ``pyfunc`` is
2348- assumed to take scalars as input and output.
2349-
2350- Returns
2351- -------
2352- out : callable
2353- A vectorized function if ``pyfunc`` was provided,
2354- a decorator otherwise.
2355-
2356- See Also
2357- --------
2358- frompyfunc : Takes an arbitrary Python function and returns a ufunc
2359-
2360- Notes
2361- -----
2362- The `vectorize` function is provided primarily for convenience, not for
2363- performance. The implementation is essentially a for loop.
2364-
2365- If neither `otypes` nor `signature` are specified, then a call to the function with
2366- the first argument will be used to determine the number of outputs. The results of
2367- this call will be cached if `cache` is `True` to prevent calling the function
2368- twice. However, to implement the cache, the original function must be wrapped
2369- which will slow down subsequent calls, so only do this if your function is
2370- expensive.
2371-
2372- The new keyword argument interface and `excluded` argument support
2373- further degrades performance.
2374-
2375- References
2376- ----------
2377- .. [1] :doc:`/reference/c-api/generalized-ufuncs`
2378-
2379- Examples
2380- --------
2381- >>> import numpy as np
2382- >>> def myfunc(a, b):
2383- ... "Return a-b if a>b, otherwise return a+b"
2384- ... if a > b:
2385- ... return a - b
2386- ... else:
2387- ... return a + b
2388-
2389- >>> vfunc = np.vectorize(myfunc)
2390- >>> vfunc([1, 2, 3, 4], 2)
2391- array([3, 4, 1, 2])
2392-
2393- The docstring is taken from the input function to `vectorize` unless it
2394- is specified:
2395-
2396- >>> vfunc.__doc__
2397- 'Return a-b if a>b, otherwise return a+b'
2398- >>> vfunc = np.vectorize(myfunc, doc='Vectorized `myfunc`')
2399- >>> vfunc.__doc__
2400- 'Vectorized `myfunc`'
2401-
2402- The output type is determined by evaluating the first element of the input,
2403- unless it is specified:
2404-
2405- >>> out = vfunc([1, 2, 3, 4], 2)
2406- >>> type(out[0])
2407- <class 'numpy.int64'>
2408- >>> vfunc = np.vectorize(myfunc, otypes=[float])
2409- >>> out = vfunc([1, 2, 3, 4], 2)
2410- >>> type(out[0])
2411- <class 'numpy.float64'>
2412-
2413- The `excluded` argument can be used to prevent vectorizing over certain
2414- arguments. This can be useful for array-like arguments of a fixed length
2415- such as the coefficients for a polynomial as in `polyval`:
2416-
2417- >>> def mypolyval(p, x):
2418- ... _p = list(p)
2419- ... res = _p.pop(0)
2420- ... while _p:
2421- ... res = res*x + _p.pop(0)
2422- ... return res
2423-
2424- Here, we exclude the zeroth argument from vectorization whether it is
2425- passed by position or keyword.
2426-
2427- >>> vpolyval = np.vectorize(mypolyval, excluded={0, 'p'})
2428- >>> vpolyval([1, 2, 3], x=[0, 1])
2429- array([3, 6])
2430- >>> vpolyval(p=[1, 2, 3], x=[0, 1])
2431- array([3, 6])
2432-
2433- The `signature` argument allows for vectorizing functions that act on
2434- non-scalar arrays of fixed length. For example, you can use it for a
2435- vectorized calculation of Pearson correlation coefficient and its p-value:
2436-
2437- >>> import scipy.stats
2438- >>> pearsonr = np.vectorize(scipy.stats.pearsonr,
2439- ... signature='(n),(n)->(),()')
2440- >>> pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], [4, 3, 2, 1]])
2441- (array([ 1., -1.]), array([ 0., 0.]))
2442-
2443- Or for a vectorized convolution:
2444-
2445- >>> convolve = np.vectorize(np.convolve, signature='(n),(m)->(k)')
2446- >>> convolve(np.eye(4), [1, 2, 1])
2447- array([[1., 2., 1., 0., 0., 0.],
2448- [0., 1., 2., 1., 0., 0.],
2449- [0., 0., 1., 2., 1., 0.],
2450- [0., 0., 0., 1., 2., 1.]])
2451-
2452- Decorator syntax is supported. The decorator can be called as
2453- a function to provide keyword arguments:
2454-
2455- >>> @np.vectorize
2456- ... def identity(x):
2457- ... return x
2458- ...
2459- >>> identity([0, 1, 2])
2460- array([0, 1, 2])
2461- >>> @np.vectorize(otypes=[float])
2462- ... def as_float(x):
2463- ... return x
2464- ...
2465- >>> as_float([0, 1, 2])
2466- array([0., 1., 2.])
2467- """
24682307 def __init__ (self , pyfunc = np ._NoValue , otypes = None , doc = None ,
24692308 excluded = None , cache = False , signature = None ):
2309+ """
2310+ vectorize(pyfunc=np._NoValue, otypes=None, doc=None, excluded=None,
2311+ cache=False, signature=None)
2312+
2313+ Returns an object that acts like pyfunc, but takes arrays as input.
2314+
2315+ Define a vectorized function which takes a nested sequence of objects or
2316+ numpy arrays as inputs and returns a single numpy array or a tuple of numpy
2317+ arrays. The vectorized function evaluates `pyfunc` over successive tuples
2318+ of the input arrays like the python map function, except it uses the
2319+ broadcasting rules of numpy.
2320+
2321+ The data type of the output of `vectorized` is determined by calling
2322+ the function with the first element of the input. This can be avoided
2323+ by specifying the `otypes` argument.
2324+
2325+ Parameters
2326+ ----------
2327+ pyfunc : callable, optional
2328+ A python function or method.
2329+ Can be omitted to produce a decorator with keyword arguments.
2330+ otypes : str or list of dtypes, optional
2331+ The output data type. It must be specified as either a string of
2332+ typecode characters or a list of data type specifiers. There should
2333+ be one data type specifier for each output.
2334+ doc : str, optional
2335+ The docstring for the function. If None, the docstring will be the
2336+ ``pyfunc.__doc__``.
2337+ excluded : set, optional
2338+ Set of strings or integers representing the positional or keyword
2339+ arguments for which the function will not be vectorized. These will be
2340+ passed directly to `pyfunc` unmodified.
2341+
2342+ cache : bool, optional
2343+ If neither `otypes` nor `signature` are provided, and `cache` is ``True``,
2344+ then cache the number of outputs.
2345+
2346+ signature : string, optional
2347+ Generalized universal function signature, e.g., ``(m,n),(n)->(m)`` for
2348+ vectorized matrix-vector multiplication. If provided, ``pyfunc`` will
2349+ be called with (and expected to return) arrays with shapes given by the
2350+ size of corresponding core dimensions. By default, ``pyfunc`` is
2351+ assumed to take scalars as input and output.
2352+
2353+ Returns
2354+ -------
2355+ out : callable
2356+ A vectorized function if ``pyfunc`` was provided,
2357+ a decorator otherwise.
2358+
2359+ See Also
2360+ --------
2361+ frompyfunc : Takes an arbitrary Python function and returns a ufunc
2362+
2363+ Notes
2364+ -----
2365+ The `vectorize` function is provided primarily for convenience, not for
2366+ performance. The implementation is essentially a for loop.
2367+
2368+ If neither `otypes` nor `signature` are specified, then a call to the function
2369+ with the first argument will be used to determine the number of outputs.
2370+ The results of this call will be cached if `cache` is `True` to prevent
2371+ calling the function twice. However, to implement the cache,
2372+ the original function must be wrapped which will slow down subsequent calls,
2373+ so only do this if your function is expensive.
2374+
2375+ The new keyword argument interface and `excluded` argument support
2376+ further degrades performance.
2377+
2378+ References
2379+ ----------
2380+ .. [1] :doc:`/reference/c-api/generalized-ufuncs`
2381+
2382+ Examples
2383+ --------
2384+ >>> import numpy as np
2385+ >>> def myfunc(a, b):
2386+ ... "Return a-b if a>b, otherwise return a+b"
2387+ ... if a > b:
2388+ ... return a - b
2389+ ... else:
2390+ ... return a + b
2391+
2392+ >>> vfunc = np.vectorize(myfunc)
2393+ >>> vfunc([1, 2, 3, 4], 2)
2394+ array([3, 4, 1, 2])
2395+
2396+ The docstring is taken from the input function to `vectorize` unless it
2397+ is specified:
2398+
2399+ >>> vfunc.__doc__
2400+ 'Return a-b if a>b, otherwise return a+b'
2401+ >>> vfunc = np.vectorize(myfunc, doc='Vectorized `myfunc`')
2402+ >>> vfunc.__doc__
2403+ 'Vectorized `myfunc`'
2404+
2405+ The output type is determined by evaluating the first element of the input,
2406+ unless it is specified:
2407+
2408+ >>> out = vfunc([1, 2, 3, 4], 2)
2409+ >>> type(out[0])
2410+ <class 'numpy.int64'>
2411+ >>> vfunc = np.vectorize(myfunc, otypes=[float])
2412+ >>> out = vfunc([1, 2, 3, 4], 2)
2413+ >>> type(out[0])
2414+ <class 'numpy.float64'>
2415+
2416+ The `excluded` argument can be used to prevent vectorizing over certain
2417+ arguments. This can be useful for array-like arguments of a fixed length
2418+ such as the coefficients for a polynomial as in `polyval`:
2419+
2420+ >>> def mypolyval(p, x):
2421+ ... _p = list(p)
2422+ ... res = _p.pop(0)
2423+ ... while _p:
2424+ ... res = res*x + _p.pop(0)
2425+ ... return res
2426+
2427+ Here, we exclude the zeroth argument from vectorization whether it is
2428+ passed by position or keyword.
2429+
2430+ >>> vpolyval = np.vectorize(mypolyval, excluded={0, 'p'})
2431+ >>> vpolyval([1, 2, 3], x=[0, 1])
2432+ array([3, 6])
2433+ >>> vpolyval(p=[1, 2, 3], x=[0, 1])
2434+ array([3, 6])
2435+
2436+ The `signature` argument allows for vectorizing functions that act on
2437+ non-scalar arrays of fixed length. For example, you can use it for a
2438+ vectorized calculation of Pearson correlation coefficient and its p-value:
2439+
2440+ >>> import scipy.stats
2441+ >>> pearsonr = np.vectorize(scipy.stats.pearsonr,
2442+ ... signature='(n),(n)->(),()')
2443+ >>> pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], [4, 3, 2, 1]])
2444+ (array([ 1., -1.]), array([ 0., 0.]))
2445+
2446+ Or for a vectorized convolution:
2447+
2448+ >>> convolve = np.vectorize(np.convolve, signature='(n),(m)->(k)')
2449+ >>> convolve(np.eye(4), [1, 2, 1])
2450+ array([[1., 2., 1., 0., 0., 0.],
2451+ [0., 1., 2., 1., 0., 0.],
2452+ [0., 0., 1., 2., 1., 0.],
2453+ [0., 0., 0., 1., 2., 1.]])
2454+
2455+ Decorator syntax is supported. The decorator can be called as
2456+ a function to provide keyword arguments:
2457+
2458+ >>> @np.vectorize
2459+ ... def identity(x):
2460+ ... return x
2461+ ...
2462+ >>> identity([0, 1, 2])
2463+ array([0, 1, 2])
2464+ >>> @np.vectorize(otypes=[float])
2465+ ... def as_float(x):
2466+ ... return x
2467+ ...
2468+ >>> as_float([0, 1, 2])
2469+ array([0., 1., 2.])
2470+ """
24702471
24712472 if (pyfunc != np ._NoValue ) and (not callable (pyfunc )):
24722473 # Splitting the error message to keep
@@ -2489,6 +2490,12 @@ def __init__(self, pyfunc=np._NoValue, otypes=None, doc=None,
24892490 else :
24902491 self ._doc = doc
24912492
2493+ try :
2494+ self .__signature__ = inspect .signature (pyfunc )
2495+ self .__wrapped__ = pyfunc
2496+ except (ValueError , TypeError ):
2497+ pass
2498+
24922499 if isinstance (otypes , str ):
24932500 for char in otypes :
24942501 if char not in typecodes ['All' ]:
0 commit comments