id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
169,102
import numpy as np from numpy.core.numeric import normalize_axis_tuple from numpy.core.overrides import array_function_dispatch, set_module def _broadcast_shape(*args): """Returns the shape of the arrays that would result from broadcasting the supplied arrays against each other. """ # use the old-iterator because np.nditer does not handle size 0 arrays # consistently b = np.broadcast(*args[:32]) # unfortunately, it cannot handle 32 or more arguments directly for pos in range(32, len(args), 31): # ironically, np.broadcast does not properly handle np.broadcast # objects (it treats them as scalars) # use broadcasting to avoid allocating the full array b = broadcast_to(0, b.shape) b = np.broadcast(b, *args[pos:(pos + 31)]) return b.shape The provided code snippet includes necessary dependencies for implementing the `broadcast_shapes` function. Write a Python function `def broadcast_shapes(*args)` to solve the following problem: Broadcast the input shapes into a single shape. :ref:`Learn more about broadcasting here <basics.broadcasting>`. .. versionadded:: 1.20.0 Parameters ---------- `*args` : tuples of ints, or ints The shapes to be broadcast against each other. Returns ------- tuple Broadcasted shape. Raises ------ ValueError If the shapes are not compatible and cannot be broadcast according to NumPy's broadcasting rules. See Also -------- broadcast broadcast_arrays broadcast_to Examples -------- >>> np.broadcast_shapes((1, 2), (3, 1), (3, 2)) (3, 2) >>> np.broadcast_shapes((6, 7), (5, 6, 1), (7,), (5, 1, 7)) (5, 6, 7) Here is the function: def broadcast_shapes(*args): """ Broadcast the input shapes into a single shape. :ref:`Learn more about broadcasting here <basics.broadcasting>`. .. versionadded:: 1.20.0 Parameters ---------- `*args` : tuples of ints, or ints The shapes to be broadcast against each other. Returns ------- tuple Broadcasted shape. Raises ------ ValueError If the shapes are not compatible and cannot be broadcast according to NumPy's broadcasting rules. See Also -------- broadcast broadcast_arrays broadcast_to Examples -------- >>> np.broadcast_shapes((1, 2), (3, 1), (3, 2)) (3, 2) >>> np.broadcast_shapes((6, 7), (5, 6, 1), (7,), (5, 1, 7)) (5, 6, 7) """ arrays = [np.empty(x, dtype=[]) for x in args] return _broadcast_shape(*arrays)
Broadcast the input shapes into a single shape. :ref:`Learn more about broadcasting here <basics.broadcasting>`. .. versionadded:: 1.20.0 Parameters ---------- `*args` : tuples of ints, or ints The shapes to be broadcast against each other. Returns ------- tuple Broadcasted shape. Raises ------ ValueError If the shapes are not compatible and cannot be broadcast according to NumPy's broadcasting rules. See Also -------- broadcast broadcast_arrays broadcast_to Examples -------- >>> np.broadcast_shapes((1, 2), (3, 1), (3, 2)) (3, 2) >>> np.broadcast_shapes((6, 7), (5, 6, 1), (7,), (5, 1, 7)) (5, 6, 7)
169,103
import numpy as np from numpy.core.numeric import normalize_axis_tuple from numpy.core.overrides import array_function_dispatch, set_module def _broadcast_arrays_dispatcher(*args, subok=None): return args
null
169,104
import numpy as np from numpy.core.numeric import normalize_axis_tuple from numpy.core.overrides import array_function_dispatch, set_module def _broadcast_to(array, shape, subok, readonly): shape = tuple(shape) if np.iterable(shape) else (shape,) array = np.array(array, copy=False, subok=subok) if not shape and array.shape: raise ValueError('cannot broadcast a non-scalar to a scalar array') if any(size < 0 for size in shape): raise ValueError('all elements of broadcast shape must be non-' 'negative') extras = [] it = np.nditer( (array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras, op_flags=['readonly'], itershape=shape, order='C') with it: # never really has writebackifcopy semantics broadcast = it.itviews[0] result = _maybe_view_as_subclass(array, broadcast) # In a future version this will go away if not readonly and array.flags._writeable_no_warn: result.flags.writeable = True result.flags._warn_on_write = True return result def _broadcast_shape(*args): """Returns the shape of the arrays that would result from broadcasting the supplied arrays against each other. """ # use the old-iterator because np.nditer does not handle size 0 arrays # consistently b = np.broadcast(*args[:32]) # unfortunately, it cannot handle 32 or more arguments directly for pos in range(32, len(args), 31): # ironically, np.broadcast does not properly handle np.broadcast # objects (it treats them as scalars) # use broadcasting to avoid allocating the full array b = broadcast_to(0, b.shape) b = np.broadcast(b, *args[pos:(pos + 31)]) return b.shape The provided code snippet includes necessary dependencies for implementing the `broadcast_arrays` function. Write a Python function `def broadcast_arrays(*args, subok=False)` to solve the following problem: Broadcast any number of arrays against each other. Parameters ---------- `*args` : array_likes The arrays to broadcast. subok : bool, optional If True, then sub-classes will be passed-through, otherwise the returned arrays will be forced to be a base-class array (default). Returns ------- broadcasted : list of arrays These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first. While you can set the ``writable`` flag True, writing to a single output value may end up changing more than one location in the output array. .. deprecated:: 1.17 The output is currently marked so that if written to, a deprecation warning will be emitted. A future version will set the ``writable`` flag False so writing to it will raise an error. See Also -------- broadcast broadcast_to broadcast_shapes Examples -------- >>> x = np.array([[1,2,3]]) >>> y = np.array([[4],[5]]) >>> np.broadcast_arrays(x, y) [array([[1, 2, 3], [1, 2, 3]]), array([[4, 4, 4], [5, 5, 5]])] Here is a useful idiom for getting contiguous copies instead of non-contiguous views. >>> [np.array(a) for a in np.broadcast_arrays(x, y)] [array([[1, 2, 3], [1, 2, 3]]), array([[4, 4, 4], [5, 5, 5]])] Here is the function: def broadcast_arrays(*args, subok=False): """ Broadcast any number of arrays against each other. Parameters ---------- `*args` : array_likes The arrays to broadcast. subok : bool, optional If True, then sub-classes will be passed-through, otherwise the returned arrays will be forced to be a base-class array (default). Returns ------- broadcasted : list of arrays These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first. While you can set the ``writable`` flag True, writing to a single output value may end up changing more than one location in the output array. .. deprecated:: 1.17 The output is currently marked so that if written to, a deprecation warning will be emitted. A future version will set the ``writable`` flag False so writing to it will raise an error. See Also -------- broadcast broadcast_to broadcast_shapes Examples -------- >>> x = np.array([[1,2,3]]) >>> y = np.array([[4],[5]]) >>> np.broadcast_arrays(x, y) [array([[1, 2, 3], [1, 2, 3]]), array([[4, 4, 4], [5, 5, 5]])] Here is a useful idiom for getting contiguous copies instead of non-contiguous views. >>> [np.array(a) for a in np.broadcast_arrays(x, y)] [array([[1, 2, 3], [1, 2, 3]]), array([[4, 4, 4], [5, 5, 5]])] """ # nditer is not used here to avoid the limit of 32 arrays. # Otherwise, something like the following one-liner would suffice: # return np.nditer(args, flags=['multi_index', 'zerosize_ok'], # order='C').itviews args = [np.array(_m, copy=False, subok=subok) for _m in args] shape = _broadcast_shape(*args) if all(array.shape == shape for array in args): # Common case where nothing needs to be broadcasted. return args return [_broadcast_to(array, shape, subok=subok, readonly=False) for array in args]
Broadcast any number of arrays against each other. Parameters ---------- `*args` : array_likes The arrays to broadcast. subok : bool, optional If True, then sub-classes will be passed-through, otherwise the returned arrays will be forced to be a base-class array (default). Returns ------- broadcasted : list of arrays These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first. While you can set the ``writable`` flag True, writing to a single output value may end up changing more than one location in the output array. .. deprecated:: 1.17 The output is currently marked so that if written to, a deprecation warning will be emitted. A future version will set the ``writable`` flag False so writing to it will raise an error. See Also -------- broadcast broadcast_to broadcast_shapes Examples -------- >>> x = np.array([[1,2,3]]) >>> y = np.array([[4],[5]]) >>> np.broadcast_arrays(x, y) [array([[1, 2, 3], [1, 2, 3]]), array([[4, 4, 4], [5, 5, 5]])] Here is a useful idiom for getting contiguous copies instead of non-contiguous views. >>> [np.array(a) for a in np.broadcast_arrays(x, y)] [array([[1, 2, 3], [1, 2, 3]]), array([[4, 4, 4], [5, 5, 5]])]
169,122
import os import io from numpy.core.overrides import set_module The provided code snippet includes necessary dependencies for implementing the `_check_mode` function. Write a Python function `def _check_mode(mode, encoding, newline)` to solve the following problem: Check mode and that encoding and newline are compatible. Parameters ---------- mode : str File open mode. encoding : str File encoding. newline : str Newline for text files. Here is the function: def _check_mode(mode, encoding, newline): """Check mode and that encoding and newline are compatible. Parameters ---------- mode : str File open mode. encoding : str File encoding. newline : str Newline for text files. """ if "t" in mode: if "b" in mode: raise ValueError("Invalid mode: %r" % (mode,)) else: if encoding is not None: raise ValueError("Argument 'encoding' not supported in binary mode") if newline is not None: raise ValueError("Argument 'newline' not supported in binary mode")
Check mode and that encoding and newline are compatible. Parameters ---------- mode : str File open mode. encoding : str File encoding. newline : str Newline for text files.
169,123
import functools import sys import math import warnings import numpy.core.numeric as _nx from numpy.core.numeric import ( asarray, ScalarType, array, alltrue, cumprod, arange, ndim ) from numpy.core.numerictypes import find_common_type, issubdtype import numpy.matrixlib as matrixlib from .function_base import diff from numpy.core.multiarray import ravel_multi_index, unravel_index from numpy.core.overrides import set_module from numpy.core import overrides, linspace from numpy.lib.stride_tricks import as_strided def _ix__dispatcher(*args): return args
null
169,124
import functools import sys import math import warnings import numpy.core.numeric as _nx from numpy.core.numeric import ( asarray, ScalarType, array, alltrue, cumprod, arange, ndim ) from numpy.core.numerictypes import find_common_type, issubdtype import numpy.matrixlib as matrixlib from .function_base import diff from numpy.core.multiarray import ravel_multi_index, unravel_index from numpy.core.overrides import set_module from numpy.core import overrides, linspace from numpy.lib.stride_tricks import as_strided def issubdtype(arg1, arg2): r""" Returns True if first argument is a typecode lower/equal in type hierarchy. This is like the builtin :func:`issubclass`, but for `dtype`\ s. Parameters ---------- arg1, arg2 : dtype_like `dtype` or object coercible to one Returns ------- out : bool See Also -------- :ref:`arrays.scalars` : Overview of the numpy type hierarchy. issubsctype, issubclass_ Examples -------- `issubdtype` can be used to check the type of arrays: >>> ints = np.array([1, 2, 3], dtype=np.int32) >>> np.issubdtype(ints.dtype, np.integer) True >>> np.issubdtype(ints.dtype, np.floating) False >>> floats = np.array([1, 2, 3], dtype=np.float32) >>> np.issubdtype(floats.dtype, np.integer) False >>> np.issubdtype(floats.dtype, np.floating) True Similar types of different sizes are not subdtypes of each other: >>> np.issubdtype(np.float64, np.float32) False >>> np.issubdtype(np.float32, np.float64) False but both are subtypes of `floating`: >>> np.issubdtype(np.float64, np.floating) True >>> np.issubdtype(np.float32, np.floating) True For convenience, dtype-like objects are allowed too: >>> np.issubdtype('S1', np.string_) True >>> np.issubdtype('i4', np.signedinteger) True """ if not issubclass_(arg1, generic): arg1 = dtype(arg1).type if not issubclass_(arg2, generic): arg2 = dtype(arg2).type return issubclass(arg1, arg2) The provided code snippet includes necessary dependencies for implementing the `ix_` function. Write a Python function `def ix_(*args)` to solve the following problem: Construct an open mesh from multiple sequences. This function takes N 1-D sequences and returns N outputs with N dimensions each, such that the shape is 1 in all but one dimension and the dimension with the non-unit shape value cycles through all N dimensions. Using `ix_` one can quickly construct index arrays that will index the cross product. ``a[np.ix_([1,3],[2,5])]`` returns the array ``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``. Parameters ---------- args : 1-D sequences Each sequence should be of integer or boolean type. Boolean sequences will be interpreted as boolean masks for the corresponding dimension (equivalent to passing in ``np.nonzero(boolean_sequence)``). Returns ------- out : tuple of ndarrays N arrays with N dimensions each, with N the number of input sequences. Together these arrays form an open mesh. See Also -------- ogrid, mgrid, meshgrid Examples -------- >>> a = np.arange(10).reshape(2, 5) >>> a array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) >>> ixgrid = np.ix_([0, 1], [2, 4]) >>> ixgrid (array([[0], [1]]), array([[2, 4]])) >>> ixgrid[0].shape, ixgrid[1].shape ((2, 1), (1, 2)) >>> a[ixgrid] array([[2, 4], [7, 9]]) >>> ixgrid = np.ix_([True, True], [2, 4]) >>> a[ixgrid] array([[2, 4], [7, 9]]) >>> ixgrid = np.ix_([True, True], [False, False, True, False, True]) >>> a[ixgrid] array([[2, 4], [7, 9]]) Here is the function: def ix_(*args): """ Construct an open mesh from multiple sequences. This function takes N 1-D sequences and returns N outputs with N dimensions each, such that the shape is 1 in all but one dimension and the dimension with the non-unit shape value cycles through all N dimensions. Using `ix_` one can quickly construct index arrays that will index the cross product. ``a[np.ix_([1,3],[2,5])]`` returns the array ``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``. Parameters ---------- args : 1-D sequences Each sequence should be of integer or boolean type. Boolean sequences will be interpreted as boolean masks for the corresponding dimension (equivalent to passing in ``np.nonzero(boolean_sequence)``). Returns ------- out : tuple of ndarrays N arrays with N dimensions each, with N the number of input sequences. Together these arrays form an open mesh. See Also -------- ogrid, mgrid, meshgrid Examples -------- >>> a = np.arange(10).reshape(2, 5) >>> a array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) >>> ixgrid = np.ix_([0, 1], [2, 4]) >>> ixgrid (array([[0], [1]]), array([[2, 4]])) >>> ixgrid[0].shape, ixgrid[1].shape ((2, 1), (1, 2)) >>> a[ixgrid] array([[2, 4], [7, 9]]) >>> ixgrid = np.ix_([True, True], [2, 4]) >>> a[ixgrid] array([[2, 4], [7, 9]]) >>> ixgrid = np.ix_([True, True], [False, False, True, False, True]) >>> a[ixgrid] array([[2, 4], [7, 9]]) """ out = [] nd = len(args) for k, new in enumerate(args): if not isinstance(new, _nx.ndarray): new = asarray(new) if new.size == 0: # Explicitly type empty arrays to avoid float default new = new.astype(_nx.intp) if new.ndim != 1: raise ValueError("Cross index must be 1 dimensional") if issubdtype(new.dtype, _nx.bool_): new, = new.nonzero() new = new.reshape((1,)*k + (new.size,) + (1,)*(nd-k-1)) out.append(new) return tuple(out)
Construct an open mesh from multiple sequences. This function takes N 1-D sequences and returns N outputs with N dimensions each, such that the shape is 1 in all but one dimension and the dimension with the non-unit shape value cycles through all N dimensions. Using `ix_` one can quickly construct index arrays that will index the cross product. ``a[np.ix_([1,3],[2,5])]`` returns the array ``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``. Parameters ---------- args : 1-D sequences Each sequence should be of integer or boolean type. Boolean sequences will be interpreted as boolean masks for the corresponding dimension (equivalent to passing in ``np.nonzero(boolean_sequence)``). Returns ------- out : tuple of ndarrays N arrays with N dimensions each, with N the number of input sequences. Together these arrays form an open mesh. See Also -------- ogrid, mgrid, meshgrid Examples -------- >>> a = np.arange(10).reshape(2, 5) >>> a array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) >>> ixgrid = np.ix_([0, 1], [2, 4]) >>> ixgrid (array([[0], [1]]), array([[2, 4]])) >>> ixgrid[0].shape, ixgrid[1].shape ((2, 1), (1, 2)) >>> a[ixgrid] array([[2, 4], [7, 9]]) >>> ixgrid = np.ix_([True, True], [2, 4]) >>> a[ixgrid] array([[2, 4], [7, 9]]) >>> ixgrid = np.ix_([True, True], [False, False, True, False, True]) >>> a[ixgrid] array([[2, 4], [7, 9]])
169,125
import functools import sys import math import warnings import numpy.core.numeric as _nx from numpy.core.numeric import ( asarray, ScalarType, array, alltrue, cumprod, arange, ndim ) from numpy.core.numerictypes import find_common_type, issubdtype import numpy.matrixlib as matrixlib from .function_base import diff from numpy.core.multiarray import ravel_multi_index, unravel_index from numpy.core.overrides import set_module from numpy.core import overrides, linspace from numpy.lib.stride_tricks import as_strided def _fill_diagonal_dispatcher(a, val, wrap=None): return (a,)
null
169,126
import functools import sys import math import warnings import numpy.core.numeric as _nx from numpy.core.numeric import ( asarray, ScalarType, array, alltrue, cumprod, arange, ndim ) from numpy.core.numerictypes import find_common_type, issubdtype import numpy.matrixlib as matrixlib from .function_base import diff from numpy.core.multiarray import ravel_multi_index, unravel_index from numpy.core.overrides import set_module from numpy.core import overrides, linspace from numpy.lib.stride_tricks import as_strided def diff(a, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue): """ Calculate the n-th discrete difference along the given axis. The first difference is given by ``out[i] = a[i+1] - a[i]`` along the given axis, higher differences are calculated by using `diff` recursively. Parameters ---------- a : array_like Input array n : int, optional The number of times values are differenced. If zero, the input is returned as-is. axis : int, optional The axis along which the difference is taken, default is the last axis. prepend, append : array_like, optional Values to prepend or append to `a` along axis prior to performing the difference. Scalar values are expanded to arrays with length 1 in the direction of axis and the shape of the input array in along all other axes. Otherwise the dimension and shape must match `a` except along axis. .. versionadded:: 1.16.0 Returns ------- diff : ndarray The n-th differences. The shape of the output is the same as `a` except along `axis` where the dimension is smaller by `n`. The type of the output is the same as the type of the difference between any two elements of `a`. This is the same as the type of `a` in most cases. A notable exception is `datetime64`, which results in a `timedelta64` output array. See Also -------- gradient, ediff1d, cumsum Notes ----- Type is preserved for boolean arrays, so the result will contain `False` when consecutive elements are the same and `True` when they differ. For unsigned integer arrays, the results will also be unsigned. This should not be surprising, as the result is consistent with calculating the difference directly: >>> u8_arr = np.array([1, 0], dtype=np.uint8) >>> np.diff(u8_arr) array([255], dtype=uint8) >>> u8_arr[1,...] - u8_arr[0,...] 255 If this is not desirable, then the array should be cast to a larger integer type first: >>> i16_arr = u8_arr.astype(np.int16) >>> np.diff(i16_arr) array([-1], dtype=int16) Examples -------- >>> x = np.array([1, 2, 4, 7, 0]) >>> np.diff(x) array([ 1, 2, 3, -7]) >>> np.diff(x, n=2) array([ 1, 1, -10]) >>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]]) >>> np.diff(x) array([[2, 3, 4], [5, 1, 2]]) >>> np.diff(x, axis=0) array([[-1, 2, 0, -2]]) >>> x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64) >>> np.diff(x) array([1, 1], dtype='timedelta64[D]') """ if n == 0: return a if n < 0: raise ValueError( "order must be non-negative but got " + repr(n)) a = asanyarray(a) nd = a.ndim if nd == 0: raise ValueError("diff requires input that is at least one dimensional") axis = normalize_axis_index(axis, nd) combined = [] if prepend is not np._NoValue: prepend = np.asanyarray(prepend) if prepend.ndim == 0: shape = list(a.shape) shape[axis] = 1 prepend = np.broadcast_to(prepend, tuple(shape)) combined.append(prepend) combined.append(a) if append is not np._NoValue: append = np.asanyarray(append) if append.ndim == 0: shape = list(a.shape) shape[axis] = 1 append = np.broadcast_to(append, tuple(shape)) combined.append(append) if len(combined) > 1: a = np.concatenate(combined, axis) slice1 = [slice(None)] * nd slice2 = [slice(None)] * nd slice1[axis] = slice(1, None) slice2[axis] = slice(None, -1) slice1 = tuple(slice1) slice2 = tuple(slice2) op = not_equal if a.dtype == np.bool_ else subtract for _ in range(n): a = op(a[slice1], a[slice2]) return a The provided code snippet includes necessary dependencies for implementing the `fill_diagonal` function. Write a Python function `def fill_diagonal(a, val, wrap=False)` to solve the following problem: Fill the main diagonal of the given array of any dimensionality. For an array `a` with ``a.ndim >= 2``, the diagonal is the list of locations with indices ``a[i, ..., i]`` all identical. This function modifies the input array in-place, it does not return a value. Parameters ---------- a : array, at least 2-D. Array whose diagonal is to be filled, it gets modified in-place. val : scalar or array_like Value(s) to write on the diagonal. If `val` is scalar, the value is written along the diagonal. If array-like, the flattened `val` is written along the diagonal, repeating if necessary to fill all diagonal entries. wrap : bool For tall matrices in NumPy version up to 1.6.2, the diagonal "wrapped" after N columns. You can have this behavior with this option. This affects only tall matrices. See also -------- diag_indices, diag_indices_from Notes ----- .. versionadded:: 1.4.0 This functionality can be obtained via `diag_indices`, but internally this version uses a much faster implementation that never constructs the indices and uses simple slicing. Examples -------- >>> a = np.zeros((3, 3), int) >>> np.fill_diagonal(a, 5) >>> a array([[5, 0, 0], [0, 5, 0], [0, 0, 5]]) The same function can operate on a 4-D array: >>> a = np.zeros((3, 3, 3, 3), int) >>> np.fill_diagonal(a, 4) We only show a few blocks for clarity: >>> a[0, 0] array([[4, 0, 0], [0, 0, 0], [0, 0, 0]]) >>> a[1, 1] array([[0, 0, 0], [0, 4, 0], [0, 0, 0]]) >>> a[2, 2] array([[0, 0, 0], [0, 0, 0], [0, 0, 4]]) The wrap option affects only tall matrices: >>> # tall matrices no wrap >>> a = np.zeros((5, 3), int) >>> np.fill_diagonal(a, 4) >>> a array([[4, 0, 0], [0, 4, 0], [0, 0, 4], [0, 0, 0], [0, 0, 0]]) >>> # tall matrices wrap >>> a = np.zeros((5, 3), int) >>> np.fill_diagonal(a, 4, wrap=True) >>> a array([[4, 0, 0], [0, 4, 0], [0, 0, 4], [0, 0, 0], [4, 0, 0]]) >>> # wide matrices >>> a = np.zeros((3, 5), int) >>> np.fill_diagonal(a, 4, wrap=True) >>> a array([[4, 0, 0, 0, 0], [0, 4, 0, 0, 0], [0, 0, 4, 0, 0]]) The anti-diagonal can be filled by reversing the order of elements using either `numpy.flipud` or `numpy.fliplr`. >>> a = np.zeros((3, 3), int); >>> np.fill_diagonal(np.fliplr(a), [1,2,3]) # Horizontal flip >>> a array([[0, 0, 1], [0, 2, 0], [3, 0, 0]]) >>> np.fill_diagonal(np.flipud(a), [1,2,3]) # Vertical flip >>> a array([[0, 0, 3], [0, 2, 0], [1, 0, 0]]) Note that the order in which the diagonal is filled varies depending on the flip function. Here is the function: def fill_diagonal(a, val, wrap=False): """Fill the main diagonal of the given array of any dimensionality. For an array `a` with ``a.ndim >= 2``, the diagonal is the list of locations with indices ``a[i, ..., i]`` all identical. This function modifies the input array in-place, it does not return a value. Parameters ---------- a : array, at least 2-D. Array whose diagonal is to be filled, it gets modified in-place. val : scalar or array_like Value(s) to write on the diagonal. If `val` is scalar, the value is written along the diagonal. If array-like, the flattened `val` is written along the diagonal, repeating if necessary to fill all diagonal entries. wrap : bool For tall matrices in NumPy version up to 1.6.2, the diagonal "wrapped" after N columns. You can have this behavior with this option. This affects only tall matrices. See also -------- diag_indices, diag_indices_from Notes ----- .. versionadded:: 1.4.0 This functionality can be obtained via `diag_indices`, but internally this version uses a much faster implementation that never constructs the indices and uses simple slicing. Examples -------- >>> a = np.zeros((3, 3), int) >>> np.fill_diagonal(a, 5) >>> a array([[5, 0, 0], [0, 5, 0], [0, 0, 5]]) The same function can operate on a 4-D array: >>> a = np.zeros((3, 3, 3, 3), int) >>> np.fill_diagonal(a, 4) We only show a few blocks for clarity: >>> a[0, 0] array([[4, 0, 0], [0, 0, 0], [0, 0, 0]]) >>> a[1, 1] array([[0, 0, 0], [0, 4, 0], [0, 0, 0]]) >>> a[2, 2] array([[0, 0, 0], [0, 0, 0], [0, 0, 4]]) The wrap option affects only tall matrices: >>> # tall matrices no wrap >>> a = np.zeros((5, 3), int) >>> np.fill_diagonal(a, 4) >>> a array([[4, 0, 0], [0, 4, 0], [0, 0, 4], [0, 0, 0], [0, 0, 0]]) >>> # tall matrices wrap >>> a = np.zeros((5, 3), int) >>> np.fill_diagonal(a, 4, wrap=True) >>> a array([[4, 0, 0], [0, 4, 0], [0, 0, 4], [0, 0, 0], [4, 0, 0]]) >>> # wide matrices >>> a = np.zeros((3, 5), int) >>> np.fill_diagonal(a, 4, wrap=True) >>> a array([[4, 0, 0, 0, 0], [0, 4, 0, 0, 0], [0, 0, 4, 0, 0]]) The anti-diagonal can be filled by reversing the order of elements using either `numpy.flipud` or `numpy.fliplr`. >>> a = np.zeros((3, 3), int); >>> np.fill_diagonal(np.fliplr(a), [1,2,3]) # Horizontal flip >>> a array([[0, 0, 1], [0, 2, 0], [3, 0, 0]]) >>> np.fill_diagonal(np.flipud(a), [1,2,3]) # Vertical flip >>> a array([[0, 0, 3], [0, 2, 0], [1, 0, 0]]) Note that the order in which the diagonal is filled varies depending on the flip function. """ if a.ndim < 2: raise ValueError("array must be at least 2-d") end = None if a.ndim == 2: # Explicit, fast formula for the common case. For 2-d arrays, we # accept rectangular ones. step = a.shape[1] + 1 # This is needed to don't have tall matrix have the diagonal wrap. if not wrap: end = a.shape[1] * a.shape[1] else: # For more than d=2, the strided formula is only valid for arrays with # all dimensions equal, so we check first. if not alltrue(diff(a.shape) == 0): raise ValueError("All dimensions of input must be of equal length") step = 1 + (cumprod(a.shape[:-1])).sum() # Write the value out into the diagonal. a.flat[:end:step] = val
Fill the main diagonal of the given array of any dimensionality. For an array `a` with ``a.ndim >= 2``, the diagonal is the list of locations with indices ``a[i, ..., i]`` all identical. This function modifies the input array in-place, it does not return a value. Parameters ---------- a : array, at least 2-D. Array whose diagonal is to be filled, it gets modified in-place. val : scalar or array_like Value(s) to write on the diagonal. If `val` is scalar, the value is written along the diagonal. If array-like, the flattened `val` is written along the diagonal, repeating if necessary to fill all diagonal entries. wrap : bool For tall matrices in NumPy version up to 1.6.2, the diagonal "wrapped" after N columns. You can have this behavior with this option. This affects only tall matrices. See also -------- diag_indices, diag_indices_from Notes ----- .. versionadded:: 1.4.0 This functionality can be obtained via `diag_indices`, but internally this version uses a much faster implementation that never constructs the indices and uses simple slicing. Examples -------- >>> a = np.zeros((3, 3), int) >>> np.fill_diagonal(a, 5) >>> a array([[5, 0, 0], [0, 5, 0], [0, 0, 5]]) The same function can operate on a 4-D array: >>> a = np.zeros((3, 3, 3, 3), int) >>> np.fill_diagonal(a, 4) We only show a few blocks for clarity: >>> a[0, 0] array([[4, 0, 0], [0, 0, 0], [0, 0, 0]]) >>> a[1, 1] array([[0, 0, 0], [0, 4, 0], [0, 0, 0]]) >>> a[2, 2] array([[0, 0, 0], [0, 0, 0], [0, 0, 4]]) The wrap option affects only tall matrices: >>> # tall matrices no wrap >>> a = np.zeros((5, 3), int) >>> np.fill_diagonal(a, 4) >>> a array([[4, 0, 0], [0, 4, 0], [0, 0, 4], [0, 0, 0], [0, 0, 0]]) >>> # tall matrices wrap >>> a = np.zeros((5, 3), int) >>> np.fill_diagonal(a, 4, wrap=True) >>> a array([[4, 0, 0], [0, 4, 0], [0, 0, 4], [0, 0, 0], [4, 0, 0]]) >>> # wide matrices >>> a = np.zeros((3, 5), int) >>> np.fill_diagonal(a, 4, wrap=True) >>> a array([[4, 0, 0, 0, 0], [0, 4, 0, 0, 0], [0, 0, 4, 0, 0]]) The anti-diagonal can be filled by reversing the order of elements using either `numpy.flipud` or `numpy.fliplr`. >>> a = np.zeros((3, 3), int); >>> np.fill_diagonal(np.fliplr(a), [1,2,3]) # Horizontal flip >>> a array([[0, 0, 1], [0, 2, 0], [3, 0, 0]]) >>> np.fill_diagonal(np.flipud(a), [1,2,3]) # Vertical flip >>> a array([[0, 0, 3], [0, 2, 0], [1, 0, 0]]) Note that the order in which the diagonal is filled varies depending on the flip function.
169,127
import functools import sys import math import warnings import numpy.core.numeric as _nx from numpy.core.numeric import ( asarray, ScalarType, array, alltrue, cumprod, arange, ndim ) from numpy.core.numerictypes import find_common_type, issubdtype import numpy.matrixlib as matrixlib from .function_base import diff from numpy.core.multiarray import ravel_multi_index, unravel_index from numpy.core.overrides import set_module from numpy.core import overrides, linspace from numpy.lib.stride_tricks import as_strided def _diag_indices_from(arr): return (arr,)
null
169,128
import functools import sys import math import warnings import numpy.core.numeric as _nx from numpy.core.numeric import ( asarray, ScalarType, array, alltrue, cumprod, arange, ndim ) from numpy.core.numerictypes import find_common_type, issubdtype import numpy.matrixlib as matrixlib from .function_base import diff from numpy.core.multiarray import ravel_multi_index, unravel_index from numpy.core.overrides import set_module from numpy.core import overrides, linspace from numpy.lib.stride_tricks import as_strided def diag_indices(n, ndim=2): """ Return the indices to access the main diagonal of an array. This returns a tuple of indices that can be used to access the main diagonal of an array `a` with ``a.ndim >= 2`` dimensions and shape (n, n, ..., n). For ``a.ndim = 2`` this is the usual diagonal, for ``a.ndim > 2`` this is the set of indices to access ``a[i, i, ..., i]`` for ``i = [0..n-1]``. Parameters ---------- n : int The size, along each dimension, of the arrays for which the returned indices can be used. ndim : int, optional The number of dimensions. See Also -------- diag_indices_from Notes ----- .. versionadded:: 1.4.0 Examples -------- Create a set of indices to access the diagonal of a (4, 4) array: >>> di = np.diag_indices(4) >>> di (array([0, 1, 2, 3]), array([0, 1, 2, 3])) >>> a = np.arange(16).reshape(4, 4) >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> a[di] = 100 >>> a array([[100, 1, 2, 3], [ 4, 100, 6, 7], [ 8, 9, 100, 11], [ 12, 13, 14, 100]]) Now, we create indices to manipulate a 3-D array: >>> d3 = np.diag_indices(2, 3) >>> d3 (array([0, 1]), array([0, 1]), array([0, 1])) And use it to set the diagonal of an array of zeros to 1: >>> a = np.zeros((2, 2, 2), dtype=int) >>> a[d3] = 1 >>> a array([[[1, 0], [0, 0]], [[0, 0], [0, 1]]]) """ idx = arange(n) return (idx,) * ndim def diff(a, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue): """ Calculate the n-th discrete difference along the given axis. The first difference is given by ``out[i] = a[i+1] - a[i]`` along the given axis, higher differences are calculated by using `diff` recursively. Parameters ---------- a : array_like Input array n : int, optional The number of times values are differenced. If zero, the input is returned as-is. axis : int, optional The axis along which the difference is taken, default is the last axis. prepend, append : array_like, optional Values to prepend or append to `a` along axis prior to performing the difference. Scalar values are expanded to arrays with length 1 in the direction of axis and the shape of the input array in along all other axes. Otherwise the dimension and shape must match `a` except along axis. .. versionadded:: 1.16.0 Returns ------- diff : ndarray The n-th differences. The shape of the output is the same as `a` except along `axis` where the dimension is smaller by `n`. The type of the output is the same as the type of the difference between any two elements of `a`. This is the same as the type of `a` in most cases. A notable exception is `datetime64`, which results in a `timedelta64` output array. See Also -------- gradient, ediff1d, cumsum Notes ----- Type is preserved for boolean arrays, so the result will contain `False` when consecutive elements are the same and `True` when they differ. For unsigned integer arrays, the results will also be unsigned. This should not be surprising, as the result is consistent with calculating the difference directly: >>> u8_arr = np.array([1, 0], dtype=np.uint8) >>> np.diff(u8_arr) array([255], dtype=uint8) >>> u8_arr[1,...] - u8_arr[0,...] 255 If this is not desirable, then the array should be cast to a larger integer type first: >>> i16_arr = u8_arr.astype(np.int16) >>> np.diff(i16_arr) array([-1], dtype=int16) Examples -------- >>> x = np.array([1, 2, 4, 7, 0]) >>> np.diff(x) array([ 1, 2, 3, -7]) >>> np.diff(x, n=2) array([ 1, 1, -10]) >>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]]) >>> np.diff(x) array([[2, 3, 4], [5, 1, 2]]) >>> np.diff(x, axis=0) array([[-1, 2, 0, -2]]) >>> x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64) >>> np.diff(x) array([1, 1], dtype='timedelta64[D]') """ if n == 0: return a if n < 0: raise ValueError( "order must be non-negative but got " + repr(n)) a = asanyarray(a) nd = a.ndim if nd == 0: raise ValueError("diff requires input that is at least one dimensional") axis = normalize_axis_index(axis, nd) combined = [] if prepend is not np._NoValue: prepend = np.asanyarray(prepend) if prepend.ndim == 0: shape = list(a.shape) shape[axis] = 1 prepend = np.broadcast_to(prepend, tuple(shape)) combined.append(prepend) combined.append(a) if append is not np._NoValue: append = np.asanyarray(append) if append.ndim == 0: shape = list(a.shape) shape[axis] = 1 append = np.broadcast_to(append, tuple(shape)) combined.append(append) if len(combined) > 1: a = np.concatenate(combined, axis) slice1 = [slice(None)] * nd slice2 = [slice(None)] * nd slice1[axis] = slice(1, None) slice2[axis] = slice(None, -1) slice1 = tuple(slice1) slice2 = tuple(slice2) op = not_equal if a.dtype == np.bool_ else subtract for _ in range(n): a = op(a[slice1], a[slice2]) return a The provided code snippet includes necessary dependencies for implementing the `diag_indices_from` function. Write a Python function `def diag_indices_from(arr)` to solve the following problem: Return the indices to access the main diagonal of an n-dimensional array. See `diag_indices` for full details. Parameters ---------- arr : array, at least 2-D See Also -------- diag_indices Notes ----- .. versionadded:: 1.4.0 Here is the function: def diag_indices_from(arr): """ Return the indices to access the main diagonal of an n-dimensional array. See `diag_indices` for full details. Parameters ---------- arr : array, at least 2-D See Also -------- diag_indices Notes ----- .. versionadded:: 1.4.0 """ if not arr.ndim >= 2: raise ValueError("input array must be at least 2-d") # For more than d=2, the strided formula is only valid for arrays with # all dimensions equal, so we check first. if not alltrue(diff(arr.shape) == 0): raise ValueError("All dimensions of input must be of equal length") return diag_indices(arr.shape[0], arr.ndim)
Return the indices to access the main diagonal of an n-dimensional array. See `diag_indices` for full details. Parameters ---------- arr : array, at least 2-D See Also -------- diag_indices Notes ----- .. versionadded:: 1.4.0
169,174
import functools import numbers import sys import numpy as np from . import numerictypes as _nt from .umath import absolute, isinf, isfinite, isnat from . import multiarray from .multiarray import (array, dragon4_positional, dragon4_scientific, datetime_as_string, datetime_data, ndarray, set_legacy_print_mode) from .fromnumeric import any from .numeric import concatenate, asarray, errstate from .numerictypes import (longlong, intc, int_, float_, complex_, bool_, flexible) from .overrides import array_function_dispatch, set_module import operator import warnings import contextlib _format_options = { 'edgeitems': 3, # repr N leading and trailing items of each dimension 'threshold': 1000, # total items > triggers array summarization 'floatmode': 'maxprec', 'precision': 8, # precision of floating point representations 'suppress': False, # suppress printing small floating values in exp format 'linewidth': 75, 'nanstr': 'nan', 'infstr': 'inf', 'sign': '-', 'formatter': None, # Internally stored as an int to simplify comparisons; converted from/to # str/False on the way in/out. 'legacy': sys.maxsize} The provided code snippet includes necessary dependencies for implementing the `_get_legacy_print_mode` function. Write a Python function `def _get_legacy_print_mode()` to solve the following problem: Return the legacy print mode as an int. Here is the function: def _get_legacy_print_mode(): """Return the legacy print mode as an int.""" return _format_options['legacy']
Return the legacy print mode as an int.
169,175
import functools import numbers import sys import numpy as np from . import numerictypes as _nt from .umath import absolute, isinf, isfinite, isnat from . import multiarray from .multiarray import (array, dragon4_positional, dragon4_scientific, datetime_as_string, datetime_data, ndarray, set_legacy_print_mode) from .fromnumeric import any from .numeric import concatenate, asarray, errstate from .numerictypes import (longlong, intc, int_, float_, complex_, bool_, flexible) from .overrides import array_function_dispatch, set_module import operator import warnings import contextlib def set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None, sign=None, floatmode=None, *, legacy=None): """ Set printing options. These options determine the way floating point numbers, arrays and other NumPy objects are displayed. Parameters ---------- precision : int or None, optional Number of digits of precision for floating point output (default 8). May be None if `floatmode` is not `fixed`, to print as many digits as necessary to uniquely specify the value. threshold : int, optional Total number of array elements which trigger summarization rather than full repr (default 1000). To always use the full repr without summarization, pass `sys.maxsize`. edgeitems : int, optional Number of array items in summary at beginning and end of each dimension (default 3). linewidth : int, optional The number of characters per line for the purpose of inserting line breaks (default 75). suppress : bool, optional If True, always print floating point numbers using fixed point notation, in which case numbers equal to zero in the current precision will print as zero. If False, then scientific notation is used when absolute value of the smallest number is < 1e-4 or the ratio of the maximum absolute value to the minimum is > 1e3. The default is False. nanstr : str, optional String representation of floating point not-a-number (default nan). infstr : str, optional String representation of floating point infinity (default inf). sign : string, either '-', '+', or ' ', optional Controls printing of the sign of floating-point types. If '+', always print the sign of positive values. If ' ', always prints a space (whitespace character) in the sign position of positive values. If '-', omit the sign character of positive values. (default '-') formatter : dict of callables, optional If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are: - 'bool' - 'int' - 'timedelta' : a `numpy.timedelta64` - 'datetime' : a `numpy.datetime64` - 'float' - 'longfloat' : 128-bit floats - 'complexfloat' - 'longcomplexfloat' : composed of two 128-bit floats - 'numpystr' : types `numpy.string_` and `numpy.unicode_` - 'object' : `np.object_` arrays Other keys that can be used to set a group of types at once are: - 'all' : sets all types - 'int_kind' : sets 'int' - 'float_kind' : sets 'float' and 'longfloat' - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat' - 'str_kind' : sets 'numpystr' floatmode : str, optional Controls the interpretation of the `precision` option for floating-point types. Can take the following values (default maxprec_equal): * 'fixed': Always print exactly `precision` fractional digits, even if this would print more or fewer digits than necessary to specify the value uniquely. * 'unique': Print the minimum number of fractional digits necessary to represent each value uniquely. Different elements may have a different number of digits. The value of the `precision` option is ignored. * 'maxprec': Print at most `precision` fractional digits, but if an element can be uniquely represented with fewer digits only print it with that many. * 'maxprec_equal': Print at most `precision` fractional digits, but if every element in the array can be uniquely represented with an equal number of fewer digits, use that many digits for all elements. legacy : string or `False`, optional If set to the string `'1.13'` enables 1.13 legacy printing mode. This approximates numpy 1.13 print output by including a space in the sign position of floats and different behavior for 0d arrays. This also enables 1.21 legacy printing mode (described below). If set to the string `'1.21'` enables 1.21 legacy printing mode. This approximates numpy 1.21 print output of complex structured dtypes by not inserting spaces after commas that separate fields and after colons. If set to `False`, disables legacy mode. Unrecognized strings will be ignored with a warning for forward compatibility. .. versionadded:: 1.14.0 .. versionchanged:: 1.22.0 See Also -------- get_printoptions, printoptions, set_string_function, array2string Notes ----- `formatter` is always reset with a call to `set_printoptions`. Use `printoptions` as a context manager to set the values temporarily. Examples -------- Floating point precision can be set: >>> np.set_printoptions(precision=4) >>> np.array([1.123456789]) [1.1235] Long arrays can be summarised: >>> np.set_printoptions(threshold=5) >>> np.arange(10) array([0, 1, 2, ..., 7, 8, 9]) Small results can be suppressed: >>> eps = np.finfo(float).eps >>> x = np.arange(4.) >>> x**2 - (x + eps)**2 array([-4.9304e-32, -4.4409e-16, 0.0000e+00, 0.0000e+00]) >>> np.set_printoptions(suppress=True) >>> x**2 - (x + eps)**2 array([-0., -0., 0., 0.]) A custom formatter can be used to display array elements as desired: >>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)}) >>> x = np.arange(3) >>> x array([int: 0, int: -1, int: -2]) >>> np.set_printoptions() # formatter gets reset >>> x array([0, 1, 2]) To put back the default options, you can use: >>> np.set_printoptions(edgeitems=3, infstr='inf', ... linewidth=75, nanstr='nan', precision=8, ... suppress=False, threshold=1000, formatter=None) Also to temporarily override options, use `printoptions` as a context manager: >>> with np.printoptions(precision=2, suppress=True, threshold=5): ... np.linspace(0, 10, 10) array([ 0. , 1.11, 2.22, ..., 7.78, 8.89, 10. ]) """ opt = _make_options_dict(precision, threshold, edgeitems, linewidth, suppress, nanstr, infstr, sign, formatter, floatmode, legacy) # formatter is always reset opt['formatter'] = formatter _format_options.update(opt) # set the C variable for legacy mode if _format_options['legacy'] == 113: set_legacy_print_mode(113) # reset the sign option in legacy mode to avoid confusion _format_options['sign'] = '-' elif _format_options['legacy'] == 121: set_legacy_print_mode(121) elif _format_options['legacy'] == sys.maxsize: set_legacy_print_mode(0) def get_printoptions(): """ Return the current print options. Returns ------- print_opts : dict Dictionary of current print options with keys - precision : int - threshold : int - edgeitems : int - linewidth : int - suppress : bool - nanstr : str - infstr : str - formatter : dict of callables - sign : str For a full description of these options, see `set_printoptions`. See Also -------- set_printoptions, printoptions, set_string_function """ opts = _format_options.copy() opts['legacy'] = { 113: '1.13', 121: '1.21', sys.maxsize: False, }[opts['legacy']] return opts The provided code snippet includes necessary dependencies for implementing the `printoptions` function. Write a Python function `def printoptions(*args, **kwargs)` to solve the following problem: Context manager for setting print options. Set print options for the scope of the `with` block, and restore the old options at the end. See `set_printoptions` for the full description of available options. Examples -------- >>> from numpy.testing import assert_equal >>> with np.printoptions(precision=2): ... np.array([2.0]) / 3 array([0.67]) The `as`-clause of the `with`-statement gives the current print options: >>> with np.printoptions(precision=2) as opts: ... assert_equal(opts, np.get_printoptions()) See Also -------- set_printoptions, get_printoptions Here is the function: def printoptions(*args, **kwargs): """Context manager for setting print options. Set print options for the scope of the `with` block, and restore the old options at the end. See `set_printoptions` for the full description of available options. Examples -------- >>> from numpy.testing import assert_equal >>> with np.printoptions(precision=2): ... np.array([2.0]) / 3 array([0.67]) The `as`-clause of the `with`-statement gives the current print options: >>> with np.printoptions(precision=2) as opts: ... assert_equal(opts, np.get_printoptions()) See Also -------- set_printoptions, get_printoptions """ opts = np.get_printoptions() try: np.set_printoptions(*args, **kwargs) yield np.get_printoptions() finally: np.set_printoptions(**opts)
Context manager for setting print options. Set print options for the scope of the `with` block, and restore the old options at the end. See `set_printoptions` for the full description of available options. Examples -------- >>> from numpy.testing import assert_equal >>> with np.printoptions(precision=2): ... np.array([2.0]) / 3 array([0.67]) The `as`-clause of the `with`-statement gives the current print options: >>> with np.printoptions(precision=2) as opts: ... assert_equal(opts, np.get_printoptions()) See Also -------- set_printoptions, get_printoptions
169,176
import functools import numbers import sys import numpy as np from . import numerictypes as _nt from .umath import absolute, isinf, isfinite, isnat from . import multiarray from .multiarray import (array, dragon4_positional, dragon4_scientific, datetime_as_string, datetime_data, ndarray, set_legacy_print_mode) from .fromnumeric import any from .numeric import concatenate, asarray, errstate from .numerictypes import (longlong, intc, int_, float_, complex_, bool_, flexible) from .overrides import array_function_dispatch, set_module import operator import warnings import contextlib def get_ident() -> int: ... def get_ident() -> int: ... The provided code snippet includes necessary dependencies for implementing the `_recursive_guard` function. Write a Python function `def _recursive_guard(fillvalue='...')` to solve the following problem: Like the python 3.2 reprlib.recursive_repr, but forwards *args and **kwargs Decorates a function such that if it calls itself with the same first argument, it returns `fillvalue` instead of recursing. Largely copied from reprlib.recursive_repr Here is the function: def _recursive_guard(fillvalue='...'): """ Like the python 3.2 reprlib.recursive_repr, but forwards *args and **kwargs Decorates a function such that if it calls itself with the same first argument, it returns `fillvalue` instead of recursing. Largely copied from reprlib.recursive_repr """ def decorating_function(f): repr_running = set() @functools.wraps(f) def wrapper(self, *args, **kwargs): key = id(self), get_ident() if key in repr_running: return fillvalue repr_running.add(key) try: return f(self, *args, **kwargs) finally: repr_running.discard(key) return wrapper return decorating_function
Like the python 3.2 reprlib.recursive_repr, but forwards *args and **kwargs Decorates a function such that if it calls itself with the same first argument, it returns `fillvalue` instead of recursing. Largely copied from reprlib.recursive_repr
169,177
import functools import numbers import sys import numpy as np from . import numerictypes as _nt from .umath import absolute, isinf, isfinite, isnat from . import multiarray from .multiarray import (array, dragon4_positional, dragon4_scientific, datetime_as_string, datetime_data, ndarray, set_legacy_print_mode) from .fromnumeric import any from .numeric import concatenate, asarray, errstate from .numerictypes import (longlong, intc, int_, float_, complex_, bool_, flexible) from .overrides import array_function_dispatch, set_module import operator import warnings import contextlib def _array2string_dispatcher( a, max_line_width=None, precision=None, suppress_small=None, separator=None, prefix=None, style=None, formatter=None, threshold=None, edgeitems=None, sign=None, floatmode=None, suffix=None, *, legacy=None): return (a,)
null
169,178
import functools import numbers import sys import numpy as np from . import numerictypes as _nt from .umath import absolute, isinf, isfinite, isnat from . import multiarray from .multiarray import (array, dragon4_positional, dragon4_scientific, datetime_as_string, datetime_data, ndarray, set_legacy_print_mode) from .fromnumeric import any from .numeric import concatenate, asarray, errstate from .numerictypes import (longlong, intc, int_, float_, complex_, bool_, flexible) from .overrides import array_function_dispatch, set_module import operator import warnings import contextlib _format_options = { 'edgeitems': 3, # repr N leading and trailing items of each dimension 'threshold': 1000, # total items > triggers array summarization 'floatmode': 'maxprec', 'precision': 8, # precision of floating point representations 'suppress': False, # suppress printing small floating values in exp format 'linewidth': 75, 'nanstr': 'nan', 'infstr': 'inf', 'sign': '-', 'formatter': None, # Internally stored as an int to simplify comparisons; converted from/to # str/False on the way in/out. 'legacy': sys.maxsize} def _make_options_dict(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, sign=None, formatter=None, floatmode=None, legacy=None): """ Make a dictionary out of the non-None arguments, plus conversion of *legacy* and sanity checks. """ options = {k: v for k, v in locals().items() if v is not None} if suppress is not None: options['suppress'] = bool(suppress) modes = ['fixed', 'unique', 'maxprec', 'maxprec_equal'] if floatmode not in modes + [None]: raise ValueError("floatmode option must be one of " + ", ".join('"{}"'.format(m) for m in modes)) if sign not in [None, '-', '+', ' ']: raise ValueError("sign option must be one of ' ', '+', or '-'") if legacy == False: options['legacy'] = sys.maxsize elif legacy == '1.13': options['legacy'] = 113 elif legacy == '1.21': options['legacy'] = 121 elif legacy is None: pass # OK, do nothing. else: warnings.warn( "legacy printing option can currently only be '1.13', '1.21', or " "`False`", stacklevel=3) if threshold is not None: # forbid the bad threshold arg suggested by stack overflow, gh-12351 if not isinstance(threshold, numbers.Number): raise TypeError("threshold must be numeric") if np.isnan(threshold): raise ValueError("threshold must be non-NAN, try " "sys.maxsize for untruncated representation") if precision is not None: # forbid the bad precision arg as suggested by issue #18254 try: options['precision'] = operator.index(precision) except TypeError as e: raise TypeError('precision must be an integer') from e return options def _array2string(a, options, separator=' ', prefix=""): # The formatter __init__s in _get_format_function cannot deal with # subclasses yet, and we also need to avoid recursion issues in # _formatArray with subclasses which return 0d arrays in place of scalars data = asarray(a) if a.shape == (): a = data if a.size > options['threshold']: summary_insert = "..." data = _leading_trailing(data, options['edgeitems']) else: summary_insert = "" # find the right formatting function for the array format_function = _get_format_function(data, **options) # skip over "[" next_line_prefix = " " # skip over array( next_line_prefix += " "*len(prefix) lst = _formatArray(a, format_function, options['linewidth'], next_line_prefix, separator, options['edgeitems'], summary_insert, options['legacy']) return lst The provided code snippet includes necessary dependencies for implementing the `array2string` function. Write a Python function `def array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ', prefix="", style=np._NoValue, formatter=None, threshold=None, edgeitems=None, sign=None, floatmode=None, suffix="", *, legacy=None)` to solve the following problem: Return a string representation of an array. Parameters ---------- a : ndarray Input array. max_line_width : int, optional Inserts newlines if text is longer than `max_line_width`. Defaults to ``numpy.get_printoptions()['linewidth']``. precision : int or None, optional Floating point precision. Defaults to ``numpy.get_printoptions()['precision']``. suppress_small : bool, optional Represent numbers "very close" to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to ``numpy.get_printoptions()['suppress']``. separator : str, optional Inserted between elements. prefix : str, optional suffix : str, optional The length of the prefix and suffix strings are used to respectively align and wrap the output. An array is typically printed as:: prefix + array2string(a) + suffix The output is left-padded by the length of the prefix string, and wrapping is forced at the column ``max_line_width - len(suffix)``. It should be noted that the content of prefix and suffix strings are not included in the output. style : _NoValue, optional Has no effect, do not use. .. deprecated:: 1.14.0 formatter : dict of callables, optional If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are: - 'bool' - 'int' - 'timedelta' : a `numpy.timedelta64` - 'datetime' : a `numpy.datetime64` - 'float' - 'longfloat' : 128-bit floats - 'complexfloat' - 'longcomplexfloat' : composed of two 128-bit floats - 'void' : type `numpy.void` - 'numpystr' : types `numpy.string_` and `numpy.unicode_` Other keys that can be used to set a group of types at once are: - 'all' : sets all types - 'int_kind' : sets 'int' - 'float_kind' : sets 'float' and 'longfloat' - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat' - 'str_kind' : sets 'numpystr' threshold : int, optional Total number of array elements which trigger summarization rather than full repr. Defaults to ``numpy.get_printoptions()['threshold']``. edgeitems : int, optional Number of array items in summary at beginning and end of each dimension. Defaults to ``numpy.get_printoptions()['edgeitems']``. sign : string, either '-', '+', or ' ', optional Controls printing of the sign of floating-point types. If '+', always print the sign of positive values. If ' ', always prints a space (whitespace character) in the sign position of positive values. If '-', omit the sign character of positive values. Defaults to ``numpy.get_printoptions()['sign']``. floatmode : str, optional Controls the interpretation of the `precision` option for floating-point types. Defaults to ``numpy.get_printoptions()['floatmode']``. Can take the following values: - 'fixed': Always print exactly `precision` fractional digits, even if this would print more or fewer digits than necessary to specify the value uniquely. - 'unique': Print the minimum number of fractional digits necessary to represent each value uniquely. Different elements may have a different number of digits. The value of the `precision` option is ignored. - 'maxprec': Print at most `precision` fractional digits, but if an element can be uniquely represented with fewer digits only print it with that many. - 'maxprec_equal': Print at most `precision` fractional digits, but if every element in the array can be uniquely represented with an equal number of fewer digits, use that many digits for all elements. legacy : string or `False`, optional If set to the string `'1.13'` enables 1.13 legacy printing mode. This approximates numpy 1.13 print output by including a space in the sign position of floats and different behavior for 0d arrays. If set to `False`, disables legacy mode. Unrecognized strings will be ignored with a warning for forward compatibility. .. versionadded:: 1.14.0 Returns ------- array_str : str String representation of the array. Raises ------ TypeError if a callable in `formatter` does not return a string. See Also -------- array_str, array_repr, set_printoptions, get_printoptions Notes ----- If a formatter is specified for a certain type, the `precision` keyword is ignored for that type. This is a very flexible function; `array_repr` and `array_str` are using `array2string` internally so keywords with the same name should work identically in all three functions. Examples -------- >>> x = np.array([1e-16,1,2,3]) >>> np.array2string(x, precision=2, separator=',', ... suppress_small=True) '[0.,1.,2.,3.]' >>> x = np.arange(3.) >>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) '[0.00 1.00 2.00]' >>> x = np.arange(3) >>> np.array2string(x, formatter={'int':lambda x: hex(x)}) '[0x0 0x1 0x2]' Here is the function: def array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ', prefix="", style=np._NoValue, formatter=None, threshold=None, edgeitems=None, sign=None, floatmode=None, suffix="", *, legacy=None): """ Return a string representation of an array. Parameters ---------- a : ndarray Input array. max_line_width : int, optional Inserts newlines if text is longer than `max_line_width`. Defaults to ``numpy.get_printoptions()['linewidth']``. precision : int or None, optional Floating point precision. Defaults to ``numpy.get_printoptions()['precision']``. suppress_small : bool, optional Represent numbers "very close" to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to ``numpy.get_printoptions()['suppress']``. separator : str, optional Inserted between elements. prefix : str, optional suffix : str, optional The length of the prefix and suffix strings are used to respectively align and wrap the output. An array is typically printed as:: prefix + array2string(a) + suffix The output is left-padded by the length of the prefix string, and wrapping is forced at the column ``max_line_width - len(suffix)``. It should be noted that the content of prefix and suffix strings are not included in the output. style : _NoValue, optional Has no effect, do not use. .. deprecated:: 1.14.0 formatter : dict of callables, optional If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are: - 'bool' - 'int' - 'timedelta' : a `numpy.timedelta64` - 'datetime' : a `numpy.datetime64` - 'float' - 'longfloat' : 128-bit floats - 'complexfloat' - 'longcomplexfloat' : composed of two 128-bit floats - 'void' : type `numpy.void` - 'numpystr' : types `numpy.string_` and `numpy.unicode_` Other keys that can be used to set a group of types at once are: - 'all' : sets all types - 'int_kind' : sets 'int' - 'float_kind' : sets 'float' and 'longfloat' - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat' - 'str_kind' : sets 'numpystr' threshold : int, optional Total number of array elements which trigger summarization rather than full repr. Defaults to ``numpy.get_printoptions()['threshold']``. edgeitems : int, optional Number of array items in summary at beginning and end of each dimension. Defaults to ``numpy.get_printoptions()['edgeitems']``. sign : string, either '-', '+', or ' ', optional Controls printing of the sign of floating-point types. If '+', always print the sign of positive values. If ' ', always prints a space (whitespace character) in the sign position of positive values. If '-', omit the sign character of positive values. Defaults to ``numpy.get_printoptions()['sign']``. floatmode : str, optional Controls the interpretation of the `precision` option for floating-point types. Defaults to ``numpy.get_printoptions()['floatmode']``. Can take the following values: - 'fixed': Always print exactly `precision` fractional digits, even if this would print more or fewer digits than necessary to specify the value uniquely. - 'unique': Print the minimum number of fractional digits necessary to represent each value uniquely. Different elements may have a different number of digits. The value of the `precision` option is ignored. - 'maxprec': Print at most `precision` fractional digits, but if an element can be uniquely represented with fewer digits only print it with that many. - 'maxprec_equal': Print at most `precision` fractional digits, but if every element in the array can be uniquely represented with an equal number of fewer digits, use that many digits for all elements. legacy : string or `False`, optional If set to the string `'1.13'` enables 1.13 legacy printing mode. This approximates numpy 1.13 print output by including a space in the sign position of floats and different behavior for 0d arrays. If set to `False`, disables legacy mode. Unrecognized strings will be ignored with a warning for forward compatibility. .. versionadded:: 1.14.0 Returns ------- array_str : str String representation of the array. Raises ------ TypeError if a callable in `formatter` does not return a string. See Also -------- array_str, array_repr, set_printoptions, get_printoptions Notes ----- If a formatter is specified for a certain type, the `precision` keyword is ignored for that type. This is a very flexible function; `array_repr` and `array_str` are using `array2string` internally so keywords with the same name should work identically in all three functions. Examples -------- >>> x = np.array([1e-16,1,2,3]) >>> np.array2string(x, precision=2, separator=',', ... suppress_small=True) '[0.,1.,2.,3.]' >>> x = np.arange(3.) >>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) '[0.00 1.00 2.00]' >>> x = np.arange(3) >>> np.array2string(x, formatter={'int':lambda x: hex(x)}) '[0x0 0x1 0x2]' """ overrides = _make_options_dict(precision, threshold, edgeitems, max_line_width, suppress_small, None, None, sign, formatter, floatmode, legacy) options = _format_options.copy() options.update(overrides) if options['legacy'] <= 113: if style is np._NoValue: style = repr if a.shape == () and a.dtype.names is None: return style(a.item()) elif style is not np._NoValue: # Deprecation 11-9-2017 v1.14 warnings.warn("'style' argument is deprecated and no longer functional" " except in 1.13 'legacy' mode", DeprecationWarning, stacklevel=3) if options['legacy'] > 113: options['linewidth'] -= len(suffix) # treat as a null array if any of shape elements == 0 if a.size == 0: return "[]" return _array2string(a, options, separator, prefix)
Return a string representation of an array. Parameters ---------- a : ndarray Input array. max_line_width : int, optional Inserts newlines if text is longer than `max_line_width`. Defaults to ``numpy.get_printoptions()['linewidth']``. precision : int or None, optional Floating point precision. Defaults to ``numpy.get_printoptions()['precision']``. suppress_small : bool, optional Represent numbers "very close" to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to ``numpy.get_printoptions()['suppress']``. separator : str, optional Inserted between elements. prefix : str, optional suffix : str, optional The length of the prefix and suffix strings are used to respectively align and wrap the output. An array is typically printed as:: prefix + array2string(a) + suffix The output is left-padded by the length of the prefix string, and wrapping is forced at the column ``max_line_width - len(suffix)``. It should be noted that the content of prefix and suffix strings are not included in the output. style : _NoValue, optional Has no effect, do not use. .. deprecated:: 1.14.0 formatter : dict of callables, optional If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are: - 'bool' - 'int' - 'timedelta' : a `numpy.timedelta64` - 'datetime' : a `numpy.datetime64` - 'float' - 'longfloat' : 128-bit floats - 'complexfloat' - 'longcomplexfloat' : composed of two 128-bit floats - 'void' : type `numpy.void` - 'numpystr' : types `numpy.string_` and `numpy.unicode_` Other keys that can be used to set a group of types at once are: - 'all' : sets all types - 'int_kind' : sets 'int' - 'float_kind' : sets 'float' and 'longfloat' - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat' - 'str_kind' : sets 'numpystr' threshold : int, optional Total number of array elements which trigger summarization rather than full repr. Defaults to ``numpy.get_printoptions()['threshold']``. edgeitems : int, optional Number of array items in summary at beginning and end of each dimension. Defaults to ``numpy.get_printoptions()['edgeitems']``. sign : string, either '-', '+', or ' ', optional Controls printing of the sign of floating-point types. If '+', always print the sign of positive values. If ' ', always prints a space (whitespace character) in the sign position of positive values. If '-', omit the sign character of positive values. Defaults to ``numpy.get_printoptions()['sign']``. floatmode : str, optional Controls the interpretation of the `precision` option for floating-point types. Defaults to ``numpy.get_printoptions()['floatmode']``. Can take the following values: - 'fixed': Always print exactly `precision` fractional digits, even if this would print more or fewer digits than necessary to specify the value uniquely. - 'unique': Print the minimum number of fractional digits necessary to represent each value uniquely. Different elements may have a different number of digits. The value of the `precision` option is ignored. - 'maxprec': Print at most `precision` fractional digits, but if an element can be uniquely represented with fewer digits only print it with that many. - 'maxprec_equal': Print at most `precision` fractional digits, but if every element in the array can be uniquely represented with an equal number of fewer digits, use that many digits for all elements. legacy : string or `False`, optional If set to the string `'1.13'` enables 1.13 legacy printing mode. This approximates numpy 1.13 print output by including a space in the sign position of floats and different behavior for 0d arrays. If set to `False`, disables legacy mode. Unrecognized strings will be ignored with a warning for forward compatibility. .. versionadded:: 1.14.0 Returns ------- array_str : str String representation of the array. Raises ------ TypeError if a callable in `formatter` does not return a string. See Also -------- array_str, array_repr, set_printoptions, get_printoptions Notes ----- If a formatter is specified for a certain type, the `precision` keyword is ignored for that type. This is a very flexible function; `array_repr` and `array_str` are using `array2string` internally so keywords with the same name should work identically in all three functions. Examples -------- >>> x = np.array([1e-16,1,2,3]) >>> np.array2string(x, precision=2, separator=',', ... suppress_small=True) '[0.,1.,2.,3.]' >>> x = np.arange(3.) >>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) '[0.00 1.00 2.00]' >>> x = np.arange(3) >>> np.array2string(x, formatter={'int':lambda x: hex(x)}) '[0x0 0x1 0x2]'
169,179
import functools import numbers import sys import numpy as np from . import numerictypes as _nt from .umath import absolute, isinf, isfinite, isnat from . import multiarray from .multiarray import (array, dragon4_positional, dragon4_scientific, datetime_as_string, datetime_data, ndarray, set_legacy_print_mode) from .fromnumeric import any from .numeric import concatenate, asarray, errstate from .numerictypes import (longlong, intc, int_, float_, complex_, bool_, flexible) from .overrides import array_function_dispatch, set_module import operator import warnings import contextlib def _none_or_positive_arg(x, name): if x is None: return -1 if x < 0: raise ValueError("{} must be >= 0".format(name)) return x The provided code snippet includes necessary dependencies for implementing the `format_float_scientific` function. Write a Python function `def format_float_scientific(x, precision=None, unique=True, trim='k', sign=False, pad_left=None, exp_digits=None, min_digits=None)` to solve the following problem: Format a floating-point scalar as a decimal string in scientific notation. Provides control over rounding, trimming and padding. Uses and assumes IEEE unbiased rounding. Uses the "Dragon4" algorithm. Parameters ---------- x : python float or numpy floating scalar Value to format. precision : non-negative integer or None, optional Maximum number of digits to print. May be None if `unique` is `True`, but must be an integer if unique is `False`. unique : boolean, optional If `True`, use a digit-generation strategy which gives the shortest representation which uniquely identifies the floating-point number from other values of the same type, by judicious rounding. If `precision` is given fewer digits than necessary can be printed. If `min_digits` is given more can be printed, in which cases the last digit is rounded with unbiased rounding. If `False`, digits are generated as if printing an infinite-precision value and stopping after `precision` digits, rounding the remaining value with unbiased rounding trim : one of 'k', '.', '0', '-', optional Controls post-processing trimming of trailing digits, as follows: * 'k' : keep trailing zeros, keep decimal point (no trimming) * '.' : trim all trailing zeros, leave decimal point * '0' : trim all but the zero before the decimal point. Insert the zero if it is missing. * '-' : trim trailing zeros and any trailing decimal point sign : boolean, optional Whether to show the sign for positive values. pad_left : non-negative integer, optional Pad the left side of the string with whitespace until at least that many characters are to the left of the decimal point. exp_digits : non-negative integer, optional Pad the exponent with zeros until it contains at least this many digits. If omitted, the exponent will be at least 2 digits. min_digits : non-negative integer or None, optional Minimum number of digits to print. This only has an effect for `unique=True`. In that case more digits than necessary to uniquely identify the value may be printed and rounded unbiased. -- versionadded:: 1.21.0 Returns ------- rep : string The string representation of the floating point value See Also -------- format_float_positional Examples -------- >>> np.format_float_scientific(np.float32(np.pi)) '3.1415927e+00' >>> s = np.float32(1.23e24) >>> np.format_float_scientific(s, unique=False, precision=15) '1.230000071797338e+24' >>> np.format_float_scientific(s, exp_digits=4) '1.23e+0024' Here is the function: def format_float_scientific(x, precision=None, unique=True, trim='k', sign=False, pad_left=None, exp_digits=None, min_digits=None): """ Format a floating-point scalar as a decimal string in scientific notation. Provides control over rounding, trimming and padding. Uses and assumes IEEE unbiased rounding. Uses the "Dragon4" algorithm. Parameters ---------- x : python float or numpy floating scalar Value to format. precision : non-negative integer or None, optional Maximum number of digits to print. May be None if `unique` is `True`, but must be an integer if unique is `False`. unique : boolean, optional If `True`, use a digit-generation strategy which gives the shortest representation which uniquely identifies the floating-point number from other values of the same type, by judicious rounding. If `precision` is given fewer digits than necessary can be printed. If `min_digits` is given more can be printed, in which cases the last digit is rounded with unbiased rounding. If `False`, digits are generated as if printing an infinite-precision value and stopping after `precision` digits, rounding the remaining value with unbiased rounding trim : one of 'k', '.', '0', '-', optional Controls post-processing trimming of trailing digits, as follows: * 'k' : keep trailing zeros, keep decimal point (no trimming) * '.' : trim all trailing zeros, leave decimal point * '0' : trim all but the zero before the decimal point. Insert the zero if it is missing. * '-' : trim trailing zeros and any trailing decimal point sign : boolean, optional Whether to show the sign for positive values. pad_left : non-negative integer, optional Pad the left side of the string with whitespace until at least that many characters are to the left of the decimal point. exp_digits : non-negative integer, optional Pad the exponent with zeros until it contains at least this many digits. If omitted, the exponent will be at least 2 digits. min_digits : non-negative integer or None, optional Minimum number of digits to print. This only has an effect for `unique=True`. In that case more digits than necessary to uniquely identify the value may be printed and rounded unbiased. -- versionadded:: 1.21.0 Returns ------- rep : string The string representation of the floating point value See Also -------- format_float_positional Examples -------- >>> np.format_float_scientific(np.float32(np.pi)) '3.1415927e+00' >>> s = np.float32(1.23e24) >>> np.format_float_scientific(s, unique=False, precision=15) '1.230000071797338e+24' >>> np.format_float_scientific(s, exp_digits=4) '1.23e+0024' """ precision = _none_or_positive_arg(precision, 'precision') pad_left = _none_or_positive_arg(pad_left, 'pad_left') exp_digits = _none_or_positive_arg(exp_digits, 'exp_digits') min_digits = _none_or_positive_arg(min_digits, 'min_digits') if min_digits > 0 and precision > 0 and min_digits > precision: raise ValueError("min_digits must be less than or equal to precision") return dragon4_scientific(x, precision=precision, unique=unique, trim=trim, sign=sign, pad_left=pad_left, exp_digits=exp_digits, min_digits=min_digits)
Format a floating-point scalar as a decimal string in scientific notation. Provides control over rounding, trimming and padding. Uses and assumes IEEE unbiased rounding. Uses the "Dragon4" algorithm. Parameters ---------- x : python float or numpy floating scalar Value to format. precision : non-negative integer or None, optional Maximum number of digits to print. May be None if `unique` is `True`, but must be an integer if unique is `False`. unique : boolean, optional If `True`, use a digit-generation strategy which gives the shortest representation which uniquely identifies the floating-point number from other values of the same type, by judicious rounding. If `precision` is given fewer digits than necessary can be printed. If `min_digits` is given more can be printed, in which cases the last digit is rounded with unbiased rounding. If `False`, digits are generated as if printing an infinite-precision value and stopping after `precision` digits, rounding the remaining value with unbiased rounding trim : one of 'k', '.', '0', '-', optional Controls post-processing trimming of trailing digits, as follows: * 'k' : keep trailing zeros, keep decimal point (no trimming) * '.' : trim all trailing zeros, leave decimal point * '0' : trim all but the zero before the decimal point. Insert the zero if it is missing. * '-' : trim trailing zeros and any trailing decimal point sign : boolean, optional Whether to show the sign for positive values. pad_left : non-negative integer, optional Pad the left side of the string with whitespace until at least that many characters are to the left of the decimal point. exp_digits : non-negative integer, optional Pad the exponent with zeros until it contains at least this many digits. If omitted, the exponent will be at least 2 digits. min_digits : non-negative integer or None, optional Minimum number of digits to print. This only has an effect for `unique=True`. In that case more digits than necessary to uniquely identify the value may be printed and rounded unbiased. -- versionadded:: 1.21.0 Returns ------- rep : string The string representation of the floating point value See Also -------- format_float_positional Examples -------- >>> np.format_float_scientific(np.float32(np.pi)) '3.1415927e+00' >>> s = np.float32(1.23e24) >>> np.format_float_scientific(s, unique=False, precision=15) '1.230000071797338e+24' >>> np.format_float_scientific(s, exp_digits=4) '1.23e+0024'
169,180
import functools import numbers import sys import numpy as np from . import numerictypes as _nt from .umath import absolute, isinf, isfinite, isnat from . import multiarray from .multiarray import (array, dragon4_positional, dragon4_scientific, datetime_as_string, datetime_data, ndarray, set_legacy_print_mode) from .fromnumeric import any from .numeric import concatenate, asarray, errstate from .numerictypes import (longlong, intc, int_, float_, complex_, bool_, flexible) from .overrides import array_function_dispatch, set_module import operator import warnings import contextlib def _none_or_positive_arg(x, name): if x is None: return -1 if x < 0: raise ValueError("{} must be >= 0".format(name)) return x The provided code snippet includes necessary dependencies for implementing the `format_float_positional` function. Write a Python function `def format_float_positional(x, precision=None, unique=True, fractional=True, trim='k', sign=False, pad_left=None, pad_right=None, min_digits=None)` to solve the following problem: Format a floating-point scalar as a decimal string in positional notation. Provides control over rounding, trimming and padding. Uses and assumes IEEE unbiased rounding. Uses the "Dragon4" algorithm. Parameters ---------- x : python float or numpy floating scalar Value to format. precision : non-negative integer or None, optional Maximum number of digits to print. May be None if `unique` is `True`, but must be an integer if unique is `False`. unique : boolean, optional If `True`, use a digit-generation strategy which gives the shortest representation which uniquely identifies the floating-point number from other values of the same type, by judicious rounding. If `precision` is given fewer digits than necessary can be printed, or if `min_digits` is given more can be printed, in which cases the last digit is rounded with unbiased rounding. If `False`, digits are generated as if printing an infinite-precision value and stopping after `precision` digits, rounding the remaining value with unbiased rounding fractional : boolean, optional If `True`, the cutoffs of `precision` and `min_digits` refer to the total number of digits after the decimal point, including leading zeros. If `False`, `precision` and `min_digits` refer to the total number of significant digits, before or after the decimal point, ignoring leading zeros. trim : one of 'k', '.', '0', '-', optional Controls post-processing trimming of trailing digits, as follows: * 'k' : keep trailing zeros, keep decimal point (no trimming) * '.' : trim all trailing zeros, leave decimal point * '0' : trim all but the zero before the decimal point. Insert the zero if it is missing. * '-' : trim trailing zeros and any trailing decimal point sign : boolean, optional Whether to show the sign for positive values. pad_left : non-negative integer, optional Pad the left side of the string with whitespace until at least that many characters are to the left of the decimal point. pad_right : non-negative integer, optional Pad the right side of the string with whitespace until at least that many characters are to the right of the decimal point. min_digits : non-negative integer or None, optional Minimum number of digits to print. Only has an effect if `unique=True` in which case additional digits past those necessary to uniquely identify the value may be printed, rounding the last additional digit. -- versionadded:: 1.21.0 Returns ------- rep : string The string representation of the floating point value See Also -------- format_float_scientific Examples -------- >>> np.format_float_positional(np.float32(np.pi)) '3.1415927' >>> np.format_float_positional(np.float16(np.pi)) '3.14' >>> np.format_float_positional(np.float16(0.3)) '0.3' >>> np.format_float_positional(np.float16(0.3), unique=False, precision=10) '0.3000488281' Here is the function: def format_float_positional(x, precision=None, unique=True, fractional=True, trim='k', sign=False, pad_left=None, pad_right=None, min_digits=None): """ Format a floating-point scalar as a decimal string in positional notation. Provides control over rounding, trimming and padding. Uses and assumes IEEE unbiased rounding. Uses the "Dragon4" algorithm. Parameters ---------- x : python float or numpy floating scalar Value to format. precision : non-negative integer or None, optional Maximum number of digits to print. May be None if `unique` is `True`, but must be an integer if unique is `False`. unique : boolean, optional If `True`, use a digit-generation strategy which gives the shortest representation which uniquely identifies the floating-point number from other values of the same type, by judicious rounding. If `precision` is given fewer digits than necessary can be printed, or if `min_digits` is given more can be printed, in which cases the last digit is rounded with unbiased rounding. If `False`, digits are generated as if printing an infinite-precision value and stopping after `precision` digits, rounding the remaining value with unbiased rounding fractional : boolean, optional If `True`, the cutoffs of `precision` and `min_digits` refer to the total number of digits after the decimal point, including leading zeros. If `False`, `precision` and `min_digits` refer to the total number of significant digits, before or after the decimal point, ignoring leading zeros. trim : one of 'k', '.', '0', '-', optional Controls post-processing trimming of trailing digits, as follows: * 'k' : keep trailing zeros, keep decimal point (no trimming) * '.' : trim all trailing zeros, leave decimal point * '0' : trim all but the zero before the decimal point. Insert the zero if it is missing. * '-' : trim trailing zeros and any trailing decimal point sign : boolean, optional Whether to show the sign for positive values. pad_left : non-negative integer, optional Pad the left side of the string with whitespace until at least that many characters are to the left of the decimal point. pad_right : non-negative integer, optional Pad the right side of the string with whitespace until at least that many characters are to the right of the decimal point. min_digits : non-negative integer or None, optional Minimum number of digits to print. Only has an effect if `unique=True` in which case additional digits past those necessary to uniquely identify the value may be printed, rounding the last additional digit. -- versionadded:: 1.21.0 Returns ------- rep : string The string representation of the floating point value See Also -------- format_float_scientific Examples -------- >>> np.format_float_positional(np.float32(np.pi)) '3.1415927' >>> np.format_float_positional(np.float16(np.pi)) '3.14' >>> np.format_float_positional(np.float16(0.3)) '0.3' >>> np.format_float_positional(np.float16(0.3), unique=False, precision=10) '0.3000488281' """ precision = _none_or_positive_arg(precision, 'precision') pad_left = _none_or_positive_arg(pad_left, 'pad_left') pad_right = _none_or_positive_arg(pad_right, 'pad_right') min_digits = _none_or_positive_arg(min_digits, 'min_digits') if not fractional and precision == 0: raise ValueError("precision must be greater than 0 if " "fractional=False") if min_digits > 0 and precision > 0 and min_digits > precision: raise ValueError("min_digits must be less than or equal to precision") return dragon4_positional(x, precision=precision, unique=unique, fractional=fractional, trim=trim, sign=sign, pad_left=pad_left, pad_right=pad_right, min_digits=min_digits)
Format a floating-point scalar as a decimal string in positional notation. Provides control over rounding, trimming and padding. Uses and assumes IEEE unbiased rounding. Uses the "Dragon4" algorithm. Parameters ---------- x : python float or numpy floating scalar Value to format. precision : non-negative integer or None, optional Maximum number of digits to print. May be None if `unique` is `True`, but must be an integer if unique is `False`. unique : boolean, optional If `True`, use a digit-generation strategy which gives the shortest representation which uniquely identifies the floating-point number from other values of the same type, by judicious rounding. If `precision` is given fewer digits than necessary can be printed, or if `min_digits` is given more can be printed, in which cases the last digit is rounded with unbiased rounding. If `False`, digits are generated as if printing an infinite-precision value and stopping after `precision` digits, rounding the remaining value with unbiased rounding fractional : boolean, optional If `True`, the cutoffs of `precision` and `min_digits` refer to the total number of digits after the decimal point, including leading zeros. If `False`, `precision` and `min_digits` refer to the total number of significant digits, before or after the decimal point, ignoring leading zeros. trim : one of 'k', '.', '0', '-', optional Controls post-processing trimming of trailing digits, as follows: * 'k' : keep trailing zeros, keep decimal point (no trimming) * '.' : trim all trailing zeros, leave decimal point * '0' : trim all but the zero before the decimal point. Insert the zero if it is missing. * '-' : trim trailing zeros and any trailing decimal point sign : boolean, optional Whether to show the sign for positive values. pad_left : non-negative integer, optional Pad the left side of the string with whitespace until at least that many characters are to the left of the decimal point. pad_right : non-negative integer, optional Pad the right side of the string with whitespace until at least that many characters are to the right of the decimal point. min_digits : non-negative integer or None, optional Minimum number of digits to print. Only has an effect if `unique=True` in which case additional digits past those necessary to uniquely identify the value may be printed, rounding the last additional digit. -- versionadded:: 1.21.0 Returns ------- rep : string The string representation of the floating point value See Also -------- format_float_scientific Examples -------- >>> np.format_float_positional(np.float32(np.pi)) '3.1415927' >>> np.format_float_positional(np.float16(np.pi)) '3.14' >>> np.format_float_positional(np.float16(0.3)) '0.3' >>> np.format_float_positional(np.float16(0.3), unique=False, precision=10) '0.3000488281'
169,181
import functools import numbers import sys import numpy as np from . import numerictypes as _nt from .umath import absolute, isinf, isfinite, isnat from . import multiarray from .multiarray import (array, dragon4_positional, dragon4_scientific, datetime_as_string, datetime_data, ndarray, set_legacy_print_mode) from .fromnumeric import any from .numeric import concatenate, asarray, errstate from .numerictypes import (longlong, intc, int_, float_, complex_, bool_, flexible) from .overrides import array_function_dispatch, set_module import operator import warnings import contextlib _format_options = { 'edgeitems': 3, # repr N leading and trailing items of each dimension 'threshold': 1000, # total items > triggers array summarization 'floatmode': 'maxprec', 'precision': 8, # precision of floating point representations 'suppress': False, # suppress printing small floating values in exp format 'linewidth': 75, 'nanstr': 'nan', 'infstr': 'inf', 'sign': '-', 'formatter': None, # Internally stored as an int to simplify comparisons; converted from/to # str/False on the way in/out. 'legacy': sys.maxsize} class StructuredVoidFormat: """ Formatter for structured np.void objects. This does not work on structured alias types like np.dtype(('i4', 'i2,i2')), as alias scalars lose their field information, and the implementation relies upon np.void.__getitem__. """ def __init__(self, format_functions): self.format_functions = format_functions def from_data(cls, data, **options): """ This is a second way to initialize StructuredVoidFormat, using the raw data as input. Added to avoid changing the signature of __init__. """ format_functions = [] for field_name in data.dtype.names: format_function = _get_format_function(data[field_name], **options) if data.dtype[field_name].shape != (): format_function = SubArrayFormat(format_function) format_functions.append(format_function) return cls(format_functions) def __call__(self, x): str_fields = [ format_function(field) for field, format_function in zip(x, self.format_functions) ] if len(str_fields) == 1: return "({},)".format(str_fields[0]) else: return "({})".format(", ".join(str_fields)) array.__module__ = 'numpy' The provided code snippet includes necessary dependencies for implementing the `_void_scalar_repr` function. Write a Python function `def _void_scalar_repr(x)` to solve the following problem: Implements the repr for structured-void scalars. It is called from the scalartypes.c.src code, and is placed here because it uses the elementwise formatters defined above. Here is the function: def _void_scalar_repr(x): """ Implements the repr for structured-void scalars. It is called from the scalartypes.c.src code, and is placed here because it uses the elementwise formatters defined above. """ return StructuredVoidFormat.from_data(array(x), **_format_options)(x)
Implements the repr for structured-void scalars. It is called from the scalartypes.c.src code, and is placed here because it uses the elementwise formatters defined above.
169,182
import functools import numbers import sys import numpy as np from . import numerictypes as _nt from .umath import absolute, isinf, isfinite, isnat from . import multiarray from .multiarray import (array, dragon4_positional, dragon4_scientific, datetime_as_string, datetime_data, ndarray, set_legacy_print_mode) from .fromnumeric import any from .numeric import concatenate, asarray, errstate from .numerictypes import (longlong, intc, int_, float_, complex_, bool_, flexible) from .overrides import array_function_dispatch, set_module import operator import warnings import contextlib def _array_repr_dispatcher( arr, max_line_width=None, precision=None, suppress_small=None): return (arr,)
null
169,183
import functools import numbers import sys import numpy as np from . import numerictypes as _nt from .umath import absolute, isinf, isfinite, isnat from . import multiarray from .multiarray import (array, dragon4_positional, dragon4_scientific, datetime_as_string, datetime_data, ndarray, set_legacy_print_mode) from .fromnumeric import any from .numeric import concatenate, asarray, errstate from .numerictypes import (longlong, intc, int_, float_, complex_, bool_, flexible) from .overrides import array_function_dispatch, set_module import operator import warnings import contextlib def _array_repr_implementation( arr, max_line_width=None, precision=None, suppress_small=None, array2string=array2string): """Internal version of array_repr() that allows overriding array2string.""" if max_line_width is None: max_line_width = _format_options['linewidth'] if type(arr) is not ndarray: class_name = type(arr).__name__ else: class_name = "array" skipdtype = dtype_is_implied(arr.dtype) and arr.size > 0 prefix = class_name + "(" suffix = ")" if skipdtype else "," if (_format_options['legacy'] <= 113 and arr.shape == () and not arr.dtype.names): lst = repr(arr.item()) elif arr.size > 0 or arr.shape == (0,): lst = array2string(arr, max_line_width, precision, suppress_small, ', ', prefix, suffix=suffix) else: # show zero-length shape unless it is (0,) lst = "[], shape=%s" % (repr(arr.shape),) arr_str = prefix + lst + suffix if skipdtype: return arr_str dtype_str = "dtype={})".format(dtype_short_repr(arr.dtype)) # compute whether we should put dtype on a new line: Do so if adding the # dtype would extend the last line past max_line_width. # Note: This line gives the correct result even when rfind returns -1. last_line_len = len(arr_str) - (arr_str.rfind('\n') + 1) spacer = " " if _format_options['legacy'] <= 113: if issubclass(arr.dtype.type, flexible): spacer = '\n' + ' '*len(class_name + "(") elif last_line_len + len(dtype_str) + 1 > max_line_width: spacer = '\n' + ' '*len(class_name + "(") return arr_str + spacer + dtype_str The provided code snippet includes necessary dependencies for implementing the `array_repr` function. Write a Python function `def array_repr(arr, max_line_width=None, precision=None, suppress_small=None)` to solve the following problem: Return the string representation of an array. Parameters ---------- arr : ndarray Input array. max_line_width : int, optional Inserts newlines if text is longer than `max_line_width`. Defaults to ``numpy.get_printoptions()['linewidth']``. precision : int, optional Floating point precision. Defaults to ``numpy.get_printoptions()['precision']``. suppress_small : bool, optional Represent numbers "very close" to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to ``numpy.get_printoptions()['suppress']``. Returns ------- string : str The string representation of an array. See Also -------- array_str, array2string, set_printoptions Examples -------- >>> np.array_repr(np.array([1,2])) 'array([1, 2])' >>> np.array_repr(np.ma.array([0.])) 'MaskedArray([0.])' >>> np.array_repr(np.array([], np.int32)) 'array([], dtype=int32)' >>> x = np.array([1e-6, 4e-7, 2, 3]) >>> np.array_repr(x, precision=6, suppress_small=True) 'array([0.000001, 0. , 2. , 3. ])' Here is the function: def array_repr(arr, max_line_width=None, precision=None, suppress_small=None): """ Return the string representation of an array. Parameters ---------- arr : ndarray Input array. max_line_width : int, optional Inserts newlines if text is longer than `max_line_width`. Defaults to ``numpy.get_printoptions()['linewidth']``. precision : int, optional Floating point precision. Defaults to ``numpy.get_printoptions()['precision']``. suppress_small : bool, optional Represent numbers "very close" to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to ``numpy.get_printoptions()['suppress']``. Returns ------- string : str The string representation of an array. See Also -------- array_str, array2string, set_printoptions Examples -------- >>> np.array_repr(np.array([1,2])) 'array([1, 2])' >>> np.array_repr(np.ma.array([0.])) 'MaskedArray([0.])' >>> np.array_repr(np.array([], np.int32)) 'array([], dtype=int32)' >>> x = np.array([1e-6, 4e-7, 2, 3]) >>> np.array_repr(x, precision=6, suppress_small=True) 'array([0.000001, 0. , 2. , 3. ])' """ return _array_repr_implementation( arr, max_line_width, precision, suppress_small)
Return the string representation of an array. Parameters ---------- arr : ndarray Input array. max_line_width : int, optional Inserts newlines if text is longer than `max_line_width`. Defaults to ``numpy.get_printoptions()['linewidth']``. precision : int, optional Floating point precision. Defaults to ``numpy.get_printoptions()['precision']``. suppress_small : bool, optional Represent numbers "very close" to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to ``numpy.get_printoptions()['suppress']``. Returns ------- string : str The string representation of an array. See Also -------- array_str, array2string, set_printoptions Examples -------- >>> np.array_repr(np.array([1,2])) 'array([1, 2])' >>> np.array_repr(np.ma.array([0.])) 'MaskedArray([0.])' >>> np.array_repr(np.array([], np.int32)) 'array([], dtype=int32)' >>> x = np.array([1e-6, 4e-7, 2, 3]) >>> np.array_repr(x, precision=6, suppress_small=True) 'array([0.000001, 0. , 2. , 3. ])'
169,184
import functools import numbers import sys import numpy as np from . import numerictypes as _nt from .umath import absolute, isinf, isfinite, isnat from . import multiarray from .multiarray import (array, dragon4_positional, dragon4_scientific, datetime_as_string, datetime_data, ndarray, set_legacy_print_mode) from .fromnumeric import any from .numeric import concatenate, asarray, errstate from .numerictypes import (longlong, intc, int_, float_, complex_, bool_, flexible) from .overrides import array_function_dispatch, set_module import operator import warnings import contextlib def _array_str_dispatcher( a, max_line_width=None, precision=None, suppress_small=None): return (a,)
null
169,185
import functools import numbers import sys import numpy as np from . import numerictypes as _nt from .umath import absolute, isinf, isfinite, isnat from . import multiarray from .multiarray import (array, dragon4_positional, dragon4_scientific, datetime_as_string, datetime_data, ndarray, set_legacy_print_mode) from .fromnumeric import any from .numeric import concatenate, asarray, errstate from .numerictypes import (longlong, intc, int_, float_, complex_, bool_, flexible) from .overrides import array_function_dispatch, set_module import operator import warnings import contextlib def _array_str_implementation( a, max_line_width=None, precision=None, suppress_small=None, array2string=array2string): """Internal version of array_str() that allows overriding array2string.""" if (_format_options['legacy'] <= 113 and a.shape == () and not a.dtype.names): return str(a.item()) # the str of 0d arrays is a special case: It should appear like a scalar, # so floats are not truncated by `precision`, and strings are not wrapped # in quotes. So we return the str of the scalar value. if a.shape == (): # obtain a scalar and call str on it, avoiding problems for subclasses # for which indexing with () returns a 0d instead of a scalar by using # ndarray's getindex. Also guard against recursive 0d object arrays. return _guarded_repr_or_str(np.ndarray.__getitem__(a, ())) return array2string(a, max_line_width, precision, suppress_small, ' ', "") The provided code snippet includes necessary dependencies for implementing the `array_str` function. Write a Python function `def array_str(a, max_line_width=None, precision=None, suppress_small=None)` to solve the following problem: Return a string representation of the data in an array. The data in the array is returned as a single string. This function is similar to `array_repr`, the difference being that `array_repr` also returns information on the kind of array and its data type. Parameters ---------- a : ndarray Input array. max_line_width : int, optional Inserts newlines if text is longer than `max_line_width`. Defaults to ``numpy.get_printoptions()['linewidth']``. precision : int, optional Floating point precision. Defaults to ``numpy.get_printoptions()['precision']``. suppress_small : bool, optional Represent numbers "very close" to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to ``numpy.get_printoptions()['suppress']``. See Also -------- array2string, array_repr, set_printoptions Examples -------- >>> np.array_str(np.arange(3)) '[0 1 2]' Here is the function: def array_str(a, max_line_width=None, precision=None, suppress_small=None): """ Return a string representation of the data in an array. The data in the array is returned as a single string. This function is similar to `array_repr`, the difference being that `array_repr` also returns information on the kind of array and its data type. Parameters ---------- a : ndarray Input array. max_line_width : int, optional Inserts newlines if text is longer than `max_line_width`. Defaults to ``numpy.get_printoptions()['linewidth']``. precision : int, optional Floating point precision. Defaults to ``numpy.get_printoptions()['precision']``. suppress_small : bool, optional Represent numbers "very close" to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to ``numpy.get_printoptions()['suppress']``. See Also -------- array2string, array_repr, set_printoptions Examples -------- >>> np.array_str(np.arange(3)) '[0 1 2]' """ return _array_str_implementation( a, max_line_width, precision, suppress_small)
Return a string representation of the data in an array. The data in the array is returned as a single string. This function is similar to `array_repr`, the difference being that `array_repr` also returns information on the kind of array and its data type. Parameters ---------- a : ndarray Input array. max_line_width : int, optional Inserts newlines if text is longer than `max_line_width`. Defaults to ``numpy.get_printoptions()['linewidth']``. precision : int, optional Floating point precision. Defaults to ``numpy.get_printoptions()['precision']``. suppress_small : bool, optional Represent numbers "very close" to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to ``numpy.get_printoptions()['suppress']``. See Also -------- array2string, array_repr, set_printoptions Examples -------- >>> np.array_str(np.arange(3)) '[0 1 2]'
169,186
import functools import numbers import sys import numpy as np from . import numerictypes as _nt from .umath import absolute, isinf, isfinite, isnat from . import multiarray from .multiarray import (array, dragon4_positional, dragon4_scientific, datetime_as_string, datetime_data, ndarray, set_legacy_print_mode) from .fromnumeric import any from .numeric import concatenate, asarray, errstate from .numerictypes import (longlong, intc, int_, float_, complex_, bool_, flexible) from .overrides import array_function_dispatch, set_module import operator import warnings import contextlib _default_array_str = functools.partial(_array_str_implementation, array2string=_array2string_impl) _default_array_repr = functools.partial(_array_repr_implementation, array2string=_array2string_impl) The provided code snippet includes necessary dependencies for implementing the `set_string_function` function. Write a Python function `def set_string_function(f, repr=True)` to solve the following problem: Set a Python function to be used when pretty printing arrays. Parameters ---------- f : function or None Function to be used to pretty print arrays. The function should expect a single array argument and return a string of the representation of the array. If None, the function is reset to the default NumPy function to print arrays. repr : bool, optional If True (default), the function for pretty printing (``__repr__``) is set, if False the function that returns the default string representation (``__str__``) is set. See Also -------- set_printoptions, get_printoptions Examples -------- >>> def pprint(arr): ... return 'HA! - What are you going to do now?' ... >>> np.set_string_function(pprint) >>> a = np.arange(10) >>> a HA! - What are you going to do now? >>> _ = a >>> # [0 1 2 3 4 5 6 7 8 9] We can reset the function to the default: >>> np.set_string_function(None) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) `repr` affects either pretty printing or normal string representation. Note that ``__repr__`` is still affected by setting ``__str__`` because the width of each array element in the returned string becomes equal to the length of the result of ``__str__()``. >>> x = np.arange(4) >>> np.set_string_function(lambda x:'random', repr=False) >>> x.__str__() 'random' >>> x.__repr__() 'array([0, 1, 2, 3])' Here is the function: def set_string_function(f, repr=True): """ Set a Python function to be used when pretty printing arrays. Parameters ---------- f : function or None Function to be used to pretty print arrays. The function should expect a single array argument and return a string of the representation of the array. If None, the function is reset to the default NumPy function to print arrays. repr : bool, optional If True (default), the function for pretty printing (``__repr__``) is set, if False the function that returns the default string representation (``__str__``) is set. See Also -------- set_printoptions, get_printoptions Examples -------- >>> def pprint(arr): ... return 'HA! - What are you going to do now?' ... >>> np.set_string_function(pprint) >>> a = np.arange(10) >>> a HA! - What are you going to do now? >>> _ = a >>> # [0 1 2 3 4 5 6 7 8 9] We can reset the function to the default: >>> np.set_string_function(None) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) `repr` affects either pretty printing or normal string representation. Note that ``__repr__`` is still affected by setting ``__str__`` because the width of each array element in the returned string becomes equal to the length of the result of ``__str__()``. >>> x = np.arange(4) >>> np.set_string_function(lambda x:'random', repr=False) >>> x.__str__() 'random' >>> x.__repr__() 'array([0, 1, 2, 3])' """ if f is None: if repr: return multiarray.set_string_function(_default_array_repr, 1) else: return multiarray.set_string_function(_default_array_str, 0) else: return multiarray.set_string_function(f, repr)
Set a Python function to be used when pretty printing arrays. Parameters ---------- f : function or None Function to be used to pretty print arrays. The function should expect a single array argument and return a string of the representation of the array. If None, the function is reset to the default NumPy function to print arrays. repr : bool, optional If True (default), the function for pretty printing (``__repr__``) is set, if False the function that returns the default string representation (``__str__``) is set. See Also -------- set_printoptions, get_printoptions Examples -------- >>> def pprint(arr): ... return 'HA! - What are you going to do now?' ... >>> np.set_string_function(pprint) >>> a = np.arange(10) >>> a HA! - What are you going to do now? >>> _ = a >>> # [0 1 2 3 4 5 6 7 8 9] We can reset the function to the default: >>> np.set_string_function(None) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) `repr` affects either pretty printing or normal string representation. Note that ``__repr__`` is still affected by setting ``__str__`` because the width of each array element in the returned string becomes equal to the length of the result of ``__str__()``. >>> x = np.arange(4) >>> np.set_string_function(lambda x:'random', repr=False) >>> x.__str__() 'random' >>> x.__repr__() 'array([0, 1, 2, 3])'
169,187
import os import sys import sysconfig import pickle import copy import warnings import textwrap import glob from os.path import join from numpy.distutils import log from numpy.distutils.msvccompiler import lib_opts_if_msvc from distutils.dep_util import newer from sysconfig import get_config_var from numpy.compat import npy_load_module from setup_common import * NPY_RELAXED_STRIDES_DEBUG = (os.environ.get('NPY_RELAXED_STRIDES_DEBUG', "0") != "0") NPY_RELAXED_STRIDES_DEBUG = NPY_RELAXED_STRIDES_DEBUG and NPY_RELAXED_STRIDES_CHECKING class CallOnceOnly: def __init__(self): self._check_types = None self._check_ieee_macros = None self._check_complex = None def check_types(self, *a, **kw): if self._check_types is None: out = check_types(*a, **kw) self._check_types = pickle.dumps(out) else: out = copy.deepcopy(pickle.loads(self._check_types)) return out def check_ieee_macros(self, *a, **kw): if self._check_ieee_macros is None: out = check_ieee_macros(*a, **kw) self._check_ieee_macros = pickle.dumps(out) else: out = copy.deepcopy(pickle.loads(self._check_ieee_macros)) return out def check_complex(self, *a, **kw): if self._check_complex is None: out = check_complex(*a, **kw) self._check_complex = pickle.dumps(out) else: out = copy.deepcopy(pickle.loads(self._check_complex)) return out def can_link_svml(): """SVML library is supported only on x86_64 architecture and currently only on linux """ if NPY_DISABLE_SVML: return False platform = sysconfig.get_platform() return ("x86_64" in platform and "linux" in platform and sys.maxsize > 2**31) def check_svml_submodule(svmlpath): if not os.path.exists(svmlpath + "/README.md"): raise RuntimeError("Missing `SVML` submodule! Run `git submodule " "update --init` to fix this.") return True def is_npy_no_signal(): """Return True if the NPY_NO_SIGNAL symbol must be defined in configuration header.""" return sys.platform == 'win32' def is_npy_no_smp(): """Return True if the NPY_NO_SMP symbol must be defined in public header (when SMP support cannot be reliably enabled).""" # Perhaps a fancier check is in order here. # so that threads are only enabled if there # are actually multiple CPUS? -- but # threaded code can be nice even on a single # CPU so that long-calculating code doesn't # block. return 'NPY_NOSMP' in os.environ def win32_checks(deflist): from numpy.distutils.misc_util import get_build_architecture a = get_build_architecture() # Distutils hack on AMD64 on windows print('BUILD_ARCHITECTURE: %r, os.name=%r, sys.platform=%r' % (a, os.name, sys.platform)) if a == 'AMD64': deflist.append('DISTUTILS_USE_SDK') # On win32, force long double format string to be 'g', not # 'Lg', since the MS runtime does not support long double whose # size is > sizeof(double) if a == "Intel" or a == "AMD64": deflist.append('FORCE_NO_LONG_DOUBLE_FORMATTING') def check_math_capabilities(config, ext, moredefs, mathlibs): def check_func( func_name, decl=False, headers=["feature_detection_math.h", "feature_detection_cmath.h"], ): return config.check_func( func_name, libraries=mathlibs, decl=decl, call=True, call_args=FUNC_CALL_ARGS[func_name], headers=headers, ) def check_funcs_once( funcs_name, headers=["feature_detection_math.h", "feature_detection_cmath.h"], add_to_moredefs=True): call = dict([(f, True) for f in funcs_name]) call_args = dict([(f, FUNC_CALL_ARGS[f]) for f in funcs_name]) st = config.check_funcs_once( funcs_name, libraries=mathlibs, decl=False, call=call, call_args=call_args, headers=headers, ) if st and add_to_moredefs: moredefs.extend([(fname2def(f), 1) for f in funcs_name]) return st def check_funcs( funcs_name, headers=["feature_detection_math.h", "feature_detection_cmath.h"]): # Use check_funcs_once first, and if it does not work, test func per # func. Return success only if all the functions are available if not check_funcs_once(funcs_name, headers=headers): # Global check failed, check func per func for f in funcs_name: if check_func(f, headers=headers): moredefs.append((fname2def(f), 1)) return 0 else: return 1 # GH-14787: Work around GCC<8.4 bug when compiling with AVX512 # support on Windows-based platforms def check_gh14787(fn): if fn == 'attribute_target_avx512f': if (sys.platform in ('win32', 'cygwin') and config.check_compiler_gcc() and not config.check_gcc_version_at_least(8, 4)): ext.extra_compile_args.extend( ['-ffixed-xmm%s' % n for n in range(16, 32)]) #use_msvc = config.check_decl("_MSC_VER") if not check_funcs_once(MANDATORY_FUNCS, add_to_moredefs=False): raise SystemError("One of the required function to build numpy is not" " available (the list is %s)." % str(MANDATORY_FUNCS)) # Standard functions which may not be available and for which we have a # replacement implementation. Note that some of these are C99 functions. # XXX: hack to circumvent cpp pollution from python: python put its # config.h in the public namespace, so we have a clash for the common # functions we test. We remove every function tested by python's # autoconf, hoping their own test are correct for f in OPTIONAL_FUNCS_MAYBE: if config.check_decl(fname2def(f), headers=["Python.h"]): OPTIONAL_FILE_FUNCS.remove(f) check_funcs(OPTIONAL_FILE_FUNCS, headers=["feature_detection_stdio.h"]) check_funcs(OPTIONAL_MISC_FUNCS, headers=["feature_detection_misc.h"]) for h in OPTIONAL_HEADERS: if config.check_func("", decl=False, call=False, headers=[h]): h = h.replace(".", "_").replace(os.path.sep, "_") moredefs.append((fname2def(h), 1)) # Try with both "locale.h" and "xlocale.h" locale_headers = [ "stdlib.h", "xlocale.h", "feature_detection_locale.h", ] if not check_funcs(OPTIONAL_LOCALE_FUNCS, headers=locale_headers): # It didn't work with xlocale.h, maybe it will work with locale.h? locale_headers[1] = "locale.h" check_funcs(OPTIONAL_LOCALE_FUNCS, headers=locale_headers) for tup in OPTIONAL_INTRINSICS: headers = None if len(tup) == 2: f, args, m = tup[0], tup[1], fname2def(tup[0]) elif len(tup) == 3: f, args, headers, m = tup[0], tup[1], [tup[2]], fname2def(tup[0]) else: f, args, headers, m = tup[0], tup[1], [tup[2]], fname2def(tup[3]) if config.check_func(f, decl=False, call=True, call_args=args, headers=headers): moredefs.append((m, 1)) for dec, fn in OPTIONAL_FUNCTION_ATTRIBUTES: if config.check_gcc_function_attribute(dec, fn): moredefs.append((fname2def(fn), 1)) check_gh14787(fn) platform = sysconfig.get_platform() if ("x86_64" in platform): for dec, fn in OPTIONAL_FUNCTION_ATTRIBUTES_AVX: if config.check_gcc_function_attribute(dec, fn): moredefs.append((fname2def(fn), 1)) check_gh14787(fn) for dec, fn, code, header in ( OPTIONAL_FUNCTION_ATTRIBUTES_WITH_INTRINSICS_AVX): if config.check_gcc_function_attribute_with_intrinsics( dec, fn, code, header): moredefs.append((fname2def(fn), 1)) for fn in OPTIONAL_VARIABLE_ATTRIBUTES: if config.check_gcc_variable_attribute(fn): m = fn.replace("(", "_").replace(")", "_") moredefs.append((fname2def(m), 1)) def check_complex(config, mathlibs): priv = [] pub = [] # Check for complex support st = config.check_header('complex.h') if st: priv.append(('HAVE_COMPLEX_H', 1)) pub.append(('NPY_USE_C99_COMPLEX', 1)) for t in C99_COMPLEX_TYPES: st = config.check_type(t, headers=["complex.h"]) if st: pub.append(('NPY_HAVE_%s' % type2def(t), 1)) def check_prec(prec): flist = [f + prec for f in C99_COMPLEX_FUNCS] decl = dict([(f, True) for f in flist]) if not config.check_funcs_once(flist, call=decl, decl=decl, libraries=mathlibs): for f in flist: if config.check_func(f, call=True, decl=True, libraries=mathlibs): priv.append((fname2def(f), 1)) else: priv.extend([(fname2def(f), 1) for f in flist]) check_prec('') check_prec('f') check_prec('l') return priv, pub def check_ieee_macros(config): priv = [] pub = [] macros = [] def _add_decl(f): priv.append(fname2def("decl_%s" % f)) pub.append('NPY_%s' % fname2def("decl_%s" % f)) # XXX: hack to circumvent cpp pollution from python: python put its # config.h in the public namespace, so we have a clash for the common # functions we test. We remove every function tested by python's # autoconf, hoping their own test are correct _macros = ["isnan", "isinf", "signbit", "isfinite"] for f in _macros: py_symbol = fname2def("decl_%s" % f) already_declared = config.check_decl(py_symbol, headers=["Python.h", "math.h"]) if already_declared: if config.check_macro_true(py_symbol, headers=["Python.h", "math.h"]): pub.append('NPY_%s' % fname2def("decl_%s" % f)) else: macros.append(f) # Normally, isnan and isinf are macro (C99), but some platforms only have # func, or both func and macro version. Check for macro only, and define # replacement ones if not found. # Note: including Python.h is necessary because it modifies some math.h # definitions for f in macros: st = config.check_decl(f, headers=["Python.h", "math.h"]) if st: _add_decl(f) return priv, pub def check_types(config_cmd, ext, build_dir): private_defines = [] public_defines = [] # Expected size (in number of bytes) for each type. This is an # optimization: those are only hints, and an exhaustive search for the size # is done if the hints are wrong. expected = {'short': [2], 'int': [4], 'long': [8, 4], 'float': [4], 'double': [8], 'long double': [16, 12, 8], 'Py_intptr_t': [8, 4], 'PY_LONG_LONG': [8], 'long long': [8], 'off_t': [8, 4]} # Check we have the python header (-dev* packages on Linux) result = config_cmd.check_header('Python.h') if not result: python = 'python' if '__pypy__' in sys.builtin_module_names: python = 'pypy' raise SystemError( "Cannot compile 'Python.h'. Perhaps you need to " "install {0}-dev|{0}-devel.".format(python)) res = config_cmd.check_header("endian.h") if res: private_defines.append(('HAVE_ENDIAN_H', 1)) public_defines.append(('NPY_HAVE_ENDIAN_H', 1)) res = config_cmd.check_header("sys/endian.h") if res: private_defines.append(('HAVE_SYS_ENDIAN_H', 1)) public_defines.append(('NPY_HAVE_SYS_ENDIAN_H', 1)) # Check basic types sizes for type in ('short', 'int', 'long'): res = config_cmd.check_decl("SIZEOF_%s" % sym2def(type), headers=["Python.h"]) if res: public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), "SIZEOF_%s" % sym2def(type))) else: res = config_cmd.check_type_size(type, expected=expected[type]) if res >= 0: public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % type) for type in ('float', 'double', 'long double'): already_declared = config_cmd.check_decl("SIZEOF_%s" % sym2def(type), headers=["Python.h"]) res = config_cmd.check_type_size(type, expected=expected[type]) if res >= 0: public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res)) if not already_declared and not type == 'long double': private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % type) # Compute size of corresponding complex type: used to check that our # definition is binary compatible with C99 complex type (check done at # build time in npy_common.h) complex_def = "struct {%s __x; %s __y;}" % (type, type) res = config_cmd.check_type_size(complex_def, expected=[2 * x for x in expected[type]]) if res >= 0: public_defines.append(('NPY_SIZEOF_COMPLEX_%s' % sym2def(type), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % complex_def) for type in ('Py_intptr_t', 'off_t'): res = config_cmd.check_type_size(type, headers=["Python.h"], library_dirs=[pythonlib_dir()], expected=expected[type]) if res >= 0: private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res)) public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % type) # We check declaration AND type because that's how distutils does it. if config_cmd.check_decl('PY_LONG_LONG', headers=['Python.h']): res = config_cmd.check_type_size('PY_LONG_LONG', headers=['Python.h'], library_dirs=[pythonlib_dir()], expected=expected['PY_LONG_LONG']) if res >= 0: private_defines.append(('SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res)) public_defines.append(('NPY_SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % 'PY_LONG_LONG') res = config_cmd.check_type_size('long long', expected=expected['long long']) if res >= 0: #private_defines.append(('SIZEOF_%s' % sym2def('long long'), '%d' % res)) public_defines.append(('NPY_SIZEOF_%s' % sym2def('long long'), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % 'long long') if not config_cmd.check_decl('CHAR_BIT', headers=['Python.h']): raise RuntimeError( "Config wo CHAR_BIT is not supported" ", please contact the maintainers") return private_defines, public_defines def check_mathlib(config_cmd): # Testing the C math library mathlibs = [] mathlibs_choices = [[], ["m"], ["cpml"]] mathlib = os.environ.get("MATHLIB") if mathlib: mathlibs_choices.insert(0, mathlib.split(",")) for libs in mathlibs_choices: if config_cmd.check_func( "log", libraries=libs, call_args="0", decl="double log(double);", call=True ): mathlibs = libs break else: raise RuntimeError( "math library missing; rerun setup.py after setting the " "MATHLIB env variable" ) return mathlibs def visibility_define(config): """Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty string).""" hide = '__attribute__((visibility("hidden")))' if config.check_gcc_function_attribute(hide, 'hideme'): return hide else: return '' import os del os import sys if 'setuptools' in sys.modules: have_setuptools = True from setuptools import setup as old_setup # easy_install imports math, it may be picked up from cwd from setuptools.command import easy_install try: # very old versions of setuptools don't have this from setuptools.command import bdist_egg except ImportError: have_setuptools = False else: from distutils.core import setup as old_setup have_setuptools = False def lib_opts_if_msvc(build_cmd): """ Add flags if we are using MSVC compiler We can't see `build_cmd` in our scope, because we have not initialized the distutils build command, so use this deferred calculation to run when we are building the library. """ if build_cmd.compiler.compiler_type != 'msvc': return [] # Explicitly disable whole-program optimization. flags = ['/GL-'] # Disable voltbl section for vc142 to allow link using mingw-w64; see: # https://github.com/matthew-brett/dll_investigation/issues/1#issuecomment-1100468171 if build_cmd.compiler_opt.cc_test_flags(['-d2VolatileMetadata-']): flags.append('-d2VolatileMetadata-') return flags def dot_join(*args): return '.'.join([a for a in args if a]) class Configuration: _list_keys = ['packages', 'ext_modules', 'data_files', 'include_dirs', 'libraries', 'headers', 'scripts', 'py_modules', 'installed_libraries', 'define_macros'] _dict_keys = ['package_dir', 'installed_pkg_config'] _extra_keys = ['name', 'version'] numpy_include_dirs = [] def __init__(self, package_name=None, parent_name=None, top_path=None, package_path=None, caller_level=1, setup_name='setup.py', **attrs): """Construct configuration instance of a package. package_name -- name of the package Ex.: 'distutils' parent_name -- name of the parent package Ex.: 'numpy' top_path -- directory of the toplevel package Ex.: the directory where the numpy package source sits package_path -- directory of package. Will be computed by magic from the directory of the caller module if not specified Ex.: the directory where numpy.distutils is caller_level -- frame level to caller namespace, internal parameter. """ self.name = dot_join(parent_name, package_name) self.version = None caller_frame = get_frame(caller_level) self.local_path = get_path_from_frame(caller_frame, top_path) # local_path -- directory of a file (usually setup.py) that # defines a configuration() function. # local_path -- directory of a file (usually setup.py) that # defines a configuration() function. if top_path is None: top_path = self.local_path self.local_path = '' if package_path is None: package_path = self.local_path elif os.path.isdir(njoin(self.local_path, package_path)): package_path = njoin(self.local_path, package_path) if not os.path.isdir(package_path or '.'): raise ValueError("%r is not a directory" % (package_path,)) self.top_path = top_path self.package_path = package_path # this is the relative path in the installed package self.path_in_package = os.path.join(*self.name.split('.')) self.list_keys = self._list_keys[:] self.dict_keys = self._dict_keys[:] for n in self.list_keys: v = copy.copy(attrs.get(n, [])) setattr(self, n, as_list(v)) for n in self.dict_keys: v = copy.copy(attrs.get(n, {})) setattr(self, n, v) known_keys = self.list_keys + self.dict_keys self.extra_keys = self._extra_keys[:] for n in attrs.keys(): if n in known_keys: continue a = attrs[n] setattr(self, n, a) if isinstance(a, list): self.list_keys.append(n) elif isinstance(a, dict): self.dict_keys.append(n) else: self.extra_keys.append(n) if os.path.exists(njoin(package_path, '__init__.py')): self.packages.append(self.name) self.package_dir[self.name] = package_path self.options = dict( ignore_setup_xxx_py = False, assume_default_configuration = False, delegate_options_to_subpackages = False, quiet = False, ) caller_instance = None for i in range(1, 3): try: f = get_frame(i) except ValueError: break try: caller_instance = eval('self', f.f_globals, f.f_locals) break except NameError: pass if isinstance(caller_instance, self.__class__): if caller_instance.options['delegate_options_to_subpackages']: self.set_options(**caller_instance.options) self.setup_name = setup_name def todict(self): """ Return a dictionary compatible with the keyword arguments of distutils setup function. Examples -------- >>> setup(**config.todict()) #doctest: +SKIP """ self._optimize_data_files() d = {} known_keys = self.list_keys + self.dict_keys + self.extra_keys for n in known_keys: a = getattr(self, n) if a: d[n] = a return d def info(self, message): if not self.options['quiet']: print(message) def warn(self, message): sys.stderr.write('Warning: %s\n' % (message,)) def set_options(self, **options): """ Configure Configuration instance. The following options are available: - ignore_setup_xxx_py - assume_default_configuration - delegate_options_to_subpackages - quiet """ for key, value in options.items(): if key in self.options: self.options[key] = value else: raise ValueError('Unknown option: '+key) def get_distribution(self): """Return the distutils distribution object for self.""" from numpy.distutils.core import get_distribution return get_distribution() def _wildcard_get_subpackage(self, subpackage_name, parent_name, caller_level = 1): l = subpackage_name.split('.') subpackage_path = njoin([self.local_path]+l) dirs = [_m for _m in sorted_glob(subpackage_path) if os.path.isdir(_m)] config_list = [] for d in dirs: if not os.path.isfile(njoin(d, '__init__.py')): continue if 'build' in d.split(os.sep): continue n = '.'.join(d.split(os.sep)[-len(l):]) c = self.get_subpackage(n, parent_name = parent_name, caller_level = caller_level+1) config_list.extend(c) return config_list def _get_configuration_from_setup_py(self, setup_py, subpackage_name, subpackage_path, parent_name, caller_level = 1): # In case setup_py imports local modules: sys.path.insert(0, os.path.dirname(setup_py)) try: setup_name = os.path.splitext(os.path.basename(setup_py))[0] n = dot_join(self.name, subpackage_name, setup_name) setup_module = exec_mod_from_location( '_'.join(n.split('.')), setup_py) if not hasattr(setup_module, 'configuration'): if not self.options['assume_default_configuration']: self.warn('Assuming default configuration '\ '(%s does not define configuration())'\ % (setup_module)) config = Configuration(subpackage_name, parent_name, self.top_path, subpackage_path, caller_level = caller_level + 1) else: pn = dot_join(*([parent_name] + subpackage_name.split('.')[:-1])) args = (pn,) if setup_module.configuration.__code__.co_argcount > 1: args = args + (self.top_path,) config = setup_module.configuration(*args) if config.name!=dot_join(parent_name, subpackage_name): self.warn('Subpackage %r configuration returned as %r' % \ (dot_join(parent_name, subpackage_name), config.name)) finally: del sys.path[0] return config def get_subpackage(self,subpackage_name, subpackage_path=None, parent_name=None, caller_level = 1): """Return list of subpackage configurations. Parameters ---------- subpackage_name : str or None Name of the subpackage to get the configuration. '*' in subpackage_name is handled as a wildcard. subpackage_path : str If None, then the path is assumed to be the local path plus the subpackage_name. If a setup.py file is not found in the subpackage_path, then a default configuration is used. parent_name : str Parent name. """ if subpackage_name is None: if subpackage_path is None: raise ValueError( "either subpackage_name or subpackage_path must be specified") subpackage_name = os.path.basename(subpackage_path) # handle wildcards l = subpackage_name.split('.') if subpackage_path is None and '*' in subpackage_name: return self._wildcard_get_subpackage(subpackage_name, parent_name, caller_level = caller_level+1) assert '*' not in subpackage_name, repr((subpackage_name, subpackage_path, parent_name)) if subpackage_path is None: subpackage_path = njoin([self.local_path] + l) else: subpackage_path = njoin([subpackage_path] + l[:-1]) subpackage_path = self.paths([subpackage_path])[0] setup_py = njoin(subpackage_path, self.setup_name) if not self.options['ignore_setup_xxx_py']: if not os.path.isfile(setup_py): setup_py = njoin(subpackage_path, 'setup_%s.py' % (subpackage_name)) if not os.path.isfile(setup_py): if not self.options['assume_default_configuration']: self.warn('Assuming default configuration '\ '(%s/{setup_%s,setup}.py was not found)' \ % (os.path.dirname(setup_py), subpackage_name)) config = Configuration(subpackage_name, parent_name, self.top_path, subpackage_path, caller_level = caller_level+1) else: config = self._get_configuration_from_setup_py( setup_py, subpackage_name, subpackage_path, parent_name, caller_level = caller_level + 1) if config: return [config] else: return [] def add_subpackage(self,subpackage_name, subpackage_path=None, standalone = False): """Add a sub-package to the current Configuration instance. This is useful in a setup.py script for adding sub-packages to a package. Parameters ---------- subpackage_name : str name of the subpackage subpackage_path : str if given, the subpackage path such as the subpackage is in subpackage_path / subpackage_name. If None,the subpackage is assumed to be located in the local path / subpackage_name. standalone : bool """ if standalone: parent_name = None else: parent_name = self.name config_list = self.get_subpackage(subpackage_name, subpackage_path, parent_name = parent_name, caller_level = 2) if not config_list: self.warn('No configuration returned, assuming unavailable.') for config in config_list: d = config if isinstance(config, Configuration): d = config.todict() assert isinstance(d, dict), repr(type(d)) self.info('Appending %s configuration to %s' \ % (d.get('name'), self.name)) self.dict_append(**d) dist = self.get_distribution() if dist is not None: self.warn('distutils distribution has been initialized,'\ ' it may be too late to add a subpackage '+ subpackage_name) def add_data_dir(self, data_path): """Recursively add files under data_path to data_files list. Recursively add files under data_path to the list of data_files to be installed (and distributed). The data_path can be either a relative path-name, or an absolute path-name, or a 2-tuple where the first argument shows where in the install directory the data directory should be installed to. Parameters ---------- data_path : seq or str Argument can be either * 2-sequence (<datadir suffix>, <path to data directory>) * path to data directory where python datadir suffix defaults to package dir. Notes ----- Rules for installation paths:: foo/bar -> (foo/bar, foo/bar) -> parent/foo/bar (gun, foo/bar) -> parent/gun foo/* -> (foo/a, foo/a), (foo/b, foo/b) -> parent/foo/a, parent/foo/b (gun, foo/*) -> (gun, foo/a), (gun, foo/b) -> gun (gun/*, foo/*) -> parent/gun/a, parent/gun/b /foo/bar -> (bar, /foo/bar) -> parent/bar (gun, /foo/bar) -> parent/gun (fun/*/gun/*, sun/foo/bar) -> parent/fun/foo/gun/bar Examples -------- For example suppose the source directory contains fun/foo.dat and fun/bar/car.dat: >>> self.add_data_dir('fun') #doctest: +SKIP >>> self.add_data_dir(('sun', 'fun')) #doctest: +SKIP >>> self.add_data_dir(('gun', '/full/path/to/fun'))#doctest: +SKIP Will install data-files to the locations:: <package install directory>/ fun/ foo.dat bar/ car.dat sun/ foo.dat bar/ car.dat gun/ foo.dat car.dat """ if is_sequence(data_path): d, data_path = data_path else: d = None if is_sequence(data_path): [self.add_data_dir((d, p)) for p in data_path] return if not is_string(data_path): raise TypeError("not a string: %r" % (data_path,)) if d is None: if os.path.isabs(data_path): return self.add_data_dir((os.path.basename(data_path), data_path)) return self.add_data_dir((data_path, data_path)) paths = self.paths(data_path, include_non_existing=False) if is_glob_pattern(data_path): if is_glob_pattern(d): pattern_list = allpath(d).split(os.sep) pattern_list.reverse() # /a/*//b/ -> /a/*/b rl = list(range(len(pattern_list)-1)); rl.reverse() for i in rl: if not pattern_list[i]: del pattern_list[i] # for path in paths: if not os.path.isdir(path): print('Not a directory, skipping', path) continue rpath = rel_path(path, self.local_path) path_list = rpath.split(os.sep) path_list.reverse() target_list = [] i = 0 for s in pattern_list: if is_glob_pattern(s): if i>=len(path_list): raise ValueError('cannot fill pattern %r with %r' \ % (d, path)) target_list.append(path_list[i]) else: assert s==path_list[i], repr((s, path_list[i], data_path, d, path, rpath)) target_list.append(s) i += 1 if path_list[i:]: self.warn('mismatch of pattern_list=%s and path_list=%s'\ % (pattern_list, path_list)) target_list.reverse() self.add_data_dir((os.sep.join(target_list), path)) else: for path in paths: self.add_data_dir((d, path)) return assert not is_glob_pattern(d), repr(d) dist = self.get_distribution() if dist is not None and dist.data_files is not None: data_files = dist.data_files else: data_files = self.data_files for path in paths: for d1, f in list(general_source_directories_files(path)): target_path = os.path.join(self.path_in_package, d, d1) data_files.append((target_path, f)) def _optimize_data_files(self): data_dict = {} for p, files in self.data_files: if p not in data_dict: data_dict[p] = set() for f in files: data_dict[p].add(f) self.data_files[:] = [(p, list(files)) for p, files in data_dict.items()] def add_data_files(self,*files): """Add data files to configuration data_files. Parameters ---------- files : sequence Argument(s) can be either * 2-sequence (<datadir prefix>,<path to data file(s)>) * paths to data files where python datadir prefix defaults to package dir. Notes ----- The form of each element of the files sequence is very flexible allowing many combinations of where to get the files from the package and where they should ultimately be installed on the system. The most basic usage is for an element of the files argument sequence to be a simple filename. This will cause that file from the local path to be installed to the installation path of the self.name package (package path). The file argument can also be a relative path in which case the entire relative path will be installed into the package directory. Finally, the file can be an absolute path name in which case the file will be found at the absolute path name but installed to the package path. This basic behavior can be augmented by passing a 2-tuple in as the file argument. The first element of the tuple should specify the relative path (under the package install directory) where the remaining sequence of files should be installed to (it has nothing to do with the file-names in the source distribution). The second element of the tuple is the sequence of files that should be installed. The files in this sequence can be filenames, relative paths, or absolute paths. For absolute paths the file will be installed in the top-level package installation directory (regardless of the first argument). Filenames and relative path names will be installed in the package install directory under the path name given as the first element of the tuple. Rules for installation paths: #. file.txt -> (., file.txt)-> parent/file.txt #. foo/file.txt -> (foo, foo/file.txt) -> parent/foo/file.txt #. /foo/bar/file.txt -> (., /foo/bar/file.txt) -> parent/file.txt #. ``*``.txt -> parent/a.txt, parent/b.txt #. foo/``*``.txt`` -> parent/foo/a.txt, parent/foo/b.txt #. ``*/*.txt`` -> (``*``, ``*``/``*``.txt) -> parent/c/a.txt, parent/d/b.txt #. (sun, file.txt) -> parent/sun/file.txt #. (sun, bar/file.txt) -> parent/sun/file.txt #. (sun, /foo/bar/file.txt) -> parent/sun/file.txt #. (sun, ``*``.txt) -> parent/sun/a.txt, parent/sun/b.txt #. (sun, bar/``*``.txt) -> parent/sun/a.txt, parent/sun/b.txt #. (sun/``*``, ``*``/``*``.txt) -> parent/sun/c/a.txt, parent/d/b.txt An additional feature is that the path to a data-file can actually be a function that takes no arguments and returns the actual path(s) to the data-files. This is useful when the data files are generated while building the package. Examples -------- Add files to the list of data_files to be included with the package. >>> self.add_data_files('foo.dat', ... ('fun', ['gun.dat', 'nun/pun.dat', '/tmp/sun.dat']), ... 'bar/cat.dat', ... '/full/path/to/can.dat') #doctest: +SKIP will install these data files to:: <package install directory>/ foo.dat fun/ gun.dat nun/ pun.dat sun.dat bar/ car.dat can.dat where <package install directory> is the package (or sub-package) directory such as '/usr/lib/python2.4/site-packages/mypackage' ('C: \\Python2.4 \\Lib \\site-packages \\mypackage') or '/usr/lib/python2.4/site- packages/mypackage/mysubpackage' ('C: \\Python2.4 \\Lib \\site-packages \\mypackage \\mysubpackage'). """ if len(files)>1: for f in files: self.add_data_files(f) return assert len(files)==1 if is_sequence(files[0]): d, files = files[0] else: d = None if is_string(files): filepat = files elif is_sequence(files): if len(files)==1: filepat = files[0] else: for f in files: self.add_data_files((d, f)) return else: raise TypeError(repr(type(files))) if d is None: if hasattr(filepat, '__call__'): d = '' elif os.path.isabs(filepat): d = '' else: d = os.path.dirname(filepat) self.add_data_files((d, files)) return paths = self.paths(filepat, include_non_existing=False) if is_glob_pattern(filepat): if is_glob_pattern(d): pattern_list = d.split(os.sep) pattern_list.reverse() for path in paths: path_list = path.split(os.sep) path_list.reverse() path_list.pop() # filename target_list = [] i = 0 for s in pattern_list: if is_glob_pattern(s): target_list.append(path_list[i]) i += 1 else: target_list.append(s) target_list.reverse() self.add_data_files((os.sep.join(target_list), path)) else: self.add_data_files((d, paths)) return assert not is_glob_pattern(d), repr((d, filepat)) dist = self.get_distribution() if dist is not None and dist.data_files is not None: data_files = dist.data_files else: data_files = self.data_files data_files.append((os.path.join(self.path_in_package, d), paths)) ### XXX Implement add_py_modules def add_define_macros(self, macros): """Add define macros to configuration Add the given sequence of macro name and value duples to the beginning of the define_macros list This list will be visible to all extension modules of the current package. """ dist = self.get_distribution() if dist is not None: if not hasattr(dist, 'define_macros'): dist.define_macros = [] dist.define_macros.extend(macros) else: self.define_macros.extend(macros) def add_include_dirs(self,*paths): """Add paths to configuration include directories. Add the given sequence of paths to the beginning of the include_dirs list. This list will be visible to all extension modules of the current package. """ include_dirs = self.paths(paths) dist = self.get_distribution() if dist is not None: if dist.include_dirs is None: dist.include_dirs = [] dist.include_dirs.extend(include_dirs) else: self.include_dirs.extend(include_dirs) def add_headers(self,*files): """Add installable headers to configuration. Add the given sequence of files to the beginning of the headers list. By default, headers will be installed under <python- include>/<self.name.replace('.','/')>/ directory. If an item of files is a tuple, then its first argument specifies the actual installation location relative to the <python-include> path. Parameters ---------- files : str or seq Argument(s) can be either: * 2-sequence (<includedir suffix>,<path to header file(s)>) * path(s) to header file(s) where python includedir suffix will default to package name. """ headers = [] for path in files: if is_string(path): [headers.append((self.name, p)) for p in self.paths(path)] else: if not isinstance(path, (tuple, list)) or len(path) != 2: raise TypeError(repr(path)) [headers.append((path[0], p)) for p in self.paths(path[1])] dist = self.get_distribution() if dist is not None: if dist.headers is None: dist.headers = [] dist.headers.extend(headers) else: self.headers.extend(headers) def paths(self,*paths,**kws): """Apply glob to paths and prepend local_path if needed. Applies glob.glob(...) to each path in the sequence (if needed) and pre-pends the local_path if needed. Because this is called on all source lists, this allows wildcard characters to be specified in lists of sources for extension modules and libraries and scripts and allows path-names be relative to the source directory. """ include_non_existing = kws.get('include_non_existing', True) return gpaths(paths, local_path = self.local_path, include_non_existing=include_non_existing) def _fix_paths_dict(self, kw): for k in kw.keys(): v = kw[k] if k in ['sources', 'depends', 'include_dirs', 'library_dirs', 'module_dirs', 'extra_objects']: new_v = self.paths(v) kw[k] = new_v def add_extension(self,name,sources,**kw): """Add extension to configuration. Create and add an Extension instance to the ext_modules list. This method also takes the following optional keyword arguments that are passed on to the Extension constructor. Parameters ---------- name : str name of the extension sources : seq list of the sources. The list of sources may contain functions (called source generators) which must take an extension instance and a build directory as inputs and return a source file or list of source files or None. If None is returned then no sources are generated. If the Extension instance has no sources after processing all source generators, then no extension module is built. include_dirs : define_macros : undef_macros : library_dirs : libraries : runtime_library_dirs : extra_objects : extra_compile_args : extra_link_args : extra_f77_compile_args : extra_f90_compile_args : export_symbols : swig_opts : depends : The depends list contains paths to files or directories that the sources of the extension module depend on. If any path in the depends list is newer than the extension module, then the module will be rebuilt. language : f2py_options : module_dirs : extra_info : dict or list dict or list of dict of keywords to be appended to keywords. Notes ----- The self.paths(...) method is applied to all lists that may contain paths. """ ext_args = copy.copy(kw) ext_args['name'] = dot_join(self.name, name) ext_args['sources'] = sources if 'extra_info' in ext_args: extra_info = ext_args['extra_info'] del ext_args['extra_info'] if isinstance(extra_info, dict): extra_info = [extra_info] for info in extra_info: assert isinstance(info, dict), repr(info) dict_append(ext_args,**info) self._fix_paths_dict(ext_args) # Resolve out-of-tree dependencies libraries = ext_args.get('libraries', []) libnames = [] ext_args['libraries'] = [] for libname in libraries: if isinstance(libname, tuple): self._fix_paths_dict(libname[1]) # Handle library names of the form libname@relative/path/to/library if '@' in libname: lname, lpath = libname.split('@', 1) lpath = os.path.abspath(njoin(self.local_path, lpath)) if os.path.isdir(lpath): c = self.get_subpackage(None, lpath, caller_level = 2) if isinstance(c, Configuration): c = c.todict() for l in [l[0] for l in c.get('libraries', [])]: llname = l.split('__OF__', 1)[0] if llname == lname: c.pop('name', None) dict_append(ext_args,**c) break continue libnames.append(libname) ext_args['libraries'] = libnames + ext_args['libraries'] ext_args['define_macros'] = \ self.define_macros + ext_args.get('define_macros', []) from numpy.distutils.core import Extension ext = Extension(**ext_args) self.ext_modules.append(ext) dist = self.get_distribution() if dist is not None: self.warn('distutils distribution has been initialized,'\ ' it may be too late to add an extension '+name) return ext def add_library(self,name,sources,**build_info): """ Add library to configuration. Parameters ---------- name : str Name of the extension. sources : sequence List of the sources. The list of sources may contain functions (called source generators) which must take an extension instance and a build directory as inputs and return a source file or list of source files or None. If None is returned then no sources are generated. If the Extension instance has no sources after processing all source generators, then no extension module is built. build_info : dict, optional The following keys are allowed: * depends * macros * include_dirs * extra_compiler_args * extra_f77_compile_args * extra_f90_compile_args * f2py_options * language """ self._add_library(name, sources, None, build_info) dist = self.get_distribution() if dist is not None: self.warn('distutils distribution has been initialized,'\ ' it may be too late to add a library '+ name) def _add_library(self, name, sources, install_dir, build_info): """Common implementation for add_library and add_installed_library. Do not use directly""" build_info = copy.copy(build_info) build_info['sources'] = sources # Sometimes, depends is not set up to an empty list by default, and if # depends is not given to add_library, distutils barfs (#1134) if not 'depends' in build_info: build_info['depends'] = [] self._fix_paths_dict(build_info) # Add to libraries list so that it is build with build_clib self.libraries.append((name, build_info)) def add_installed_library(self, name, sources, install_dir, build_info=None): """ Similar to add_library, but the specified library is installed. Most C libraries used with `distutils` are only used to build python extensions, but libraries built through this method will be installed so that they can be reused by third-party packages. Parameters ---------- name : str Name of the installed library. sources : sequence List of the library's source files. See `add_library` for details. install_dir : str Path to install the library, relative to the current sub-package. build_info : dict, optional The following keys are allowed: * depends * macros * include_dirs * extra_compiler_args * extra_f77_compile_args * extra_f90_compile_args * f2py_options * language Returns ------- None See Also -------- add_library, add_npy_pkg_config, get_info Notes ----- The best way to encode the options required to link against the specified C libraries is to use a "libname.ini" file, and use `get_info` to retrieve the required options (see `add_npy_pkg_config` for more information). """ if not build_info: build_info = {} install_dir = os.path.join(self.package_path, install_dir) self._add_library(name, sources, install_dir, build_info) self.installed_libraries.append(InstallableLib(name, build_info, install_dir)) def add_npy_pkg_config(self, template, install_dir, subst_dict=None): """ Generate and install a npy-pkg config file from a template. The config file generated from `template` is installed in the given install directory, using `subst_dict` for variable substitution. Parameters ---------- template : str The path of the template, relatively to the current package path. install_dir : str Where to install the npy-pkg config file, relatively to the current package path. subst_dict : dict, optional If given, any string of the form ``@key@`` will be replaced by ``subst_dict[key]`` in the template file when installed. The install prefix is always available through the variable ``@prefix@``, since the install prefix is not easy to get reliably from setup.py. See also -------- add_installed_library, get_info Notes ----- This works for both standard installs and in-place builds, i.e. the ``@prefix@`` refer to the source directory for in-place builds. Examples -------- :: config.add_npy_pkg_config('foo.ini.in', 'lib', {'foo': bar}) Assuming the foo.ini.in file has the following content:: [meta] Name=@foo@ Version=1.0 Description=dummy description [default] Cflags=-I@prefix@/include Libs= The generated file will have the following content:: [meta] Name=bar Version=1.0 Description=dummy description [default] Cflags=-Iprefix_dir/include Libs= and will be installed as foo.ini in the 'lib' subpath. When cross-compiling with numpy distutils, it might be necessary to use modified npy-pkg-config files. Using the default/generated files will link with the host libraries (i.e. libnpymath.a). For cross-compilation you of-course need to link with target libraries, while using the host Python installation. You can copy out the numpy/core/lib/npy-pkg-config directory, add a pkgdir value to the .ini files and set NPY_PKG_CONFIG_PATH environment variable to point to the directory with the modified npy-pkg-config files. Example npymath.ini modified for cross-compilation:: [meta] Name=npymath Description=Portable, core math library implementing C99 standard Version=0.1 [variables] pkgname=numpy.core pkgdir=/build/arm-linux-gnueabi/sysroot/usr/lib/python3.7/site-packages/numpy/core prefix=${pkgdir} libdir=${prefix}/lib includedir=${prefix}/include [default] Libs=-L${libdir} -lnpymath Cflags=-I${includedir} Requires=mlib [msvc] Libs=/LIBPATH:${libdir} npymath.lib Cflags=/INCLUDE:${includedir} Requires=mlib """ if subst_dict is None: subst_dict = {} template = os.path.join(self.package_path, template) if self.name in self.installed_pkg_config: self.installed_pkg_config[self.name].append((template, install_dir, subst_dict)) else: self.installed_pkg_config[self.name] = [(template, install_dir, subst_dict)] def add_scripts(self,*files): """Add scripts to configuration. Add the sequence of files to the beginning of the scripts list. Scripts will be installed under the <prefix>/bin/ directory. """ scripts = self.paths(files) dist = self.get_distribution() if dist is not None: if dist.scripts is None: dist.scripts = [] dist.scripts.extend(scripts) else: self.scripts.extend(scripts) def dict_append(self,**dict): for key in self.list_keys: a = getattr(self, key) a.extend(dict.get(key, [])) for key in self.dict_keys: a = getattr(self, key) a.update(dict.get(key, {})) known_keys = self.list_keys + self.dict_keys + self.extra_keys for key in dict.keys(): if key not in known_keys: a = getattr(self, key, None) if a and a==dict[key]: continue self.warn('Inheriting attribute %r=%r from %r' \ % (key, dict[key], dict.get('name', '?'))) setattr(self, key, dict[key]) self.extra_keys.append(key) elif key in self.extra_keys: self.info('Ignoring attempt to set %r (from %r to %r)' \ % (key, getattr(self, key), dict[key])) elif key in known_keys: # key is already processed above pass else: raise ValueError("Don't know about key=%r" % (key)) def __str__(self): from pprint import pformat known_keys = self.list_keys + self.dict_keys + self.extra_keys s = '<'+5*'-' + '\n' s += 'Configuration of '+self.name+':\n' known_keys.sort() for k in known_keys: a = getattr(self, k, None) if a: s += '%s = %s\n' % (k, pformat(a)) s += 5*'-' + '>' return s def get_config_cmd(self): """ Returns the numpy.distutils config command instance. """ cmd = get_cmd('config') cmd.ensure_finalized() cmd.dump_source = 0 cmd.noisy = 0 old_path = os.environ.get('PATH') if old_path: path = os.pathsep.join(['.', old_path]) os.environ['PATH'] = path return cmd def get_build_temp_dir(self): """ Return a path to a temporary directory where temporary files should be placed. """ cmd = get_cmd('build') cmd.ensure_finalized() return cmd.build_temp def have_f77c(self): """Check for availability of Fortran 77 compiler. Use it inside source generating function to ensure that setup distribution instance has been initialized. Notes ----- True if a Fortran 77 compiler is available (because a simple Fortran 77 code was able to be compiled successfully). """ simple_fortran_subroutine = ''' subroutine simple end ''' config_cmd = self.get_config_cmd() flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f77') return flag def have_f90c(self): """Check for availability of Fortran 90 compiler. Use it inside source generating function to ensure that setup distribution instance has been initialized. Notes ----- True if a Fortran 90 compiler is available (because a simple Fortran 90 code was able to be compiled successfully) """ simple_fortran_subroutine = ''' subroutine simple end ''' config_cmd = self.get_config_cmd() flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f90') return flag def append_to(self, extlib): """Append libraries, include_dirs to extension or library item. """ if is_sequence(extlib): lib_name, build_info = extlib dict_append(build_info, libraries=self.libraries, include_dirs=self.include_dirs) else: from numpy.distutils.core import Extension assert isinstance(extlib, Extension), repr(extlib) extlib.libraries.extend(self.libraries) extlib.include_dirs.extend(self.include_dirs) def _get_svn_revision(self, path): """Return path's SVN revision number. """ try: output = subprocess.check_output(['svnversion'], cwd=path) except (subprocess.CalledProcessError, OSError): pass else: m = re.match(rb'(?P<revision>\d+)', output) if m: return int(m.group('revision')) if sys.platform=='win32' and os.environ.get('SVN_ASP_DOT_NET_HACK', None): entries = njoin(path, '_svn', 'entries') else: entries = njoin(path, '.svn', 'entries') if os.path.isfile(entries): with open(entries) as f: fstr = f.read() if fstr[:5] == '<?xml': # pre 1.4 m = re.search(r'revision="(?P<revision>\d+)"', fstr) if m: return int(m.group('revision')) else: # non-xml entries file --- check to be sure that m = re.search(r'dir[\n\r]+(?P<revision>\d+)', fstr) if m: return int(m.group('revision')) return None def _get_hg_revision(self, path): """Return path's Mercurial revision number. """ try: output = subprocess.check_output( ['hg', 'identify', '--num'], cwd=path) except (subprocess.CalledProcessError, OSError): pass else: m = re.match(rb'(?P<revision>\d+)', output) if m: return int(m.group('revision')) branch_fn = njoin(path, '.hg', 'branch') branch_cache_fn = njoin(path, '.hg', 'branch.cache') if os.path.isfile(branch_fn): branch0 = None with open(branch_fn) as f: revision0 = f.read().strip() branch_map = {} with open(branch_cache_fn, 'r') as f: for line in f: branch1, revision1 = line.split()[:2] if revision1==revision0: branch0 = branch1 try: revision1 = int(revision1) except ValueError: continue branch_map[branch1] = revision1 return branch_map.get(branch0) return None def get_version(self, version_file=None, version_variable=None): """Try to get version string of a package. Return a version string of the current package or None if the version information could not be detected. Notes ----- This method scans files named __version__.py, <packagename>_version.py, version.py, and __svn_version__.py for string variables version, __version__, and <packagename>_version, until a version number is found. """ version = getattr(self, 'version', None) if version is not None: return version # Get version from version file. if version_file is None: files = ['__version__.py', self.name.split('.')[-1]+'_version.py', 'version.py', '__svn_version__.py', '__hg_version__.py'] else: files = [version_file] if version_variable is None: version_vars = ['version', '__version__', self.name.split('.')[-1]+'_version'] else: version_vars = [version_variable] for f in files: fn = njoin(self.local_path, f) if os.path.isfile(fn): info = ('.py', 'U', 1) name = os.path.splitext(os.path.basename(fn))[0] n = dot_join(self.name, name) try: version_module = exec_mod_from_location( '_'.join(n.split('.')), fn) except ImportError as e: self.warn(str(e)) version_module = None if version_module is None: continue for a in version_vars: version = getattr(version_module, a, None) if version is not None: break # Try if versioneer module try: version = version_module.get_versions()['version'] except AttributeError: pass if version is not None: break if version is not None: self.version = version return version # Get version as SVN or Mercurial revision number revision = self._get_svn_revision(self.local_path) if revision is None: revision = self._get_hg_revision(self.local_path) if revision is not None: version = str(revision) self.version = version return version def make_svn_version_py(self, delete=True): """Appends a data function to the data_files list that will generate __svn_version__.py file to the current package directory. Generate package __svn_version__.py file from SVN revision number, it will be removed after python exits but will be available when sdist, etc commands are executed. Notes ----- If __svn_version__.py existed before, nothing is done. This is intended for working with source directories that are in an SVN repository. """ target = njoin(self.local_path, '__svn_version__.py') revision = self._get_svn_revision(self.local_path) if os.path.isfile(target) or revision is None: return else: def generate_svn_version_py(): if not os.path.isfile(target): version = str(revision) self.info('Creating %s (version=%r)' % (target, version)) with open(target, 'w') as f: f.write('version = %r\n' % (version)) def rm_file(f=target,p=self.info): if delete: try: os.remove(f); p('removed '+f) except OSError: pass try: os.remove(f+'c'); p('removed '+f+'c') except OSError: pass atexit.register(rm_file) return target self.add_data_files(('', generate_svn_version_py())) def make_hg_version_py(self, delete=True): """Appends a data function to the data_files list that will generate __hg_version__.py file to the current package directory. Generate package __hg_version__.py file from Mercurial revision, it will be removed after python exits but will be available when sdist, etc commands are executed. Notes ----- If __hg_version__.py existed before, nothing is done. This is intended for working with source directories that are in an Mercurial repository. """ target = njoin(self.local_path, '__hg_version__.py') revision = self._get_hg_revision(self.local_path) if os.path.isfile(target) or revision is None: return else: def generate_hg_version_py(): if not os.path.isfile(target): version = str(revision) self.info('Creating %s (version=%r)' % (target, version)) with open(target, 'w') as f: f.write('version = %r\n' % (version)) def rm_file(f=target,p=self.info): if delete: try: os.remove(f); p('removed '+f) except OSError: pass try: os.remove(f+'c'); p('removed '+f+'c') except OSError: pass atexit.register(rm_file) return target self.add_data_files(('', generate_hg_version_py())) def make_config_py(self,name='__config__'): """Generate package __config__.py file containing system_info information used during building the package. This file is installed to the package installation directory. """ self.py_modules.append((self.name, name, generate_config_py)) def get_info(self,*names): """Get resources information. Return information (from system_info.get_info) for all of the names in the argument list in a single dictionary. """ from .system_info import get_info, dict_append info_dict = {} for a in names: dict_append(info_dict,**get_info(a)) return info_dict def exec_mod_from_location(modname, modfile): ''' Use importlib machinery to import a module `modname` from the file `modfile`. Depending on the `spec.loader`, the module may not be registered in sys.modules. ''' spec = importlib.util.spec_from_file_location(modname, modfile) foo = importlib.util.module_from_spec(spec) spec.loader.exec_module(foo) return foo def get_info(name, notfound_action=0): """ notfound_action: 0 - do nothing 1 - display warning message 2 - raise error """ cl = {'armpl': armpl_info, 'blas_armpl': blas_armpl_info, 'lapack_armpl': lapack_armpl_info, 'fftw3_armpl': fftw3_armpl_info, 'atlas': atlas_info, # use lapack_opt or blas_opt instead 'atlas_threads': atlas_threads_info, # ditto 'atlas_blas': atlas_blas_info, 'atlas_blas_threads': atlas_blas_threads_info, 'lapack_atlas': lapack_atlas_info, # use lapack_opt instead 'lapack_atlas_threads': lapack_atlas_threads_info, # ditto 'atlas_3_10': atlas_3_10_info, # use lapack_opt or blas_opt instead 'atlas_3_10_threads': atlas_3_10_threads_info, # ditto 'atlas_3_10_blas': atlas_3_10_blas_info, 'atlas_3_10_blas_threads': atlas_3_10_blas_threads_info, 'lapack_atlas_3_10': lapack_atlas_3_10_info, # use lapack_opt instead 'lapack_atlas_3_10_threads': lapack_atlas_3_10_threads_info, # ditto 'flame': flame_info, # use lapack_opt instead 'mkl': mkl_info, # openblas which may or may not have embedded lapack 'openblas': openblas_info, # use blas_opt instead # openblas with embedded lapack 'openblas_lapack': openblas_lapack_info, # use blas_opt instead 'openblas_clapack': openblas_clapack_info, # use blas_opt instead 'blis': blis_info, # use blas_opt instead 'lapack_mkl': lapack_mkl_info, # use lapack_opt instead 'blas_mkl': blas_mkl_info, # use blas_opt instead 'accelerate': accelerate_info, # use blas_opt instead 'openblas64_': openblas64__info, 'openblas64__lapack': openblas64__lapack_info, 'openblas_ilp64': openblas_ilp64_info, 'openblas_ilp64_lapack': openblas_ilp64_lapack_info, 'x11': x11_info, 'fft_opt': fft_opt_info, 'fftw': fftw_info, 'fftw2': fftw2_info, 'fftw3': fftw3_info, 'dfftw': dfftw_info, 'sfftw': sfftw_info, 'fftw_threads': fftw_threads_info, 'dfftw_threads': dfftw_threads_info, 'sfftw_threads': sfftw_threads_info, 'djbfft': djbfft_info, 'blas': blas_info, # use blas_opt instead 'lapack': lapack_info, # use lapack_opt instead 'lapack_src': lapack_src_info, 'blas_src': blas_src_info, 'numpy': numpy_info, 'f2py': f2py_info, 'Numeric': Numeric_info, 'numeric': Numeric_info, 'numarray': numarray_info, 'numerix': numerix_info, 'lapack_opt': lapack_opt_info, 'lapack_ilp64_opt': lapack_ilp64_opt_info, 'lapack_ilp64_plain_opt': lapack_ilp64_plain_opt_info, 'lapack64__opt': lapack64__opt_info, 'blas_opt': blas_opt_info, 'blas_ilp64_opt': blas_ilp64_opt_info, 'blas_ilp64_plain_opt': blas_ilp64_plain_opt_info, 'blas64__opt': blas64__opt_info, 'boost_python': boost_python_info, 'agg2': agg2_info, 'wx': wx_info, 'gdk_pixbuf_xlib_2': gdk_pixbuf_xlib_2_info, 'gdk-pixbuf-xlib-2.0': gdk_pixbuf_xlib_2_info, 'gdk_pixbuf_2': gdk_pixbuf_2_info, 'gdk-pixbuf-2.0': gdk_pixbuf_2_info, 'gdk': gdk_info, 'gdk_2': gdk_2_info, 'gdk-2.0': gdk_2_info, 'gdk_x11_2': gdk_x11_2_info, 'gdk-x11-2.0': gdk_x11_2_info, 'gtkp_x11_2': gtkp_x11_2_info, 'gtk+-x11-2.0': gtkp_x11_2_info, 'gtkp_2': gtkp_2_info, 'gtk+-2.0': gtkp_2_info, 'xft': xft_info, 'freetype2': freetype2_info, 'umfpack': umfpack_info, 'amd': amd_info, }.get(name.lower(), system_info) return cl().get_info(notfound_action) class lapack_opt_info(system_info): notfounderror = LapackNotFoundError # List of all known LAPACK libraries, in the default order lapack_order = ['armpl', 'mkl', 'openblas', 'flame', 'accelerate', 'atlas', 'lapack'] order_env_var_name = 'NPY_LAPACK_ORDER' def _calc_info_armpl(self): info = get_info('lapack_armpl') if info: self.set_info(**info) return True return False def _calc_info_mkl(self): info = get_info('lapack_mkl') if info: self.set_info(**info) return True return False def _calc_info_openblas(self): info = get_info('openblas_lapack') if info: self.set_info(**info) return True info = get_info('openblas_clapack') if info: self.set_info(**info) return True return False def _calc_info_flame(self): info = get_info('flame') if info: self.set_info(**info) return True return False def _calc_info_atlas(self): info = get_info('atlas_3_10_threads') if not info: info = get_info('atlas_3_10') if not info: info = get_info('atlas_threads') if not info: info = get_info('atlas') if info: # Figure out if ATLAS has lapack... # If not we need the lapack library, but not BLAS! l = info.get('define_macros', []) if ('ATLAS_WITH_LAPACK_ATLAS', None) in l \ or ('ATLAS_WITHOUT_LAPACK', None) in l: # Get LAPACK (with possible warnings) # If not found we don't accept anything # since we can't use ATLAS with LAPACK! lapack_info = self._get_info_lapack() if not lapack_info: return False dict_append(info, **lapack_info) self.set_info(**info) return True return False def _calc_info_accelerate(self): info = get_info('accelerate') if info: self.set_info(**info) return True return False def _get_info_blas(self): # Default to get the optimized BLAS implementation info = get_info('blas_opt') if not info: warnings.warn(BlasNotFoundError.__doc__ or '', stacklevel=3) info_src = get_info('blas_src') if not info_src: warnings.warn(BlasSrcNotFoundError.__doc__ or '', stacklevel=3) return {} dict_append(info, libraries=[('fblas_src', info_src)]) return info def _get_info_lapack(self): info = get_info('lapack') if not info: warnings.warn(LapackNotFoundError.__doc__ or '', stacklevel=3) info_src = get_info('lapack_src') if not info_src: warnings.warn(LapackSrcNotFoundError.__doc__ or '', stacklevel=3) return {} dict_append(info, libraries=[('flapack_src', info_src)]) return info def _calc_info_lapack(self): info = self._get_info_lapack() if info: info_blas = self._get_info_blas() dict_append(info, **info_blas) dict_append(info, define_macros=[('NO_ATLAS_INFO', 1)]) self.set_info(**info) return True return False def _calc_info_from_envvar(self): info = {} info['language'] = 'f77' info['libraries'] = [] info['include_dirs'] = [] info['define_macros'] = [] info['extra_link_args'] = os.environ['NPY_LAPACK_LIBS'].split() self.set_info(**info) return True def _calc_info(self, name): return getattr(self, '_calc_info_{}'.format(name))() def calc_info(self): lapack_order, unknown_order = _parse_env_order(self.lapack_order, self.order_env_var_name) if len(unknown_order) > 0: raise ValueError("lapack_opt_info user defined " "LAPACK order has unacceptable " "values: {}".format(unknown_order)) if 'NPY_LAPACK_LIBS' in os.environ: # Bypass autodetection, set language to F77 and use env var linker # flags directly self._calc_info_from_envvar() return for lapack in lapack_order: if self._calc_info(lapack): return if 'lapack' not in lapack_order: # Since the user may request *not* to use any library, we still need # to raise warnings to signal missing packages! warnings.warn(LapackNotFoundError.__doc__ or '', stacklevel=2) warnings.warn(LapackSrcNotFoundError.__doc__ or '', stacklevel=2) class blas_opt_info(system_info): notfounderror = BlasNotFoundError # List of all known BLAS libraries, in the default order blas_order = ['armpl', 'mkl', 'blis', 'openblas', 'accelerate', 'atlas', 'blas'] order_env_var_name = 'NPY_BLAS_ORDER' def _calc_info_armpl(self): info = get_info('blas_armpl') if info: self.set_info(**info) return True return False def _calc_info_mkl(self): info = get_info('blas_mkl') if info: self.set_info(**info) return True return False def _calc_info_blis(self): info = get_info('blis') if info: self.set_info(**info) return True return False def _calc_info_openblas(self): info = get_info('openblas') if info: self.set_info(**info) return True return False def _calc_info_atlas(self): info = get_info('atlas_3_10_blas_threads') if not info: info = get_info('atlas_3_10_blas') if not info: info = get_info('atlas_blas_threads') if not info: info = get_info('atlas_blas') if info: self.set_info(**info) return True return False def _calc_info_accelerate(self): info = get_info('accelerate') if info: self.set_info(**info) return True return False def _calc_info_blas(self): # Warn about a non-optimized BLAS library warnings.warn(BlasOptNotFoundError.__doc__ or '', stacklevel=3) info = {} dict_append(info, define_macros=[('NO_ATLAS_INFO', 1)]) blas = get_info('blas') if blas: dict_append(info, **blas) else: # Not even BLAS was found! warnings.warn(BlasNotFoundError.__doc__ or '', stacklevel=3) blas_src = get_info('blas_src') if not blas_src: warnings.warn(BlasSrcNotFoundError.__doc__ or '', stacklevel=3) return False dict_append(info, libraries=[('fblas_src', blas_src)]) self.set_info(**info) return True def _calc_info_from_envvar(self): info = {} info['language'] = 'f77' info['libraries'] = [] info['include_dirs'] = [] info['define_macros'] = [] info['extra_link_args'] = os.environ['NPY_BLAS_LIBS'].split() if 'NPY_CBLAS_LIBS' in os.environ: info['define_macros'].append(('HAVE_CBLAS', None)) info['extra_link_args'].extend( os.environ['NPY_CBLAS_LIBS'].split()) self.set_info(**info) return True def _calc_info(self, name): return getattr(self, '_calc_info_{}'.format(name))() def calc_info(self): blas_order, unknown_order = _parse_env_order(self.blas_order, self.order_env_var_name) if len(unknown_order) > 0: raise ValueError("blas_opt_info user defined BLAS order has unacceptable values: {}".format(unknown_order)) if 'NPY_BLAS_LIBS' in os.environ: # Bypass autodetection, set language to F77 and use env var linker # flags directly self._calc_info_from_envvar() return for blas in blas_order: if self._calc_info(blas): return if 'blas' not in blas_order: # Since the user may request *not* to use any library, we still need # to raise warnings to signal missing packages! warnings.warn(BlasNotFoundError.__doc__ or '', stacklevel=2) warnings.warn(BlasSrcNotFoundError.__doc__ or '', stacklevel=2) NPY_CXX_FLAGS = [ '-std=c++11', # Minimal standard version '-D__STDC_VERSION__=0', # for compatibility with C headers '-fno-exceptions', # no exception support '-fno-rtti'] release = 'dev0' not in version and '+' not in version def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import (Configuration, dot_join, exec_mod_from_location) from numpy.distutils.system_info import (get_info, blas_opt_info, lapack_opt_info) from numpy.distutils.ccompiler_opt import NPY_CXX_FLAGS from numpy.version import release as is_released config = Configuration('core', parent_package, top_path) local_dir = config.local_path codegen_dir = join(local_dir, 'code_generators') # Check whether we have a mismatch between the set C API VERSION and the # actual C API VERSION. Will raise a MismatchCAPIError if so. check_api_version(C_API_VERSION, codegen_dir) generate_umath_py = join(codegen_dir, 'generate_umath.py') n = dot_join(config.name, 'generate_umath') generate_umath = exec_mod_from_location('_'.join(n.split('.')), generate_umath_py) header_dir = 'include/numpy' # this is relative to config.path_in_package cocache = CallOnceOnly() def generate_config_h(ext, build_dir): target = join(build_dir, header_dir, 'config.h') d = os.path.dirname(target) if not os.path.exists(d): os.makedirs(d) if newer(__file__, target): config_cmd = config.get_config_cmd() log.info('Generating %s', target) # Check sizeof moredefs, ignored = cocache.check_types(config_cmd, ext, build_dir) # Check math library and C99 math funcs availability mathlibs = check_mathlib(config_cmd) moredefs.append(('MATHLIB', ','.join(mathlibs))) check_math_capabilities(config_cmd, ext, moredefs, mathlibs) moredefs.extend(cocache.check_ieee_macros(config_cmd)[0]) moredefs.extend(cocache.check_complex(config_cmd, mathlibs)[0]) # Signal check if is_npy_no_signal(): moredefs.append('__NPY_PRIVATE_NO_SIGNAL') # Windows checks if sys.platform == 'win32' or os.name == 'nt': win32_checks(moredefs) # C99 restrict keyword moredefs.append(('NPY_RESTRICT', config_cmd.check_restrict())) # Inline check inline = config_cmd.check_inline() if can_link_svml(): moredefs.append(('NPY_CAN_LINK_SVML', 1)) # Use bogus stride debug aid to flush out bugs where users use # strides of dimensions with length 1 to index a full contiguous # array. if NPY_RELAXED_STRIDES_DEBUG: moredefs.append(('NPY_RELAXED_STRIDES_DEBUG', 1)) else: moredefs.append(('NPY_RELAXED_STRIDES_DEBUG', 0)) # Get long double representation rep = check_long_double_representation(config_cmd) moredefs.append(('HAVE_LDOUBLE_%s' % rep, 1)) if check_for_right_shift_internal_compiler_error(config_cmd): moredefs.append('NPY_DO_NOT_OPTIMIZE_LONG_right_shift') moredefs.append('NPY_DO_NOT_OPTIMIZE_ULONG_right_shift') moredefs.append('NPY_DO_NOT_OPTIMIZE_LONGLONG_right_shift') moredefs.append('NPY_DO_NOT_OPTIMIZE_ULONGLONG_right_shift') # Generate the config.h file from moredefs with open(target, 'w') as target_f: if sys.platform == 'darwin': target_f.write( "/* may be overridden by numpyconfig.h on darwin */\n" ) for d in moredefs: if isinstance(d, str): target_f.write('#define %s\n' % (d)) else: target_f.write('#define %s %s\n' % (d[0], d[1])) # define inline to our keyword, or nothing target_f.write('#ifndef __cplusplus\n') if inline == 'inline': target_f.write('/* #undef inline */\n') else: target_f.write('#define inline %s\n' % inline) target_f.write('#endif\n') # add the guard to make sure config.h is never included directly, # but always through npy_config.h target_f.write(textwrap.dedent(""" #ifndef NUMPY_CORE_SRC_COMMON_NPY_CONFIG_H_ #error config.h should never be included directly, include npy_config.h instead #endif """)) log.info('File: %s' % target) with open(target) as target_f: log.info(target_f.read()) log.info('EOF') else: mathlibs = [] with open(target) as target_f: for line in target_f: s = '#define MATHLIB' if line.startswith(s): value = line[len(s):].strip() if value: mathlibs.extend(value.split(',')) # Ugly: this can be called within a library and not an extension, # in which case there is no libraries attributes (and none is # needed). if hasattr(ext, 'libraries'): ext.libraries.extend(mathlibs) incl_dir = os.path.dirname(target) if incl_dir not in config.numpy_include_dirs: config.numpy_include_dirs.append(incl_dir) return target def generate_numpyconfig_h(ext, build_dir): """Depends on config.h: generate_config_h has to be called before !""" # put common include directory in build_dir on search path # allows using code generation in headers config.add_include_dirs(join(build_dir, "src", "common")) config.add_include_dirs(join(build_dir, "src", "npymath")) target = join(build_dir, header_dir, '_numpyconfig.h') d = os.path.dirname(target) if not os.path.exists(d): os.makedirs(d) if newer(__file__, target): config_cmd = config.get_config_cmd() log.info('Generating %s', target) # Check sizeof ignored, moredefs = cocache.check_types(config_cmd, ext, build_dir) if is_npy_no_signal(): moredefs.append(('NPY_NO_SIGNAL', 1)) if is_npy_no_smp(): moredefs.append(('NPY_NO_SMP', 1)) else: moredefs.append(('NPY_NO_SMP', 0)) mathlibs = check_mathlib(config_cmd) moredefs.extend(cocache.check_ieee_macros(config_cmd)[1]) moredefs.extend(cocache.check_complex(config_cmd, mathlibs)[1]) if NPY_RELAXED_STRIDES_DEBUG: moredefs.append(('NPY_RELAXED_STRIDES_DEBUG', 1)) # Check whether we can use inttypes (C99) formats if config_cmd.check_decl('PRIdPTR', headers=['inttypes.h']): moredefs.append(('NPY_USE_C99_FORMATS', 1)) # visibility check hidden_visibility = visibility_define(config_cmd) moredefs.append(('NPY_VISIBILITY_HIDDEN', hidden_visibility)) # Add the C API/ABI versions moredefs.append(('NPY_ABI_VERSION', '0x%.8X' % C_ABI_VERSION)) moredefs.append(('NPY_API_VERSION', '0x%.8X' % C_API_VERSION)) # Add moredefs to header with open(target, 'w') as target_f: for d in moredefs: if isinstance(d, str): target_f.write('#define %s\n' % (d)) else: target_f.write('#define %s %s\n' % (d[0], d[1])) # Define __STDC_FORMAT_MACROS target_f.write(textwrap.dedent(""" #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS 1 #endif """)) # Dump the numpyconfig.h header to stdout log.info('File: %s' % target) with open(target) as target_f: log.info(target_f.read()) log.info('EOF') config.add_data_files((header_dir, target)) return target def generate_api_func(module_name): def generate_api(ext, build_dir): script = join(codegen_dir, module_name + '.py') sys.path.insert(0, codegen_dir) try: m = __import__(module_name) log.info('executing %s', script) h_file, c_file, doc_file = m.generate_api(os.path.join(build_dir, header_dir)) finally: del sys.path[0] config.add_data_files((header_dir, h_file), (header_dir, doc_file)) return (h_file,) return generate_api generate_numpy_api = generate_api_func('generate_numpy_api') generate_ufunc_api = generate_api_func('generate_ufunc_api') config.add_include_dirs(join(local_dir, "src", "common")) config.add_include_dirs(join(local_dir, "src")) config.add_include_dirs(join(local_dir)) config.add_data_dir('include/numpy') config.add_include_dirs(join('src', 'npymath')) config.add_include_dirs(join('src', 'multiarray')) config.add_include_dirs(join('src', 'umath')) config.add_include_dirs(join('src', 'npysort')) config.add_include_dirs(join('src', '_simd')) config.add_define_macros([("NPY_INTERNAL_BUILD", "1")]) # this macro indicates that Numpy build is in process config.add_define_macros([("HAVE_NPY_CONFIG_H", "1")]) if sys.platform[:3] == "aix": config.add_define_macros([("_LARGE_FILES", None)]) else: config.add_define_macros([("_FILE_OFFSET_BITS", "64")]) config.add_define_macros([('_LARGEFILE_SOURCE', '1')]) config.add_define_macros([('_LARGEFILE64_SOURCE', '1')]) config.numpy_include_dirs.extend(config.paths('include')) deps = [join('src', 'npymath', '_signbit.c'), join('include', 'numpy', '*object.h'), join(codegen_dir, 'genapi.py'), ] ####################################################################### # npymath library # ####################################################################### subst_dict = dict([("sep", os.path.sep), ("pkgname", "numpy.core")]) def get_mathlib_info(*args): # Another ugly hack: the mathlib info is known once build_src is run, # but we cannot use add_installed_pkg_config here either, so we only # update the substitution dictionary during npymath build config_cmd = config.get_config_cmd() # Check that the toolchain works, to fail early if it doesn't # (avoid late errors with MATHLIB which are confusing if the # compiler does not work). for lang, test_code, note in ( ('c', 'int main(void) { return 0;}', ''), ('c++', ( 'int main(void)' '{ auto x = 0.0; return static_cast<int>(x); }' ), ( 'note: A compiler with support for C++11 language ' 'features is required.' ) ), ): is_cpp = lang == 'c++' if is_cpp: # this a workaround to get rid of invalid c++ flags # without doing big changes to config. # c tested first, compiler should be here bk_c = config_cmd.compiler config_cmd.compiler = bk_c.cxx_compiler() # Check that Linux compiler actually support the default flags if hasattr(config_cmd.compiler, 'compiler'): config_cmd.compiler.compiler.extend(NPY_CXX_FLAGS) config_cmd.compiler.compiler_so.extend(NPY_CXX_FLAGS) st = config_cmd.try_link(test_code, lang=lang) if not st: # rerun the failing command in verbose mode config_cmd.compiler.verbose = True config_cmd.try_link(test_code, lang=lang) raise RuntimeError( f"Broken toolchain: cannot link a simple {lang.upper()} " f"program. {note}" ) if is_cpp: config_cmd.compiler = bk_c mlibs = check_mathlib(config_cmd) posix_mlib = ' '.join(['-l%s' % l for l in mlibs]) msvc_mlib = ' '.join(['%s.lib' % l for l in mlibs]) subst_dict["posix_mathlib"] = posix_mlib subst_dict["msvc_mathlib"] = msvc_mlib npymath_sources = [join('src', 'npymath', 'npy_math_internal.h.src'), join('src', 'npymath', 'npy_math.c'), # join('src', 'npymath', 'ieee754.cpp'), join('src', 'npymath', 'ieee754.c.src'), join('src', 'npymath', 'npy_math_complex.c.src'), join('src', 'npymath', 'halffloat.c'), ] config.add_installed_library('npymath', sources=npymath_sources + [get_mathlib_info], install_dir='lib', build_info={ 'include_dirs' : [], # empty list required for creating npy_math_internal.h 'extra_compiler_args': [lib_opts_if_msvc], }) config.add_npy_pkg_config("npymath.ini.in", "lib/npy-pkg-config", subst_dict) config.add_npy_pkg_config("mlib.ini.in", "lib/npy-pkg-config", subst_dict) ####################################################################### # multiarray_tests module # ####################################################################### config.add_extension('_multiarray_tests', sources=[join('src', 'multiarray', '_multiarray_tests.c.src'), join('src', 'common', 'mem_overlap.c'), join('src', 'common', 'npy_argparse.c'), join('src', 'common', 'npy_hashtable.c')], depends=[join('src', 'common', 'mem_overlap.h'), join('src', 'common', 'npy_argparse.h'), join('src', 'common', 'npy_hashtable.h'), join('src', 'common', 'npy_extint128.h')], libraries=['npymath']) ####################################################################### # _multiarray_umath module - common part # ####################################################################### common_deps = [ join('src', 'common', 'dlpack', 'dlpack.h'), join('src', 'common', 'array_assign.h'), join('src', 'common', 'binop_override.h'), join('src', 'common', 'cblasfuncs.h'), join('src', 'common', 'lowlevel_strided_loops.h'), join('src', 'common', 'mem_overlap.h'), join('src', 'common', 'npy_argparse.h'), join('src', 'common', 'npy_cblas.h'), join('src', 'common', 'npy_config.h'), join('src', 'common', 'npy_ctypes.h'), join('src', 'common', 'npy_dlpack.h'), join('src', 'common', 'npy_extint128.h'), join('src', 'common', 'npy_import.h'), join('src', 'common', 'npy_hashtable.h'), join('src', 'common', 'npy_longdouble.h'), join('src', 'common', 'npy_svml.h'), join('src', 'common', 'templ_common.h.src'), join('src', 'common', 'ucsnarrow.h'), join('src', 'common', 'ufunc_override.h'), join('src', 'common', 'umathmodule.h'), join('src', 'common', 'numpyos.h'), join('src', 'common', 'npy_cpu_dispatch.h'), join('src', 'common', 'simd', 'simd.h'), ] common_src = [ join('src', 'common', 'array_assign.c'), join('src', 'common', 'mem_overlap.c'), join('src', 'common', 'npy_argparse.c'), join('src', 'common', 'npy_hashtable.c'), join('src', 'common', 'npy_longdouble.c'), join('src', 'common', 'templ_common.h.src'), join('src', 'common', 'ucsnarrow.c'), join('src', 'common', 'ufunc_override.c'), join('src', 'common', 'numpyos.c'), join('src', 'common', 'npy_cpu_features.c'), ] if os.environ.get('NPY_USE_BLAS_ILP64', "0") != "0": blas_info = get_info('blas_ilp64_opt', 2) else: blas_info = get_info('blas_opt', 0) have_blas = blas_info and ('HAVE_CBLAS', None) in blas_info.get('define_macros', []) if have_blas: extra_info = blas_info # These files are also in MANIFEST.in so that they are always in # the source distribution independently of HAVE_CBLAS. common_src.extend([join('src', 'common', 'cblasfuncs.c'), join('src', 'common', 'python_xerbla.c'), ]) else: extra_info = {} ####################################################################### # _multiarray_umath module - multiarray part # ####################################################################### multiarray_deps = [ join('src', 'multiarray', 'abstractdtypes.h'), join('src', 'multiarray', 'arrayobject.h'), join('src', 'multiarray', 'arraytypes.h.src'), join('src', 'multiarray', 'arrayfunction_override.h'), join('src', 'multiarray', 'array_coercion.h'), join('src', 'multiarray', 'array_method.h'), join('src', 'multiarray', 'npy_buffer.h'), join('src', 'multiarray', 'calculation.h'), join('src', 'multiarray', 'common.h'), join('src', 'multiarray', 'common_dtype.h'), join('src', 'multiarray', 'convert_datatype.h'), join('src', 'multiarray', 'convert.h'), join('src', 'multiarray', 'conversion_utils.h'), join('src', 'multiarray', 'ctors.h'), join('src', 'multiarray', 'descriptor.h'), join('src', 'multiarray', 'dtypemeta.h'), join('src', 'multiarray', 'dtype_transfer.h'), join('src', 'multiarray', 'dragon4.h'), join('src', 'multiarray', 'einsum_debug.h'), join('src', 'multiarray', 'einsum_sumprod.h'), join('src', 'multiarray', 'experimental_public_dtype_api.h'), join('src', 'multiarray', 'getset.h'), join('src', 'multiarray', 'hashdescr.h'), join('src', 'multiarray', 'iterators.h'), join('src', 'multiarray', 'legacy_dtype_implementation.h'), join('src', 'multiarray', 'mapping.h'), join('src', 'multiarray', 'methods.h'), join('src', 'multiarray', 'multiarraymodule.h'), join('src', 'multiarray', 'nditer_impl.h'), join('src', 'multiarray', 'number.h'), join('src', 'multiarray', 'refcount.h'), join('src', 'multiarray', 'scalartypes.h'), join('src', 'multiarray', 'sequence.h'), join('src', 'multiarray', 'shape.h'), join('src', 'multiarray', 'strfuncs.h'), join('src', 'multiarray', 'typeinfo.h'), join('src', 'multiarray', 'usertypes.h'), join('src', 'multiarray', 'vdot.h'), join('src', 'multiarray', 'textreading', 'readtext.h'), join('include', 'numpy', 'arrayobject.h'), join('include', 'numpy', '_neighborhood_iterator_imp.h'), join('include', 'numpy', 'npy_endian.h'), join('include', 'numpy', 'arrayscalars.h'), join('include', 'numpy', 'noprefix.h'), join('include', 'numpy', 'npy_interrupt.h'), join('include', 'numpy', 'npy_3kcompat.h'), join('include', 'numpy', 'npy_math.h'), join('include', 'numpy', 'halffloat.h'), join('include', 'numpy', 'npy_common.h'), join('include', 'numpy', 'npy_os.h'), join('include', 'numpy', 'utils.h'), join('include', 'numpy', 'ndarrayobject.h'), join('include', 'numpy', 'npy_cpu.h'), join('include', 'numpy', 'numpyconfig.h'), join('include', 'numpy', 'ndarraytypes.h'), join('include', 'numpy', 'npy_1_7_deprecated_api.h'), # add library sources as distuils does not consider libraries # dependencies ] + npymath_sources multiarray_src = [ join('src', 'multiarray', 'abstractdtypes.c'), join('src', 'multiarray', 'alloc.c'), join('src', 'multiarray', 'arrayobject.c'), join('src', 'multiarray', 'arraytypes.h.src'), join('src', 'multiarray', 'arraytypes.c.src'), join('src', 'multiarray', 'argfunc.dispatch.c.src'), join('src', 'multiarray', 'array_coercion.c'), join('src', 'multiarray', 'array_method.c'), join('src', 'multiarray', 'array_assign_scalar.c'), join('src', 'multiarray', 'array_assign_array.c'), join('src', 'multiarray', 'arrayfunction_override.c'), join('src', 'multiarray', 'buffer.c'), join('src', 'multiarray', 'calculation.c'), join('src', 'multiarray', 'compiled_base.c'), join('src', 'multiarray', 'common.c'), join('src', 'multiarray', 'common_dtype.c'), join('src', 'multiarray', 'convert.c'), join('src', 'multiarray', 'convert_datatype.c'), join('src', 'multiarray', 'conversion_utils.c'), join('src', 'multiarray', 'ctors.c'), join('src', 'multiarray', 'datetime.c'), join('src', 'multiarray', 'datetime_strings.c'), join('src', 'multiarray', 'datetime_busday.c'), join('src', 'multiarray', 'datetime_busdaycal.c'), join('src', 'multiarray', 'descriptor.c'), join('src', 'multiarray', 'dlpack.c'), join('src', 'multiarray', 'dtypemeta.c'), join('src', 'multiarray', 'dragon4.c'), join('src', 'multiarray', 'dtype_transfer.c'), join('src', 'multiarray', 'einsum.c.src'), join('src', 'multiarray', 'einsum_sumprod.c.src'), join('src', 'multiarray', 'experimental_public_dtype_api.c'), join('src', 'multiarray', 'flagsobject.c'), join('src', 'multiarray', 'getset.c'), join('src', 'multiarray', 'hashdescr.c'), join('src', 'multiarray', 'item_selection.c'), join('src', 'multiarray', 'iterators.c'), join('src', 'multiarray', 'legacy_dtype_implementation.c'), join('src', 'multiarray', 'lowlevel_strided_loops.c.src'), join('src', 'multiarray', 'mapping.c'), join('src', 'multiarray', 'methods.c'), join('src', 'multiarray', 'multiarraymodule.c'), join('src', 'multiarray', 'nditer_templ.c.src'), join('src', 'multiarray', 'nditer_api.c'), join('src', 'multiarray', 'nditer_constr.c'), join('src', 'multiarray', 'nditer_pywrap.c'), join('src', 'multiarray', 'number.c'), join('src', 'multiarray', 'refcount.c'), join('src', 'multiarray', 'sequence.c'), join('src', 'multiarray', 'shape.c'), join('src', 'multiarray', 'scalarapi.c'), join('src', 'multiarray', 'scalartypes.c.src'), join('src', 'multiarray', 'strfuncs.c'), join('src', 'multiarray', 'temp_elide.c'), join('src', 'multiarray', 'typeinfo.c'), join('src', 'multiarray', 'usertypes.c'), join('src', 'multiarray', 'vdot.c'), join('src', 'common', 'npy_sort.h.src'), join('src', 'npysort', 'x86-qsort.dispatch.cpp'), join('src', 'npysort', 'quicksort.cpp'), join('src', 'npysort', 'mergesort.cpp'), join('src', 'npysort', 'timsort.cpp'), join('src', 'npysort', 'heapsort.cpp'), join('src', 'npysort', 'radixsort.cpp'), join('src', 'common', 'npy_partition.h'), join('src', 'npysort', 'selection.cpp'), join('src', 'common', 'npy_binsearch.h'), join('src', 'npysort', 'binsearch.cpp'), join('src', 'multiarray', 'textreading', 'conversions.c'), join('src', 'multiarray', 'textreading', 'field_types.c'), join('src', 'multiarray', 'textreading', 'growth.c'), join('src', 'multiarray', 'textreading', 'readtext.c'), join('src', 'multiarray', 'textreading', 'rows.c'), join('src', 'multiarray', 'textreading', 'stream_pyobject.c'), join('src', 'multiarray', 'textreading', 'str_to_int.c'), join('src', 'multiarray', 'textreading', 'tokenize.cpp'), # Remove this once scipy macos arm64 build correctly # links to the arm64 npymath library, # see gh-22673 join('src', 'npymath', 'arm64_exports.c'), ] ####################################################################### # _multiarray_umath module - umath part # ####################################################################### def generate_umath_c(ext, build_dir): target = join(build_dir, header_dir, '__umath_generated.c') dir = os.path.dirname(target) if not os.path.exists(dir): os.makedirs(dir) script = generate_umath_py if newer(script, target): with open(target, 'w') as f: f.write(generate_umath.make_code(generate_umath.defdict, generate_umath.__file__)) return [] def generate_umath_doc_header(ext, build_dir): from numpy.distutils.misc_util import exec_mod_from_location target = join(build_dir, header_dir, '_umath_doc_generated.h') dir = os.path.dirname(target) if not os.path.exists(dir): os.makedirs(dir) generate_umath_doc_py = join(codegen_dir, 'generate_umath_doc.py') if newer(generate_umath_doc_py, target): n = dot_join(config.name, 'generate_umath_doc') generate_umath_doc = exec_mod_from_location( '_'.join(n.split('.')), generate_umath_doc_py) generate_umath_doc.write_code(target) umath_src = [ join('src', 'umath', 'umathmodule.c'), join('src', 'umath', 'reduction.c'), join('src', 'umath', 'funcs.inc.src'), join('src', 'umath', 'simd.inc.src'), join('src', 'umath', 'loops.h.src'), join('src', 'umath', 'loops_utils.h.src'), join('src', 'umath', 'loops.c.src'), join('src', 'umath', 'loops_unary_fp.dispatch.c.src'), join('src', 'umath', 'loops_arithm_fp.dispatch.c.src'), join('src', 'umath', 'loops_arithmetic.dispatch.c.src'), join('src', 'umath', 'loops_minmax.dispatch.c.src'), join('src', 'umath', 'loops_trigonometric.dispatch.c.src'), join('src', 'umath', 'loops_umath_fp.dispatch.c.src'), join('src', 'umath', 'loops_exponent_log.dispatch.c.src'), join('src', 'umath', 'loops_hyperbolic.dispatch.c.src'), join('src', 'umath', 'loops_modulo.dispatch.c.src'), join('src', 'umath', 'loops_comparison.dispatch.c.src'), join('src', 'umath', 'matmul.h.src'), join('src', 'umath', 'matmul.c.src'), join('src', 'umath', 'clip.h'), join('src', 'umath', 'clip.cpp'), join('src', 'umath', 'dispatching.c'), join('src', 'umath', 'legacy_array_method.c'), join('src', 'umath', 'wrapping_array_method.c'), join('src', 'umath', 'ufunc_object.c'), join('src', 'umath', 'extobj.c'), join('src', 'umath', 'scalarmath.c.src'), join('src', 'umath', 'ufunc_type_resolution.c'), join('src', 'umath', 'override.c'), join('src', 'umath', 'string_ufuncs.cpp'), # For testing. Eventually, should use public API and be separate: join('src', 'umath', '_scaled_float_dtype.c'), ] umath_deps = [ generate_umath_py, join('include', 'numpy', 'npy_math.h'), join('include', 'numpy', 'halffloat.h'), join('src', 'multiarray', 'common.h'), join('src', 'multiarray', 'number.h'), join('src', 'common', 'templ_common.h.src'), join('src', 'umath', 'simd.inc.src'), join('src', 'umath', 'override.h'), join(codegen_dir, 'generate_ufunc_api.py'), join(codegen_dir, 'ufunc_docstrings.py'), ] svml_path = join('numpy', 'core', 'src', 'umath', 'svml') svml_objs = [] # we have converted the following into universal intrinsics # so we can bring the benefits of performance for all platforms # not just for avx512 on linux without performance/accuracy regression, # actually the other way around, better performance and # after all maintainable code. svml_filter = ( ) if can_link_svml() and check_svml_submodule(svml_path): svml_objs = glob.glob(svml_path + '/**/*.s', recursive=True) svml_objs = [o for o in svml_objs if not o.endswith(svml_filter)] # The ordering of names returned by glob is undefined, so we sort # to make builds reproducible. svml_objs.sort() config.add_extension('_multiarray_umath', # Forcing C language even though we have C++ sources. # It forces the C linker and don't link C++ runtime. language = 'c', sources=multiarray_src + umath_src + common_src + [generate_config_h, generate_numpyconfig_h, generate_numpy_api, join(codegen_dir, 'generate_numpy_api.py'), join('*.py'), generate_umath_c, generate_umath_doc_header, generate_ufunc_api, ], depends=deps + multiarray_deps + umath_deps + common_deps, libraries=['npymath'], extra_objects=svml_objs, extra_info=extra_info, extra_cxx_compile_args=NPY_CXX_FLAGS) ####################################################################### # umath_tests module # ####################################################################### config.add_extension('_umath_tests', sources=[ join('src', 'umath', '_umath_tests.c.src'), join('src', 'umath', '_umath_tests.dispatch.c'), join('src', 'common', 'npy_cpu_features.c'), ]) ####################################################################### # custom rational dtype module # ####################################################################### config.add_extension('_rational_tests', sources=[join('src', 'umath', '_rational_tests.c')]) ####################################################################### # struct_ufunc_test module # ####################################################################### config.add_extension('_struct_ufunc_tests', sources=[join('src', 'umath', '_struct_ufunc_tests.c')]) ####################################################################### # operand_flag_tests module # ####################################################################### config.add_extension('_operand_flag_tests', sources=[join('src', 'umath', '_operand_flag_tests.c')]) ####################################################################### # SIMD module # ####################################################################### config.add_extension('_simd', sources=[ join('src', 'common', 'npy_cpu_features.c'), join('src', '_simd', '_simd.c'), join('src', '_simd', '_simd_inc.h.src'), join('src', '_simd', '_simd_data.inc.src'), join('src', '_simd', '_simd.dispatch.c.src'), ], depends=[ join('src', 'common', 'npy_cpu_dispatch.h'), join('src', 'common', 'simd', 'simd.h'), join('src', '_simd', '_simd.h'), join('src', '_simd', '_simd_inc.h.src'), join('src', '_simd', '_simd_data.inc.src'), join('src', '_simd', '_simd_arg.inc'), join('src', '_simd', '_simd_convert.inc'), join('src', '_simd', '_simd_easyintrin.inc'), join('src', '_simd', '_simd_vector.inc'), ], libraries=['npymath'] ) config.add_subpackage('tests') config.add_data_dir('tests/data') config.add_data_dir('tests/examples') config.add_data_files('*.pyi') config.make_svn_version_py() return config
null
169,188
from .overrides import ( array_function_dispatch, set_array_function_like_doc, set_module, ) from .multiarray import array, asanyarray def _require_dispatcher(a, dtype=None, requirements=None, *, like=None): return (like,)
null
169,189
from .overrides import ( array_function_dispatch, set_array_function_like_doc, set_module, ) from .multiarray import array, asanyarray POSSIBLE_FLAGS = { 'C': 'C', 'C_CONTIGUOUS': 'C', 'CONTIGUOUS': 'C', 'F': 'F', 'F_CONTIGUOUS': 'F', 'FORTRAN': 'F', 'A': 'A', 'ALIGNED': 'A', 'W': 'W', 'WRITEABLE': 'W', 'O': 'O', 'OWNDATA': 'O', 'E': 'E', 'ENSUREARRAY': 'E' } _require_with_like = array_function_dispatch( _require_dispatcher )(require) array.__module__ = 'numpy' asanyarray.__module__ = 'numpy' The provided code snippet includes necessary dependencies for implementing the `require` function. Write a Python function `def require(a, dtype=None, requirements=None, *, like=None)` to solve the following problem: Return an ndarray of the provided type that satisfies requirements. This function is useful to be sure that an array with the correct flags is returned for passing to compiled code (perhaps through ctypes). Parameters ---------- a : array_like The object to be converted to a type-and-requirement-satisfying array. dtype : data-type The required data-type. If None preserve the current dtype. If your application requires the data to be in native byteorder, include a byteorder specification as a part of the dtype specification. requirements : str or sequence of str The requirements list can be any of the following * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array * 'ALIGNED' ('A') - ensure a data-type aligned array * 'WRITEABLE' ('W') - ensure a writable array * 'OWNDATA' ('O') - ensure an array that owns its own data * 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass ${ARRAY_FUNCTION_LIKE} .. versionadded:: 1.20.0 Returns ------- out : ndarray Array with specified requirements and type if given. See Also -------- asarray : Convert input to an ndarray. asanyarray : Convert to an ndarray, but pass through ndarray subclasses. ascontiguousarray : Convert input to a contiguous array. asfortranarray : Convert input to an ndarray with column-major memory order. ndarray.flags : Information about the memory layout of the array. Notes ----- The returned array will be guaranteed to have the listed requirements by making a copy if needed. Examples -------- >>> x = np.arange(6).reshape(2,3) >>> x.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : False WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F']) >>> y.flags C_CONTIGUOUS : False F_CONTIGUOUS : True OWNDATA : True WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False Here is the function: def require(a, dtype=None, requirements=None, *, like=None): """ Return an ndarray of the provided type that satisfies requirements. This function is useful to be sure that an array with the correct flags is returned for passing to compiled code (perhaps through ctypes). Parameters ---------- a : array_like The object to be converted to a type-and-requirement-satisfying array. dtype : data-type The required data-type. If None preserve the current dtype. If your application requires the data to be in native byteorder, include a byteorder specification as a part of the dtype specification. requirements : str or sequence of str The requirements list can be any of the following * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array * 'ALIGNED' ('A') - ensure a data-type aligned array * 'WRITEABLE' ('W') - ensure a writable array * 'OWNDATA' ('O') - ensure an array that owns its own data * 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass ${ARRAY_FUNCTION_LIKE} .. versionadded:: 1.20.0 Returns ------- out : ndarray Array with specified requirements and type if given. See Also -------- asarray : Convert input to an ndarray. asanyarray : Convert to an ndarray, but pass through ndarray subclasses. ascontiguousarray : Convert input to a contiguous array. asfortranarray : Convert input to an ndarray with column-major memory order. ndarray.flags : Information about the memory layout of the array. Notes ----- The returned array will be guaranteed to have the listed requirements by making a copy if needed. Examples -------- >>> x = np.arange(6).reshape(2,3) >>> x.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : False WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F']) >>> y.flags C_CONTIGUOUS : False F_CONTIGUOUS : True OWNDATA : True WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False """ if like is not None: return _require_with_like( a, dtype=dtype, requirements=requirements, like=like, ) if not requirements: return asanyarray(a, dtype=dtype) requirements = {POSSIBLE_FLAGS[x.upper()] for x in requirements} if 'E' in requirements: requirements.remove('E') subok = False else: subok = True order = 'A' if requirements >= {'C', 'F'}: raise ValueError('Cannot specify both "C" and "F" order') elif 'F' in requirements: order = 'F' requirements.remove('F') elif 'C' in requirements: order = 'C' requirements.remove('C') arr = array(a, dtype=dtype, order=order, copy=False, subok=subok) for prop in requirements: if not arr.flags[prop]: return arr.copy(order) return arr
Return an ndarray of the provided type that satisfies requirements. This function is useful to be sure that an array with the correct flags is returned for passing to compiled code (perhaps through ctypes). Parameters ---------- a : array_like The object to be converted to a type-and-requirement-satisfying array. dtype : data-type The required data-type. If None preserve the current dtype. If your application requires the data to be in native byteorder, include a byteorder specification as a part of the dtype specification. requirements : str or sequence of str The requirements list can be any of the following * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array * 'ALIGNED' ('A') - ensure a data-type aligned array * 'WRITEABLE' ('W') - ensure a writable array * 'OWNDATA' ('O') - ensure an array that owns its own data * 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass ${ARRAY_FUNCTION_LIKE} .. versionadded:: 1.20.0 Returns ------- out : ndarray Array with specified requirements and type if given. See Also -------- asarray : Convert input to an ndarray. asanyarray : Convert to an ndarray, but pass through ndarray subclasses. ascontiguousarray : Convert input to a contiguous array. asfortranarray : Convert input to an ndarray with column-major memory order. ndarray.flags : Information about the memory layout of the array. Notes ----- The returned array will be guaranteed to have the listed requirements by making a copy if needed. Examples -------- >>> x = np.arange(6).reshape(2,3) >>> x.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : False WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F']) >>> y.flags C_CONTIGUOUS : False F_CONTIGUOUS : True OWNDATA : True WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False
169,190
import os import genapi from genapi import \ TypeApi, GlobalVarApi, FunctionApi, BoolValuesApi import numpy_api def do_generate_api(targets, sources): import os del os def generate_api(output_dir, force=False): basename = 'multiarray_api' h_file = os.path.join(output_dir, '__%s.h' % basename) c_file = os.path.join(output_dir, '__%s.c' % basename) d_file = os.path.join(output_dir, '%s.txt' % basename) targets = (h_file, c_file, d_file) sources = numpy_api.multiarray_api if (not force and not genapi.should_rebuild(targets, [numpy_api.__file__, __file__])): return targets else: do_generate_api(targets, sources) return targets
null
169,191
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _binary_op_dispatcher(x1, x2): return (x1, x2)
null
169,192
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy The provided code snippet includes necessary dependencies for implementing the `equal` function. Write a Python function `def equal(x1, x2)` to solve the following problem: Return (x1 == x2) element-wise. Unlike `numpy.equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- not_equal, greater_equal, less_equal, greater, less Here is the function: def equal(x1, x2): """ Return (x1 == x2) element-wise. Unlike `numpy.equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- not_equal, greater_equal, less_equal, greater, less """ return compare_chararrays(x1, x2, '==', True)
Return (x1 == x2) element-wise. Unlike `numpy.equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- not_equal, greater_equal, less_equal, greater, less
169,193
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy The provided code snippet includes necessary dependencies for implementing the `not_equal` function. Write a Python function `def not_equal(x1, x2)` to solve the following problem: Return (x1 != x2) element-wise. Unlike `numpy.not_equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- equal, greater_equal, less_equal, greater, less Here is the function: def not_equal(x1, x2): """ Return (x1 != x2) element-wise. Unlike `numpy.not_equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- equal, greater_equal, less_equal, greater, less """ return compare_chararrays(x1, x2, '!=', True)
Return (x1 != x2) element-wise. Unlike `numpy.not_equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- equal, greater_equal, less_equal, greater, less
169,194
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy The provided code snippet includes necessary dependencies for implementing the `greater_equal` function. Write a Python function `def greater_equal(x1, x2)` to solve the following problem: Return (x1 >= x2) element-wise. Unlike `numpy.greater_equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- equal, not_equal, less_equal, greater, less Here is the function: def greater_equal(x1, x2): """ Return (x1 >= x2) element-wise. Unlike `numpy.greater_equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- equal, not_equal, less_equal, greater, less """ return compare_chararrays(x1, x2, '>=', True)
Return (x1 >= x2) element-wise. Unlike `numpy.greater_equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- equal, not_equal, less_equal, greater, less
169,195
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy The provided code snippet includes necessary dependencies for implementing the `less_equal` function. Write a Python function `def less_equal(x1, x2)` to solve the following problem: Return (x1 <= x2) element-wise. Unlike `numpy.less_equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- equal, not_equal, greater_equal, greater, less Here is the function: def less_equal(x1, x2): """ Return (x1 <= x2) element-wise. Unlike `numpy.less_equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- equal, not_equal, greater_equal, greater, less """ return compare_chararrays(x1, x2, '<=', True)
Return (x1 <= x2) element-wise. Unlike `numpy.less_equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- equal, not_equal, greater_equal, greater, less
169,196
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy The provided code snippet includes necessary dependencies for implementing the `greater` function. Write a Python function `def greater(x1, x2)` to solve the following problem: Return (x1 > x2) element-wise. Unlike `numpy.greater`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- equal, not_equal, greater_equal, less_equal, less Here is the function: def greater(x1, x2): """ Return (x1 > x2) element-wise. Unlike `numpy.greater`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- equal, not_equal, greater_equal, less_equal, less """ return compare_chararrays(x1, x2, '>', True)
Return (x1 > x2) element-wise. Unlike `numpy.greater`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- equal, not_equal, greater_equal, less_equal, less
169,197
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy The provided code snippet includes necessary dependencies for implementing the `less` function. Write a Python function `def less(x1, x2)` to solve the following problem: Return (x1 < x2) element-wise. Unlike `numpy.greater`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- equal, not_equal, greater_equal, less_equal, greater Here is the function: def less(x1, x2): """ Return (x1 < x2) element-wise. Unlike `numpy.greater`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- equal, not_equal, greater_equal, less_equal, greater """ return compare_chararrays(x1, x2, '<', True)
Return (x1 < x2) element-wise. Unlike `numpy.greater`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. See Also -------- equal, not_equal, greater_equal, less_equal, greater
169,198
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _unary_op_dispatcher(a): return (a,)
null
169,199
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy The provided code snippet includes necessary dependencies for implementing the `str_len` function. Write a Python function `def str_len(a)` to solve the following problem: Return len(a) element-wise. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of integers See Also -------- builtins.len Examples -------- >>> a = np.array(['Grace Hopper Conference', 'Open Source Day']) >>> np.char.str_len(a) array([23, 15]) >>> a = np.array([u'\u0420', u'\u043e']) >>> np.char.str_len(a) array([1, 1]) >>> a = np.array([['hello', 'world'], [u'\u0420', u'\u043e']]) >>> np.char.str_len(a) array([[5, 5], [1, 1]]) Here is the function: def str_len(a): """ Return len(a) element-wise. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of integers See Also -------- builtins.len Examples -------- >>> a = np.array(['Grace Hopper Conference', 'Open Source Day']) >>> np.char.str_len(a) array([23, 15]) >>> a = np.array([u'\u0420', u'\u043e']) >>> np.char.str_len(a) array([1, 1]) >>> a = np.array([['hello', 'world'], [u'\u0420', u'\u043e']]) >>> np.char.str_len(a) array([[5, 5], [1, 1]]) """ # Note: __len__, etc. currently return ints, which are not C-integers. # Generally intp would be expected for lengths, although int is sufficient # due to the dtype itemsize limitation. return _vec_string(a, int_, '__len__')
Return len(a) element-wise. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of integers See Also -------- builtins.len Examples -------- >>> a = np.array(['Grace Hopper Conference', 'Open Source Day']) >>> np.char.str_len(a) array([23, 15]) >>> a = np.array([u'\u0420', u'\u043e']) >>> np.char.str_len(a) array([1, 1]) >>> a = np.array([['hello', 'world'], [u'\u0420', u'\u043e']]) >>> np.char.str_len(a) array([[5, 5], [1, 1]])
169,200
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _use_unicode(*args): """ Helper function for determining the output type of some string operations. For an operation on two ndarrays, if at least one is unicode, the result should be unicode. """ for x in args: if (isinstance(x, str) or issubclass(numpy.asarray(x).dtype.type, unicode_)): return unicode_ return string_ def _get_num_chars(a): """ Helper function that returns the number of characters per field in a string or unicode array. This is to abstract out the fact that for a unicode array this is itemsize / 4. """ if issubclass(a.dtype.type, unicode_): return a.itemsize // 4 return a.itemsize def asarray(obj, itemsize=None, unicode=None, order=None): """ Convert the input to a `chararray`, copying the data only if necessary. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). """ return array(obj, itemsize, copy=False, unicode=unicode, order=order) The provided code snippet includes necessary dependencies for implementing the `add` function. Write a Python function `def add(x1, x2)` to solve the following problem: Return element-wise string concatenation for two arrays of str or unicode. Arrays `x1` and `x2` must have the same shape. Parameters ---------- x1 : array_like of str or unicode Input array. x2 : array_like of str or unicode Input array. Returns ------- add : ndarray Output array of `string_` or `unicode_`, depending on input types of the same shape as `x1` and `x2`. Here is the function: def add(x1, x2): """ Return element-wise string concatenation for two arrays of str or unicode. Arrays `x1` and `x2` must have the same shape. Parameters ---------- x1 : array_like of str or unicode Input array. x2 : array_like of str or unicode Input array. Returns ------- add : ndarray Output array of `string_` or `unicode_`, depending on input types of the same shape as `x1` and `x2`. """ arr1 = numpy.asarray(x1) arr2 = numpy.asarray(x2) out_size = _get_num_chars(arr1) + _get_num_chars(arr2) dtype = _use_unicode(arr1, arr2) return _vec_string(arr1, (dtype, out_size), '__add__', (arr2,))
Return element-wise string concatenation for two arrays of str or unicode. Arrays `x1` and `x2` must have the same shape. Parameters ---------- x1 : array_like of str or unicode Input array. x2 : array_like of str or unicode Input array. Returns ------- add : ndarray Output array of `string_` or `unicode_`, depending on input types of the same shape as `x1` and `x2`.
169,201
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _multiply_dispatcher(a, i): return (a,)
null
169,202
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _get_num_chars(a): """ Helper function that returns the number of characters per field in a string or unicode array. This is to abstract out the fact that for a unicode array this is itemsize / 4. """ if issubclass(a.dtype.type, unicode_): return a.itemsize // 4 return a.itemsize def asarray(obj, itemsize=None, unicode=None, order=None): """ Convert the input to a `chararray`, copying the data only if necessary. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). """ return array(obj, itemsize, copy=False, unicode=unicode, order=order) The provided code snippet includes necessary dependencies for implementing the `multiply` function. Write a Python function `def multiply(a, i)` to solve the following problem: Return (a * i), that is string multiple concatenation, element-wise. Values in `i` of less than 0 are treated as 0 (which yields an empty string). Parameters ---------- a : array_like of str or unicode i : array_like of ints Returns ------- out : ndarray Output array of str or unicode, depending on input types Examples -------- >>> a = np.array(["a", "b", "c"]) >>> np.char.multiply(x, 3) array(['aaa', 'bbb', 'ccc'], dtype='<U3') >>> i = np.array([1, 2, 3]) >>> np.char.multiply(a, i) array(['a', 'bb', 'ccc'], dtype='<U3') >>> np.char.multiply(np.array(['a']), i) array(['a', 'aa', 'aaa'], dtype='<U3') >>> a = np.array(['a', 'b', 'c', 'd', 'e', 'f']).reshape((2, 3)) >>> np.char.multiply(a, 3) array([['aaa', 'bbb', 'ccc'], ['ddd', 'eee', 'fff']], dtype='<U3') >>> np.char.multiply(a, i) array([['a', 'bb', 'ccc'], ['d', 'ee', 'fff']], dtype='<U3') Here is the function: def multiply(a, i): """ Return (a * i), that is string multiple concatenation, element-wise. Values in `i` of less than 0 are treated as 0 (which yields an empty string). Parameters ---------- a : array_like of str or unicode i : array_like of ints Returns ------- out : ndarray Output array of str or unicode, depending on input types Examples -------- >>> a = np.array(["a", "b", "c"]) >>> np.char.multiply(x, 3) array(['aaa', 'bbb', 'ccc'], dtype='<U3') >>> i = np.array([1, 2, 3]) >>> np.char.multiply(a, i) array(['a', 'bb', 'ccc'], dtype='<U3') >>> np.char.multiply(np.array(['a']), i) array(['a', 'aa', 'aaa'], dtype='<U3') >>> a = np.array(['a', 'b', 'c', 'd', 'e', 'f']).reshape((2, 3)) >>> np.char.multiply(a, 3) array([['aaa', 'bbb', 'ccc'], ['ddd', 'eee', 'fff']], dtype='<U3') >>> np.char.multiply(a, i) array([['a', 'bb', 'ccc'], ['d', 'ee', 'fff']], dtype='<U3') """ a_arr = numpy.asarray(a) i_arr = numpy.asarray(i) if not issubclass(i_arr.dtype.type, integer): raise ValueError("Can only multiply by integers") out_size = _get_num_chars(a_arr) * max(int(i_arr.max()), 0) return _vec_string( a_arr, (a_arr.dtype.type, out_size), '__mul__', (i_arr,))
Return (a * i), that is string multiple concatenation, element-wise. Values in `i` of less than 0 are treated as 0 (which yields an empty string). Parameters ---------- a : array_like of str or unicode i : array_like of ints Returns ------- out : ndarray Output array of str or unicode, depending on input types Examples -------- >>> a = np.array(["a", "b", "c"]) >>> np.char.multiply(x, 3) array(['aaa', 'bbb', 'ccc'], dtype='<U3') >>> i = np.array([1, 2, 3]) >>> np.char.multiply(a, i) array(['a', 'bb', 'ccc'], dtype='<U3') >>> np.char.multiply(np.array(['a']), i) array(['a', 'aa', 'aaa'], dtype='<U3') >>> a = np.array(['a', 'b', 'c', 'd', 'e', 'f']).reshape((2, 3)) >>> np.char.multiply(a, 3) array([['aaa', 'bbb', 'ccc'], ['ddd', 'eee', 'fff']], dtype='<U3') >>> np.char.multiply(a, i) array([['a', 'bb', 'ccc'], ['d', 'ee', 'fff']], dtype='<U3')
169,203
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _mod_dispatcher(a, values): return (a, values)
null
169,204
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _to_string_or_unicode_array(result): """ Helper function to cast a result back into a string or unicode array if an object array must be used as an intermediary. """ return numpy.asarray(result.tolist()) The provided code snippet includes necessary dependencies for implementing the `mod` function. Write a Python function `def mod(a, values)` to solve the following problem: Return (a % i), that is pre-Python 2.6 string formatting (interpolation), element-wise for a pair of array_likes of str or unicode. Parameters ---------- a : array_like of str or unicode values : array_like of values These values will be element-wise interpolated into the string. Returns ------- out : ndarray Output array of str or unicode, depending on input types See Also -------- str.__mod__ Here is the function: def mod(a, values): """ Return (a % i), that is pre-Python 2.6 string formatting (interpolation), element-wise for a pair of array_likes of str or unicode. Parameters ---------- a : array_like of str or unicode values : array_like of values These values will be element-wise interpolated into the string. Returns ------- out : ndarray Output array of str or unicode, depending on input types See Also -------- str.__mod__ """ return _to_string_or_unicode_array( _vec_string(a, object_, '__mod__', (values,)))
Return (a % i), that is pre-Python 2.6 string formatting (interpolation), element-wise for a pair of array_likes of str or unicode. Parameters ---------- a : array_like of str or unicode values : array_like of values These values will be element-wise interpolated into the string. Returns ------- out : ndarray Output array of str or unicode, depending on input types See Also -------- str.__mod__
169,205
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def asarray(obj, itemsize=None, unicode=None, order=None): """ Convert the input to a `chararray`, copying the data only if necessary. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). """ return array(obj, itemsize, copy=False, unicode=unicode, order=order) The provided code snippet includes necessary dependencies for implementing the `capitalize` function. Write a Python function `def capitalize(a)` to solve the following problem: Return a copy of `a` with only the first character of each element capitalized. Calls `str.capitalize` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Input array of strings to capitalize. Returns ------- out : ndarray Output array of str or unicode, depending on input types See Also -------- str.capitalize Examples -------- >>> c = np.array(['a1b2','1b2a','b2a1','2a1b'],'S4'); c array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='|S4') >>> np.char.capitalize(c) array(['A1b2', '1b2a', 'B2a1', '2a1b'], dtype='|S4') Here is the function: def capitalize(a): """ Return a copy of `a` with only the first character of each element capitalized. Calls `str.capitalize` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Input array of strings to capitalize. Returns ------- out : ndarray Output array of str or unicode, depending on input types See Also -------- str.capitalize Examples -------- >>> c = np.array(['a1b2','1b2a','b2a1','2a1b'],'S4'); c array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='|S4') >>> np.char.capitalize(c) array(['A1b2', '1b2a', 'B2a1', '2a1b'], dtype='|S4') """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'capitalize')
Return a copy of `a` with only the first character of each element capitalized. Calls `str.capitalize` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Input array of strings to capitalize. Returns ------- out : ndarray Output array of str or unicode, depending on input types See Also -------- str.capitalize Examples -------- >>> c = np.array(['a1b2','1b2a','b2a1','2a1b'],'S4'); c array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='|S4') >>> np.char.capitalize(c) array(['A1b2', '1b2a', 'B2a1', '2a1b'], dtype='|S4')
169,206
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _center_dispatcher(a, width, fillchar=None): return (a,)
null
169,207
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def asarray(obj, itemsize=None, unicode=None, order=None): """ Convert the input to a `chararray`, copying the data only if necessary. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). """ return array(obj, itemsize, copy=False, unicode=unicode, order=order) The provided code snippet includes necessary dependencies for implementing the `center` function. Write a Python function `def center(a, width, fillchar=' ')` to solve the following problem: Return a copy of `a` with its elements centered in a string of length `width`. Calls `str.center` element-wise. Parameters ---------- a : array_like of str or unicode width : int The length of the resulting strings fillchar : str or unicode, optional The padding character to use (default is space). Returns ------- out : ndarray Output array of str or unicode, depending on input types See Also -------- str.center Notes ----- This function is intended to work with arrays of strings. The fill character is not applied to numeric types. Examples -------- >>> c = np.array(['a1b2','1b2a','b2a1','2a1b']); c array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='<U4') >>> np.char.center(c, width=9) array([' a1b2 ', ' 1b2a ', ' b2a1 ', ' 2a1b '], dtype='<U9') >>> np.char.center(c, width=9, fillchar='*') array(['***a1b2**', '***1b2a**', '***b2a1**', '***2a1b**'], dtype='<U9') >>> np.char.center(c, width=1) array(['a', '1', 'b', '2'], dtype='<U1') Here is the function: def center(a, width, fillchar=' '): """ Return a copy of `a` with its elements centered in a string of length `width`. Calls `str.center` element-wise. Parameters ---------- a : array_like of str or unicode width : int The length of the resulting strings fillchar : str or unicode, optional The padding character to use (default is space). Returns ------- out : ndarray Output array of str or unicode, depending on input types See Also -------- str.center Notes ----- This function is intended to work with arrays of strings. The fill character is not applied to numeric types. Examples -------- >>> c = np.array(['a1b2','1b2a','b2a1','2a1b']); c array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='<U4') >>> np.char.center(c, width=9) array([' a1b2 ', ' 1b2a ', ' b2a1 ', ' 2a1b '], dtype='<U9') >>> np.char.center(c, width=9, fillchar='*') array(['***a1b2**', '***1b2a**', '***b2a1**', '***2a1b**'], dtype='<U9') >>> np.char.center(c, width=1) array(['a', '1', 'b', '2'], dtype='<U1') """ a_arr = numpy.asarray(a) width_arr = numpy.asarray(width) size = int(numpy.max(width_arr.flat)) if numpy.issubdtype(a_arr.dtype, numpy.string_): fillchar = asbytes(fillchar) return _vec_string( a_arr, (a_arr.dtype.type, size), 'center', (width_arr, fillchar))
Return a copy of `a` with its elements centered in a string of length `width`. Calls `str.center` element-wise. Parameters ---------- a : array_like of str or unicode width : int The length of the resulting strings fillchar : str or unicode, optional The padding character to use (default is space). Returns ------- out : ndarray Output array of str or unicode, depending on input types See Also -------- str.center Notes ----- This function is intended to work with arrays of strings. The fill character is not applied to numeric types. Examples -------- >>> c = np.array(['a1b2','1b2a','b2a1','2a1b']); c array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='<U4') >>> np.char.center(c, width=9) array([' a1b2 ', ' 1b2a ', ' b2a1 ', ' 2a1b '], dtype='<U9') >>> np.char.center(c, width=9, fillchar='*') array(['***a1b2**', '***1b2a**', '***b2a1**', '***2a1b**'], dtype='<U9') >>> np.char.center(c, width=1) array(['a', '1', 'b', '2'], dtype='<U1')
169,208
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _count_dispatcher(a, sub, start=None, end=None): return (a,)
null
169,209
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _clean_args(*args): """ Helper function for delegating arguments to Python string functions. Many of the Python string operations that have optional arguments do not use 'None' to indicate a default value. In these cases, we need to remove all None arguments, and those following them. """ newargs = [] for chk in args: if chk is None: break newargs.append(chk) return newargs The provided code snippet includes necessary dependencies for implementing the `count` function. Write a Python function `def count(a, sub, start=0, end=None)` to solve the following problem: Returns an array with the number of non-overlapping occurrences of substring `sub` in the range [`start`, `end`]. Calls `str.count` element-wise. Parameters ---------- a : array_like of str or unicode sub : str or unicode The substring to search for. start, end : int, optional Optional arguments `start` and `end` are interpreted as slice notation to specify the range in which to count. Returns ------- out : ndarray Output array of ints. See Also -------- str.count Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') >>> np.char.count(c, 'A') array([3, 1, 1]) >>> np.char.count(c, 'aA') array([3, 1, 0]) >>> np.char.count(c, 'A', start=1, end=4) array([2, 1, 1]) >>> np.char.count(c, 'A', start=1, end=3) array([1, 0, 0]) Here is the function: def count(a, sub, start=0, end=None): """ Returns an array with the number of non-overlapping occurrences of substring `sub` in the range [`start`, `end`]. Calls `str.count` element-wise. Parameters ---------- a : array_like of str or unicode sub : str or unicode The substring to search for. start, end : int, optional Optional arguments `start` and `end` are interpreted as slice notation to specify the range in which to count. Returns ------- out : ndarray Output array of ints. See Also -------- str.count Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') >>> np.char.count(c, 'A') array([3, 1, 1]) >>> np.char.count(c, 'aA') array([3, 1, 0]) >>> np.char.count(c, 'A', start=1, end=4) array([2, 1, 1]) >>> np.char.count(c, 'A', start=1, end=3) array([1, 0, 0]) """ return _vec_string(a, int_, 'count', [sub, start] + _clean_args(end))
Returns an array with the number of non-overlapping occurrences of substring `sub` in the range [`start`, `end`]. Calls `str.count` element-wise. Parameters ---------- a : array_like of str or unicode sub : str or unicode The substring to search for. start, end : int, optional Optional arguments `start` and `end` are interpreted as slice notation to specify the range in which to count. Returns ------- out : ndarray Output array of ints. See Also -------- str.count Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') >>> np.char.count(c, 'A') array([3, 1, 1]) >>> np.char.count(c, 'aA') array([3, 1, 0]) >>> np.char.count(c, 'A', start=1, end=4) array([2, 1, 1]) >>> np.char.count(c, 'A', start=1, end=3) array([1, 0, 0])
169,210
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _code_dispatcher(a, encoding=None, errors=None): return (a,)
null
169,211
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _to_string_or_unicode_array(result): """ Helper function to cast a result back into a string or unicode array if an object array must be used as an intermediary. """ return numpy.asarray(result.tolist()) def _clean_args(*args): """ Helper function for delegating arguments to Python string functions. Many of the Python string operations that have optional arguments do not use 'None' to indicate a default value. In these cases, we need to remove all None arguments, and those following them. """ newargs = [] for chk in args: if chk is None: break newargs.append(chk) return newargs The provided code snippet includes necessary dependencies for implementing the `decode` function. Write a Python function `def decode(a, encoding=None, errors=None)` to solve the following problem: r""" Calls ``bytes.decode`` element-wise. The set of available codecs comes from the Python standard library, and may be extended at runtime. For more information, see the :mod:`codecs` module. Parameters ---------- a : array_like of str or unicode encoding : str, optional The name of an encoding errors : str, optional Specifies how to handle encoding errors Returns ------- out : ndarray See Also -------- :py:meth:`bytes.decode` Notes ----- The type of the result will depend on the encoding specified. Examples -------- >>> c = np.array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@', ... b'\x81\x82\xc2\xc1\xc2\x82\x81']) >>> c array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@', ... b'\x81\x82\xc2\xc1\xc2\x82\x81'], dtype='|S7') >>> np.char.decode(c, encoding='cp037') array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') Here is the function: def decode(a, encoding=None, errors=None): r""" Calls ``bytes.decode`` element-wise. The set of available codecs comes from the Python standard library, and may be extended at runtime. For more information, see the :mod:`codecs` module. Parameters ---------- a : array_like of str or unicode encoding : str, optional The name of an encoding errors : str, optional Specifies how to handle encoding errors Returns ------- out : ndarray See Also -------- :py:meth:`bytes.decode` Notes ----- The type of the result will depend on the encoding specified. Examples -------- >>> c = np.array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@', ... b'\x81\x82\xc2\xc1\xc2\x82\x81']) >>> c array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@', ... b'\x81\x82\xc2\xc1\xc2\x82\x81'], dtype='|S7') >>> np.char.decode(c, encoding='cp037') array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') """ return _to_string_or_unicode_array( _vec_string(a, object_, 'decode', _clean_args(encoding, errors)))
r""" Calls ``bytes.decode`` element-wise. The set of available codecs comes from the Python standard library, and may be extended at runtime. For more information, see the :mod:`codecs` module. Parameters ---------- a : array_like of str or unicode encoding : str, optional The name of an encoding errors : str, optional Specifies how to handle encoding errors Returns ------- out : ndarray See Also -------- :py:meth:`bytes.decode` Notes ----- The type of the result will depend on the encoding specified. Examples -------- >>> c = np.array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@', ... b'\x81\x82\xc2\xc1\xc2\x82\x81']) >>> c array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@', ... b'\x81\x82\xc2\xc1\xc2\x82\x81'], dtype='|S7') >>> np.char.decode(c, encoding='cp037') array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
169,212
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _to_string_or_unicode_array(result): """ Helper function to cast a result back into a string or unicode array if an object array must be used as an intermediary. """ return numpy.asarray(result.tolist()) def _clean_args(*args): """ Helper function for delegating arguments to Python string functions. Many of the Python string operations that have optional arguments do not use 'None' to indicate a default value. In these cases, we need to remove all None arguments, and those following them. """ newargs = [] for chk in args: if chk is None: break newargs.append(chk) return newargs The provided code snippet includes necessary dependencies for implementing the `encode` function. Write a Python function `def encode(a, encoding=None, errors=None)` to solve the following problem: Calls `str.encode` element-wise. The set of available codecs comes from the Python standard library, and may be extended at runtime. For more information, see the codecs module. Parameters ---------- a : array_like of str or unicode encoding : str, optional The name of an encoding errors : str, optional Specifies how to handle encoding errors Returns ------- out : ndarray See Also -------- str.encode Notes ----- The type of the result will depend on the encoding specified. Here is the function: def encode(a, encoding=None, errors=None): """ Calls `str.encode` element-wise. The set of available codecs comes from the Python standard library, and may be extended at runtime. For more information, see the codecs module. Parameters ---------- a : array_like of str or unicode encoding : str, optional The name of an encoding errors : str, optional Specifies how to handle encoding errors Returns ------- out : ndarray See Also -------- str.encode Notes ----- The type of the result will depend on the encoding specified. """ return _to_string_or_unicode_array( _vec_string(a, object_, 'encode', _clean_args(encoding, errors)))
Calls `str.encode` element-wise. The set of available codecs comes from the Python standard library, and may be extended at runtime. For more information, see the codecs module. Parameters ---------- a : array_like of str or unicode encoding : str, optional The name of an encoding errors : str, optional Specifies how to handle encoding errors Returns ------- out : ndarray See Also -------- str.encode Notes ----- The type of the result will depend on the encoding specified.
169,213
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _endswith_dispatcher(a, suffix, start=None, end=None): return (a,)
null
169,214
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _clean_args(*args): """ Helper function for delegating arguments to Python string functions. Many of the Python string operations that have optional arguments do not use 'None' to indicate a default value. In these cases, we need to remove all None arguments, and those following them. """ newargs = [] for chk in args: if chk is None: break newargs.append(chk) return newargs The provided code snippet includes necessary dependencies for implementing the `endswith` function. Write a Python function `def endswith(a, suffix, start=0, end=None)` to solve the following problem: Returns a boolean array which is `True` where the string element in `a` ends with `suffix`, otherwise `False`. Calls `str.endswith` element-wise. Parameters ---------- a : array_like of str or unicode suffix : str start, end : int, optional With optional `start`, test beginning at that position. With optional `end`, stop comparing at that position. Returns ------- out : ndarray Outputs an array of bools. See Also -------- str.endswith Examples -------- >>> s = np.array(['foo', 'bar']) >>> s[0] = 'foo' >>> s[1] = 'bar' >>> s array(['foo', 'bar'], dtype='<U3') >>> np.char.endswith(s, 'ar') array([False, True]) >>> np.char.endswith(s, 'a', start=1, end=2) array([False, True]) Here is the function: def endswith(a, suffix, start=0, end=None): """ Returns a boolean array which is `True` where the string element in `a` ends with `suffix`, otherwise `False`. Calls `str.endswith` element-wise. Parameters ---------- a : array_like of str or unicode suffix : str start, end : int, optional With optional `start`, test beginning at that position. With optional `end`, stop comparing at that position. Returns ------- out : ndarray Outputs an array of bools. See Also -------- str.endswith Examples -------- >>> s = np.array(['foo', 'bar']) >>> s[0] = 'foo' >>> s[1] = 'bar' >>> s array(['foo', 'bar'], dtype='<U3') >>> np.char.endswith(s, 'ar') array([False, True]) >>> np.char.endswith(s, 'a', start=1, end=2) array([False, True]) """ return _vec_string( a, bool_, 'endswith', [suffix, start] + _clean_args(end))
Returns a boolean array which is `True` where the string element in `a` ends with `suffix`, otherwise `False`. Calls `str.endswith` element-wise. Parameters ---------- a : array_like of str or unicode suffix : str start, end : int, optional With optional `start`, test beginning at that position. With optional `end`, stop comparing at that position. Returns ------- out : ndarray Outputs an array of bools. See Also -------- str.endswith Examples -------- >>> s = np.array(['foo', 'bar']) >>> s[0] = 'foo' >>> s[1] = 'bar' >>> s array(['foo', 'bar'], dtype='<U3') >>> np.char.endswith(s, 'ar') array([False, True]) >>> np.char.endswith(s, 'a', start=1, end=2) array([False, True])
169,215
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _expandtabs_dispatcher(a, tabsize=None): return (a,)
null
169,216
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _to_string_or_unicode_array(result): """ Helper function to cast a result back into a string or unicode array if an object array must be used as an intermediary. """ return numpy.asarray(result.tolist()) The provided code snippet includes necessary dependencies for implementing the `expandtabs` function. Write a Python function `def expandtabs(a, tabsize=8)` to solve the following problem: Return a copy of each string element where all tab characters are replaced by one or more spaces. Calls `str.expandtabs` element-wise. Return a copy of each string element where all tab characters are replaced by one or more spaces, depending on the current column and the given `tabsize`. The column number is reset to zero after each newline occurring in the string. This doesn't understand other non-printing characters or escape sequences. Parameters ---------- a : array_like of str or unicode Input array tabsize : int, optional Replace tabs with `tabsize` number of spaces. If not given defaults to 8 spaces. Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.expandtabs Here is the function: def expandtabs(a, tabsize=8): """ Return a copy of each string element where all tab characters are replaced by one or more spaces. Calls `str.expandtabs` element-wise. Return a copy of each string element where all tab characters are replaced by one or more spaces, depending on the current column and the given `tabsize`. The column number is reset to zero after each newline occurring in the string. This doesn't understand other non-printing characters or escape sequences. Parameters ---------- a : array_like of str or unicode Input array tabsize : int, optional Replace tabs with `tabsize` number of spaces. If not given defaults to 8 spaces. Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.expandtabs """ return _to_string_or_unicode_array( _vec_string(a, object_, 'expandtabs', (tabsize,)))
Return a copy of each string element where all tab characters are replaced by one or more spaces. Calls `str.expandtabs` element-wise. Return a copy of each string element where all tab characters are replaced by one or more spaces, depending on the current column and the given `tabsize`. The column number is reset to zero after each newline occurring in the string. This doesn't understand other non-printing characters or escape sequences. Parameters ---------- a : array_like of str or unicode Input array tabsize : int, optional Replace tabs with `tabsize` number of spaces. If not given defaults to 8 spaces. Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.expandtabs
169,217
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _clean_args(*args): """ Helper function for delegating arguments to Python string functions. Many of the Python string operations that have optional arguments do not use 'None' to indicate a default value. In these cases, we need to remove all None arguments, and those following them. """ newargs = [] for chk in args: if chk is None: break newargs.append(chk) return newargs The provided code snippet includes necessary dependencies for implementing the `find` function. Write a Python function `def find(a, sub, start=0, end=None)` to solve the following problem: For each element, return the lowest index in the string where substring `sub` is found. Calls `str.find` element-wise. For each element, return the lowest index in the string where substring `sub` is found, such that `sub` is contained in the range [`start`, `end`]. Parameters ---------- a : array_like of str or unicode sub : str or unicode start, end : int, optional Optional arguments `start` and `end` are interpreted as in slice notation. Returns ------- out : ndarray or int Output array of ints. Returns -1 if `sub` is not found. See Also -------- str.find Examples -------- >>> a = np.array(["NumPy is a Python library"]) >>> np.char.find(a, "Python", start=0, end=None) array([11]) Here is the function: def find(a, sub, start=0, end=None): """ For each element, return the lowest index in the string where substring `sub` is found. Calls `str.find` element-wise. For each element, return the lowest index in the string where substring `sub` is found, such that `sub` is contained in the range [`start`, `end`]. Parameters ---------- a : array_like of str or unicode sub : str or unicode start, end : int, optional Optional arguments `start` and `end` are interpreted as in slice notation. Returns ------- out : ndarray or int Output array of ints. Returns -1 if `sub` is not found. See Also -------- str.find Examples -------- >>> a = np.array(["NumPy is a Python library"]) >>> np.char.find(a, "Python", start=0, end=None) array([11]) """ return _vec_string( a, int_, 'find', [sub, start] + _clean_args(end))
For each element, return the lowest index in the string where substring `sub` is found. Calls `str.find` element-wise. For each element, return the lowest index in the string where substring `sub` is found, such that `sub` is contained in the range [`start`, `end`]. Parameters ---------- a : array_like of str or unicode sub : str or unicode start, end : int, optional Optional arguments `start` and `end` are interpreted as in slice notation. Returns ------- out : ndarray or int Output array of ints. Returns -1 if `sub` is not found. See Also -------- str.find Examples -------- >>> a = np.array(["NumPy is a Python library"]) >>> np.char.find(a, "Python", start=0, end=None) array([11])
169,218
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _clean_args(*args): """ Helper function for delegating arguments to Python string functions. Many of the Python string operations that have optional arguments do not use 'None' to indicate a default value. In these cases, we need to remove all None arguments, and those following them. """ newargs = [] for chk in args: if chk is None: break newargs.append(chk) return newargs The provided code snippet includes necessary dependencies for implementing the `index` function. Write a Python function `def index(a, sub, start=0, end=None)` to solve the following problem: Like `find`, but raises `ValueError` when the substring is not found. Calls `str.index` element-wise. Parameters ---------- a : array_like of str or unicode sub : str or unicode start, end : int, optional Returns ------- out : ndarray Output array of ints. Returns -1 if `sub` is not found. See Also -------- find, str.find Examples -------- >>> a = np.array(["Computer Science"]) >>> np.char.index(a, "Science", start=0, end=None) array([9]) Here is the function: def index(a, sub, start=0, end=None): """ Like `find`, but raises `ValueError` when the substring is not found. Calls `str.index` element-wise. Parameters ---------- a : array_like of str or unicode sub : str or unicode start, end : int, optional Returns ------- out : ndarray Output array of ints. Returns -1 if `sub` is not found. See Also -------- find, str.find Examples -------- >>> a = np.array(["Computer Science"]) >>> np.char.index(a, "Science", start=0, end=None) array([9]) """ return _vec_string( a, int_, 'index', [sub, start] + _clean_args(end))
Like `find`, but raises `ValueError` when the substring is not found. Calls `str.index` element-wise. Parameters ---------- a : array_like of str or unicode sub : str or unicode start, end : int, optional Returns ------- out : ndarray Output array of ints. Returns -1 if `sub` is not found. See Also -------- find, str.find Examples -------- >>> a = np.array(["Computer Science"]) >>> np.char.index(a, "Science", start=0, end=None) array([9])
169,219
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy The provided code snippet includes necessary dependencies for implementing the `isalnum` function. Write a Python function `def isalnum(a)` to solve the following problem: Returns true for each element if all characters in the string are alphanumeric and there is at least one character, false otherwise. Calls `str.isalnum` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.isalnum Here is the function: def isalnum(a): """ Returns true for each element if all characters in the string are alphanumeric and there is at least one character, false otherwise. Calls `str.isalnum` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.isalnum """ return _vec_string(a, bool_, 'isalnum')
Returns true for each element if all characters in the string are alphanumeric and there is at least one character, false otherwise. Calls `str.isalnum` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.isalnum
169,220
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy The provided code snippet includes necessary dependencies for implementing the `isalpha` function. Write a Python function `def isalpha(a)` to solve the following problem: Returns true for each element if all characters in the string are alphabetic and there is at least one character, false otherwise. Calls `str.isalpha` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.isalpha Here is the function: def isalpha(a): """ Returns true for each element if all characters in the string are alphabetic and there is at least one character, false otherwise. Calls `str.isalpha` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.isalpha """ return _vec_string(a, bool_, 'isalpha')
Returns true for each element if all characters in the string are alphabetic and there is at least one character, false otherwise. Calls `str.isalpha` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.isalpha
169,221
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy The provided code snippet includes necessary dependencies for implementing the `isdigit` function. Write a Python function `def isdigit(a)` to solve the following problem: Returns true for each element if all characters in the string are digits and there is at least one character, false otherwise. Calls `str.isdigit` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.isdigit Examples -------- >>> a = np.array(['a', 'b', '0']) >>> np.char.isdigit(a) array([False, False, True]) >>> a = np.array([['a', 'b', '0'], ['c', '1', '2']]) >>> np.char.isdigit(a) array([[False, False, True], [False, True, True]]) Here is the function: def isdigit(a): """ Returns true for each element if all characters in the string are digits and there is at least one character, false otherwise. Calls `str.isdigit` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.isdigit Examples -------- >>> a = np.array(['a', 'b', '0']) >>> np.char.isdigit(a) array([False, False, True]) >>> a = np.array([['a', 'b', '0'], ['c', '1', '2']]) >>> np.char.isdigit(a) array([[False, False, True], [False, True, True]]) """ return _vec_string(a, bool_, 'isdigit')
Returns true for each element if all characters in the string are digits and there is at least one character, false otherwise. Calls `str.isdigit` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.isdigit Examples -------- >>> a = np.array(['a', 'b', '0']) >>> np.char.isdigit(a) array([False, False, True]) >>> a = np.array([['a', 'b', '0'], ['c', '1', '2']]) >>> np.char.isdigit(a) array([[False, False, True], [False, True, True]])
169,222
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy The provided code snippet includes necessary dependencies for implementing the `islower` function. Write a Python function `def islower(a)` to solve the following problem: Returns true for each element if all cased characters in the string are lowercase and there is at least one cased character, false otherwise. Calls `str.islower` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.islower Here is the function: def islower(a): """ Returns true for each element if all cased characters in the string are lowercase and there is at least one cased character, false otherwise. Calls `str.islower` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.islower """ return _vec_string(a, bool_, 'islower')
Returns true for each element if all cased characters in the string are lowercase and there is at least one cased character, false otherwise. Calls `str.islower` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.islower
169,223
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy The provided code snippet includes necessary dependencies for implementing the `isspace` function. Write a Python function `def isspace(a)` to solve the following problem: Returns true for each element if there are only whitespace characters in the string and there is at least one character, false otherwise. Calls `str.isspace` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.isspace Here is the function: def isspace(a): """ Returns true for each element if there are only whitespace characters in the string and there is at least one character, false otherwise. Calls `str.isspace` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.isspace """ return _vec_string(a, bool_, 'isspace')
Returns true for each element if there are only whitespace characters in the string and there is at least one character, false otherwise. Calls `str.isspace` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.isspace
169,224
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy The provided code snippet includes necessary dependencies for implementing the `istitle` function. Write a Python function `def istitle(a)` to solve the following problem: Returns true for each element if the element is a titlecased string and there is at least one character, false otherwise. Call `str.istitle` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.istitle Here is the function: def istitle(a): """ Returns true for each element if the element is a titlecased string and there is at least one character, false otherwise. Call `str.istitle` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.istitle """ return _vec_string(a, bool_, 'istitle')
Returns true for each element if the element is a titlecased string and there is at least one character, false otherwise. Call `str.istitle` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.istitle
169,225
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy The provided code snippet includes necessary dependencies for implementing the `isupper` function. Write a Python function `def isupper(a)` to solve the following problem: Return true for each element if all cased characters in the string are uppercase and there is at least one character, false otherwise. Call `str.isupper` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.isupper Examples -------- >>> str = "GHC" >>> np.char.isupper(str) array(True) >>> a = np.array(["hello", "HELLO", "Hello"]) >>> np.char.isupper(a) array([False, True, False]) Here is the function: def isupper(a): """ Return true for each element if all cased characters in the string are uppercase and there is at least one character, false otherwise. Call `str.isupper` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.isupper Examples -------- >>> str = "GHC" >>> np.char.isupper(str) array(True) >>> a = np.array(["hello", "HELLO", "Hello"]) >>> np.char.isupper(a) array([False, True, False]) """ return _vec_string(a, bool_, 'isupper')
Return true for each element if all cased characters in the string are uppercase and there is at least one character, false otherwise. Call `str.isupper` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See Also -------- str.isupper Examples -------- >>> str = "GHC" >>> np.char.isupper(str) array(True) >>> a = np.array(["hello", "HELLO", "Hello"]) >>> np.char.isupper(a) array([False, True, False])
169,226
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _join_dispatcher(sep, seq): return (sep, seq)
null
169,227
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _to_string_or_unicode_array(result): """ Helper function to cast a result back into a string or unicode array if an object array must be used as an intermediary. """ return numpy.asarray(result.tolist()) The provided code snippet includes necessary dependencies for implementing the `join` function. Write a Python function `def join(sep, seq)` to solve the following problem: Return a string which is the concatenation of the strings in the sequence `seq`. Calls `str.join` element-wise. Parameters ---------- sep : array_like of str or unicode seq : array_like of str or unicode Returns ------- out : ndarray Output array of str or unicode, depending on input types See Also -------- str.join Examples -------- >>> np.char.join('-', 'osd') array('o-s-d', dtype='<U5') >>> np.char.join(['-', '.'], ['ghc', 'osd']) array(['g-h-c', 'o.s.d'], dtype='<U5') Here is the function: def join(sep, seq): """ Return a string which is the concatenation of the strings in the sequence `seq`. Calls `str.join` element-wise. Parameters ---------- sep : array_like of str or unicode seq : array_like of str or unicode Returns ------- out : ndarray Output array of str or unicode, depending on input types See Also -------- str.join Examples -------- >>> np.char.join('-', 'osd') array('o-s-d', dtype='<U5') >>> np.char.join(['-', '.'], ['ghc', 'osd']) array(['g-h-c', 'o.s.d'], dtype='<U5') """ return _to_string_or_unicode_array( _vec_string(sep, object_, 'join', (seq,)))
Return a string which is the concatenation of the strings in the sequence `seq`. Calls `str.join` element-wise. Parameters ---------- sep : array_like of str or unicode seq : array_like of str or unicode Returns ------- out : ndarray Output array of str or unicode, depending on input types See Also -------- str.join Examples -------- >>> np.char.join('-', 'osd') array('o-s-d', dtype='<U5') >>> np.char.join(['-', '.'], ['ghc', 'osd']) array(['g-h-c', 'o.s.d'], dtype='<U5')
169,228
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _just_dispatcher(a, width, fillchar=None): return (a,)
null
169,229
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def asarray(obj, itemsize=None, unicode=None, order=None): """ Convert the input to a `chararray`, copying the data only if necessary. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). """ return array(obj, itemsize, copy=False, unicode=unicode, order=order) The provided code snippet includes necessary dependencies for implementing the `ljust` function. Write a Python function `def ljust(a, width, fillchar=' ')` to solve the following problem: Return an array with the elements of `a` left-justified in a string of length `width`. Calls `str.ljust` element-wise. Parameters ---------- a : array_like of str or unicode width : int The length of the resulting strings fillchar : str or unicode, optional The character to use for padding Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.ljust Here is the function: def ljust(a, width, fillchar=' '): """ Return an array with the elements of `a` left-justified in a string of length `width`. Calls `str.ljust` element-wise. Parameters ---------- a : array_like of str or unicode width : int The length of the resulting strings fillchar : str or unicode, optional The character to use for padding Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.ljust """ a_arr = numpy.asarray(a) width_arr = numpy.asarray(width) size = int(numpy.max(width_arr.flat)) if numpy.issubdtype(a_arr.dtype, numpy.string_): fillchar = asbytes(fillchar) return _vec_string( a_arr, (a_arr.dtype.type, size), 'ljust', (width_arr, fillchar))
Return an array with the elements of `a` left-justified in a string of length `width`. Calls `str.ljust` element-wise. Parameters ---------- a : array_like of str or unicode width : int The length of the resulting strings fillchar : str or unicode, optional The character to use for padding Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.ljust
169,230
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def asarray(obj, itemsize=None, unicode=None, order=None): """ Convert the input to a `chararray`, copying the data only if necessary. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). """ return array(obj, itemsize, copy=False, unicode=unicode, order=order) The provided code snippet includes necessary dependencies for implementing the `lower` function. Write a Python function `def lower(a)` to solve the following problem: Return an array with the elements converted to lowercase. Call `str.lower` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like, {str, unicode} Input array. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See Also -------- str.lower Examples -------- >>> c = np.array(['A1B C', '1BCA', 'BCA1']); c array(['A1B C', '1BCA', 'BCA1'], dtype='<U5') >>> np.char.lower(c) array(['a1b c', '1bca', 'bca1'], dtype='<U5') Here is the function: def lower(a): """ Return an array with the elements converted to lowercase. Call `str.lower` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like, {str, unicode} Input array. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See Also -------- str.lower Examples -------- >>> c = np.array(['A1B C', '1BCA', 'BCA1']); c array(['A1B C', '1BCA', 'BCA1'], dtype='<U5') >>> np.char.lower(c) array(['a1b c', '1bca', 'bca1'], dtype='<U5') """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'lower')
Return an array with the elements converted to lowercase. Call `str.lower` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like, {str, unicode} Input array. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See Also -------- str.lower Examples -------- >>> c = np.array(['A1B C', '1BCA', 'BCA1']); c array(['A1B C', '1BCA', 'BCA1'], dtype='<U5') >>> np.char.lower(c) array(['a1b c', '1bca', 'bca1'], dtype='<U5')
169,231
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def asarray(obj, itemsize=None, unicode=None, order=None): """ Convert the input to a `chararray`, copying the data only if necessary. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). """ return array(obj, itemsize, copy=False, unicode=unicode, order=order) The provided code snippet includes necessary dependencies for implementing the `lstrip` function. Write a Python function `def lstrip(a, chars=None)` to solve the following problem: For each element in `a`, return a copy with the leading characters removed. Calls `str.lstrip` element-wise. Parameters ---------- a : array-like, {str, unicode} Input array. chars : {str, unicode}, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` argument defaults to removing whitespace. The `chars` argument is not a prefix; rather, all combinations of its values are stripped. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See Also -------- str.lstrip Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') The 'a' variable is unstripped from c[1] because whitespace leading. >>> np.char.lstrip(c, 'a') array(['AaAaA', ' aA ', 'bBABba'], dtype='<U7') >>> np.char.lstrip(c, 'A') # leaves c unchanged array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, '')).all() ... # XXX: is this a regression? This used to return True ... # np.char.lstrip(c,'') does not modify c at all. False >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, None)).all() True Here is the function: def lstrip(a, chars=None): """ For each element in `a`, return a copy with the leading characters removed. Calls `str.lstrip` element-wise. Parameters ---------- a : array-like, {str, unicode} Input array. chars : {str, unicode}, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` argument defaults to removing whitespace. The `chars` argument is not a prefix; rather, all combinations of its values are stripped. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See Also -------- str.lstrip Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') The 'a' variable is unstripped from c[1] because whitespace leading. >>> np.char.lstrip(c, 'a') array(['AaAaA', ' aA ', 'bBABba'], dtype='<U7') >>> np.char.lstrip(c, 'A') # leaves c unchanged array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, '')).all() ... # XXX: is this a regression? This used to return True ... # np.char.lstrip(c,'') does not modify c at all. False >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, None)).all() True """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'lstrip', (chars,))
For each element in `a`, return a copy with the leading characters removed. Calls `str.lstrip` element-wise. Parameters ---------- a : array-like, {str, unicode} Input array. chars : {str, unicode}, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` argument defaults to removing whitespace. The `chars` argument is not a prefix; rather, all combinations of its values are stripped. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See Also -------- str.lstrip Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') The 'a' variable is unstripped from c[1] because whitespace leading. >>> np.char.lstrip(c, 'a') array(['AaAaA', ' aA ', 'bBABba'], dtype='<U7') >>> np.char.lstrip(c, 'A') # leaves c unchanged array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, '')).all() ... # XXX: is this a regression? This used to return True ... # np.char.lstrip(c,'') does not modify c at all. False >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, None)).all() True
169,232
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _partition_dispatcher(a, sep): return (a,)
null
169,233
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _to_string_or_unicode_array(result): """ Helper function to cast a result back into a string or unicode array if an object array must be used as an intermediary. """ return numpy.asarray(result.tolist()) The provided code snippet includes necessary dependencies for implementing the `partition` function. Write a Python function `def partition(a, sep)` to solve the following problem: Partition each element in `a` around `sep`. Calls `str.partition` element-wise. For each element in `a`, split the element as the first occurrence of `sep`, and return 3 strings containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return 3 strings containing the string itself, followed by two empty strings. Parameters ---------- a : array_like, {str, unicode} Input array sep : {str, unicode} Separator to split each string element in `a`. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type. The output array will have an extra dimension with 3 elements per input element. See Also -------- str.partition Here is the function: def partition(a, sep): """ Partition each element in `a` around `sep`. Calls `str.partition` element-wise. For each element in `a`, split the element as the first occurrence of `sep`, and return 3 strings containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return 3 strings containing the string itself, followed by two empty strings. Parameters ---------- a : array_like, {str, unicode} Input array sep : {str, unicode} Separator to split each string element in `a`. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type. The output array will have an extra dimension with 3 elements per input element. See Also -------- str.partition """ return _to_string_or_unicode_array( _vec_string(a, object_, 'partition', (sep,)))
Partition each element in `a` around `sep`. Calls `str.partition` element-wise. For each element in `a`, split the element as the first occurrence of `sep`, and return 3 strings containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return 3 strings containing the string itself, followed by two empty strings. Parameters ---------- a : array_like, {str, unicode} Input array sep : {str, unicode} Separator to split each string element in `a`. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type. The output array will have an extra dimension with 3 elements per input element. See Also -------- str.partition
169,234
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _replace_dispatcher(a, old, new, count=None): return (a,)
null
169,235
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _to_string_or_unicode_array(result): """ Helper function to cast a result back into a string or unicode array if an object array must be used as an intermediary. """ return numpy.asarray(result.tolist()) def _clean_args(*args): """ Helper function for delegating arguments to Python string functions. Many of the Python string operations that have optional arguments do not use 'None' to indicate a default value. In these cases, we need to remove all None arguments, and those following them. """ newargs = [] for chk in args: if chk is None: break newargs.append(chk) return newargs The provided code snippet includes necessary dependencies for implementing the `replace` function. Write a Python function `def replace(a, old, new, count=None)` to solve the following problem: For each element in `a`, return a copy of the string with all occurrences of substring `old` replaced by `new`. Calls `str.replace` element-wise. Parameters ---------- a : array-like of str or unicode old, new : str or unicode count : int, optional If the optional argument `count` is given, only the first `count` occurrences are replaced. Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.replace Examples -------- >>> a = np.array(["That is a mango", "Monkeys eat mangos"]) >>> np.char.replace(a, 'mango', 'banana') array(['That is a banana', 'Monkeys eat bananas'], dtype='<U19') >>> a = np.array(["The dish is fresh", "This is it"]) >>> np.char.replace(a, 'is', 'was') array(['The dwash was fresh', 'Thwas was it'], dtype='<U19') Here is the function: def replace(a, old, new, count=None): """ For each element in `a`, return a copy of the string with all occurrences of substring `old` replaced by `new`. Calls `str.replace` element-wise. Parameters ---------- a : array-like of str or unicode old, new : str or unicode count : int, optional If the optional argument `count` is given, only the first `count` occurrences are replaced. Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.replace Examples -------- >>> a = np.array(["That is a mango", "Monkeys eat mangos"]) >>> np.char.replace(a, 'mango', 'banana') array(['That is a banana', 'Monkeys eat bananas'], dtype='<U19') >>> a = np.array(["The dish is fresh", "This is it"]) >>> np.char.replace(a, 'is', 'was') array(['The dwash was fresh', 'Thwas was it'], dtype='<U19') """ return _to_string_or_unicode_array( _vec_string( a, object_, 'replace', [old, new] + _clean_args(count)))
For each element in `a`, return a copy of the string with all occurrences of substring `old` replaced by `new`. Calls `str.replace` element-wise. Parameters ---------- a : array-like of str or unicode old, new : str or unicode count : int, optional If the optional argument `count` is given, only the first `count` occurrences are replaced. Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.replace Examples -------- >>> a = np.array(["That is a mango", "Monkeys eat mangos"]) >>> np.char.replace(a, 'mango', 'banana') array(['That is a banana', 'Monkeys eat bananas'], dtype='<U19') >>> a = np.array(["The dish is fresh", "This is it"]) >>> np.char.replace(a, 'is', 'was') array(['The dwash was fresh', 'Thwas was it'], dtype='<U19')
169,236
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _clean_args(*args): """ Helper function for delegating arguments to Python string functions. Many of the Python string operations that have optional arguments do not use 'None' to indicate a default value. In these cases, we need to remove all None arguments, and those following them. """ newargs = [] for chk in args: if chk is None: break newargs.append(chk) return newargs The provided code snippet includes necessary dependencies for implementing the `rfind` function. Write a Python function `def rfind(a, sub, start=0, end=None)` to solve the following problem: For each element in `a`, return the highest index in the string where substring `sub` is found, such that `sub` is contained within [`start`, `end`]. Calls `str.rfind` element-wise. Parameters ---------- a : array-like of str or unicode sub : str or unicode start, end : int, optional Optional arguments `start` and `end` are interpreted as in slice notation. Returns ------- out : ndarray Output array of ints. Return -1 on failure. See Also -------- str.rfind Here is the function: def rfind(a, sub, start=0, end=None): """ For each element in `a`, return the highest index in the string where substring `sub` is found, such that `sub` is contained within [`start`, `end`]. Calls `str.rfind` element-wise. Parameters ---------- a : array-like of str or unicode sub : str or unicode start, end : int, optional Optional arguments `start` and `end` are interpreted as in slice notation. Returns ------- out : ndarray Output array of ints. Return -1 on failure. See Also -------- str.rfind """ return _vec_string( a, int_, 'rfind', [sub, start] + _clean_args(end))
For each element in `a`, return the highest index in the string where substring `sub` is found, such that `sub` is contained within [`start`, `end`]. Calls `str.rfind` element-wise. Parameters ---------- a : array-like of str or unicode sub : str or unicode start, end : int, optional Optional arguments `start` and `end` are interpreted as in slice notation. Returns ------- out : ndarray Output array of ints. Return -1 on failure. See Also -------- str.rfind
169,237
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _clean_args(*args): """ Helper function for delegating arguments to Python string functions. Many of the Python string operations that have optional arguments do not use 'None' to indicate a default value. In these cases, we need to remove all None arguments, and those following them. """ newargs = [] for chk in args: if chk is None: break newargs.append(chk) return newargs The provided code snippet includes necessary dependencies for implementing the `rindex` function. Write a Python function `def rindex(a, sub, start=0, end=None)` to solve the following problem: Like `rfind`, but raises `ValueError` when the substring `sub` is not found. Calls `str.rindex` element-wise. Parameters ---------- a : array-like of str or unicode sub : str or unicode start, end : int, optional Returns ------- out : ndarray Output array of ints. See Also -------- rfind, str.rindex Here is the function: def rindex(a, sub, start=0, end=None): """ Like `rfind`, but raises `ValueError` when the substring `sub` is not found. Calls `str.rindex` element-wise. Parameters ---------- a : array-like of str or unicode sub : str or unicode start, end : int, optional Returns ------- out : ndarray Output array of ints. See Also -------- rfind, str.rindex """ return _vec_string( a, int_, 'rindex', [sub, start] + _clean_args(end))
Like `rfind`, but raises `ValueError` when the substring `sub` is not found. Calls `str.rindex` element-wise. Parameters ---------- a : array-like of str or unicode sub : str or unicode start, end : int, optional Returns ------- out : ndarray Output array of ints. See Also -------- rfind, str.rindex
169,238
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def asarray(obj, itemsize=None, unicode=None, order=None): """ Convert the input to a `chararray`, copying the data only if necessary. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). """ return array(obj, itemsize, copy=False, unicode=unicode, order=order) The provided code snippet includes necessary dependencies for implementing the `rjust` function. Write a Python function `def rjust(a, width, fillchar=' ')` to solve the following problem: Return an array with the elements of `a` right-justified in a string of length `width`. Calls `str.rjust` element-wise. Parameters ---------- a : array_like of str or unicode width : int The length of the resulting strings fillchar : str or unicode, optional The character to use for padding Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.rjust Here is the function: def rjust(a, width, fillchar=' '): """ Return an array with the elements of `a` right-justified in a string of length `width`. Calls `str.rjust` element-wise. Parameters ---------- a : array_like of str or unicode width : int The length of the resulting strings fillchar : str or unicode, optional The character to use for padding Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.rjust """ a_arr = numpy.asarray(a) width_arr = numpy.asarray(width) size = int(numpy.max(width_arr.flat)) if numpy.issubdtype(a_arr.dtype, numpy.string_): fillchar = asbytes(fillchar) return _vec_string( a_arr, (a_arr.dtype.type, size), 'rjust', (width_arr, fillchar))
Return an array with the elements of `a` right-justified in a string of length `width`. Calls `str.rjust` element-wise. Parameters ---------- a : array_like of str or unicode width : int The length of the resulting strings fillchar : str or unicode, optional The character to use for padding Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.rjust
169,239
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _to_string_or_unicode_array(result): """ Helper function to cast a result back into a string or unicode array if an object array must be used as an intermediary. """ return numpy.asarray(result.tolist()) The provided code snippet includes necessary dependencies for implementing the `rpartition` function. Write a Python function `def rpartition(a, sep)` to solve the following problem: Partition (split) each element around the right-most separator. Calls `str.rpartition` element-wise. For each element in `a`, split the element as the last occurrence of `sep`, and return 3 strings containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return 3 strings containing the string itself, followed by two empty strings. Parameters ---------- a : array_like of str or unicode Input array sep : str or unicode Right-most separator to split each element in array. Returns ------- out : ndarray Output array of string or unicode, depending on input type. The output array will have an extra dimension with 3 elements per input element. See Also -------- str.rpartition Here is the function: def rpartition(a, sep): """ Partition (split) each element around the right-most separator. Calls `str.rpartition` element-wise. For each element in `a`, split the element as the last occurrence of `sep`, and return 3 strings containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return 3 strings containing the string itself, followed by two empty strings. Parameters ---------- a : array_like of str or unicode Input array sep : str or unicode Right-most separator to split each element in array. Returns ------- out : ndarray Output array of string or unicode, depending on input type. The output array will have an extra dimension with 3 elements per input element. See Also -------- str.rpartition """ return _to_string_or_unicode_array( _vec_string(a, object_, 'rpartition', (sep,)))
Partition (split) each element around the right-most separator. Calls `str.rpartition` element-wise. For each element in `a`, split the element as the last occurrence of `sep`, and return 3 strings containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return 3 strings containing the string itself, followed by two empty strings. Parameters ---------- a : array_like of str or unicode Input array sep : str or unicode Right-most separator to split each element in array. Returns ------- out : ndarray Output array of string or unicode, depending on input type. The output array will have an extra dimension with 3 elements per input element. See Also -------- str.rpartition
169,240
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _split_dispatcher(a, sep=None, maxsplit=None): return (a,)
null
169,241
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _clean_args(*args): """ Helper function for delegating arguments to Python string functions. Many of the Python string operations that have optional arguments do not use 'None' to indicate a default value. In these cases, we need to remove all None arguments, and those following them. """ newargs = [] for chk in args: if chk is None: break newargs.append(chk) return newargs The provided code snippet includes necessary dependencies for implementing the `rsplit` function. Write a Python function `def rsplit(a, sep=None, maxsplit=None)` to solve the following problem: For each element in `a`, return a list of the words in the string, using `sep` as the delimiter string. Calls `str.rsplit` element-wise. Except for splitting from the right, `rsplit` behaves like `split`. Parameters ---------- a : array_like of str or unicode sep : str or unicode, optional If `sep` is not specified or None, any whitespace string is a separator. maxsplit : int, optional If `maxsplit` is given, at most `maxsplit` splits are done, the rightmost ones. Returns ------- out : ndarray Array of list objects See Also -------- str.rsplit, split Here is the function: def rsplit(a, sep=None, maxsplit=None): """ For each element in `a`, return a list of the words in the string, using `sep` as the delimiter string. Calls `str.rsplit` element-wise. Except for splitting from the right, `rsplit` behaves like `split`. Parameters ---------- a : array_like of str or unicode sep : str or unicode, optional If `sep` is not specified or None, any whitespace string is a separator. maxsplit : int, optional If `maxsplit` is given, at most `maxsplit` splits are done, the rightmost ones. Returns ------- out : ndarray Array of list objects See Also -------- str.rsplit, split """ # This will return an array of lists of different sizes, so we # leave it as an object array return _vec_string( a, object_, 'rsplit', [sep] + _clean_args(maxsplit))
For each element in `a`, return a list of the words in the string, using `sep` as the delimiter string. Calls `str.rsplit` element-wise. Except for splitting from the right, `rsplit` behaves like `split`. Parameters ---------- a : array_like of str or unicode sep : str or unicode, optional If `sep` is not specified or None, any whitespace string is a separator. maxsplit : int, optional If `maxsplit` is given, at most `maxsplit` splits are done, the rightmost ones. Returns ------- out : ndarray Array of list objects See Also -------- str.rsplit, split
169,242
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def asarray(obj, itemsize=None, unicode=None, order=None): """ Convert the input to a `chararray`, copying the data only if necessary. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). """ return array(obj, itemsize, copy=False, unicode=unicode, order=order) The provided code snippet includes necessary dependencies for implementing the `rstrip` function. Write a Python function `def rstrip(a, chars=None)` to solve the following problem: For each element in `a`, return a copy with the trailing characters removed. Calls `str.rstrip` element-wise. Parameters ---------- a : array-like of str or unicode chars : str or unicode, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` argument defaults to removing whitespace. The `chars` argument is not a suffix; rather, all combinations of its values are stripped. Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.rstrip Examples -------- >>> c = np.array(['aAaAaA', 'abBABba'], dtype='S7'); c array(['aAaAaA', 'abBABba'], dtype='|S7') >>> np.char.rstrip(c, b'a') array(['aAaAaA', 'abBABb'], dtype='|S7') >>> np.char.rstrip(c, b'A') array(['aAaAa', 'abBABba'], dtype='|S7') Here is the function: def rstrip(a, chars=None): """ For each element in `a`, return a copy with the trailing characters removed. Calls `str.rstrip` element-wise. Parameters ---------- a : array-like of str or unicode chars : str or unicode, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` argument defaults to removing whitespace. The `chars` argument is not a suffix; rather, all combinations of its values are stripped. Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.rstrip Examples -------- >>> c = np.array(['aAaAaA', 'abBABba'], dtype='S7'); c array(['aAaAaA', 'abBABba'], dtype='|S7') >>> np.char.rstrip(c, b'a') array(['aAaAaA', 'abBABb'], dtype='|S7') >>> np.char.rstrip(c, b'A') array(['aAaAa', 'abBABba'], dtype='|S7') """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'rstrip', (chars,))
For each element in `a`, return a copy with the trailing characters removed. Calls `str.rstrip` element-wise. Parameters ---------- a : array-like of str or unicode chars : str or unicode, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` argument defaults to removing whitespace. The `chars` argument is not a suffix; rather, all combinations of its values are stripped. Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.rstrip Examples -------- >>> c = np.array(['aAaAaA', 'abBABba'], dtype='S7'); c array(['aAaAaA', 'abBABba'], dtype='|S7') >>> np.char.rstrip(c, b'a') array(['aAaAaA', 'abBABb'], dtype='|S7') >>> np.char.rstrip(c, b'A') array(['aAaAa', 'abBABba'], dtype='|S7')
169,243
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _clean_args(*args): """ Helper function for delegating arguments to Python string functions. Many of the Python string operations that have optional arguments do not use 'None' to indicate a default value. In these cases, we need to remove all None arguments, and those following them. """ newargs = [] for chk in args: if chk is None: break newargs.append(chk) return newargs The provided code snippet includes necessary dependencies for implementing the `split` function. Write a Python function `def split(a, sep=None, maxsplit=None)` to solve the following problem: For each element in `a`, return a list of the words in the string, using `sep` as the delimiter string. Calls `str.split` element-wise. Parameters ---------- a : array_like of str or unicode sep : str or unicode, optional If `sep` is not specified or None, any whitespace string is a separator. maxsplit : int, optional If `maxsplit` is given, at most `maxsplit` splits are done. Returns ------- out : ndarray Array of list objects See Also -------- str.split, rsplit Here is the function: def split(a, sep=None, maxsplit=None): """ For each element in `a`, return a list of the words in the string, using `sep` as the delimiter string. Calls `str.split` element-wise. Parameters ---------- a : array_like of str or unicode sep : str or unicode, optional If `sep` is not specified or None, any whitespace string is a separator. maxsplit : int, optional If `maxsplit` is given, at most `maxsplit` splits are done. Returns ------- out : ndarray Array of list objects See Also -------- str.split, rsplit """ # This will return an array of lists of different sizes, so we # leave it as an object array return _vec_string( a, object_, 'split', [sep] + _clean_args(maxsplit))
For each element in `a`, return a list of the words in the string, using `sep` as the delimiter string. Calls `str.split` element-wise. Parameters ---------- a : array_like of str or unicode sep : str or unicode, optional If `sep` is not specified or None, any whitespace string is a separator. maxsplit : int, optional If `maxsplit` is given, at most `maxsplit` splits are done. Returns ------- out : ndarray Array of list objects See Also -------- str.split, rsplit
169,244
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _splitlines_dispatcher(a, keepends=None): return (a,)
null
169,245
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _clean_args(*args): """ Helper function for delegating arguments to Python string functions. Many of the Python string operations that have optional arguments do not use 'None' to indicate a default value. In these cases, we need to remove all None arguments, and those following them. """ newargs = [] for chk in args: if chk is None: break newargs.append(chk) return newargs The provided code snippet includes necessary dependencies for implementing the `splitlines` function. Write a Python function `def splitlines(a, keepends=None)` to solve the following problem: For each element in `a`, return a list of the lines in the element, breaking at line boundaries. Calls `str.splitlines` element-wise. Parameters ---------- a : array_like of str or unicode keepends : bool, optional Line breaks are not included in the resulting list unless keepends is given and true. Returns ------- out : ndarray Array of list objects See Also -------- str.splitlines Here is the function: def splitlines(a, keepends=None): """ For each element in `a`, return a list of the lines in the element, breaking at line boundaries. Calls `str.splitlines` element-wise. Parameters ---------- a : array_like of str or unicode keepends : bool, optional Line breaks are not included in the resulting list unless keepends is given and true. Returns ------- out : ndarray Array of list objects See Also -------- str.splitlines """ return _vec_string( a, object_, 'splitlines', _clean_args(keepends))
For each element in `a`, return a list of the lines in the element, breaking at line boundaries. Calls `str.splitlines` element-wise. Parameters ---------- a : array_like of str or unicode keepends : bool, optional Line breaks are not included in the resulting list unless keepends is given and true. Returns ------- out : ndarray Array of list objects See Also -------- str.splitlines
169,246
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _startswith_dispatcher(a, prefix, start=None, end=None): return (a,)
null
169,247
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _clean_args(*args): """ Helper function for delegating arguments to Python string functions. Many of the Python string operations that have optional arguments do not use 'None' to indicate a default value. In these cases, we need to remove all None arguments, and those following them. """ newargs = [] for chk in args: if chk is None: break newargs.append(chk) return newargs The provided code snippet includes necessary dependencies for implementing the `startswith` function. Write a Python function `def startswith(a, prefix, start=0, end=None)` to solve the following problem: Returns a boolean array which is `True` where the string element in `a` starts with `prefix`, otherwise `False`. Calls `str.startswith` element-wise. Parameters ---------- a : array_like of str or unicode prefix : str start, end : int, optional With optional `start`, test beginning at that position. With optional `end`, stop comparing at that position. Returns ------- out : ndarray Array of booleans See Also -------- str.startswith Here is the function: def startswith(a, prefix, start=0, end=None): """ Returns a boolean array which is `True` where the string element in `a` starts with `prefix`, otherwise `False`. Calls `str.startswith` element-wise. Parameters ---------- a : array_like of str or unicode prefix : str start, end : int, optional With optional `start`, test beginning at that position. With optional `end`, stop comparing at that position. Returns ------- out : ndarray Array of booleans See Also -------- str.startswith """ return _vec_string( a, bool_, 'startswith', [prefix, start] + _clean_args(end))
Returns a boolean array which is `True` where the string element in `a` starts with `prefix`, otherwise `False`. Calls `str.startswith` element-wise. Parameters ---------- a : array_like of str or unicode prefix : str start, end : int, optional With optional `start`, test beginning at that position. With optional `end`, stop comparing at that position. Returns ------- out : ndarray Array of booleans See Also -------- str.startswith
169,248
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _clean_args(*args): """ Helper function for delegating arguments to Python string functions. Many of the Python string operations that have optional arguments do not use 'None' to indicate a default value. In these cases, we need to remove all None arguments, and those following them. """ newargs = [] for chk in args: if chk is None: break newargs.append(chk) return newargs def asarray(obj, itemsize=None, unicode=None, order=None): """ Convert the input to a `chararray`, copying the data only if necessary. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). """ return array(obj, itemsize, copy=False, unicode=unicode, order=order) The provided code snippet includes necessary dependencies for implementing the `strip` function. Write a Python function `def strip(a, chars=None)` to solve the following problem: For each element in `a`, return a copy with the leading and trailing characters removed. Calls `str.strip` element-wise. Parameters ---------- a : array-like of str or unicode chars : str or unicode, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` argument defaults to removing whitespace. The `chars` argument is not a prefix or suffix; rather, all combinations of its values are stripped. Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.strip Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') >>> np.char.strip(c) array(['aAaAaA', 'aA', 'abBABba'], dtype='<U7') >>> np.char.strip(c, 'a') # 'a' unstripped from c[1] because whitespace leads array(['AaAaA', ' aA ', 'bBABb'], dtype='<U7') >>> np.char.strip(c, 'A') # 'A' unstripped from c[1] because (unprinted) ws trails array(['aAaAa', ' aA ', 'abBABba'], dtype='<U7') Here is the function: def strip(a, chars=None): """ For each element in `a`, return a copy with the leading and trailing characters removed. Calls `str.strip` element-wise. Parameters ---------- a : array-like of str or unicode chars : str or unicode, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` argument defaults to removing whitespace. The `chars` argument is not a prefix or suffix; rather, all combinations of its values are stripped. Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.strip Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') >>> np.char.strip(c) array(['aAaAaA', 'aA', 'abBABba'], dtype='<U7') >>> np.char.strip(c, 'a') # 'a' unstripped from c[1] because whitespace leads array(['AaAaA', ' aA ', 'bBABb'], dtype='<U7') >>> np.char.strip(c, 'A') # 'A' unstripped from c[1] because (unprinted) ws trails array(['aAaAa', ' aA ', 'abBABba'], dtype='<U7') """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'strip', _clean_args(chars))
For each element in `a`, return a copy with the leading and trailing characters removed. Calls `str.strip` element-wise. Parameters ---------- a : array-like of str or unicode chars : str or unicode, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` argument defaults to removing whitespace. The `chars` argument is not a prefix or suffix; rather, all combinations of its values are stripped. Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.strip Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7') >>> np.char.strip(c) array(['aAaAaA', 'aA', 'abBABba'], dtype='<U7') >>> np.char.strip(c, 'a') # 'a' unstripped from c[1] because whitespace leads array(['AaAaA', ' aA ', 'bBABb'], dtype='<U7') >>> np.char.strip(c, 'A') # 'A' unstripped from c[1] because (unprinted) ws trails array(['aAaAa', ' aA ', 'abBABba'], dtype='<U7')
169,249
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def asarray(obj, itemsize=None, unicode=None, order=None): """ Convert the input to a `chararray`, copying the data only if necessary. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). """ return array(obj, itemsize, copy=False, unicode=unicode, order=order) The provided code snippet includes necessary dependencies for implementing the `swapcase` function. Write a Python function `def swapcase(a)` to solve the following problem: Return element-wise a copy of the string with uppercase characters converted to lowercase and vice versa. Calls `str.swapcase` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like, {str, unicode} Input array. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See Also -------- str.swapcase Examples -------- >>> c=np.array(['a1B c','1b Ca','b Ca1','cA1b'],'S5'); c array(['a1B c', '1b Ca', 'b Ca1', 'cA1b'], dtype='|S5') >>> np.char.swapcase(c) array(['A1b C', '1B cA', 'B cA1', 'Ca1B'], dtype='|S5') Here is the function: def swapcase(a): """ Return element-wise a copy of the string with uppercase characters converted to lowercase and vice versa. Calls `str.swapcase` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like, {str, unicode} Input array. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See Also -------- str.swapcase Examples -------- >>> c=np.array(['a1B c','1b Ca','b Ca1','cA1b'],'S5'); c array(['a1B c', '1b Ca', 'b Ca1', 'cA1b'], dtype='|S5') >>> np.char.swapcase(c) array(['A1b C', '1B cA', 'B cA1', 'Ca1B'], dtype='|S5') """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'swapcase')
Return element-wise a copy of the string with uppercase characters converted to lowercase and vice versa. Calls `str.swapcase` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like, {str, unicode} Input array. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See Also -------- str.swapcase Examples -------- >>> c=np.array(['a1B c','1b Ca','b Ca1','cA1b'],'S5'); c array(['a1B c', '1b Ca', 'b Ca1', 'cA1b'], dtype='|S5') >>> np.char.swapcase(c) array(['A1b C', '1B cA', 'B cA1', 'Ca1B'], dtype='|S5')
169,250
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def asarray(obj, itemsize=None, unicode=None, order=None): """ Convert the input to a `chararray`, copying the data only if necessary. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). """ return array(obj, itemsize, copy=False, unicode=unicode, order=order) The provided code snippet includes necessary dependencies for implementing the `title` function. Write a Python function `def title(a)` to solve the following problem: Return element-wise title cased version of string or unicode. Title case words start with uppercase characters, all remaining cased characters are lowercase. Calls `str.title` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like, {str, unicode} Input array. Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.title Examples -------- >>> c=np.array(['a1b c','1b ca','b ca1','ca1b'],'S5'); c array(['a1b c', '1b ca', 'b ca1', 'ca1b'], dtype='|S5') >>> np.char.title(c) array(['A1B C', '1B Ca', 'B Ca1', 'Ca1B'], dtype='|S5') Here is the function: def title(a): """ Return element-wise title cased version of string or unicode. Title case words start with uppercase characters, all remaining cased characters are lowercase. Calls `str.title` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like, {str, unicode} Input array. Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.title Examples -------- >>> c=np.array(['a1b c','1b ca','b ca1','ca1b'],'S5'); c array(['a1b c', '1b ca', 'b ca1', 'ca1b'], dtype='|S5') >>> np.char.title(c) array(['A1B C', '1B Ca', 'B Ca1', 'Ca1B'], dtype='|S5') """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'title')
Return element-wise title cased version of string or unicode. Title case words start with uppercase characters, all remaining cased characters are lowercase. Calls `str.title` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like, {str, unicode} Input array. Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.title Examples -------- >>> c=np.array(['a1b c','1b ca','b ca1','ca1b'],'S5'); c array(['a1b c', '1b ca', 'b ca1', 'ca1b'], dtype='|S5') >>> np.char.title(c) array(['A1B C', '1B Ca', 'B Ca1', 'Ca1B'], dtype='|S5')
169,251
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _translate_dispatcher(a, table, deletechars=None): return (a,)
null
169,252
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _clean_args(*args): """ Helper function for delegating arguments to Python string functions. Many of the Python string operations that have optional arguments do not use 'None' to indicate a default value. In these cases, we need to remove all None arguments, and those following them. """ newargs = [] for chk in args: if chk is None: break newargs.append(chk) return newargs def asarray(obj, itemsize=None, unicode=None, order=None): """ Convert the input to a `chararray`, copying the data only if necessary. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). """ return array(obj, itemsize, copy=False, unicode=unicode, order=order) The provided code snippet includes necessary dependencies for implementing the `translate` function. Write a Python function `def translate(a, table, deletechars=None)` to solve the following problem: For each element in `a`, return a copy of the string where all characters occurring in the optional argument `deletechars` are removed, and the remaining characters have been mapped through the given translation table. Calls `str.translate` element-wise. Parameters ---------- a : array-like of str or unicode table : str of length 256 deletechars : str Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.translate Here is the function: def translate(a, table, deletechars=None): """ For each element in `a`, return a copy of the string where all characters occurring in the optional argument `deletechars` are removed, and the remaining characters have been mapped through the given translation table. Calls `str.translate` element-wise. Parameters ---------- a : array-like of str or unicode table : str of length 256 deletechars : str Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.translate """ a_arr = numpy.asarray(a) if issubclass(a_arr.dtype.type, unicode_): return _vec_string( a_arr, a_arr.dtype, 'translate', (table,)) else: return _vec_string( a_arr, a_arr.dtype, 'translate', [table] + _clean_args(deletechars))
For each element in `a`, return a copy of the string where all characters occurring in the optional argument `deletechars` are removed, and the remaining characters have been mapped through the given translation table. Calls `str.translate` element-wise. Parameters ---------- a : array-like of str or unicode table : str of length 256 deletechars : str Returns ------- out : ndarray Output array of str or unicode, depending on input type See Also -------- str.translate
169,253
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def asarray(obj, itemsize=None, unicode=None, order=None): """ Convert the input to a `chararray`, copying the data only if necessary. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). """ return array(obj, itemsize, copy=False, unicode=unicode, order=order) The provided code snippet includes necessary dependencies for implementing the `upper` function. Write a Python function `def upper(a)` to solve the following problem: Return an array with the elements converted to uppercase. Calls `str.upper` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like, {str, unicode} Input array. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See Also -------- str.upper Examples -------- >>> c = np.array(['a1b c', '1bca', 'bca1']); c array(['a1b c', '1bca', 'bca1'], dtype='<U5') >>> np.char.upper(c) array(['A1B C', '1BCA', 'BCA1'], dtype='<U5') Here is the function: def upper(a): """ Return an array with the elements converted to uppercase. Calls `str.upper` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like, {str, unicode} Input array. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See Also -------- str.upper Examples -------- >>> c = np.array(['a1b c', '1bca', 'bca1']); c array(['a1b c', '1bca', 'bca1'], dtype='<U5') >>> np.char.upper(c) array(['A1B C', '1BCA', 'BCA1'], dtype='<U5') """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'upper')
Return an array with the elements converted to uppercase. Calls `str.upper` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like, {str, unicode} Input array. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See Also -------- str.upper Examples -------- >>> c = np.array(['a1b c', '1bca', 'bca1']); c array(['a1b c', '1bca', 'bca1'], dtype='<U5') >>> np.char.upper(c) array(['A1B C', '1BCA', 'BCA1'], dtype='<U5')
169,254
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _zfill_dispatcher(a, width): return (a,)
null
169,255
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def asarray(obj, itemsize=None, unicode=None, order=None): """ Convert the input to a `chararray`, copying the data only if necessary. Versus a regular NumPy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is None and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). """ return array(obj, itemsize, copy=False, unicode=unicode, order=order) The provided code snippet includes necessary dependencies for implementing the `zfill` function. Write a Python function `def zfill(a, width)` to solve the following problem: Return the numeric string left-filled with zeros Calls `str.zfill` element-wise. Parameters ---------- a : array_like, {str, unicode} Input array. width : int Width of string to left-fill elements in `a`. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See Also -------- str.zfill Here is the function: def zfill(a, width): """ Return the numeric string left-filled with zeros Calls `str.zfill` element-wise. Parameters ---------- a : array_like, {str, unicode} Input array. width : int Width of string to left-fill elements in `a`. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See Also -------- str.zfill """ a_arr = numpy.asarray(a) width_arr = numpy.asarray(width) size = int(numpy.max(width_arr.flat)) return _vec_string( a_arr, (a_arr.dtype.type, size), 'zfill', (width_arr,))
Return the numeric string left-filled with zeros Calls `str.zfill` element-wise. Parameters ---------- a : array_like, {str, unicode} Input array. width : int Width of string to left-fill elements in `a`. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See Also -------- str.zfill
169,256
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _use_unicode(*args): """ Helper function for determining the output type of some string operations. For an operation on two ndarrays, if at least one is unicode, the result should be unicode. """ for x in args: if (isinstance(x, str) or issubclass(numpy.asarray(x).dtype.type, unicode_)): return unicode_ return string_ The provided code snippet includes necessary dependencies for implementing the `isnumeric` function. Write a Python function `def isnumeric(a)` to solve the following problem: For each element, return True if there are only numeric characters in the element. Calls `unicode.isnumeric` element-wise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. ``U+2155, VULGAR FRACTION ONE FIFTH``. Parameters ---------- a : array_like, unicode Input array. Returns ------- out : ndarray, bool Array of booleans of same shape as `a`. See Also -------- unicode.isnumeric Examples -------- >>> np.char.isnumeric(['123', '123abc', '9.0', '1/4', 'VIII']) array([ True, False, False, False, False]) Here is the function: def isnumeric(a): """ For each element, return True if there are only numeric characters in the element. Calls `unicode.isnumeric` element-wise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. ``U+2155, VULGAR FRACTION ONE FIFTH``. Parameters ---------- a : array_like, unicode Input array. Returns ------- out : ndarray, bool Array of booleans of same shape as `a`. See Also -------- unicode.isnumeric Examples -------- >>> np.char.isnumeric(['123', '123abc', '9.0', '1/4', 'VIII']) array([ True, False, False, False, False]) """ if _use_unicode(a) != unicode_: raise TypeError("isnumeric is only available for Unicode strings and arrays") return _vec_string(a, bool_, 'isnumeric')
For each element, return True if there are only numeric characters in the element. Calls `unicode.isnumeric` element-wise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. ``U+2155, VULGAR FRACTION ONE FIFTH``. Parameters ---------- a : array_like, unicode Input array. Returns ------- out : ndarray, bool Array of booleans of same shape as `a`. See Also -------- unicode.isnumeric Examples -------- >>> np.char.isnumeric(['123', '123abc', '9.0', '1/4', 'VIII']) array([ True, False, False, False, False])
169,257
import functools from .numerictypes import ( string_, unicode_, integer, int_, object_, bool_, character) from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.core.overrides import set_module from numpy.core import overrides from numpy.compat import asbytes import numpy def _use_unicode(*args): """ Helper function for determining the output type of some string operations. For an operation on two ndarrays, if at least one is unicode, the result should be unicode. """ for x in args: if (isinstance(x, str) or issubclass(numpy.asarray(x).dtype.type, unicode_)): return unicode_ return string_ The provided code snippet includes necessary dependencies for implementing the `isdecimal` function. Write a Python function `def isdecimal(a)` to solve the following problem: For each element, return True if there are only decimal characters in the element. Calls `unicode.isdecimal` element-wise. Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. ``U+0660, ARABIC-INDIC DIGIT ZERO``. Parameters ---------- a : array_like, unicode Input array. Returns ------- out : ndarray, bool Array of booleans identical in shape to `a`. See Also -------- unicode.isdecimal Examples -------- >>> np.char.isdecimal(['12345', '4.99', '123ABC', '']) array([ True, False, False, False]) Here is the function: def isdecimal(a): """ For each element, return True if there are only decimal characters in the element. Calls `unicode.isdecimal` element-wise. Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. ``U+0660, ARABIC-INDIC DIGIT ZERO``. Parameters ---------- a : array_like, unicode Input array. Returns ------- out : ndarray, bool Array of booleans identical in shape to `a`. See Also -------- unicode.isdecimal Examples -------- >>> np.char.isdecimal(['12345', '4.99', '123ABC', '']) array([ True, False, False, False]) """ if _use_unicode(a) != unicode_: raise TypeError("isnumeric is only available for Unicode strings and arrays") return _vec_string(a, bool_, 'isdecimal')
For each element, return True if there are only decimal characters in the element. Calls `unicode.isdecimal` element-wise. Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. ``U+0660, ARABIC-INDIC DIGIT ZERO``. Parameters ---------- a : array_like, unicode Input array. Returns ------- out : ndarray, bool Array of booleans identical in shape to `a`. See Also -------- unicode.isdecimal Examples -------- >>> np.char.isdecimal(['12345', '4.99', '123ABC', '']) array([ True, False, False, False])
169,258
import functools import types import warnings import numpy as np from . import multiarray as mu from . import overrides from . import umath as um from . import numerictypes as nt from .multiarray import asarray, array, asanyarray, concatenate from . import _methods def _take_dispatcher(a, indices, axis=None, out=None, mode=None): return (a, out)
null
169,259
import functools import types import warnings import numpy as np from . import multiarray as mu from . import overrides from . import umath as um from . import numerictypes as nt from .multiarray import asarray, array, asanyarray, concatenate from . import _methods def _reshape_dispatcher(a, newshape, order=None): return (a,)
null
169,260
import functools import types import warnings import numpy as np from . import multiarray as mu from . import overrides from . import umath as um from . import numerictypes as nt from .multiarray import asarray, array, asanyarray, concatenate from . import _methods def _choose_dispatcher(a, choices, out=None, mode=None): yield a yield from choices yield out
null
169,261
import functools import types import warnings import numpy as np from . import multiarray as mu from . import overrides from . import umath as um from . import numerictypes as nt from .multiarray import asarray, array, asanyarray, concatenate from . import _methods def _wrapfunc(obj, method, *args, **kwds): bound = getattr(obj, method, None) if bound is None: return _wrapit(obj, method, *args, **kwds) try: return bound(*args, **kwds) except TypeError: # A TypeError occurs if the object does have such a method in its # class, but its signature is not identical to that of NumPy's. This # situation has occurred in the case of a downstream library like # 'pandas'. # # Call _wrapit from within the except clause to ensure a potential # exception has a traceback chain. return _wrapit(obj, method, *args, **kwds) The provided code snippet includes necessary dependencies for implementing the `choose` function. Write a Python function `def choose(a, choices, out=None, mode='raise')` to solve the following problem: Construct an array from an index array and a list of arrays to choose from. First of all, if confused or uncertain, definitely look at the Examples - in its full generality, this function is less simple than it might seem from the following code description (below ndi = `numpy.lib.index_tricks`): ``np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])``. But this omits some subtleties. Here is a fully general summary: Given an "index" array (`a`) of integers and a sequence of ``n`` arrays (`choices`), `a` and each choice array are first broadcast, as necessary, to arrays of a common shape; calling these *Ba* and *Bchoices[i], i = 0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape`` for each ``i``. Then, a new array with shape ``Ba.shape`` is created as follows: * if ``mode='raise'`` (the default), then, first of all, each element of ``a`` (and thus ``Ba``) must be in the range ``[0, n-1]``; now, suppose that ``i`` (in that range) is the value at the ``(j0, j1, ..., jm)`` position in ``Ba`` - then the value at the same position in the new array is the value in ``Bchoices[i]`` at that same position; * if ``mode='wrap'``, values in `a` (and thus `Ba`) may be any (signed) integer; modular arithmetic is used to map integers outside the range `[0, n-1]` back into that range; and then the new array is constructed as above; * if ``mode='clip'``, values in `a` (and thus ``Ba``) may be any (signed) integer; negative integers are mapped to 0; values greater than ``n-1`` are mapped to ``n-1``; and then the new array is constructed as above. Parameters ---------- a : int array This array must contain integers in ``[0, n-1]``, where ``n`` is the number of choices, unless ``mode=wrap`` or ``mode=clip``, in which cases any integers are permissible. choices : sequence of arrays Choice arrays. `a` and all of the choices must be broadcastable to the same shape. If `choices` is itself an array (not recommended), then its outermost dimension (i.e., the one corresponding to ``choices.shape[0]``) is taken as defining the "sequence". out : array, optional If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype. Note that `out` is always buffered if ``mode='raise'``; use other modes for better performance. mode : {'raise' (default), 'wrap', 'clip'}, optional Specifies how indices outside ``[0, n-1]`` will be treated: * 'raise' : an exception is raised * 'wrap' : value becomes value mod ``n`` * 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1 Returns ------- merged_array : array The merged result. Raises ------ ValueError: shape mismatch If `a` and each choice array are not all broadcastable to the same shape. See Also -------- ndarray.choose : equivalent method numpy.take_along_axis : Preferable if `choices` is an array Notes ----- To reduce the chance of misinterpretation, even though the following "abuse" is nominally supported, `choices` should neither be, nor be thought of as, a single array, i.e., the outermost sequence-like container should be either a list or a tuple. Examples -------- >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13], ... [20, 21, 22, 23], [30, 31, 32, 33]] >>> np.choose([2, 3, 1, 0], choices ... # the first element of the result will be the first element of the ... # third (2+1) "array" in choices, namely, 20; the second element ... # will be the second element of the fourth (3+1) choice array, i.e., ... # 31, etc. ... ) array([20, 31, 12, 3]) >>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1) array([20, 31, 12, 3]) >>> # because there are 4 choice arrays >>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4) array([20, 1, 12, 3]) >>> # i.e., 0 A couple examples illustrating how choose broadcasts: >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]] >>> choices = [-10, 10] >>> np.choose(a, choices) array([[ 10, -10, 10], [-10, 10, -10], [ 10, -10, 10]]) >>> # With thanks to Anne Archibald >>> a = np.array([0, 1]).reshape((2,1,1)) >>> c1 = np.array([1, 2, 3]).reshape((1,3,1)) >>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5)) >>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2 array([[[ 1, 1, 1, 1, 1], [ 2, 2, 2, 2, 2], [ 3, 3, 3, 3, 3]], [[-1, -2, -3, -4, -5], [-1, -2, -3, -4, -5], [-1, -2, -3, -4, -5]]]) Here is the function: def choose(a, choices, out=None, mode='raise'): """ Construct an array from an index array and a list of arrays to choose from. First of all, if confused or uncertain, definitely look at the Examples - in its full generality, this function is less simple than it might seem from the following code description (below ndi = `numpy.lib.index_tricks`): ``np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])``. But this omits some subtleties. Here is a fully general summary: Given an "index" array (`a`) of integers and a sequence of ``n`` arrays (`choices`), `a` and each choice array are first broadcast, as necessary, to arrays of a common shape; calling these *Ba* and *Bchoices[i], i = 0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape`` for each ``i``. Then, a new array with shape ``Ba.shape`` is created as follows: * if ``mode='raise'`` (the default), then, first of all, each element of ``a`` (and thus ``Ba``) must be in the range ``[0, n-1]``; now, suppose that ``i`` (in that range) is the value at the ``(j0, j1, ..., jm)`` position in ``Ba`` - then the value at the same position in the new array is the value in ``Bchoices[i]`` at that same position; * if ``mode='wrap'``, values in `a` (and thus `Ba`) may be any (signed) integer; modular arithmetic is used to map integers outside the range `[0, n-1]` back into that range; and then the new array is constructed as above; * if ``mode='clip'``, values in `a` (and thus ``Ba``) may be any (signed) integer; negative integers are mapped to 0; values greater than ``n-1`` are mapped to ``n-1``; and then the new array is constructed as above. Parameters ---------- a : int array This array must contain integers in ``[0, n-1]``, where ``n`` is the number of choices, unless ``mode=wrap`` or ``mode=clip``, in which cases any integers are permissible. choices : sequence of arrays Choice arrays. `a` and all of the choices must be broadcastable to the same shape. If `choices` is itself an array (not recommended), then its outermost dimension (i.e., the one corresponding to ``choices.shape[0]``) is taken as defining the "sequence". out : array, optional If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype. Note that `out` is always buffered if ``mode='raise'``; use other modes for better performance. mode : {'raise' (default), 'wrap', 'clip'}, optional Specifies how indices outside ``[0, n-1]`` will be treated: * 'raise' : an exception is raised * 'wrap' : value becomes value mod ``n`` * 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1 Returns ------- merged_array : array The merged result. Raises ------ ValueError: shape mismatch If `a` and each choice array are not all broadcastable to the same shape. See Also -------- ndarray.choose : equivalent method numpy.take_along_axis : Preferable if `choices` is an array Notes ----- To reduce the chance of misinterpretation, even though the following "abuse" is nominally supported, `choices` should neither be, nor be thought of as, a single array, i.e., the outermost sequence-like container should be either a list or a tuple. Examples -------- >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13], ... [20, 21, 22, 23], [30, 31, 32, 33]] >>> np.choose([2, 3, 1, 0], choices ... # the first element of the result will be the first element of the ... # third (2+1) "array" in choices, namely, 20; the second element ... # will be the second element of the fourth (3+1) choice array, i.e., ... # 31, etc. ... ) array([20, 31, 12, 3]) >>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1) array([20, 31, 12, 3]) >>> # because there are 4 choice arrays >>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4) array([20, 1, 12, 3]) >>> # i.e., 0 A couple examples illustrating how choose broadcasts: >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]] >>> choices = [-10, 10] >>> np.choose(a, choices) array([[ 10, -10, 10], [-10, 10, -10], [ 10, -10, 10]]) >>> # With thanks to Anne Archibald >>> a = np.array([0, 1]).reshape((2,1,1)) >>> c1 = np.array([1, 2, 3]).reshape((1,3,1)) >>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5)) >>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2 array([[[ 1, 1, 1, 1, 1], [ 2, 2, 2, 2, 2], [ 3, 3, 3, 3, 3]], [[-1, -2, -3, -4, -5], [-1, -2, -3, -4, -5], [-1, -2, -3, -4, -5]]]) """ return _wrapfunc(a, 'choose', choices, out=out, mode=mode)
Construct an array from an index array and a list of arrays to choose from. First of all, if confused or uncertain, definitely look at the Examples - in its full generality, this function is less simple than it might seem from the following code description (below ndi = `numpy.lib.index_tricks`): ``np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])``. But this omits some subtleties. Here is a fully general summary: Given an "index" array (`a`) of integers and a sequence of ``n`` arrays (`choices`), `a` and each choice array are first broadcast, as necessary, to arrays of a common shape; calling these *Ba* and *Bchoices[i], i = 0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape`` for each ``i``. Then, a new array with shape ``Ba.shape`` is created as follows: * if ``mode='raise'`` (the default), then, first of all, each element of ``a`` (and thus ``Ba``) must be in the range ``[0, n-1]``; now, suppose that ``i`` (in that range) is the value at the ``(j0, j1, ..., jm)`` position in ``Ba`` - then the value at the same position in the new array is the value in ``Bchoices[i]`` at that same position; * if ``mode='wrap'``, values in `a` (and thus `Ba`) may be any (signed) integer; modular arithmetic is used to map integers outside the range `[0, n-1]` back into that range; and then the new array is constructed as above; * if ``mode='clip'``, values in `a` (and thus ``Ba``) may be any (signed) integer; negative integers are mapped to 0; values greater than ``n-1`` are mapped to ``n-1``; and then the new array is constructed as above. Parameters ---------- a : int array This array must contain integers in ``[0, n-1]``, where ``n`` is the number of choices, unless ``mode=wrap`` or ``mode=clip``, in which cases any integers are permissible. choices : sequence of arrays Choice arrays. `a` and all of the choices must be broadcastable to the same shape. If `choices` is itself an array (not recommended), then its outermost dimension (i.e., the one corresponding to ``choices.shape[0]``) is taken as defining the "sequence". out : array, optional If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype. Note that `out` is always buffered if ``mode='raise'``; use other modes for better performance. mode : {'raise' (default), 'wrap', 'clip'}, optional Specifies how indices outside ``[0, n-1]`` will be treated: * 'raise' : an exception is raised * 'wrap' : value becomes value mod ``n`` * 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1 Returns ------- merged_array : array The merged result. Raises ------ ValueError: shape mismatch If `a` and each choice array are not all broadcastable to the same shape. See Also -------- ndarray.choose : equivalent method numpy.take_along_axis : Preferable if `choices` is an array Notes ----- To reduce the chance of misinterpretation, even though the following "abuse" is nominally supported, `choices` should neither be, nor be thought of as, a single array, i.e., the outermost sequence-like container should be either a list or a tuple. Examples -------- >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13], ... [20, 21, 22, 23], [30, 31, 32, 33]] >>> np.choose([2, 3, 1, 0], choices ... # the first element of the result will be the first element of the ... # third (2+1) "array" in choices, namely, 20; the second element ... # will be the second element of the fourth (3+1) choice array, i.e., ... # 31, etc. ... ) array([20, 31, 12, 3]) >>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1) array([20, 31, 12, 3]) >>> # because there are 4 choice arrays >>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4) array([20, 1, 12, 3]) >>> # i.e., 0 A couple examples illustrating how choose broadcasts: >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]] >>> choices = [-10, 10] >>> np.choose(a, choices) array([[ 10, -10, 10], [-10, 10, -10], [ 10, -10, 10]]) >>> # With thanks to Anne Archibald >>> a = np.array([0, 1]).reshape((2,1,1)) >>> c1 = np.array([1, 2, 3]).reshape((1,3,1)) >>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5)) >>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2 array([[[ 1, 1, 1, 1, 1], [ 2, 2, 2, 2, 2], [ 3, 3, 3, 3, 3]], [[-1, -2, -3, -4, -5], [-1, -2, -3, -4, -5], [-1, -2, -3, -4, -5]]])
169,262
import functools import types import warnings import numpy as np from . import multiarray as mu from . import overrides from . import umath as um from . import numerictypes as nt from .multiarray import asarray, array, asanyarray, concatenate from . import _methods def _repeat_dispatcher(a, repeats, axis=None): return (a,)
null
169,263
import functools import types import warnings import numpy as np from . import multiarray as mu from . import overrides from . import umath as um from . import numerictypes as nt from .multiarray import asarray, array, asanyarray, concatenate from . import _methods def _put_dispatcher(a, ind, v, mode=None): return (a, ind, v)
null