scico.numpy#

BlockArray and compatible functions.

This module consists of BlockArray and functions that support both instances of this class and jax arrays. This includes all the functions from jax.numpy and numpy.testing, where many have been extended to automatically map over block array blocks as described in NumPy and SciPy Functions. Also included are additional functions unique to SCICO in util.

Functions

abs(x, /)

Calculate the absolute value element-wise.

absolute(x, /)

Calculate the absolute value element-wise.

add(x1, x2, /)

Add arguments element-wise.

all(a[, axis, out, keepdims, where])

Test whether all array elements along a given axis evaluate to True.

allclose(a, b[, rtol, atol, equal_nan])

Returns True if two arrays are element-wise equal within a tolerance.

amax(a[, axis, out, keepdims, initial, where])

Return the maximum of an array or maximum along an axis.

amin(a[, axis, out, keepdims, initial, where])

Return the minimum of an array or minimum along an axis.

angle(z[, deg])

Return the angle of the complex argument.

any(a[, axis, out, keepdims, where])

Test whether any array element along a given axis evaluates to True.

append(arr, values[, axis])

Append values to the end of an array.

apply_along_axis(func1d, axis, arr, *args, ...)

Apply a function to 1-D slices along the given axis.

apply_over_axes(func, a, axes)

Apply a function repeatedly over multiple axes.

arange(start[, stop, step, dtype])

Return evenly spaced values within a given interval.

arccos(x, /)

Trigonometric inverse cosine, element-wise.

arccosh(x, /)

Inverse hyperbolic cosine, element-wise.

arcsin(x, /)

Inverse sine, element-wise.

arcsinh(x, /)

Inverse hyperbolic sine element-wise.

arctan(x, /)

Trigonometric inverse tangent, element-wise.

arctan2(x1, x2, /)

Element-wise arc tangent of x1/x2 choosing the quadrant correctly.

arctanh(x, /)

Inverse hyperbolic tangent element-wise.

argmax(a[, axis, out, keepdims])

Returns the indices of the maximum values along an axis.

argmin(a[, axis, out, keepdims])

Returns the indices of the minimum values along an axis.

argsort(a[, axis, kind, order])

Returns the indices that would sort an array.

argwhere(a, *[, size, fill_value])

Find the indices of array elements that are non-zero, grouped by element.

around(a[, decimals, out])

Evenly round to the given number of decimals.

array(object[, dtype, copy, order, ndmin])

Create an array.

array_equal(a1, a2[, equal_nan])

True if two arrays have the same shape and elements, False otherwise.

array_equiv(a1, a2)

Returns True if input arrays are shape consistent and all elements equal.

array_repr(arr[, max_line_width, precision, ...])

Return the string representation of an array.

array_split(ary, indices_or_sections[, axis])

Split an array into multiple sub-arrays.

array_str(a[, max_line_width, precision, ...])

Return a string representation of the data in an array.

asarray(a[, dtype, order])

Convert the input to an array.

atleast_1d(*arys)

Convert inputs to arrays with at least one dimension.

atleast_2d(*arys)

View inputs as arrays with at least two dimensions.

atleast_3d(*arys)

View inputs as arrays with at least three dimensions.

average(a[, axis, weights, returned, keepdims])

Compute the weighted average along the specified axis.

bartlett(M)

Return the Bartlett window.

bincount(x[, weights, minlength, length])

Count number of occurrences of each value in array of non-negative ints.

blackman(M)

Return the Blackman window.

block(arrays)

Assemble an nd-array from nested lists of blocks.

blockarray(iterable)

Construct a BlockArray from a list or tuple of existing array-like.

broadcast_arrays(*args)

Broadcast any number of arrays against each other.

broadcast_shapes(*shapes)

Broadcast the input shapes into a single shape.

broadcast_to(array, shape)

Broadcast an array to a new shape.

can_cast(from_, to[, casting])

Returns True if cast between data types can occur according to the casting rule.

cbrt(x, /)

Return the cube-root of an array, element-wise.

ceil(x, /)

Return the ceiling of the input, element-wise.

choose(a, choices[, out, mode])

Construct an array from an index array and a list of arrays to choose from.

clip(a[, a_min, a_max, out])

Clip (limit) the values in an array.

column_stack(tup)

Stack 1-D arrays as columns into a 2-D array.

compress(condition, a[, axis, out])

Return selected slices of an array along given axis.

concatenate(arrays[, axis, dtype])

Join a sequence of arrays along an existing axis.

conj(x, /)

Return the complex conjugate, element-wise.

conjugate(x, /)

Return the complex conjugate, element-wise.

convolve(a, v[, mode, precision])

Returns the discrete, linear convolution of two one-dimensional sequences.

copy(a[, order])

Return an array copy of the given object.

copysign(x1, x2, /)

Change the sign of x1 to that of x2, element-wise.

cos(x, /)

Cosine element-wise.

cosh(x, /)

Hyperbolic cosine, element-wise.

count_nonzero(a[, axis, keepdims])

Counts the number of non-zero values in the array a.

cross(a, b[, axisa, axisb, axisc, axis])

Return the cross product of two (arrays of) vectors.

cumprod(a[, axis, dtype, out])

Return the cumulative product of elements along a given axis.

cumsum(a[, axis, dtype, out])

Return the cumulative sum of the elements along a given axis.

deg2rad(x, /)

Convert angles from degrees to radians.

degrees(x, /)

Convert angles from radians to degrees.

delete(arr, obj[, axis, assume_unique_indices])

Return a new array with sub-arrays along an axis deleted.

diag(v[, k])

Extract a diagonal or construct a diagonal array.

diag_indices(n[, ndim])

Return the indices to access the main diagonal of an array.

diag_indices_from(arr)

Return the indices to access the main diagonal of an n-dimensional array.

diagflat(v[, k])

Create a two-dimensional array with the flattened input as a diagonal.

diff(a[, n, axis, prepend, append])

Calculate the n-th discrete difference along the given axis.

divide(x1, x2, /)

Divide arguments element-wise.

divmod(x1, x2, /)

Return element-wise quotient and remainder simultaneously.

dot(a, b, *[, precision])

Dot product of two arrays.

dsplit(ary, indices_or_sections)

Split array into multiple sub-arrays along the 3rd axis (depth).

dstack(tup[, dtype])

Stack arrays in sequence depth wise (along third axis).

ediff1d(ary[, to_end, to_begin])

The differences between consecutive elements of an array.

einsum(subscripts, /, *operands[, out, ...])

Evaluates the Einstein summation convention on the operands.

einsum_path(subscripts, *operands[, optimize])

Evaluates the lowest cost contraction order for an einsum expression by

empty(shape[, dtype])

Return a new array of given shape and type, without initializing entries.

empty_like(prototype[, dtype, shape])

Return a new array with the same shape and type as a given array.

equal(x1, x2, /)

Return (x1 == x2) element-wise.

exp(x, /)

Calculate the exponential of all elements in the input array.

exp2(x, /)

Calculate 2**p for all p in the input array.

expand_dims(a, axis)

Expand the shape of an array.

expm1(x, /)

Calculate exp(x) - 1 for all elements in the array.

extract(condition, arr)

Return the elements of an array that satisfy some condition.

eye(N[, M, k, dtype])

Return a 2-D array with ones on the diagonal and zeros elsewhere.

fabs(x, /)

Compute the absolute values element-wise.

fix(x[, out])

Round to nearest integer towards zero.

flatnonzero(a, *[, size, fill_value])

Return indices that are non-zero in the flattened version of a.

flip(m[, axis])

Reverse the order of elements in an array along the given axis.

fliplr(m)

Reverse the order of elements along axis 1 (left/right).

flipud(m)

Reverse the order of elements along axis 0 (up/down).

float_power(x1, x2, /)

First array elements raised to powers from second array, element-wise.

floor(x, /)

Return the floor of the input, element-wise.

floor_divide(x1, x2, /)

Return the largest integer smaller or equal to the division of the inputs.

fmax(x1, x2)

Element-wise maximum of array elements.

fmin(x1, x2)

Element-wise minimum of array elements.

fmod(x1, x2, /)

Returns the element-wise remainder of division.

frexp(x, /)

Decompose the elements of x into mantissa and twos exponent.

from_dlpack(x)

Create a NumPy array from an object implementing the __dlpack__

frombuffer(buffer[, dtype, count, offset])

Interpret a buffer as a 1-dimensional array.

fromfile(*args, **kwargs)

Unimplemented JAX wrapper for jnp.fromfile.

fromfunction(function, shape, *[, dtype])

Construct an array by executing a function over each coordinate.

fromiter(*args, **kwargs)

Unimplemented JAX wrapper for jnp.fromiter.

fromstring(string[, dtype, count])

A new 1-D array initialized from text data in a string.

full(shape, fill_value[, dtype])

Return a new array of given shape and type, filled with fill_value.

full_like(a, fill_value[, dtype, shape])

Return a full array with the same shape and type as a given array.

gcd(x1, x2)

Returns the greatest common divisor of |x1| and |x2|

geomspace(start, stop[, num, endpoint, ...])

Return numbers spaced evenly on a log scale (a geometric progression).

get_printoptions()

Return the current print options.

gradient(f, *varargs[, axis, edge_order])

Return the gradient of an N-dimensional array.

greater(x1, x2, /)

Return the truth value of (x1 > x2) element-wise.

greater_equal(x1, x2, /)

Return the truth value of (x1 >= x2) element-wise.

hamming(M)

Return the Hamming window.

hanning(M)

Return the Hanning window.

heaviside(x1, x2, /)

Compute the Heaviside step function.

histogram(a[, bins, range, weights, density])

Compute the histogram of a dataset.

histogram2d(x, y[, bins, range, weights, ...])

Compute the bi-dimensional histogram of two data samples.

histogram_bin_edges(a[, bins, range, weights])

Function to calculate only the edges of the bins used by the histogram

histogramdd(sample[, bins, range, weights, ...])

Compute the multidimensional histogram of some data.

hsplit(ary, indices_or_sections)

Split an array into multiple sub-arrays horizontally (column-wise).

hstack(tup[, dtype])

Stack arrays in sequence horizontally (column wise).

hypot(x1, x2, /)

Given the "legs" of a right triangle, return its hypotenuse.

i0(x)

Modified Bessel function of the first kind, order 0.

identity(n[, dtype])

Return the identity array.

imag(val, /)

Return the imaginary part of the complex argument.

in1d(ar1, ar2[, assume_unique, invert])

Test whether each element of a 1-D array is also present in a second array.

indices(dimensions[, dtype, sparse])

Return an array representing the indices of a grid.

inner(a, b, *[, precision])

Inner product of two arrays.

insert(arr, obj, values[, axis])

Insert values along the given axis before the given indices.

interp(x, xp, fp[, left, right, period])

One-dimensional linear interpolation for monotonically increasing sample points.

intersect1d(ar1, ar2[, assume_unique, ...])

Find the intersection of two arrays.

isclose(a, b[, rtol, atol, equal_nan])

Returns a boolean array where two arrays are element-wise equal within a

iscomplex(x)

Returns a bool array, where True if input element is complex.

iscomplexobj(x)

Check for a complex type or an array of complex numbers.

isfinite(x, /)

Test element-wise for finiteness (not infinity and not Not a Number).

isin(element, test_elements[, ...])

Calculates element in test_elements, broadcasting over element only.

isinf(x, /)

Test element-wise for positive or negative infinity.

isnan(x, /)

Test element-wise for NaN and return result as a boolean array.

isneginf(x, /[, out])

Test element-wise for negative infinity, return result as bool array.

isposinf(x, /[, out])

Test element-wise for positive infinity, return result as bool array.

isreal(x)

Returns a bool array, where True if input element is real.

isrealobj(x)

Return True if x is a not complex type or an array of complex numbers.

isscalar(element)

Returns True if the type of element is a scalar type.

issubdtype(arg1, arg2)

Returns True if first argument is a typecode lower/equal in type hierarchy.

issubsctype(arg1, arg2)

Determine if the first argument is a subclass of the second argument.

iterable(y)

Check whether or not an object can be iterated over.

ix_(*args)

Construct an open mesh from multiple sequences.

kaiser(M, beta)

Return the Kaiser window.

kron(a, b)

Kronecker product of two arrays.

lcm(x1, x2)

Returns the lowest common multiple of |x1| and |x2|

ldexp(x1, x2, /)

Returns x1 * 2**x2, element-wise.

less(x1, x2, /)

Return the truth value of (x1 < x2) element-wise.

less_equal(x1, x2, /)

Return the truth value of (x1 <= x2) element-wise.

lexsort(keys[, axis])

Perform an indirect stable sort using a sequence of keys.

linspace(start, stop[, num, endpoint, ...])

Return evenly spaced numbers over a specified interval.

load(*args, **kwargs)

Load arrays or pickled objects from .npy, .npz or pickled files.

log(x, /)

Natural logarithm, element-wise.

log10(x, /)

Return the base 10 logarithm of the input array, element-wise.

log1p(x, /)

Return the natural logarithm of one plus the input array, element-wise.

log2(x, /)

Base-2 logarithm of x.

logical_and(*args)

Compute the truth value of x1 AND x2 element-wise.

logical_not(*args)

Compute the truth value of NOT x element-wise.

logical_or(*args)

Compute the truth value of x1 OR x2 element-wise.

logical_xor(*args)

Compute the truth value of x1 XOR x2, element-wise.

logspace(start, stop[, num, endpoint, base, ...])

Return numbers spaced evenly on a log scale.

mask_indices(*args, **kwargs)

Return the indices to access (n, n) arrays, given a masking function.

matmul(a, b, *[, precision])

Matrix product of two arrays.

matrix_transpose(x, /)

Transposes the last two dimensions of x.

max(a[, axis, out, keepdims, initial, where])

Return the maximum of an array or maximum along an axis.

maximum(x1, x2, /)

Element-wise maximum of array elements.

mean(a[, axis, dtype, out, keepdims, where])

Compute the arithmetic mean along the specified axis.

meshgrid(*xi[, copy, sparse, indexing])

Return coordinate matrices from coordinate vectors.

min(a[, axis, out, keepdims, initial, where])

Return the minimum of an array or minimum along an axis.

minimum(x1, x2, /)

Element-wise minimum of array elements.

mod(x1, x2, /)

Returns the element-wise remainder of division.

modf(x, /[, out])

Return the fractional and integral parts of an array, element-wise.

moveaxis(a, source, destination)

Move axes of an array to new positions.

multiply(x1, x2, /)

Multiply arguments element-wise.

nan_to_num(x[, copy, nan, posinf, neginf])

Replace NaN with zero and infinity with large finite numbers (default

nanargmax(a[, axis, out, keepdims])

Return the indices of the maximum values in the specified axis ignoring

nanargmin(a[, axis, out, keepdims])

Return the indices of the minimum values in the specified axis ignoring

nancumprod(a[, axis, dtype, out])

Return the cumulative product of array elements over a given axis treating Not a

nancumsum(a[, axis, dtype, out])

Return the cumulative sum of array elements over a given axis treating Not a

nanmax(a[, axis, out, keepdims, initial, where])

Return the maximum of an array or maximum along an axis, ignoring any

nanmin(a[, axis, out, keepdims, initial, where])

Return minimum of an array or minimum along an axis, ignoring any NaNs.

nanprod(a[, axis, dtype, out, keepdims, ...])

Return the product of array elements over a given axis treating Not a

nansum(a[, axis, dtype, out, keepdims, ...])

Return the sum of array elements over a given axis treating Not a

ndim(a)

Return the number of dimensions of an array.

negative(x, /)

Numerical negative, element-wise.

nextafter(x1, x2, /)

Return the next floating-point value after x1 towards x2, element-wise.

nonzero(a, *[, size, fill_value])

Return the indices of the elements that are non-zero.

not_equal(x1, x2, /)

Return (x1 != x2) element-wise.

ones(shape[, dtype])

Return a new array of given shape and type, filled with ones.

ones_like(a[, dtype, shape])

Return an array of ones with the same shape and type as a given array.

outer(a, b[, out])

Compute the outer product of two vectors.

pad(array, pad_width[, mode])

Pad an array.

partition(a, kth[, axis])

Return a partitioned copy of an array.

piecewise(x, condlist, funclist, *args, **kw)

Evaluate a piecewise-defined function.

place(*args, **kwargs)

Change elements of an array based on conditional and input values.

polydiv(u, v, *[, trim_leading_zeros])

Returns the quotient and remainder of polynomial division.

polymul(a1, a2, *[, trim_leading_zeros])

Find the product of two polynomials.

positive(x, /)

Numerical positive, element-wise.

power(x1, x2, /)

First array elements raised to powers from second array, element-wise.

printoptions(*args, **kwargs)

Context manager for setting print options.

prod(a[, axis, dtype, out, keepdims, ...])

Return the product of array elements over a given axis.

promote_types(a, b)

Returns the type to which a binary operation should cast its arguments.

ptp(a[, axis, out, keepdims])

Range of values (maximum - minimum) along an axis.

put(*args, **kwargs)

Replaces specified elements of an array with given values.

rad2deg(x, /)

Convert angles from radians to degrees.

radians(x, /)

Convert angles from degrees to radians.

ravel(a[, order])

Return a contiguous flattened array.

ravel_multi_index(multi_index, dims[, mode, ...])

Converts a tuple of index arrays into an array of flat

real(val, /)

Return the real part of the complex argument.

reciprocal(x, /)

Return the reciprocal of the argument, element-wise.

remainder(x1, x2, /)

Returns the element-wise remainder of division.

repeat(a, repeats[, axis, total_repeat_length])

Repeat elements of an array.

reshape(a, newshape[, order])

Gives a new shape to an array without changing its data.

resize(a, new_shape)

Return a new array with the specified shape.

result_type(*args)

Returns the type that results from applying the NumPy

rint(x, /)

Round elements of the array to the nearest integer.

roll(a, shift[, axis])

Roll array elements along a given axis.

rollaxis(a, axis[, start])

Roll the specified axis backwards, until it lies in a given position.

roots(p, *[, strip_zeros])

Return the roots of a polynomial with coefficients given in p.

rot90(m[, k, axes])

Rotate an array by 90 degrees in the plane specified by axes.

round_(a[, decimals, out])

Evenly round to the given number of decimals.

row_stack(tup[, dtype])

Stack arrays in sequence vertically (row wise).

save(file, arr[, allow_pickle, fix_imports])

Save an array to a binary file in NumPy .npy format.

savez(file, *args, **kwds)

Save several arrays into a single file in uncompressed .npz format.

searchsorted(a, v[, side, sorter, method])

Find indices where elements should be inserted to maintain order.

select(condlist, choicelist[, default])

Return an array drawn from elements in choicelist, depending on conditions.

set_printoptions([precision, threshold, ...])

Set printing options.

setdiff1d(ar1, ar2[, assume_unique, size, ...])

Find the set difference of two arrays.

setxor1d(ar1, ar2[, assume_unique])

Find the set exclusive-or of two arrays.

shape(a)

Return the shape of an array.

sign(x, /)

Returns an element-wise indication of the sign of a number.

signbit(x, /)

Returns element-wise True where signbit is set (less than zero).

sin(x, /)

Trigonometric sine, element-wise.

sinc(x, /)

Return the normalized sinc function.

sinh(x, /)

Hyperbolic sine, element-wise.

size(a[, axis])

Return the number of elements along a given axis.

sort(a[, axis, kind, order])

Return a sorted copy of an array.

sort_complex(a)

Sort a complex array using the real part first, then the imaginary part.

split(ary, indices_or_sections[, axis])

Split an array into multiple sub-arrays as views into ary.

sqrt(x, /)

Return the non-negative square-root of an array, element-wise.

square(x, /)

Return the element-wise square of the input.

squeeze(a[, axis])

Remove axes of length one from a.

stack(arrays[, axis, out, dtype])

Join a sequence of arrays along a new axis.

std(a[, axis, dtype, out, ddof, keepdims, where])

Compute the standard deviation along the specified axis.

subtract(x1, x2, /)

Subtract arguments, element-wise.

sum(a[, axis, dtype, out, keepdims, ...])

Sum of array elements over a given axis.

swapaxes(a, axis1, axis2)

Interchange two axes of an array.

take(a, indices[, axis, out, mode, ...])

Take elements from an array along an axis.

tan(x, /)

Compute tangent element-wise.

tanh(x, /)

Compute hyperbolic tangent element-wise.

tensordot(a, b[, axes, precision])

Compute tensor dot product along specified axes.

tile(A, reps)

Construct an array by repeating A the number of times given by reps.

trace(a[, offset, axis1, axis2, dtype, out])

Return the sum along diagonals of the array.

transpose(a[, axes])

Returns an array with axes transposed.

tri(N[, M, k, dtype])

An array with ones at and below the given diagonal and zeros elsewhere.

tril_indices(n[, k, m])

Return the indices for the lower-triangle of an (n, m) array.

tril_indices_from(arr[, k])

Return the indices for the lower-triangle of arr.

trim_zeros(filt[, trim])

Trim the leading and/or trailing zeros from a 1-D array or sequence.

triu_indices(n[, k, m])

Return the indices for the upper-triangle of an (n, m) array.

triu_indices_from(arr[, k])

Return the indices for the upper-triangle of arr.

true_divide(x1, x2, /)

Divide arguments element-wise.

trunc(x)

Return the truncated value of the input, element-wise.

union1d(ar1, ar2, *[, size, fill_value])

Find the union of two arrays.

unique(ar[, return_index, return_inverse, ...])

Find the unique elements of an array.

unravel_index(indices, shape)

Converts a flat index or array of flat indices into a tuple

unwrap(p[, discont, axis, period])

Unwrap by taking the complement of large deltas with respect to the period.

var(a[, axis, dtype, out, ddof, keepdims, where])

Compute the variance along the specified axis.

vdot(a, b, *[, precision])

Return the dot product of two vectors.

vectorize(pyfunc, *[, excluded, signature])

Define a vectorized function with broadcasting.

vsplit(ary, indices_or_sections)

Split an array into multiple sub-arrays vertically (row-wise).

vstack(tup[, dtype])

Stack arrays in sequence vertically (row wise).

where(condition[, x, y, size, fill_value])

Return elements chosen from x or y depending on condition.

zeros(shape[, dtype])

Return a new array of given shape and type, filled with zeros.

zeros_like(a[, dtype, shape])

Return an array of zeros with the same shape and type as a given array.

Classes

BlockArray(inputs)

Block array class.

class scico.numpy.BlockArray(inputs)#

Bases: object

Block array class.

A block array provides a way to combine arrays of different shapes into a single object for use with other SCICO classes. For further information, see the detailed BlockArray documentation.

Example

>>> x = snp.blockarray((
...     [[1, 3, 7],
...      [2, 2, 1]],
...     [2, 4, 8]
... ))
>>> x.shape
((2, 3), (3,))
>>> snp.sum(x)
Array(30, dtype=int32)
property T#

Returns an array with axes transposed.

LAX-backend implementation of numpy.transpose.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

For a 1-D array, this returns an unchanged view of the original array, as a transposed vector is simply the same vector. To convert a 1-D array into a 2-D column vector, an additional dimension must be added, e.g., np.atleast2d(a).T achieves this, as does a[:, np.newaxis]. For a 2-D array, this is the standard matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided, then transpose(a).shape == a.shape[::-1].

Parameters:
  • a (array_like) – Input array.

  • axes (tuple or list of ints, optional) – If specified, it must be a tuple or list which contains a permutation of [0,1,…,N-1] where N is the number of axes of a. The i’th axis of the returned array will correspond to the axis numbered axes[i] of the input. If not specified, defaults to range(a.ndim)[::-1], which reverses the order of the axes.

Returns:

p (ndarray) – a with its axes permuted. A view is returned whenever possible.

all(axis=None, out=None, keepdims=False, *, where=None)#

Test whether all array elements along a given axis evaluate to True.

LAX-backend implementation of numpy.all.

Original docstring below.

Parameters:
  • a (array_like) – Input array or object that can be converted to an array.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which a logical AND reduction is performed. The default (axis=None) is to perform a logical AND over all the dimensions of the input array. axis may be negative, in which case it counts from the last to the first axis.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the all method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • where (array_like of bool, optional) – Elements to include in checking for all True values. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

all (ndarray, bool) – A new boolean or array is returned unless out is specified, in which case a reference to out is returned.

any(axis=None, out=None, keepdims=False, *, where=None)#

Test whether any array element along a given axis evaluates to True.

LAX-backend implementation of numpy.any.

Original docstring below.

Returns single boolean if axis is None

Parameters:
  • a (array_like) – Input array or object that can be converted to an array.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which a logical OR reduction is performed. The default (axis=None) is to perform a logical OR over all the dimensions of the input array. axis may be negative, in which case it counts from the last to the first axis.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the any method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • where (array_like of bool, optional) – Elements to include in checking for any True values. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

any (bool or ndarray) – A new boolean or ndarray is returned unless out is specified, in which case a reference to out is returned.

argmax(axis=None, out=None, keepdims=None)#

Returns the indices of the maximum values along an axis.

LAX-backend implementation of numpy.argmax.

Original docstring below.

Parameters:
  • a (array_like) – Input array.

  • axis (int, optional) – By default, the index is into the flattened array, otherwise along the specified axis.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array.

Return type:

Array

Returns:

index_array (ndarray of ints) – Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed. If keepdims is set to True, then the size of axis will be 1 with the resulting array having same shape as a.shape.

argmin(axis=None, out=None, keepdims=None)#

Returns the indices of the minimum values along an axis.

LAX-backend implementation of numpy.argmin.

Original docstring below.

Parameters:
  • a (array_like) – Input array.

  • axis (int, optional) – By default, the index is into the flattened array, otherwise along the specified axis.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array.

Return type:

Array

Returns:

index_array (ndarray of ints) – Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed. If keepdims is set to True, then the size of axis will be 1 with the resulting array having same shape as a.shape.

argpartition(kth, axis=-1)#

Perform an indirect partition along the given axis using the

LAX-backend implementation of numpy.argpartition.

The JAX version requires the kth argument to be a static integer rather than a general array. This is implemented via two calls to jax.lax.top_k. If you’re only accessing the top or bottom k values of the output, it may be more efficient to call jax.lax.top_k directly.

The JAX version differs from the NumPy version in the treatment of NaN entries; NaNs which have the negative bit set are sorted to the beginning of the array.

Original docstring below.

algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in partitioned order.

New in version 1.8.0.

Parameters:
  • a (array_like) – Array to sort.

  • kth (int or sequence of ints) –

    Element index to partition by. The k-th element will be in its final sorted position and all smaller elements will be moved before it and all larger elements behind it. The order of all elements in the partitions is undefined. If provided with a sequence of k-th it will partition all of them into their sorted position at once.

    Deprecated since version 1.22.0: Passing booleans as index is deprecated.

  • axis (int or None, optional) – Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used.

Return type:

Array

Returns:

index_array (ndarray, int) – Array of indices that partition a along the specified axis. If a is one-dimensional, a[index_array] yields a partitioned a. More generally, np.take_along_axis(a, index_array, axis=axis) always yields the partitioned a, irrespective of dimensionality.

argsort(axis=-1, kind='stable', order=None)#

Returns the indices that would sort an array.

LAX-backend implementation of numpy.argsort.

Only kind='stable' is supported. Other kind values will produce a warning and be treated as if they were 'stable'.

Original docstring below.

Perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in sorted order.

Parameters:
  • a (array_like) – Array to sort.

  • axis (int or None, optional) – Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used.

  • kind ({'quicksort', 'mergesort', 'heapsort', 'stable'}, optional) –

    Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort under the covers and, in general, the actual implementation will vary with data type. The ‘mergesort’ option is retained for backwards compatibility.

    Changed in version 1.15.0.: The ‘stable’ option was added.

  • order (str or list of str, optional) – When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.

Return type:

Array

Returns:

index_array (ndarray, int) – Array of indices that sort a along the specified axis. If a is one-dimensional, a[index_array] yields a sorted a. More generally, np.take_along_axis(a, index_array, axis=axis) always yields the sorted a, irrespective of dimensionality.

astype(dtype)#

Copy the array and cast to a specified dtype.

This is implemeted via jax.lax.convert_element_type, which may have slightly different behavior than numpy.ndarray.astype in some cases. In particular, the details of float-to-int and int-to-float casts are implementation dependent.

Return type:

Array

block_until_ready()#

(self: xla::PyArray) -> object

static blockarray(iterable)#

Construct a BlockArray from a list or tuple of existing array-like.

broadcast(**kwargs)#

Broadcasts an array, adding new leading dimensions

LAX-backend implementation of jax._src.lax.lax.broadcast.

Deprecated. Use jax.lax.broadcast instead.

Original docstring below.

Parameters:
  • operand – an array

  • sizes – a sequence of integers, giving the sizes of new leading dimensions to add to the front of the array.

Returns:

An array containing the result.

See also

jax.lax.broadcast_in_dim : add new dimensions at any location in the array shape.

broadcast_in_dim(**kwargs)#

Broadcasts an array, adding new leading dimensions

LAX-backend implementation of jax._src.lax.lax.broadcast.

Deprecated. Use jax.lax.broadcast_in_dim instead.

Original docstring below.

Parameters:
  • operand – an array

  • sizes – a sequence of integers, giving the sizes of new leading dimensions to add to the front of the array.

Returns:

An array containing the result.

See also

jax.lax.broadcast_in_dim : add new dimensions at any location in the array shape.

choose(choices, out=None, mode='raise')#

Construct an array from an index array and a list of arrays to choose from.

LAX-backend implementation of numpy.choose.

Original docstring below.

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”.

  • 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

Return type:

Array

Returns:

merged_array (array) – The merged result.

clip(min=None, max=None, out=None)#

Return an array whose values are limited to a specified range.

Refer to jax.numpy.clip for full documentation.

Return type:

Array

clone()#

(self: xla::PyArray) -> xla::PyArray

compress(condition, axis=None, out=None)#

Return selected slices of this array along given axis.

Refer to jax.numpy.compress for full documentation.

Return type:

Array

conj()#

Return the complex conjugate, element-wise.

LAX-backend implementation of numpy.conjugate.

Original docstring below.

The complex conjugate of a complex number is obtained by changing the sign of its imaginary part.

Parameters:

x (array_like) – Input value.

Return type:

Array

Returns:

y (ndarray) – The complex conjugate of x, with same dtype as y. This is a scalar if x is a scalar.

conjugate()#

Return the complex conjugate, element-wise.

LAX-backend implementation of numpy.conjugate.

Original docstring below.

The complex conjugate of a complex number is obtained by changing the sign of its imaginary part.

Parameters:

x (array_like) – Input value.

Return type:

Array

Returns:

y (ndarray) – The complex conjugate of x, with same dtype as y. This is a scalar if x is a scalar.

copy(order=None)#

Return an array copy of the given object.

LAX-backend implementation of numpy.copy.

This function will create arrays on JAX’s default device. For control of the device placement of data, see jax.device_put. More information is available in the JAX FAQ at Controlling data and computation placement on devices (full FAQ at https://jax.readthedocs.io/en/latest/faq.html).

Original docstring below.

Parameters:
  • a (array_like) – Input data.

  • order ({'C', 'F', 'A', 'K'}, optional) – Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. (Note that this function and ndarray.copy are very similar, but have different default values for their order= arguments.)

Return type:

Array

Returns:

arr (ndarray) – Array interpretation of a.

cumprod(axis=None, dtype=None, out=None)#

Return the cumulative product of elements along a given axis.

LAX-backend implementation of numpy.cumprod.

Original docstring below.

Parameters:
  • a (array_like) – Input array.

  • axis (int, optional) – Axis along which the cumulative product is computed. By default the input is flattened.

  • dtype (dtype, optional) – Type of the returned array, as well as of the accumulator in which the elements are multiplied. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used instead.

Return type:

Array

Returns:

cumprod (ndarray) – A new array holding the result is returned unless out is specified, in which case a reference to out is returned.

cumsum(axis=None, dtype=None, out=None)#

Return the cumulative sum of the elements along a given axis.

LAX-backend implementation of numpy.cumsum.

Original docstring below.

Parameters:
  • a (array_like) – Input array.

  • axis (int, optional) – Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.

  • dtype (dtype, optional) – Type of the returned array and of the accumulator in which the elements are summed. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.

Return type:

Array

Returns:

cumsum_along_axis (ndarray.) – A new array holding the result is returned unless out is specified, in which case a reference to out is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array.

delete()#

(self: xla::PyArray) -> None

diagonal(offset=0, axis1=0, axis2=1)#

Return specified diagonals.

LAX-backend implementation of numpy.diagonal.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

If a is 2-D, returns the diagonal of a with the given offset, i.e., the collection of elements of the form a[i, i+offset]. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-array whose diagonal is returned. The shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals.

In versions of NumPy prior to 1.7, this function always returned a new, independent array containing a copy of the values in the diagonal.

In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal, but depending on this fact is deprecated. Writing to the resulting array continues to work as it used to, but a FutureWarning is issued.

Starting in NumPy 1.9 it returns a read-only view on the original array. Attempting to write to the resulting array will produce an error.

In some future release, it will return a read/write view and writing to the returned array will alter your original array. The returned array will have the same type as the input array.

If you don’t write to the array returned by this function, then you can just ignore all of the above.

If you depend on the current behavior, then we suggest copying the returned array explicitly, i.e., use np.diagonal(a).copy() instead of just np.diagonal(a). This will work with both past and future versions of NumPy.

Parameters:
  • a (array_like) – Array from which the diagonals are taken.

  • offset (int, optional) – Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to main diagonal (0).

  • axis1 (int, optional) – Axis to be used as the first axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to first axis (0).

  • axis2 (int, optional) – Axis to be used as the second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to second axis (1).

Returns:

array_of_diagonals (ndarray) – If a is 2-D, then a 1-D array containing the diagonal and of the same type as a is returned unless a is a matrix, in which case a 1-D array rather than a (2-D) matrix is returned in order to maintain backward compatibility.

If a.ndim > 2, then the dimensions specified by axis1 and axis2 are removed, and a new axis inserted at the end corresponding to the diagonal.

dot(b, *, precision=None)#

Dot product of two arrays. Specifically,

LAX-backend implementation of numpy.dot.

In addition to the original NumPy arguments listed below, also supports precision for extra control over matrix-multiplication precision on supported devices. precision may be set to None, which means default precision for the backend, a Precision enum value (Precision.DEFAULT, Precision.HIGH or Precision.HIGHEST) or a tuple of two Precision enums indicating separate precision for each argument.

Original docstring below.

  • If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).

  • If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.

  • If either a or b is 0-D (scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a * b is preferred.

  • If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.

  • If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b:

    dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
    

It uses an optimized BLAS library when possible (see numpy.linalg).

Parameters:
  • a (array_like) – First argument.

  • b (array_like) – Second argument.

Returns:

output (ndarray) – Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If out is given, then it is returned.

property dtype#

Return the dtype of the blocks, which must currently be homogeneous.

This allows snp.zeros(x.shape, x.dtype) to work without a mechanism to handle to lists of dtypes.

flatten(order='C')#

Return a contiguous flattened array.

LAX-backend implementation of numpy.ravel.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

A 1-D array, containing the elements of the input, is returned. A copy is made only if needed.

As of NumPy 1.10, the returned array will have the same type as the input array. (for example, a masked array will be returned for a masked array input)

Parameters:
  • a (array_like) – Input array. The elements in a are read in the order specified by order, and packed as a 1-D array.

  • order ({'C','F', 'A', 'K'}, optional) – The elements of a are read using this index order. ‘C’ means to index the elements in row-major, C-style order, with the last axis index changing fastest, back to the first axis index changing slowest. ‘F’ means to index the elements in column-major, Fortran-style order, with the first index changing fastest, and the last index changing slowest. Note that the ‘C’ and ‘F’ options take no account of the memory layout of the underlying array, and only refer to the order of axis indexing. ‘A’ means to read the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise. ‘K’ means to read the elements in the order they occur in memory, except for reversing the data when strides are negative. By default, ‘C’ index order is used.

Return type:

Array

Returns:

y (array_like) – y is an array of the same subtype as a, with shape (a.size,). Note that matrices are special cased for backward compatibility, if a is a matrix, then y is a 1-D ndarray.

property global_shards#

Returns list of all Shards of the Array across all devices.

The result includes shards that are not addressable by the current process. If a Shard is not addressable, then its data will be None.

property imag#

Return the imaginary part of the complex argument.

LAX-backend implementation of numpy.imag.

Original docstring below.

Parameters:

val (array_like) – Input array.

Returns:

out (ndarray or scalar) – The imaginary component of the complex argument. If val is real, the type of val is used for the output. If val has complex elements, the returned type is float.

is_deleted()#

(self: xla::PyArray) -> bool

is_ready()#

(self: xla::PyArray) -> bool

item()#

Copy an element of an array to a standard Python scalar and return it.

Return type:

Any

property itemsize#

Length of one array element in bytes.

property mT#

Transposes the last two dimensions of x.

Parameters:

x (array_like) – Input array. Must have x.ndim >= 2.

Returns:

xT (Array) – Transposed array.

max(axis=None, out=None, keepdims=False, initial=None, where=None)#

Return the maximum of an array or maximum along an axis.

LAX-backend implementation of numpy.amax.

Original docstring below.

Parameters:
  • a (array_like) – Input data.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which to operate. By default, flattened input is used.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the amax method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • initial (scalar, optional) – The minimum value of an output element. Must be present to allow computation on empty slice. See ~numpy.ufunc.reduce for details.

  • where (array_like of bool, optional) – Elements to compare for the maximum. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

amax (ndarray or scalar) – Maximum of a. If axis is None, the result is a scalar value. If axis is an int, the result is an array of dimension a.ndim - 1. If axis is a tuple, the result is an array of dimension a.ndim - len(axis).

mean(axis=None, dtype=None, out=None, keepdims=False, *, where=None)#

Compute the arithmetic mean along the specified axis.

LAX-backend implementation of numpy.mean.

Original docstring below.

Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.

Parameters:
  • a (array_like) – Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

  • dtype (data-type, optional) – Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • where (array_like of bool, optional) – Elements to include in the mean. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

m (ndarray, see dtype parameter above) – If out=None, returns a new array containing the mean values, otherwise a reference to the output array is returned.

min(axis=None, out=None, keepdims=False, initial=None, where=None)#

Return the minimum of an array or minimum along an axis.

LAX-backend implementation of numpy.amin.

Original docstring below.

Parameters:
  • a (array_like) – Input data.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which to operate. By default, flattened input is used.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the amin method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • initial (scalar, optional) – The maximum value of an output element. Must be present to allow computation on empty slice. See ~numpy.ufunc.reduce for details.

  • where (array_like of bool, optional) – Elements to compare for the minimum. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

amin (ndarray or scalar) – Minimum of a. If axis is None, the result is a scalar value. If axis is an int, the result is an array of dimension a.ndim - 1. If axis is a tuple, the result is an array of dimension a.ndim - len(axis).

property nbytes#

Total bytes consumed by the elements of the array.

nonzero(*, size=None, fill_value=None)#

Return the indices of the elements that are non-zero.

LAX-backend implementation of numpy.nonzero.

Because the size of the output of nonzero is data-dependent, the function is not typically compatible with JIT. The JAX version adds the optional size argument which must be specified statically for jnp.nonzero to be used within some of JAX’s transformations.

Original docstring below.

Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension. The values in a are always tested and returned in row-major, C-style order.

To group the indices by element, rather than dimension, use argwhere, which returns a row for each non-zero element.

Note

When called on a zero-d array or scalar, nonzero(a) is treated as nonzero(atleast_1d(a)).

Deprecated since version 1.17.0: Use atleast_1d explicitly if this behavior is deliberate.

Parameters:
  • a (array_like) – Input array.

  • size (int, optional) – If specified, the indices of the first size True elements will be returned. If there are fewer unique elements than size indicates, the return value will be padded with fill_value.

  • fill_value (array_like, optional) – When size is specified and there are fewer than the indicated number of elements, the remaining elements will be filled with fill_value, which defaults to zero.

Return type:

Tuple[Array, ...]

Returns:

tuple_of_arrays (tuple) – Indices of elements that are non-zero.

on_device_size_in_bytes()#

(self: xla::PyArray) -> int

platform()#

(self: xla::PyArray) -> str

prod(axis=None, dtype=None, out=None, keepdims=False, initial=None, where=None, promote_integers=True)#

Return the product of array elements over a given axis.

LAX-backend implementation of numpy.prod.

Original docstring below.

Parameters:
  • a (array_like) – Input data.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which a product is performed. The default, axis=None, will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis.

  • dtype (dtype, optional) – The type of the returned array, as well as of the accumulator in which the elements are multiplied. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the prod method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • initial (scalar, optional) – The starting value for this product. See ~numpy.ufunc.reduce for details.

  • where (array_like of bool, optional) – Elements to include in the product. See ~numpy.ufunc.reduce for details.

  • promote_integers (bool, default=True) – If True, then integer inputs will be promoted to the widest available integer dtype, following numpy’s behavior. If False, the result will have the same dtype as the input. promote_integers is ignored if dtype is specified.

Return type:

Array

Returns:

product_along_axis (ndarray, see dtype parameter above.) – An array shaped as a but with the specified axis removed. Returns a reference to out if specified.

ptp(axis=None, out=None, keepdims=False)#

Range of values (maximum - minimum) along an axis.

LAX-backend implementation of numpy.ptp.

Original docstring below.

The name of the function comes from the acronym for ‘peak to peak’.

Warning

ptp preserves the data type of the array. This means the return value for an input of signed integers with n bits (e.g. np.int8, np.int16, etc) is also a signed integer with n bits. In that case, peak-to-peak values greater than 2**(n-1)-1 will be returned as negative values. An example with a work-around is shown below.

Parameters:
  • a (array_like) – Input values.

  • axis (None or int or tuple of ints, optional) – Axis along which to find the peaks. By default, flatten the array. axis may be negative, in which case it counts from the last to the first axis.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the ptp method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

Return type:

Array

Returns:

ptp (ndarray or scalar) – The range of a given array - scalar if array is one-dimensional or a new array holding the result along the given axis

ravel(order='C')#

Return a contiguous flattened array.

LAX-backend implementation of numpy.ravel.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

A 1-D array, containing the elements of the input, is returned. A copy is made only if needed.

As of NumPy 1.10, the returned array will have the same type as the input array. (for example, a masked array will be returned for a masked array input)

Parameters:
  • a (array_like) – Input array. The elements in a are read in the order specified by order, and packed as a 1-D array.

  • order ({'C','F', 'A', 'K'}, optional) – The elements of a are read using this index order. ‘C’ means to index the elements in row-major, C-style order, with the last axis index changing fastest, back to the first axis index changing slowest. ‘F’ means to index the elements in column-major, Fortran-style order, with the first index changing fastest, and the last index changing slowest. Note that the ‘C’ and ‘F’ options take no account of the memory layout of the underlying array, and only refer to the order of axis indexing. ‘A’ means to read the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise. ‘K’ means to read the elements in the order they occur in memory, except for reversing the data when strides are negative. By default, ‘C’ index order is used.

Return type:

Array

Returns:

y (array_like) – y is an array of the same subtype as a, with shape (a.size,). Note that matrices are special cased for backward compatibility, if a is a matrix, then y is a 1-D ndarray.

property real#

Return the real part of the complex argument.

LAX-backend implementation of numpy.real.

Original docstring below.

Parameters:

val (array_like) – Input array.

Returns:

out (ndarray or scalar) – The real component of the complex argument. If val is real, the type of val is used for the output. If val has complex elements, the returned type is float.

repeat(repeats, axis=None, *, total_repeat_length=None)#

Repeat elements of an array.

LAX-backend implementation of numpy.repeat.

JAX adds the optional total_repeat_length parameter which specifies the total number of repeat, and defaults to sum(repeats). It must be specified for repeat to be compilable. If sum(repeats) is larger than the specified total_repeat_length the remaining values will be discarded. In the case of sum(repeats) being smaller than the specified target length, the final value will be repeated.

Original docstring below.

Parameters:
  • a (array_like) – Input array.

  • repeats (int or array of ints) – The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.

  • axis (int, optional) – The axis along which to repeat values. By default, use the flattened input array, and return a flat output array.

Return type:

Array

Returns:

repeated_array (ndarray) – Output array which has the same shape as a, except along the given axis.

reshape(*args, order='C')#

Returns an array containing the same data with a new shape.

Refer to jax.numpy.reshape for full documentation.

Return type:

Array

round(decimals=0, out=None)#

Evenly round to the given number of decimals.

LAX-backend implementation of numpy.around.

Original docstring below.

Parameters:
  • a (array_like) – Input data.

  • decimals (int, optional) – Number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point.

Return type:

Array

Returns:

rounded_array (ndarray) – An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned.

The real and imaginary parts of complex numbers are rounded separately. The result of rounding a float is a float.

References

searchsorted(v, side='left', sorter=None, *, method='scan')#

Find indices where elements should be inserted to maintain order.

LAX-backend implementation of numpy.searchsorted.

Original docstring below.

Find the indices into a sorted array a such that, if the corresponding elements in v were inserted before the indices, the order of a would be preserved.

Assuming that a is sorted:

side

returned index i satisfies

left

a[i-1] < v <= a[i]

right

a[i-1] <= v < a[i]

Parameters:
  • a (1-D array_like) – Input array. If sorter is None, then it must be sorted in ascending order, otherwise sorter must be an array of indices that sort it.

  • v (array_like) – Values to insert into a.

  • side ({'left', 'right'}, optional) – If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of a).

  • method (str) – One of ‘scan’ (default), ‘sort’ or ‘compare_all’. Controls the method used by the implementation: ‘scan’ tends to be more performant on CPU (particularly when a is very large), ‘sort’ is often more performant on accelerator backends like GPU and TPU (particularly when v is very large), and ‘compare_all’ can be most performant when a is very small.

Return type:

Array

Returns:

indices (int or array of ints) – Array of insertion points with the same shape as v, or an integer if v is a scalar.

sort(axis=-1, kind='quicksort', order=None)#

Return a sorted copy of an array.

LAX-backend implementation of numpy.sort.

Original docstring below.

Parameters:
  • a (array_like) – Array to be sorted.

  • axis (int or None, optional) – Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.

  • kind ({'quicksort', 'mergesort', 'heapsort', 'stable'}, optional) –

    Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort or radix sort under the covers and, in general, the actual implementation will vary with data type. The ‘mergesort’ option is retained for backwards compatibility.

    Changed in version 1.15.0.: The ‘stable’ option was added.

  • order (str or list of str, optional) – When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.

Returns:

sorted_array (ndarray) – Array of the same type and shape as a.

split(**kwargs)#

Broadcasts an array, adding new leading dimensions

LAX-backend implementation of jax._src.lax.lax.broadcast.

Deprecated. Use jax.numpy.split instead.

Original docstring below.

Parameters:
  • operand – an array

  • sizes – a sequence of integers, giving the sizes of new leading dimensions to add to the front of the array.

Returns:

An array containing the result.

See also

jax.lax.broadcast_in_dim : add new dimensions at any location in the array shape.

squeeze(axis=None)#

Remove axes of length one from a.

LAX-backend implementation of numpy.squeeze.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

Parameters:
  • a (array_like) – Input data.

  • axis (None or int or tuple of ints, optional) –

Return type:

Array

Returns:

squeezed (ndarray) – The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into a. Note that if all axes are squeezed, the result is a 0d array and not a scalar.

std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=None)#

Compute the standard deviation along the specified axis.

LAX-backend implementation of numpy.std.

Original docstring below.

Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

Parameters:
  • a (array_like) – Calculate the standard deviation of these values.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.

  • dtype (dtype, optional) – Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type.

  • ddof (int, optional) – Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the std method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • where (array_like of bool, optional) – Elements to include in the standard deviation. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

standard_deviation (ndarray, see dtype parameter above.) – If out is None, return a new array containing the standard deviation, otherwise return a reference to the output array.

sum(axis=None, dtype=None, out=None, keepdims=False, initial=None, where=None, promote_integers=True)#

Sum of array elements over a given axis.

LAX-backend implementation of numpy.sum.

Original docstring below.

Parameters:
  • a (array_like) – Elements to sum.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.

  • dtype (dtype, optional) – The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • initial (scalar, optional) – Starting value for the sum. See ~numpy.ufunc.reduce for details.

  • where (array_like of bool, optional) – Elements to include in the sum. See ~numpy.ufunc.reduce for details.

  • promote_integers (bool, default=True) – If True, then integer inputs will be promoted to the widest available integer dtype, following numpy’s behavior. If False, the result will have the same dtype as the input. promote_integers is ignored if dtype is specified.

Return type:

Array

Returns:

sum_along_axis (ndarray) – An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

swapaxes(axis1, axis2)#

Interchange two axes of an array.

LAX-backend implementation of numpy.swapaxes.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

Parameters:
  • a (array_like) – Input array.

  • axis1 (int) – First axis.

  • axis2 (int) – Second axis.

Return type:

Array

Returns:

a_swapped (ndarray) – For NumPy >= 1.10.0, if a is an ndarray, then a view of a is returned; otherwise a new array is created. For earlier NumPy versions a view of a is returned only if the order of the axes is changed, otherwise the input array is returned.

take(indices, axis=None, out=None, mode=None, unique_indices=False, indices_are_sorted=False, fill_value=None)#

Take elements from an array along an axis.

LAX-backend implementation of numpy.take.

By default, JAX assumes that all indices are in-bounds. Alternative out-of-bound index semantics can be specified via the mode parameter (see below).

Original docstring below.

When axis is not None, this function does the same thing as “fancy” indexing (indexing arrays using arrays); however, it can be easier to use if you need elements along a given axis. A call such as np.take(arr, indices, axis=3) is equivalent to arr[:,:,:,indices,...].

Explained without fancy indexing, this is equivalent to the following use of ndindex, which sets each of ii, jj, and kk to a tuple of indices:

Ni, Nk = a.shape[:axis], a.shape[axis+1:]
Nj = indices.shape
for ii in ndindex(Ni):
    for jj in ndindex(Nj):
        for kk in ndindex(Nk):
            out[ii + jj + kk] = a[ii + (indices[jj],) + kk]
Parameters:
  • a (array_like (Ni..., M, Nk...)) – The source array.

  • indices (array_like (Nj...)) – The indices of the values to extract.

  • axis (int, optional) – The axis over which to select values. By default, the flattened input array is used.

  • mode (string, default="fill") – Out-of-bounds indexing mode. The default mode=”fill” returns invalid values (e.g. NaN) for out-of bounds indices (see also fill_value below). For more discussion of mode options, see jax.numpy.ndarray.at.

  • fill_value (optional) – The fill value to return for out-of-bounds slices when mode is ‘fill’. Ignored otherwise. Defaults to NaN for inexact types, the largest negative value for signed types, the largest positive value for unsigned types, and True for booleans.

  • unique_indices (bool, default=False) – If True, the implementation will assume that the indices are unique, which can result in more efficient execution on some backends.

  • indices_are_sorted (bool, default=False) – If True, the implementation will assume that the indices are sorted in ascending order, which can lead to more efficient execution on some backends.

Returns:

out (ndarray (Ni…, Nj…, Nk…)) – The returned array has the same type as a.

trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)#

Return the sum along diagonals of the array.

LAX-backend implementation of numpy.trace.

Original docstring below.

If a is 2-D, the sum along its diagonal with the given offset is returned, i.e., the sum of elements a[i,i+offset] for all i.

If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-arrays whose traces are returned. The shape of the resulting array is the same as that of a with axis1 and axis2 removed.

Parameters:
  • a (array_like) – Input array, from which the diagonals are taken.

  • offset (int, optional) – Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults to 0.

  • axis1 (int, optional) – Axes to be used as the first and second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults are the first two axes of a.

  • axis2 (int, optional) – Axes to be used as the first and second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults are the first two axes of a.

  • dtype (dtype, optional) – Determines the data-type of the returned array and of the accumulator where the elements are summed. If dtype has the value None and a is of integer type of precision less than the default integer precision, then the default integer precision is used. Otherwise, the precision is the same as that of a.

Return type:

Array

Returns:

sum_along_diagonals (ndarray) – If a is 2-D, the sum along the diagonal is returned. If a has larger dimensions, then an array of sums along diagonals is returned.

transpose(*args)#

Returns a view of the array with axes transposed.

Refer to jax.numpy.transpose for full documentation.

Return type:

Array

unsafe_buffer_pointer()#

(self: xla::PyArray) -> int

var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=None)#

Compute the variance along the specified axis.

LAX-backend implementation of numpy.var.

Original docstring below.

Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis.

Parameters:
  • a (array_like) – Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array.

  • dtype (data-type, optional) – Type to use in computing the variance. For arrays of integer type the default is float64; for arrays of float types it is the same as the array type.

  • ddof (int, optional) – “Delta Degrees of Freedom”: the divisor used in the calculation is N - ddof, where N represents the number of elements. By default ddof is zero.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the var method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • where (array_like of bool, optional) – Elements to include in the variance. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

variance (ndarray, see dtype parameter above) – If out=None, returns a new array containing the variance; otherwise, a reference to the output array is returned.

view(dtype=None, type=None)#

Return a bitwise copy of the array, viewed as a new dtype.

This is fuller-featured wrapper around jax.lax.bitcast_convert_type.

If the source and target dtype have the same bitwidth, the result has the same shape as the input array. If the bitwidth of the target dtype is different from the source, the size of the last axis of the result is adjusted accordingly.

>>> jnp.zeros([1,2,3], dtype=jnp.int16).view(jnp.int8).shape
(1, 2, 6)
:rtype: :sphinx_autodoc_typehints_type:`\:py\:class\:\`\~jax.Array\``
>>> jnp.zeros([1,2,4], dtype=jnp.int8).view(jnp.int16).shape
(1, 2, 2)

Conversions involving booleans are not well-defined in all situations. With regards to the shape of result as explained above, booleans are treated as having a bitwidth of 8. However, when converting to a boolean array, the input should only contain 0 or 1 bytes. Otherwise, results may be unpredictable or may change depending on how the result is used.

This conversion is guaranteed and safe: >>> jnp.array([1, 0, 1], dtype=jnp.int8).view(jnp.bool_) Array([ True, False, True], dtype=bool)

However, there are no guarantees about the results of any expression involving a view such as this: jnp.array([1, 2, 3], dtype=jnp.int8).view(jnp.bool_). In particular, the results may change between JAX releases and depending on the platform. To safely convert such an array to a boolean array, compare it with 0:

>>> jnp.array([1, 2, 0], dtype=jnp.int8) != 0
Array([ True,  True, False], dtype=bool)
scico.numpy.blockarray(iterable)#

Construct a BlockArray from a list or tuple of existing array-like.

scico.numpy.abs(x, /)#

Calculate the absolute value element-wise.

LAX-backend implementation of numpy.absolute.

Original docstring below.

np.abs is a shorthand for this function.

Parameters:

x (array_like) – Input array.

Return type:

Array

Returns:

absolute (ndarray) – An ndarray containing the absolute value of each element in x. For complex input, a + ib, the absolute value is \(\sqrt{ a^2 + b^2 }\). This is a scalar if x is a scalar.

scico.numpy.absolute(x, /)#

Calculate the absolute value element-wise.

LAX-backend implementation of numpy.absolute.

Original docstring below.

np.abs is a shorthand for this function.

Parameters:

x (array_like) – Input array.

Return type:

Array

Returns:

absolute (ndarray) – An ndarray containing the absolute value of each element in x. For complex input, a + ib, the absolute value is \(\sqrt{ a^2 + b^2 }\). This is a scalar if x is a scalar.

scico.numpy.add(x1, x2, /)#

Add arguments element-wise.

LAX-backend implementation of numpy.add.

Original docstring below.

Parameters:
  • x1 (array_like) – The arrays to be added. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – The arrays to be added. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Returns:

add (ndarray or scalar) – The sum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

scico.numpy.all(a, axis=None, out=None, keepdims=False, *, where=None)#

Test whether all array elements along a given axis evaluate to True.

LAX-backend implementation of numpy.all.

Original docstring below.

Parameters:
  • a (array_like) – Input array or object that can be converted to an array.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which a logical AND reduction is performed. The default (axis=None) is to perform a logical AND over all the dimensions of the input array. axis may be negative, in which case it counts from the last to the first axis.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the all method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • where (array_like of bool, optional) – Elements to include in checking for all True values. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

all (ndarray, bool) – A new boolean or array is returned unless out is specified, in which case a reference to out is returned.

scico.numpy.allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)#

Returns True if two arrays are element-wise equal within a tolerance.

LAX-backend implementation of numpy.allclose.

Original docstring below.

The tolerance values are positive, typically very small numbers. The relative difference (rtol * abs(b)) and the absolute difference atol are added together to compare against the absolute difference between a and b.

NaNs are treated as equal if they are in the same place and if equal_nan=True. Infs are treated as equal if they are in the same place and of the same sign in both arrays.

Parameters:
  • a (array_like) – Input arrays to compare.

  • b (array_like) – Input arrays to compare.

  • rtol (float) – The relative tolerance parameter (see Notes).

  • atol (float) – The absolute tolerance parameter (see Notes).

  • equal_nan (bool) – Whether to compare NaN’s as equal. If True, NaN’s in a will be considered equal to NaN’s in b in the output array.

Return type:

Array

Returns:

allclose (bool) – Returns True if the two arrays are equal within the given tolerance; False otherwise.

scico.numpy.amax(a, axis=None, out=None, keepdims=False, initial=None, where=None)#

Return the maximum of an array or maximum along an axis.

LAX-backend implementation of numpy.amax.

Original docstring below.

Parameters:
  • a (array_like) – Input data.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which to operate. By default, flattened input is used.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the amax method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • initial (scalar, optional) – The minimum value of an output element. Must be present to allow computation on empty slice. See ~numpy.ufunc.reduce for details.

  • where (array_like of bool, optional) – Elements to compare for the maximum. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

amax (ndarray or scalar) – Maximum of a. If axis is None, the result is a scalar value. If axis is an int, the result is an array of dimension a.ndim - 1. If axis is a tuple, the result is an array of dimension a.ndim - len(axis).

scico.numpy.amin(a, axis=None, out=None, keepdims=False, initial=None, where=None)#

Return the minimum of an array or minimum along an axis.

LAX-backend implementation of numpy.amin.

Original docstring below.

Parameters:
  • a (array_like) – Input data.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which to operate. By default, flattened input is used.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the amin method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • initial (scalar, optional) – The maximum value of an output element. Must be present to allow computation on empty slice. See ~numpy.ufunc.reduce for details.

  • where (array_like of bool, optional) – Elements to compare for the minimum. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

amin (ndarray or scalar) – Minimum of a. If axis is None, the result is a scalar value. If axis is an int, the result is an array of dimension a.ndim - 1. If axis is a tuple, the result is an array of dimension a.ndim - len(axis).

scico.numpy.angle(z, deg=False)#

Return the angle of the complex argument.

LAX-backend implementation of numpy.angle.

Original docstring below.

Parameters:
  • z (array_like) – A complex number or sequence of complex numbers.

  • deg (bool, optional) – Return angle in degrees if True, radians if False (default).

Return type:

Array

Returns:

angle (ndarray or scalar) – The counterclockwise angle from the positive real axis on the complex plane in the range (-pi, pi], with dtype as numpy.float64.

Changed in version 1.16.0: This function works on subclasses of ndarray like ma.array.

scico.numpy.any(a, axis=None, out=None, keepdims=False, *, where=None)#

Test whether any array element along a given axis evaluates to True.

LAX-backend implementation of numpy.any.

Original docstring below.

Returns single boolean if axis is None

Parameters:
  • a (array_like) – Input array or object that can be converted to an array.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which a logical OR reduction is performed. The default (axis=None) is to perform a logical OR over all the dimensions of the input array. axis may be negative, in which case it counts from the last to the first axis.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the any method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • where (array_like of bool, optional) – Elements to include in checking for any True values. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

any (bool or ndarray) – A new boolean or ndarray is returned unless out is specified, in which case a reference to out is returned.

scico.numpy.append(arr, values, axis=None)#

Append values to the end of an array.

LAX-backend implementation of numpy.append.

Original docstring below.

Parameters:
  • arr (array_like) – Values are appended to a copy of this array.

  • values (array_like) – These values are appended to a copy of arr. It must be of the correct shape (the same shape as arr, excluding axis). If axis is not specified, values can be any shape and will be flattened before use.

  • axis (int, optional) – The axis along which values are appended. If axis is not given, both arr and values are flattened before use.

Returns:

append (ndarray) – A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled. If axis is None, out is a flattened array.

scico.numpy.apply_along_axis(func1d, axis, arr, *args, **kwargs)#

Apply a function to 1-D slices along the given axis.

LAX-backend implementation of numpy.apply_along_axis.

Original docstring below.

Execute func1d(a, *args, **kwargs) where func1d operates on 1-D arrays and a is a 1-D slice of arr along axis.

This is equivalent to (but faster than) the following use of ndindex and s_, which sets each of ii, jj, and kk to a tuple of indices:

Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
    for kk in ndindex(Nk):
        f = func1d(arr[ii + s_[:,] + kk])
        Nj = f.shape
        for jj in ndindex(Nj):
            out[ii + jj + kk] = f[jj]

Equivalently, eliminating the inner loop, this can be expressed as:

Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
    for kk in ndindex(Nk):
        out[ii + s_[...,] + kk] = func1d(arr[ii + s_[:,] + kk])
Parameters:
  • func1d (function (M,) -> (Nj...)) – This function should accept 1-D arrays. It is applied to 1-D slices of arr along the specified axis.

  • axis (integer) – Axis along which arr is sliced.

  • arr (ndarray (Ni..., M, Nk...)) – Input array.

  • args (any) – Additional arguments to func1d.

  • kwargs (any) – Additional named arguments to func1d.

Returns:

out (ndarray (Ni…, Nj…, Nk…)) – The output array. The shape of out is identical to the shape of arr, except along the axis dimension. This axis is removed, and replaced with new dimensions equal to the shape of the return value of func1d. So if func1d returns a scalar out will have one fewer dimensions than arr.

scico.numpy.apply_over_axes(func, a, axes)#

Apply a function repeatedly over multiple axes.

LAX-backend implementation of numpy.apply_over_axes.

Original docstring below.

func is called as res = func(a, axis), where axis is the first element of axes. The result res of the function call must have either the same dimensions as a or one less dimension. If res has one less dimension than a, a dimension is inserted before axis. The call to func is then repeated for each axis in axes, with res as the first argument.

Parameters:
  • func (function) – This function must take two arguments, func(a, axis).

  • a (array_like) – Input array.

  • axes (array_like) – Axes over which func is applied; the elements must be integers.

Returns:

apply_over_axis (ndarray) – The output array. The number of dimensions is the same as a, but the shape can be different. This depends on whether func changes the shape of its output with respect to its input.

scico.numpy.arange(start, stop=None, step=None, dtype=None)#

Return evenly spaced values within a given interval.

LAX-backend implementation of numpy.arange.

Original docstring below.

arange can be called with a varying number of positional arguments:

  • arange(stop): Values are generated within the half-open interval [0, stop) (in other words, the interval including start but excluding stop).

  • arange(start, stop): Values are generated within the half-open interval [start, stop).

  • arange(start, stop, step) Values are generated within the half-open interval [start, stop), with spacing between values given by step.

For integer arguments the function is roughly equivalent to the Python built-in range, but returns an ndarray rather than a range instance.

When using a non-integer step, such as 0.1, it is often better to use numpy.linspace.

See the Warning sections below for more information.

Parameters:
  • start (integer or real, optional) – Start of interval. The interval includes this value. The default start value is 0.

  • stop (integer or real) – End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.

  • step (integer or real, optional) – Spacing between values. For any output out, this is the distance between two adjacent values, out[i+1] - out[i]. The default step size is 1. If step is specified as a position argument, start must also be given.

  • dtype (dtype, optional) – The type of the output array. If dtype is not given, infer the data type from the other input arguments.

Return type:

Array

Returns:

arange (ndarray) – Array of evenly spaced values.

For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop.

scico.numpy.arccos(x, /)#

Trigonometric inverse cosine, element-wise.

LAX-backend implementation of numpy.arccos.

Original docstring below.

The inverse of cos so that, if y = cos(x), then x = arccos(y).

Parameters:

x (array_like) – x-coordinate on the unit circle. For real arguments, the domain is [-1, 1].

Returns:

angle (ndarray) – The angle of the ray intersecting the unit circle at the given x-coordinate in radians [0, pi]. This is a scalar if x is a scalar.

scico.numpy.arccosh(x, /)#

Inverse hyperbolic cosine, element-wise.

LAX-backend implementation of numpy.arccosh.

Original docstring below.

Parameters:
  • x (array_like) – Input array.

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

Return type:

Array

Returns:

arccosh (ndarray) – Array of the same shape as x. This is a scalar if x is a scalar.

scico.numpy.arcsin(x, /)#

Inverse sine, element-wise.

LAX-backend implementation of numpy.arcsin.

Original docstring below.

Parameters:

x (array_like) – y-coordinate on the unit circle.

Returns:

angle (ndarray) – The inverse sine of each element in x, in radians and in the closed interval [-pi/2, pi/2]. This is a scalar if x is a scalar.

scico.numpy.arcsinh(x, /)#

Inverse hyperbolic sine element-wise.

LAX-backend implementation of numpy.arcsinh.

Original docstring below.

Parameters:

x (array_like) – Input array.

Returns:

out (ndarray or scalar) – Array of the same shape as x. This is a scalar if x is a scalar.

scico.numpy.arctan(x, /)#

Trigonometric inverse tangent, element-wise.

LAX-backend implementation of numpy.arctan.

Original docstring below.

The inverse of tan, so that if y = tan(x) then x = arctan(y).

Parameters:

x (array_like) –

Returns:

out (ndarray or scalar) – Out has the same shape as x. Its real part is in [-pi/2, pi/2] (arctan(+/-inf) returns +/-pi/2). This is a scalar if x is a scalar.

scico.numpy.arctan2(x1, x2, /)#

Element-wise arc tangent of x1/x2 choosing the quadrant correctly.

LAX-backend implementation of numpy.arctan2.

Original docstring below.

The quadrant (i.e., branch) is chosen so that arctan2(x1, x2) is the signed angle in radians between the ray ending at the origin and passing through the point (1,0), and the ray ending at the origin and passing through the point (x2, x1). (Note the role reversal: the “y-coordinate” is the first function parameter, the “x-coordinate” is the second.) By IEEE convention, this function is defined for x2 = +/-0 and for either or both of x1 and x2 = +/-inf (see Notes for specific values).

This function is not defined for complex-valued arguments; for the so-called argument of complex values, use angle.

Parameters:
  • x1 (array_like, real-valued) – y-coordinates.

  • x2 (array_like, real-valued) – x-coordinates. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Returns:

angle (ndarray) – Array of angles in radians, in the range [-pi, pi]. This is a scalar if both x1 and x2 are scalars.

scico.numpy.arctanh(x, /)#

Inverse hyperbolic tangent element-wise.

LAX-backend implementation of numpy.arctanh.

Original docstring below.

Parameters:

x (array_like) – Input array.

Returns:

out (ndarray or scalar) – Array of the same shape as x. This is a scalar if x is a scalar.

scico.numpy.argmax(a, axis=None, out=None, keepdims=None)#

Returns the indices of the maximum values along an axis.

LAX-backend implementation of numpy.argmax.

Original docstring below.

Parameters:
  • a (array_like) – Input array.

  • axis (int, optional) – By default, the index is into the flattened array, otherwise along the specified axis.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array.

Return type:

Array

Returns:

index_array (ndarray of ints) – Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed. If keepdims is set to True, then the size of axis will be 1 with the resulting array having same shape as a.shape.

scico.numpy.argmin(a, axis=None, out=None, keepdims=None)#

Returns the indices of the minimum values along an axis.

LAX-backend implementation of numpy.argmin.

Original docstring below.

Parameters:
  • a (array_like) – Input array.

  • axis (int, optional) – By default, the index is into the flattened array, otherwise along the specified axis.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array.

Return type:

Array

Returns:

index_array (ndarray of ints) – Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed. If keepdims is set to True, then the size of axis will be 1 with the resulting array having same shape as a.shape.

scico.numpy.argsort(a, axis=-1, kind='stable', order=None)#

Returns the indices that would sort an array.

LAX-backend implementation of numpy.argsort.

Only kind='stable' is supported. Other kind values will produce a warning and be treated as if they were 'stable'.

Original docstring below.

Perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in sorted order.

Parameters:
  • a (array_like) – Array to sort.

  • axis (int or None, optional) – Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used.

  • kind ({'quicksort', 'mergesort', 'heapsort', 'stable'}, optional) –

    Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort under the covers and, in general, the actual implementation will vary with data type. The ‘mergesort’ option is retained for backwards compatibility.

    Changed in version 1.15.0.: The ‘stable’ option was added.

  • order (str or list of str, optional) – When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.

Return type:

Array

Returns:

index_array (ndarray, int) – Array of indices that sort a along the specified axis. If a is one-dimensional, a[index_array] yields a sorted a. More generally, np.take_along_axis(a, index_array, axis=axis) always yields the sorted a, irrespective of dimensionality.

scico.numpy.argwhere(a, *, size=None, fill_value=None)#

Find the indices of array elements that are non-zero, grouped by element.

LAX-backend implementation of numpy.argwhere.

Because the size of the output of argwhere is data-dependent, the function is not typically compatible with JIT. The JAX version adds the optional size argument which must be specified statically for jnp.argwhere to be used within some of JAX’s transformations.

Original docstring below.

Parameters:
  • a (array_like) – Input data.

  • size (int, optional) – If specified, the indices of the first size True elements will be returned. If there are fewer results than size indicates, the return value will be padded with fill_value.

  • fill_value (array_like, optional) – When size is specified and there are fewer than the indicated number of elements, the remaining elements will be filled with fill_value, which defaults to zero.

Returns:

index_array ((N, a.ndim) ndarray) – Indices of elements that are non-zero. Indices are grouped by element. This array will have shape (N, a.ndim) where N is the number of non-zero items.

scico.numpy.around(a, decimals=0, out=None)#

Evenly round to the given number of decimals.

LAX-backend implementation of numpy.around.

Original docstring below.

Parameters:
  • a (array_like) – Input data.

  • decimals (int, optional) – Number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point.

Return type:

Array

Returns:

rounded_array (ndarray) – An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned.

The real and imaginary parts of complex numbers are rounded separately. The result of rounding a float is a float.

scico.numpy.array(object, dtype=None, copy=True, order='K', ndmin=0)#

Create an array.

LAX-backend implementation of numpy.array.

This function will create arrays on JAX’s default device. For control of the device placement of data, see jax.device_put. More information is available in the JAX FAQ at Controlling data and computation placement on devices (full FAQ at https://jax.readthedocs.io/en/latest/faq.html).

Original docstring below.

Parameters:
  • object (array_like) – An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. If object is a scalar, a 0-dimensional array containing object is returned.

  • dtype (data-type, optional) – The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence.

  • copy (bool, optional) – If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.).

  • order ({'K', 'A', 'C', 'F'}, optional) –

    Specify the memory layout of the array. If object is not an array, the newly created array will be in C order (row major) unless ‘F’ is specified, in which case it will be in Fortran order (column major). If object is an array the following holds.

    order

    no copy

    copy=True

    ’K’

    unchanged

    F & C order preserved, otherwise most similar order

    ’A’

    unchanged

    F order if input is F and not C, otherwise C order

    ’C’

    C order

    C order

    ’F’

    F order

    F order

    When copy=False and a copy is made for other reasons, the result is the same as if copy=True, with some exceptions for ‘A’, see the Notes section. The default order is ‘K’.

  • ndmin (int, optional) – Specifies the minimum number of dimensions that the resulting array should have. Ones will be prepended to the shape as needed to meet this requirement.

Return type:

Array

Returns:

out (ndarray) – An array object satisfying the specified requirements.

scico.numpy.array_equal(a1, a2, equal_nan=False)#

True if two arrays have the same shape and elements, False otherwise.

LAX-backend implementation of numpy.array_equal.

Original docstring below.

Parameters:
  • a1 (array_like) – Input arrays.

  • a2 (array_like) – Input arrays.

  • equal_nan (bool) – Whether to compare NaN’s as equal. If the dtype of a1 and a2 is complex, values will be considered equal if either the real or the imaginary component of a given value is nan.

Return type:

Array

Returns:

b (bool) – Returns True if the arrays are equal.

scico.numpy.array_equiv(a1, a2)#

Returns True if input arrays are shape consistent and all elements equal.

LAX-backend implementation of numpy.array_equiv.

Original docstring below.

Shape consistent means they are either the same shape, or one input array can be broadcasted to create the same shape as the other one.

Parameters:
  • a1 (array_like) – Input arrays.

  • a2 (array_like) – Input arrays.

Return type:

Array

Returns:

out (bool) – True if equivalent, False otherwise.

scico.numpy.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.      ])'
scico.numpy.array_split(ary, indices_or_sections, axis=0)#

Split an array into multiple sub-arrays.

LAX-backend implementation of numpy.array_split.

Original docstring below.

Please refer to the split documentation. The only difference between these functions is that array_split allows indices_or_sections to be an integer that does not equally divide the axis. For an array of length l that should be split into n sections, it returns l % n sub-arrays of size l//n + 1 and the rest of size l//n.

Return type:

List[Array]

scico.numpy.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]'
scico.numpy.asarray(a, dtype=None, order=None)#

Convert the input to an array.

LAX-backend implementation of numpy.asarray.

This function will create arrays on JAX’s default device. For control of the device placement of data, see jax.device_put. More information is available in the JAX FAQ at Controlling data and computation placement on devices (full FAQ at https://jax.readthedocs.io/en/latest/faq.html).

Original docstring below.

Parameters:
  • a (array_like) – Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.

  • dtype (data-type, optional) – By default, the data-type is inferred from the input data.

  • order ({'C', 'F', 'A', 'K'}, optional) – Memory layout. ‘A’ and ‘K’ depend on the order of input array a. ‘C’ row-major (C-style), ‘F’ column-major (Fortran-style) memory representation. ‘A’ (any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise ‘K’ (keep) preserve input order Defaults to ‘K’.

Return type:

Array

Returns:

out (ndarray) – Array interpretation of a. No copy is performed if the input is already an ndarray with matching dtype and order. If a is a subclass of ndarray, a base class ndarray is returned.

scico.numpy.atleast_1d(*arys)#

Convert inputs to arrays with at least one dimension.

LAX-backend implementation of numpy.atleast_1d.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.

Parameters:
  • arys1 (array_like) – One or more input arrays.

  • arys2 (array_like) – One or more input arrays.

  • ... (array_like) – One or more input arrays.

Return type:

Union[Array, List[Array]]

Returns:

ret (ndarray) – An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary.

scico.numpy.atleast_2d(*arys)#

View inputs as arrays with at least two dimensions.

LAX-backend implementation of numpy.atleast_2d.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

Parameters:
  • arys1 (array_like) – One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.

  • arys2 (array_like) – One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.

  • ... (array_like) – One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.

Return type:

Union[Array, List[Array]]

Returns:

res, res2, … (ndarray) – An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned.

scico.numpy.atleast_3d(*arys)#

View inputs as arrays with at least three dimensions.

LAX-backend implementation of numpy.atleast_3d.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

Parameters:
  • arys1 (array_like) – One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved.

  • arys2 (array_like) – One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved.

  • ... (array_like) – One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved.

Return type:

Union[Array, List[Array]]

Returns:

res1, res2, … (ndarray) – An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1).

scico.numpy.average(a, axis=None, weights=None, returned=False, keepdims=False)#

Compute the weighted average along the specified axis.

LAX-backend implementation of numpy.average.

Original docstring below.

Parameters:
  • a (array_like) – Array containing data to be averaged. If a is not an array, a conversion is attempted.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which to average a. The default, axis=None, will average over all of the elements of the input array. If axis is negative it counts from the last to the first axis.

  • weights (array_like, optional) –

    An array of weights associated with the values in a. Each value in a contributes to the average according to its associated weight. The weights array can either be 1-D (in which case its length must be the size of a along the given axis) or of the same shape as a. If weights=None, then all data in a are assumed to have a weight equal to one. The 1-D calculation is:

    avg = sum(a * weights) / sum(weights)
    

    The only constraint on weights is that sum(weights) must not be 0.

  • returned (bool, optional) – Default is False. If True, the tuple (average, sum_of_weights) is returned, otherwise only the average is returned. If weights=None, sum_of_weights is equivalent to the number of elements over which the average is taken.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a. Note: keepdims will not work with instances of numpy.matrix or other classes whose methods do not support keepdims.

Return type:

Union[Array, Tuple[Array, Array]]

Returns:

retval, [sum_of_weights] (array_type or double) – Return the average along the specified axis. When returned is True, return a tuple with the average as the first element and the sum of the weights as the second element. sum_of_weights is of the same type as retval. The result dtype follows a genereal pattern. If weights is None, the result dtype will be that of a , or float64 if a is integral. Otherwise, if weights is not None and a is non- integral, the result type will be the type of lowest precision capable of representing values of both a and weights. If a happens to be integral, the previous rules still applies but the result dtype will at least be float64.

scico.numpy.bartlett(M)#

Return the Bartlett window.

LAX-backend implementation of numpy.bartlett.

Original docstring below.

The Bartlett window is very similar to a triangular window, except that the end points are at zero. It is often used in signal processing for tapering a signal, without generating too much ripple in the frequency domain.

Parameters:

M (int) – Number of points in the output window. If zero or less, an empty array is returned.

Return type:

Array

Returns:

out (array) – The triangular window, with the maximum value normalized to one (the value one appears only if the number of samples is odd), with the first and last samples equal to zero.

scico.numpy.bincount(x, weights=None, minlength=0, *, length=None)#

Count number of occurrences of each value in array of non-negative ints.

LAX-backend implementation of numpy.bincount.

Jax adds the optional length parameter which specifies the output length, and defaults to x.max() + 1. It must be specified for bincount to be compiled with non-static operands. Values larger than the specified length will be discarded. If length is specified, minlength will be ignored.

Additionally, while np.bincount raises an error if the input array contains negative values, jax.numpy.bincount clips negative values to zero.

Original docstring below.

The number of bins (of size 1) is one larger than the largest value in x. If minlength is specified, there will be at least this number of bins in the output array (though it will be longer if necessary, depending on the contents of x). Each bin gives the number of occurrences of its index value in x. If weights is specified the input array is weighted by it, i.e. if a value n is found at position i, out[n] += weight[i] instead of out[n] += 1.

Parameters:
  • x (array_like, 1 dimension, nonnegative ints) – Input array.

  • weights (array_like, optional) – Weights, array of the same shape as x.

  • minlength (int, optional) – A minimum number of bins for the output array.

Return type:

Array

Returns:

out (ndarray of ints) – The result of binning the input array. The length of out is equal to np.amax(x)+1.

scico.numpy.blackman(M)#

Return the Blackman window.

LAX-backend implementation of numpy.blackman.

Original docstring below.

The Blackman window is a taper formed by using the first three terms of a summation of cosines. It was designed to have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser window.

Parameters:

M (int) – Number of points in the output window. If zero or less, an empty array is returned.

Return type:

Array

Returns:

out (ndarray) – The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd).

scico.numpy.block(arrays)#

Assemble an nd-array from nested lists of blocks.

LAX-backend implementation of numpy.block.

Original docstring below.

Blocks in the innermost lists are concatenated (see concatenate) along the last dimension (-1), then these are concatenated along the second-last dimension (-2), and so on until the outermost list is reached.

Blocks can be of any dimension, but will not be broadcasted using the normal rules. Instead, leading axes of size 1 are inserted, to make block.ndim the same for all blocks. This is primarily useful for working with scalars, and means that code like np.block([v, 1]) is valid, where v.ndim == 1.

When the nested list is two levels deep, this allows block matrices to be constructed from their components.

New in version 1.13.0.

Parameters:

arrays (nested list of array_like or scalars (but not tuples)) –

If passed a single ndarray or scalar (a nested list of depth 0), this is returned unmodified (and not copied).

Elements shapes must match along the appropriate axes (without broadcasting), but leading 1s will be prepended to the shape as necessary to make the dimensions match.

Return type:

Array

Returns:

block_array (ndarray) – The array assembled from the given blocks.

The dimensionality of the output is equal to the greatest of: * the dimensionality of all the inputs * the depth to which the input list is nested

scico.numpy.broadcast_arrays(*args)#

Broadcast any number of arrays against each other.

LAX-backend implementation of numpy.broadcast_arrays.

The JAX version does not necessarily return a view of the input.

Original docstring below.

Return type:

List[Array]

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 since version 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.

scico.numpy.broadcast_shapes(*shapes)#

Broadcast the input shapes into a single shape.

LAX-backend implementation of numpy.broadcast_shapes.

Original docstring below.

Learn more about broadcasting here.

New in version 1.20.0.

Returns:

tuple – Broadcasted shape.

scico.numpy.broadcast_to(array, shape)#

Broadcast an array to a new shape.

LAX-backend implementation of numpy.broadcast_to.

The JAX version does not necessarily return a view of the input.

Original docstring below.

Parameters:
  • array (array_like) – The array to broadcast.

  • shape (tuple or int) – The shape of the desired array. A single integer i is interpreted as (i,).

Return type:

Array

Returns:

broadcast (array) – A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location.

scico.numpy.can_cast(from_, to, casting='safe')#

Returns True if cast between data types can occur according to the casting rule. If from is a scalar or array scalar, also returns True if the scalar value can be cast without overflow or truncation to an integer.

Parameters:
  • from (dtype, dtype specifier, scalar, or array) – Data type, scalar, or array to cast from.

  • to (dtype or dtype specifier) – Data type to cast to.

  • casting ({'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional) –

    Controls what kind of data casting may occur.

    • ’no’ means the data types should not be cast at all.

    • ’equiv’ means only byte-order changes are allowed.

    • ’safe’ means only casts which can preserve values are allowed.

    • ’same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.

    • ’unsafe’ means any data conversions may be done.

Returns:

out (bool) – True if cast can occur according to the casting rule.

Notes

Changed in version 1.17.0: Casting between a simple data type and a structured one is possible only for “unsafe” casting. Casting to multiple fields is allowed, but casting from multiple fields is not.

Changed in version 1.9.0: Casting from numeric to string types in ‘safe’ casting mode requires that the string dtype length is long enough to store the maximum integer/float value converted.

See also

dtype, result_type

Examples

Basic examples

>>> np.can_cast(np.int32, np.int64)
True
>>> np.can_cast(np.float64, complex)
True
>>> np.can_cast(complex, float)
False
>>> np.can_cast('i8', 'f8')
True
>>> np.can_cast('i8', 'f4')
False
>>> np.can_cast('i4', 'S4')
False

Casting scalars

>>> np.can_cast(100, 'i1')
True
>>> np.can_cast(150, 'i1')
False
>>> np.can_cast(150, 'u1')
True
>>> np.can_cast(3.5e100, np.float32)
False
>>> np.can_cast(1000.0, np.float32)
True

Array scalar checks the value, array does not

>>> np.can_cast(np.array(1000.0), np.float32)
True
>>> np.can_cast(np.array([1000.0]), np.float32)
False

Using the casting rules

>>> np.can_cast('i8', 'i8', 'no')
True
>>> np.can_cast('<i8', '>i8', 'no')
False
>>> np.can_cast('<i8', '>i8', 'equiv')
True
>>> np.can_cast('<i4', '>i8', 'equiv')
False
>>> np.can_cast('<i4', '>i8', 'safe')
True
>>> np.can_cast('<i8', '>i4', 'safe')
False
>>> np.can_cast('<i8', '>i4', 'same_kind')
True
>>> np.can_cast('<i8', '>u4', 'same_kind')
False
>>> np.can_cast('<i8', '>u4', 'unsafe')
True
scico.numpy.cbrt(x, /)#

Return the cube-root of an array, element-wise.

LAX-backend implementation of numpy.cbrt.

Original docstring below.

New in version 1.10.0.

Parameters:

x (array_like) – The values whose cube-roots are required.

Returns:

y (ndarray) – An array of the same shape as x, containing the cube cube-root of each element in x. If out was provided, y is a reference to it. This is a scalar if x is a scalar.

scico.numpy.ceil(x, /)#

Return the ceiling of the input, element-wise.

LAX-backend implementation of numpy.ceil.

Original docstring below.

The ceil of the scalar x is the smallest integer i, such that i >= x. It is often denoted as \(\lceil x \rceil\).

Parameters:

x (array_like) – Input data.

Returns:

y (ndarray or scalar) – The ceiling of each element in x, with float dtype. This is a scalar if x is a scalar.

scico.numpy.choose(a, choices, out=None, mode='raise')#

Construct an array from an index array and a list of arrays to choose from.

LAX-backend implementation of numpy.choose.

Original docstring below.

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”.

  • 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

Return type:

Array

Returns:

merged_array (array) – The merged result.

scico.numpy.clip(a, a_min=None, a_max=None, out=None)#

Clip (limit) the values in an array.

LAX-backend implementation of numpy.clip.

Original docstring below.

Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1.

Equivalent to but faster than np.minimum(a_max, np.maximum(a, a_min)).

No check is performed to ensure a_min < a_max.

Parameters:
  • a (array_like) – Array containing elements to clip.

  • a_min (array_like or None) – Minimum and maximum value. If None, clipping is not performed on the corresponding edge. Only one of a_min and a_max may be None. Both are broadcast against a.

  • a_max (array_like or None) – Minimum and maximum value. If None, clipping is not performed on the corresponding edge. Only one of a_min and a_max may be None. Both are broadcast against a.

Return type:

Array

Returns:

clipped_array (ndarray) – An array with the elements of a, but where values < a_min are replaced with a_min, and those > a_max with a_max.

scico.numpy.column_stack(tup)#

Stack 1-D arrays as columns into a 2-D array.

LAX-backend implementation of numpy.column_stack.

Original docstring below.

Take a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D arrays are stacked as-is, just like with hstack. 1-D arrays are turned into 2-D columns first.

Parameters:

tup (sequence of 1-D or 2-D arrays.) – Arrays to stack. All of them must have the same first dimension.

Return type:

Array

Returns:

stacked (2-D array) – The array formed by stacking the given arrays.

scico.numpy.compress(condition, a, axis=None, out=None)#

Return selected slices of an array along given axis.

LAX-backend implementation of numpy.compress.

Original docstring below.

When working along a given axis, a slice along that axis is returned in output for each index where condition evaluates to True. When working on a 1-D array, compress is equivalent to extract.

Parameters:
  • condition (1-D array of bools) – Array that selects which entries to return. If len(condition) is less than the size of a along the given axis, then output is truncated to the length of the condition array.

  • a (array_like) – Array from which to extract a part.

  • axis (int, optional) – Axis along which to take slices. If None (default), work on the flattened array.

Return type:

Array

Returns:

compressed_array (ndarray) – A copy of a without the slices along axis for which condition is false.

scico.numpy.concatenate(arrays, axis=0, dtype=None)#

Join a sequence of arrays along an existing axis.

LAX-backend implementation of numpy.concatenate.

Original docstring below.

Parameters:
  • axis (int, optional) – The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.

  • dtype (str or dtype) – If provided, the destination array will have this dtype. Cannot be provided together with out.

Return type:

Array

Returns:

res (ndarray) – The concatenated array.

scico.numpy.conj(x, /)#

Return the complex conjugate, element-wise.

LAX-backend implementation of numpy.conjugate.

Original docstring below.

The complex conjugate of a complex number is obtained by changing the sign of its imaginary part.

Parameters:

x (array_like) – Input value.

Return type:

Array

Returns:

y (ndarray) – The complex conjugate of x, with same dtype as y. This is a scalar if x is a scalar.

scico.numpy.conjugate(x, /)#

Return the complex conjugate, element-wise.

LAX-backend implementation of numpy.conjugate.

Original docstring below.

The complex conjugate of a complex number is obtained by changing the sign of its imaginary part.

Parameters:

x (array_like) – Input value.

Return type:

Array

Returns:

y (ndarray) – The complex conjugate of x, with same dtype as y. This is a scalar if x is a scalar.

scico.numpy.convolve(a, v, mode='full', *, precision=None)#

Returns the discrete, linear convolution of two one-dimensional sequences.

LAX-backend implementation of numpy.convolve.

In addition to the original NumPy arguments listed below, also supports precision for extra control over matrix-multiplication precision on supported devices. precision may be set to None, which means default precision for the backend, a Precision enum value (Precision.DEFAULT, Precision.HIGH or Precision.HIGHEST) or a tuple of two Precision enums indicating separate precision for each argument.

Original docstring below.

The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal. In probability theory, the sum of two independent random variables is distributed according to the convolution of their individual distributions.

If v is longer than a, the arrays are swapped before computation.

Parameters:
  • a ((N,) array_like) – First one-dimensional input array.

  • v ((M,) array_like) – Second one-dimensional input array.

  • mode ({'full', 'valid', 'same'}, optional) –

    ‘full’:

    By default, mode is ‘full’. This returns the convolution at each point of overlap, with an output shape of (N+M-1,). At the end-points of the convolution, the signals do not overlap completely, and boundary effects may be seen.

    ’same’:

    Mode ‘same’ returns output of length max(M, N). Boundary effects are still visible.

    ’valid’:

    Mode ‘valid’ returns output of length max(M, N) - min(M, N) + 1. The convolution product is only given for points where the signals overlap completely. Values outside the signal boundary have no effect.

Return type:

Array

Returns:

out (ndarray) – Discrete, linear convolution of a and v.

scico.numpy.copy(a, order=None)#

Return an array copy of the given object.

LAX-backend implementation of numpy.copy.

This function will create arrays on JAX’s default device. For control of the device placement of data, see jax.device_put. More information is available in the JAX FAQ at Controlling data and computation placement on devices (full FAQ at https://jax.readthedocs.io/en/latest/faq.html).

Original docstring below.

Parameters:
  • a (array_like) – Input data.

  • order ({'C', 'F', 'A', 'K'}, optional) – Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. (Note that this function and ndarray.copy are very similar, but have different default values for their order= arguments.)

Return type:

Array

Returns:

arr (ndarray) – Array interpretation of a.

scico.numpy.copysign(x1, x2, /)#

Change the sign of x1 to that of x2, element-wise.

LAX-backend implementation of numpy.copysign.

Original docstring below.

If x2 is a scalar, its sign will be copied to all elements of x1.

Parameters:
  • x1 (array_like) – Values to change the sign of.

  • x2 (array_like) – The sign of x2 is copied to x1. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Return type:

Array

Returns:

out (ndarray or scalar) – The values of x1 with the sign of x2. This is a scalar if both x1 and x2 are scalars.

scico.numpy.cos(x, /)#

Cosine element-wise.

LAX-backend implementation of numpy.cos.

Original docstring below.

Parameters:

x (array_like) – Input array in radians.

Returns:

y (ndarray) – The corresponding cosine values. This is a scalar if x is a scalar.

scico.numpy.cosh(x, /)#

Hyperbolic cosine, element-wise.

LAX-backend implementation of numpy.cosh.

Original docstring below.

Equivalent to 1/2 * (np.exp(x) + np.exp(-x)) and np.cos(1j*x).

Parameters:

x (array_like) – Input array.

Returns:

out (ndarray or scalar) – Output array of same shape as x. This is a scalar if x is a scalar.

scico.numpy.count_nonzero(a, axis=None, keepdims=False)#

Counts the number of non-zero values in the array a.

LAX-backend implementation of numpy.count_nonzero.

Original docstring below.

The word “non-zero” is in reference to the Python 2.x built-in method __nonzero__() (renamed __bool__() in Python 3.x) of Python objects that tests an object’s “truthfulness”. For example, any number is considered truthful if it is nonzero, whereas any string is considered truthful if it is not the empty string. Thus, this function (recursively) counts how many elements in a (and in sub-arrays thereof) have their __nonzero__() or __bool__() method evaluated to True.

Parameters:
  • a (array_like) – The array for which to count non-zeros.

  • axis (int or tuple, optional) – Axis or tuple of axes along which to count non-zeros. Default is None, meaning that non-zeros will be counted along a flattened version of a.

  • keepdims (bool, optional) – If this is set to True, the axes that are counted are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

Return type:

Array

Returns:

count (int or array of int) – Number of non-zero values in the array along a given axis. Otherwise, the total number of non-zero values in the array is returned.

scico.numpy.cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None)#

Return the cross product of two (arrays of) vectors.

LAX-backend implementation of numpy.cross.

Original docstring below.

The cross product of a and b in \(R^3\) is a vector perpendicular to both a and b. If a and b are arrays of vectors, the vectors are defined by the last axis of a and b by default, and these axes can have dimensions 2 or 3. Where the dimension of either a or b is 2, the third component of the input vector is assumed to be zero and the cross product calculated accordingly. In cases where both input vectors have dimension 2, the z-component of the cross product is returned.

Parameters:
  • a (array_like) – Components of the first vector(s).

  • b (array_like) – Components of the second vector(s).

  • axisa (int, optional) – Axis of a that defines the vector(s). By default, the last axis.

  • axisb (int, optional) – Axis of b that defines the vector(s). By default, the last axis.

  • axisc (int, optional) – Axis of c containing the cross product vector(s). Ignored if both input vectors have dimension 2, as the return is scalar. By default, the last axis.

  • axis (int, optional) – If defined, the axis of a, b and c that defines the vector(s) and cross product(s). Overrides axisa, axisb and axisc.

Returns:

c (ndarray) – Vector cross product(s).

scico.numpy.cumprod(a, axis=None, dtype=None, out=None)#

Return the cumulative product of elements along a given axis.

LAX-backend implementation of numpy.cumprod.

Original docstring below.

Parameters:
  • a (array_like) – Input array.

  • axis (int, optional) – Axis along which the cumulative product is computed. By default the input is flattened.

  • dtype (dtype, optional) – Type of the returned array, as well as of the accumulator in which the elements are multiplied. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used instead.

Return type:

Array

Returns:

cumprod (ndarray) – A new array holding the result is returned unless out is specified, in which case a reference to out is returned.

scico.numpy.cumsum(a, axis=None, dtype=None, out=None)#

Return the cumulative sum of the elements along a given axis.

LAX-backend implementation of numpy.cumsum.

Original docstring below.

Parameters:
  • a (array_like) – Input array.

  • axis (int, optional) – Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.

  • dtype (dtype, optional) – Type of the returned array and of the accumulator in which the elements are summed. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.

Return type:

Array

Returns:

cumsum_along_axis (ndarray.) – A new array holding the result is returned unless out is specified, in which case a reference to out is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array.

scico.numpy.deg2rad(x, /)#

Convert angles from degrees to radians.

LAX-backend implementation of numpy.deg2rad.

Original docstring below.

Parameters:

x (array_like) – Angles in degrees.

Return type:

Array

Returns:

y (ndarray) – The corresponding angle in radians. This is a scalar if x is a scalar.

scico.numpy.degrees(x, /)#

Convert angles from radians to degrees.

LAX-backend implementation of numpy.rad2deg.

Original docstring below.

Parameters:

x (array_like) – Angle in radians.

Return type:

Array

Returns:

y (ndarray) – The corresponding angle in degrees. This is a scalar if x is a scalar.

scico.numpy.delete(arr, obj, axis=None, *, assume_unique_indices=False)#

Return a new array with sub-arrays along an axis deleted. For a one

LAX-backend implementation of numpy.delete.

delete() usually requires the index specification to be static. If the index is an integer array that is guaranteed to contain unique entries, you may specify assume_unique_indices=True to perform the operation in a manner that does not require static indices.

Original docstring below.

dimensional array, this returns those entries not returned by arr[obj].

Parameters:
  • arr (array_like) – Input array.

  • obj (slice, int or array of ints) –

    Indicate indices of sub-arrays to remove along the specified axis.

    Changed in version 1.19.0: Boolean indices are now treated as a mask of elements to remove, rather than being cast to the integers 0 and 1.

  • axis (int, optional) – The axis along which to delete the subarray defined by obj. If axis is None, obj is applied to the flattened array.

  • assume_unique_indices (int, optional (default=False)) – In case of array-like integer (not boolean) indices, assume the indices are unique, and perform the deletion in a way that is compatible with JIT and other JAX transformations.

Returns:

out (ndarray) – A copy of arr with the elements specified by obj removed. Note that delete does not occur in-place. If axis is None, out is a flattened array.

scico.numpy.diag(v, k=0)#

Extract a diagonal or construct a diagonal array.

LAX-backend implementation of numpy.diag.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

See the more detailed documentation for numpy.diagonal if you use this function to extract a diagonal and wish to write to the resulting array; whether it returns a copy or a view depends on what version of numpy you are using.

Parameters:
  • v (array_like) – If v is a 2-D array, return a copy of its k-th diagonal. If v is a 1-D array, return a 2-D array with v on the k-th diagonal.

  • k (int, optional) – Diagonal in question. The default is 0. Use k>0 for diagonals above the main diagonal, and k<0 for diagonals below the main diagonal.

Returns:

out (ndarray) – The extracted diagonal or constructed diagonal array.

scico.numpy.diag_indices(n, ndim=2)#

Return the indices to access the main diagonal of an array.

LAX-backend implementation of numpy.diag_indices.

Original docstring below.

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.

scico.numpy.diag_indices_from(arr)#

Return the indices to access the main diagonal of an n-dimensional array.

LAX-backend implementation of numpy.diag_indices_from.

Original docstring below.

See diag_indices for full details.

Parameters:

arr (array, at least 2-D) –

scico.numpy.diagflat(v, k=0)#

Create a two-dimensional array with the flattened input as a diagonal.

LAX-backend implementation of numpy.diagflat.

This differs from np.diagflat for some scalar values of v, jax always returns a two-dimensional array, whereas numpy may return a scalar depending on the type of v.

Original docstring below.

Parameters:
  • v (array_like) – Input data, which is flattened and set as the k-th diagonal of the output.

  • k (int, optional) – Diagonal to set; 0, the default, corresponds to the “main” diagonal, a positive (negative) k giving the number of the diagonal above (below) the main.

Returns:

out (ndarray) – The 2-D output array.

scico.numpy.diff(a, n=1, axis=-1, prepend=None, append=None)#

Calculate the n-th discrete difference along the given axis.

LAX-backend implementation of numpy.diff.

Original docstring below.

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 (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.

  • 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.

Return type:

Array

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.

scico.numpy.divide(x1, x2, /)#

Divide arguments element-wise.

LAX-backend implementation of numpy.divide.

Original docstring below.

Parameters:
  • x1 (array_like) – Dividend array.

  • x2 (array_like) – Divisor array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Return type:

Array

Returns:

y (ndarray or scalar) – The quotient x1/x2, element-wise. This is a scalar if both x1 and x2 are scalars.

scico.numpy.divmod(x1, x2, /)#

Return element-wise quotient and remainder simultaneously.

LAX-backend implementation of numpy.divmod.

Original docstring below.

New in version 1.13.0.

np.divmod(x, y) is equivalent to (x // y, x % y), but faster because it avoids redundant work. It is used to implement the Python built-in function divmod on NumPy arrays.

Parameters:
  • x1 (array_like) – Dividend array.

  • x2 (array_like) – Divisor array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Return type:

Tuple[Array, Array]

Returns:

  • out1 (ndarray) – Element-wise quotient resulting from floor division. This is a scalar if both x1 and x2 are scalars.

  • out2 (ndarray) – Element-wise remainder from floor division. This is a scalar if both x1 and x2 are scalars.

scico.numpy.dot(a, b, *, precision=None)#

Dot product of two arrays. Specifically,

LAX-backend implementation of numpy.dot.

In addition to the original NumPy arguments listed below, also supports precision for extra control over matrix-multiplication precision on supported devices. precision may be set to None, which means default precision for the backend, a Precision enum value (Precision.DEFAULT, Precision.HIGH or Precision.HIGHEST) or a tuple of two Precision enums indicating separate precision for each argument.

Original docstring below.

  • If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).

  • If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.

  • If either a or b is 0-D (scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a * b is preferred.

  • If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.

  • If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b:

    dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
    

It uses an optimized BLAS library when possible (see numpy.linalg).

Parameters:
  • a (array_like) – First argument.

  • b (array_like) – Second argument.

Returns:

output (ndarray) – Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If out is given, then it is returned.

scico.numpy.dsplit(ary, indices_or_sections)#

Split array into multiple sub-arrays along the 3rd axis (depth).

LAX-backend implementation of numpy.dsplit.

Original docstring below.

Please refer to the split documentation. dsplit is equivalent to split with axis=2, the array is always split along the third axis provided the array dimension is greater than or equal to 3.

Return type:

List[Array]

scico.numpy.dstack(tup, dtype=None)#

Stack arrays in sequence depth wise (along third axis).

LAX-backend implementation of numpy.dstack.

Original docstring below.

This is equivalent to concatenation along the third axis after 2-D arrays of shape (M,N) have been reshaped to (M,N,1) and 1-D arrays of shape (N,) have been reshaped to (1,N,1). Rebuilds arrays divided by dsplit.

This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations.

Parameters:

tup (sequence of arrays) – The arrays must have the same shape along all but the third axis. 1-D or 2-D arrays must have the same shape.

Return type:

Array

Returns:

stacked (ndarray) – The array formed by stacking the given arrays, will be at least 3-D.

scico.numpy.ediff1d(ary, to_end=None, to_begin=None)#

The differences between consecutive elements of an array.

LAX-backend implementation of numpy.ediff1d.

Unlike NumPy’s implementation of ediff1d, jax.numpy.ediff1d will not issue an error if casting to_end or to_begin to the type of ary loses precision.

Original docstring below.

Parameters:
  • ary (array_like) – If necessary, will be flattened before the differences are taken.

  • to_end (array_like, optional) – Number(s) to append at the end of the returned differences.

  • to_begin (array_like, optional) – Number(s) to prepend at the beginning of the returned differences.

Return type:

Array

Returns:

ediff1d (ndarray) – The differences. Loosely, this is ary.flat[1:] - ary.flat[:-1].

scico.numpy.einsum(subscripts, /, *operands, out=None, optimize='optimal', precision=None, preferred_element_type=None, _use_xeinsum=False, _dot_general=<function dot_general>)#

Evaluates the Einstein summation convention on the operands.

LAX-backend implementation of numpy.einsum.

In addition to the original NumPy arguments listed below, also supports precision for extra control over matrix-multiplication precision on supported devices. precision may be set to None, which means default precision for the backend, a Precision enum value (Precision.DEFAULT, Precision.HIGH or Precision.HIGHEST) or a tuple of two Precision enums indicating separate precision for each argument. A tuple precision does not necessarily map to multiple arguments of einsum(); rather, the specified precision is forwarded to each dot_general call used in the implementation.

Original docstring below.

Using the Einstein summation convention, many common multi-dimensional, linear algebraic array operations can be represented in a simple fashion. In implicit mode einsum computes these values.

In explicit mode, einsum provides further flexibility to compute other array operations that might not be considered classical Einstein summation operations, by disabling, or forcing summation over specified subscript labels.

See the notes and examples for clarification.

Parameters:
  • subscripts (str) – Specifies the subscripts for summation as comma separated list of subscript labels. An implicit (classical Einstein summation) calculation is performed unless the explicit indicator ‘->’ is included as well as subscript labels of the precise output form.

  • operands (list of array_like) – These are the arrays for the operation.

  • optimize ({False, True, 'greedy', 'optimal'}, optional) – Controls if intermediate optimization should occur. No optimization will occur if False and True will default to the ‘greedy’ algorithm. Also accepts an explicit contraction list from the np.einsum_path function. See np.einsum_path for more details. Defaults to False.

Return type:

Array

Returns:

output (ndarray) – The calculation based on the Einstein summation convention.

scico.numpy.einsum_path(subscripts, *operands, optimize='greedy')#

Evaluates the lowest cost contraction order for an einsum expression by

LAX-backend implementation of numpy.einsum_path.

Original docstring below.

considering the creation of intermediate arrays.

Parameters:
  • subscripts (str) – Specifies the subscripts for summation.

  • *operands (list of array_like) – These are the arrays for the operation.

  • optimize ({bool, list, tuple, 'greedy', 'optimal'}) –

    Choose the type of path. If a tuple is provided, the second argument is assumed to be the maximum intermediate size created. If only a single argument is provided the largest input or output array size is used as a maximum intermediate size.

    • if a list is given that starts with einsum_path, uses this as the contraction path

    • if False no optimization is taken

    • if True defaults to the ‘greedy’ algorithm

    • ’optimal’ An algorithm that combinatorially explores all possible ways of contracting the listed tensors and choosest the least costly path. Scales exponentially with the number of terms in the contraction.

    • ’greedy’ An algorithm that chooses the best pair contraction at each step. Effectively, this algorithm searches the largest inner, Hadamard, and then outer products at each step. Scales cubically with the number of terms in the contraction. Equivalent to the ‘optimal’ path for most contractions.

    Default is ‘greedy’.

Returns:

  • path (list of tuples) – A list representation of the einsum path.

  • string_repr (str) – A printable representation of the einsum path.

scico.numpy.empty(shape, dtype=None)#

Return a new array of given shape and type, without initializing entries.

LAX-backend implementation of numpy.empty.

Because XLA cannot create uninitialized arrays, the JAX version will return an array initialized with zeros.

Original docstring below.

Parameters:
  • shape (int or tuple of int) – Shape of the empty array, e.g., (2, 3) or 2.

  • dtype (data-type, optional) – Desired output data-type for the array, e.g, numpy.int8. Default is numpy.float64.

Return type:

Array

Returns:

out (ndarray) – Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.

scico.numpy.empty_like(prototype, dtype=None, shape=None)#

Return a new array with the same shape and type as a given array.

LAX-backend implementation of numpy.empty_like.

Because XLA cannot create uninitialized arrays, the JAX version will return an array initialized with zeros.

Original docstring below.

Parameters:
  • prototype (array_like) – The shape and data-type of prototype define these same attributes of the returned array.

  • dtype (data-type, optional) – Overrides the data type of the result.

  • shape (int or sequence of ints, optional.) – Overrides the shape of the result. If order=’K’ and the number of dimensions is unchanged, will try to keep order, otherwise, order=’C’ is implied.

Return type:

Array

Returns:

out (ndarray) – Array of uninitialized (arbitrary) data with the same shape and type as prototype.

scico.numpy.equal(x1, x2, /)#

Return (x1 == x2) element-wise.

LAX-backend implementation of numpy.equal.

Original docstring below.

Parameters:
  • x1 (array_like) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Returns:

out (ndarray or scalar) – Output array, element-wise comparison of x1 and x2. Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars.

scico.numpy.exp(x, /)#

Calculate the exponential of all elements in the input array.

LAX-backend implementation of numpy.exp.

Original docstring below.

Parameters:

x (array_like) – Input values.

Returns:

out (ndarray or scalar) – Output array, element-wise exponential of x. This is a scalar if x is a scalar.

scico.numpy.exp2(x, /)#

Calculate 2**p for all p in the input array.

LAX-backend implementation of numpy.exp2.

Original docstring below.

Parameters:

x (array_like) – Input values.

Return type:

Array

Returns:

out (ndarray or scalar) – Element-wise 2 to the power x. This is a scalar if x is a scalar.

scico.numpy.expand_dims(a, axis)#

Expand the shape of an array.

LAX-backend implementation of numpy.expand_dims.

Original docstring below.

Insert a new axis that will appear at the axis position in the expanded array shape.

Parameters:
  • a (array_like) – Input array.

  • axis (int or tuple of ints) –

    Position in the expanded axes where the new axis (or axes) is placed.

    Deprecated since version 1.13.0: Passing an axis where axis > a.ndim will be treated as axis == a.ndim, and passing axis < -a.ndim - 1 will be treated as axis == 0. This behavior is deprecated.

    Changed in version 1.18.0: A tuple of axes is now supported. Out of range axes as described above are now forbidden and raise an AxisError.

Return type:

Array

Returns:

result (ndarray) – View of a with the number of dimensions increased.

scico.numpy.expm1(x, /)#

Calculate exp(x) - 1 for all elements in the array.

LAX-backend implementation of numpy.expm1.

Original docstring below.

Parameters:

x (array_like) – Input values.

Returns:

out (ndarray or scalar) – Element-wise exponential minus one: out = exp(x) - 1. This is a scalar if x is a scalar.

scico.numpy.extract(condition, arr)#

Return the elements of an array that satisfy some condition.

LAX-backend implementation of numpy.extract.

Original docstring below.

This is equivalent to np.compress(ravel(condition), ravel(arr)). If condition is boolean np.extract is equivalent to arr[condition].

Note that place does the exact opposite of extract.

Parameters:
  • condition (array_like) – An array whose nonzero or True entries indicate the elements of arr to extract.

  • arr (array_like) – Input array of the same size as condition.

Return type:

Array

Returns:

extract (ndarray) – Rank 1 array of values from arr where condition is True.

scico.numpy.eye(N, M=None, k=0, dtype=None)#

Return a 2-D array with ones on the diagonal and zeros elsewhere.

LAX-backend implementation of numpy.eye.

Original docstring below.

Parameters:
  • N (int) – Number of rows in the output.

  • M (int, optional) – Number of columns in the output. If None, defaults to N.

  • k (int, optional) – Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal.

  • dtype (data-type, optional) – Data-type of the returned array.

Return type:

Array

Returns:

I (ndarray of shape (N,M)) – An array where all elements are equal to zero, except for the k-th diagonal, whose values are equal to one.

scico.numpy.fabs(x, /)#

Compute the absolute values element-wise.

LAX-backend implementation of numpy.fabs.

Original docstring below.

This function returns the absolute values (positive magnitude) of the data in x. Complex values are not handled, use absolute to find the absolute values of complex data.

Parameters:

x (array_like) – The array of numbers for which the absolute values are required. If x is a scalar, the result y will also be a scalar.

Returns:

y (ndarray or scalar) – The absolute values of x, the returned values are always floats. This is a scalar if x is a scalar.

scico.numpy.fix(x, out=None)#

Round to nearest integer towards zero.

LAX-backend implementation of numpy.fix.

Original docstring below.

Round an array of floats element-wise to nearest integer towards zero. The rounded values are returned as floats.

Parameters:

x (array_like) – An array of floats to be rounded

Return type:

Array

Returns:

out (ndarray of floats) – A float array with the same dimensions as the input. If second argument is not supplied then a float array is returned with the rounded values.

If a second argument is supplied the result is stored there. The return value out is then a reference to that array.

scico.numpy.flatnonzero(a, *, size=None, fill_value=None)#

Return indices that are non-zero in the flattened version of a.

LAX-backend implementation of numpy.flatnonzero.

Because the size of the output of nonzero is data-dependent, the function is not typically compatible with JIT. The JAX version adds the optional size argument which must be specified statically for jnp.nonzero to be used within some of JAX’s transformations.

Original docstring below.

This is equivalent to np.nonzero(np.ravel(a))[0].

Parameters:
  • a (array_like) – Input data.

  • size (int, optional) – If specified, the indices of the first size True elements will be returned. If there are fewer unique elements than size indicates, the return value will be padded with fill_value.

  • fill_value (array_like, optional) – When size is specified and there are fewer than the indicated number of elements, the remaining elements will be filled with fill_value, which defaults to zero.

Return type:

Array

Returns:

res (ndarray) – Output array, containing the indices of the elements of a.ravel() that are non-zero.

scico.numpy.flip(m, axis=None)#

Reverse the order of elements in an array along the given axis.

LAX-backend implementation of numpy.flip.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

The shape of the array is preserved, but the elements are reordered.

New in version 1.12.0.

Parameters:
  • m (array_like) – Input array.

  • axis (None or int or tuple of ints, optional) –

    Axis or axes along which to flip over. The default, axis=None, will flip over all of the axes of the input array. If axis is negative it counts from the last to the first axis.

    If axis is a tuple of ints, flipping is performed on all of the axes specified in the tuple.

    Changed in version 1.15.0: None and tuples of axes are supported

Return type:

Array

Returns:

out (array_like) – A view of m with the entries of axis reversed. Since a view is returned, this operation is done in constant time.

scico.numpy.fliplr(m)#

Reverse the order of elements along axis 1 (left/right).

LAX-backend implementation of numpy.fliplr.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

For a 2-D array, this flips the entries in each row in the left/right direction. Columns are preserved, but appear in a different order than before.

Parameters:

m (array_like) – Input array, must be at least 2-D.

Return type:

Array

Returns:

f (ndarray) – A view of m with the columns reversed. Since a view is returned, this operation is \(\mathcal O(1)\).

scico.numpy.flipud(m)#

Reverse the order of elements along axis 0 (up/down).

LAX-backend implementation of numpy.flipud.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

For a 2-D array, this flips the entries in each column in the up/down direction. Rows are preserved, but appear in a different order than before.

Parameters:

m (array_like) – Input array.

Return type:

Array

Returns:

out (array_like) – A view of m with the rows reversed. Since a view is returned, this operation is \(\mathcal O(1)\).

scico.numpy.float_power(x1, x2, /)#

First array elements raised to powers from second array, element-wise.

LAX-backend implementation of numpy.float_power.

Original docstring below.

Raise each base in x1 to the positionally-corresponding power in x2. x1 and x2 must be broadcastable to the same shape. This differs from the power function in that integers, float16, and float32 are promoted to floats with a minimum precision of float64 so that the result is always inexact. The intent is that the function will return a usable result for negative powers and seldom overflow for positive powers.

Negative values raised to a non-integral value will return nan. To get complex results, cast the input to complex, or specify the dtype to be complex (see the example below).

New in version 1.12.0.

Parameters:
  • x1 (array_like) – The bases.

  • x2 (array_like) – The exponents. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Returns:

y (ndarray) – The bases in x1 raised to the exponents in x2. This is a scalar if both x1 and x2 are scalars.

scico.numpy.floor(x, /)#

Return the floor of the input, element-wise.

LAX-backend implementation of numpy.floor.

Original docstring below.

The floor of the scalar x is the largest integer i, such that i <= x. It is often denoted as \(\lfloor x \rfloor\).

Parameters:

x (array_like) – Input data.

Returns:

y (ndarray or scalar) – The floor of each element in x. This is a scalar if x is a scalar.

scico.numpy.floor_divide(x1, x2, /)#

Return the largest integer smaller or equal to the division of the inputs.

LAX-backend implementation of numpy.floor_divide.

Original docstring below.

It is equivalent to the Python // operator and pairs with the Python % (remainder), function so that a = a % b + b * (a // b) up to roundoff.

Parameters:
  • x1 (array_like) – Numerator.

  • x2 (array_like) – Denominator. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

Return type:

Array

Returns:

y (ndarray) – y = floor(x1/x2) This is a scalar if both x1 and x2 are scalars.

scico.numpy.fmax(x1, x2)#

Element-wise maximum of array elements.

LAX-backend implementation of numpy.fmax.

Original docstring below.

Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are ignored when possible.

Parameters:
  • x1 (array_like) – The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Return type:

Array

Returns:

y (ndarray or scalar) – The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

scico.numpy.fmin(x1, x2)#

Element-wise minimum of array elements.

LAX-backend implementation of numpy.fmin.

Original docstring below.

Compare two arrays and returns a new array containing the element-wise minima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are ignored when possible.

Parameters:
  • x1 (array_like) – The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Return type:

Array

Returns:

y (ndarray or scalar) – The minimum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

scico.numpy.fmod(x1, x2, /)#

Returns the element-wise remainder of division.

LAX-backend implementation of numpy.fmod.

Original docstring below.

This is the NumPy implementation of the C library function fmod, the remainder has the same sign as the dividend x1. It is equivalent to the Matlab(TM) rem function and should not be confused with the Python modulus operator x1 % x2.

Parameters:
  • x1 (array_like) – Dividend.

  • x2 (array_like) – Divisor. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Return type:

Array

Returns:

y (array_like) – The remainder of the division of x1 by x2. This is a scalar if both x1 and x2 are scalars.

scico.numpy.frexp(x, /)#

Decompose the elements of x into mantissa and twos exponent.

LAX-backend implementation of numpy.frexp.

Original docstring below.

Returns (mantissa, exponent), where x = mantissa * 2**exponent. The mantissa lies in the open interval(-1, 1), while the twos exponent is a signed integer.

Parameters:

x (array_like) – Array of numbers to be decomposed.

Return type:

Tuple[Array, Array]

Returns:

  • mantissa (ndarray) – Floating values between -1 and 1. This is a scalar if x is a scalar.

  • exponent (ndarray) – Integer exponents of 2. This is a scalar if x is a scalar.

scico.numpy.from_dlpack(x)#

Create a NumPy array from an object implementing the __dlpack__

LAX-backend implementation of numpy.from_dlpack.

Original docstring below.

protocol. Generally, the returned NumPy array is a read-only view of the input object. See and for more details.

Parameters:

x (object) – A Python object that implements the __dlpack__ and __dlpack_device__ methods.

Return type:

Array

Returns:

out (ndarray)

scico.numpy.frombuffer(buffer, dtype=<class 'float'>, count=-1, offset=0)#

Interpret a buffer as a 1-dimensional array.

LAX-backend implementation of numpy.frombuffer.

Original docstring below.

Parameters:
  • buffer (buffer_like) – An object that exposes the buffer interface.

  • dtype (data-type, optional) – Data-type of the returned array; default: float.

  • count (int, optional) – Number of items to read. -1 means all data in the buffer.

  • offset (int, optional) – Start reading the buffer from this offset (in bytes); default: 0.

Return type:

Array

Returns:

out (ndarray)

scico.numpy.fromfile(*args, **kwargs)#

Unimplemented JAX wrapper for jnp.fromfile.

This function is left deliberately unimplemented because it may be non-pure and thus unsafe for use with JIT and other JAX transformations. Consider using jnp.asarray(np.fromfile(...)) instead, although care should be taken if np.fromfile is used within jax transformations because of its potential side-effect of consuming the file object; for more information see Common Gotchas: Pure Functions.

scico.numpy.fromfunction(function, shape, *, dtype=<class 'float'>, **kwargs)#

Construct an array by executing a function over each coordinate.

LAX-backend implementation of numpy.fromfunction.

Original docstring below.

The resulting array therefore has a value fn(x, y, z) at coordinate (x, y, z).

Parameters:
  • function (callable) – The function is called with N parameters, where N is the rank of shape. Each parameter represents the coordinates of the array varying along a specific axis. For example, if shape were (2, 2), then the parameters would be array([[0, 0], [1, 1]]) and array([[0, 1], [0, 1]])

  • shape ((N,) tuple of ints) – Shape of the output array, which also determines the shape of the coordinate arrays passed to function.

  • dtype (data-type, optional) – Data-type of the coordinate arrays passed to function. By default, dtype is float.

Return type:

Array

Returns:

fromfunction (any) – The result of the call to function is passed back directly. Therefore the shape of fromfunction is completely determined by function. If function returns a scalar value, the shape of fromfunction would not match the shape parameter.

scico.numpy.fromiter(*args, **kwargs)#

Unimplemented JAX wrapper for jnp.fromiter.

This function is left deliberately unimplemented because it may be non-pure and thus unsafe for use with JIT and other JAX transformations. Consider using jnp.asarray(np.fromiter(...)) instead, although care should be taken if np.fromiter is used within jax transformations because of its potential side-effect of consuming the iterable object; for more information see Common Gotchas: Pure Functions.

scico.numpy.fromstring(string, dtype=<class 'float'>, count=-1, *, sep)#

A new 1-D array initialized from text data in a string.

LAX-backend implementation of numpy.fromstring.

Original docstring below.

Parameters:
  • string (str) – A string containing the data.

  • dtype (data-type, optional) – The data type of the array; default: float. For binary input data, the data must be in exactly this format. Most builtin numeric types are supported and extension types may be supported.

  • count (int, optional) – Read this number of dtype elements from the data. If this is negative (the default), the count will be determined from the length of the data.

  • sep (str, optional) –

    The string separating numbers in the data; extra whitespace between elements is also ignored.

    Deprecated since version 1.14: Passing sep='', the default, is deprecated since it will trigger the deprecated binary mode of this function. This mode interprets string as binary bytes, rather than ASCII text with decimal numbers, an operation which is better spelt frombuffer(string, dtype, count). If string contains unicode text, the binary mode of fromstring will first encode it into bytes using utf-8, which will not produce sane results.

Return type:

Array

Returns:

arr (ndarray) – The constructed array.

scico.numpy.full(shape, fill_value, dtype=None)#

Return a new array of given shape and type, filled with fill_value.

LAX-backend implementation of numpy.full.

Original docstring below.

Parameters:
  • shape (int or sequence of ints) – Shape of the new array, e.g., (2, 3) or 2.

  • fill_value (scalar or array_like) – Fill value.

  • dtype (data-type, optional) –

    The desired data-type for the array The default, None, means

    np.array(fill_value).dtype.

Return type:

Array

Returns:

out (ndarray) – Array of fill_value with the given shape, dtype, and order.

scico.numpy.full_like(a, fill_value, dtype=None, shape=None)#

Return a full array with the same shape and type as a given array.

LAX-backend implementation of numpy.full_like.

Original docstring below.

Parameters:
  • a (array_like) – The shape and data-type of a define these same attributes of the returned array.

  • fill_value (array_like) – Fill value.

  • dtype (data-type, optional) – Overrides the data type of the result.

  • shape (int or sequence of ints, optional.) – Overrides the shape of the result. If order=’K’ and the number of dimensions is unchanged, will try to keep order, otherwise, order=’C’ is implied.

Return type:

Array

Returns:

out (ndarray) – Array of fill_value with the same shape and type as a.

scico.numpy.gcd(x1, x2)#

Returns the greatest common divisor of |x1| and |x2|

LAX-backend implementation of numpy.gcd.

Original docstring below.

Parameters:
  • x1 (array_like, int) – Arrays of values. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like, int) – Arrays of values. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Return type:

Array

Returns:

y (ndarray or scalar) – The greatest common divisor of the absolute value of the inputs This is a scalar if both x1 and x2 are scalars.

scico.numpy.geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0)#

Return numbers spaced evenly on a log scale (a geometric progression).

LAX-backend implementation of numpy.geomspace.

Original docstring below.

This is similar to logspace, but with endpoints specified directly. Each output sample is a constant multiple of the previous.

Changed in version 1.16.0: Non-scalar start and stop are now supported.

Parameters:
  • start (array_like) – The starting value of the sequence.

  • stop (array_like) – The final value of the sequence, unless endpoint is False. In that case, num + 1 values are spaced over the interval in log-space, of which all but the last (a sequence of length num) are returned.

  • num (integer, optional) – Number of samples to generate. Default is 50.

  • endpoint (boolean, optional) – If true, stop is the last sample. Otherwise, it is not included. Default is True.

  • dtype (dtype) – The type of the output array. If dtype is not given, the data type is inferred from start and stop. The inferred dtype will never be an integer; float is chosen even if the arguments would produce an array of integers.

  • axis (int, optional) – The axis in the result to store the samples. Relevant only if start or stop are array-like. By default (0), the samples will be along a new axis inserted at the beginning. Use -1 to get an axis at the end.

Return type:

Array

Returns:

samples (ndarray) – num samples, equally spaced on a log scale.

scico.numpy.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

scico.numpy.gradient(f, *varargs, axis=None, edge_order=None)#

Return the gradient of an N-dimensional array.

LAX-backend implementation of numpy.gradient.

Original docstring below.

The gradient is computed using second order accurate central differences in the interior points and either first or second order accurate one-sides (forward or backwards) differences at the boundaries. The returned gradient hence has the same shape as the input array.

Parameters:
  • f (array_like) – An N-dimensional array containing samples of a scalar function.

  • varargs (list of scalar or array, optional) –

    Spacing between f values. Default unitary spacing for all dimensions. Spacing can be specified using:

    1. single scalar to specify a sample distance for all dimensions.

    2. N scalars to specify a constant sample distance for each dimension. i.e. dx, dy, dz, …

    3. N arrays to specify the coordinates of the values along each dimension of F. The length of the array must match the size of the corresponding dimension

    4. Any combination of N scalars/arrays with the meaning of 2. and 3.

    If axis is given, the number of varargs must equal the number of axes. Default: 1.

  • axis (None or int or tuple of ints, optional) – Gradient is calculated only along the given axis or axes The default (axis = None) is to calculate the gradient for all the axes of the input array. axis may be negative, in which case it counts from the last to the first axis.

Return type:

Union[Array, List[Array]]

Returns:

gradient (ndarray or list of ndarray) – A list of ndarrays (or a single ndarray if there is only one dimension) corresponding to the derivatives of f with respect to each dimension. Each derivative has the same shape as f.

scico.numpy.greater(x1, x2, /)#

Return the truth value of (x1 > x2) element-wise.

LAX-backend implementation of numpy.greater.

Original docstring below.

Parameters:
  • x1 (array_like) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Returns:

out (ndarray or scalar) – Output array, element-wise comparison of x1 and x2. Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars.

scico.numpy.greater_equal(x1, x2, /)#

Return the truth value of (x1 >= x2) element-wise.

LAX-backend implementation of numpy.greater_equal.

Original docstring below.

Parameters:
  • x1 (array_like) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Returns:

out (bool or ndarray of bool) – Output array, element-wise comparison of x1 and x2. Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars.

scico.numpy.hamming(M)#

Return the Hamming window.

LAX-backend implementation of numpy.hamming.

Original docstring below.

The Hamming window is a taper formed by using a weighted cosine.

Parameters:

M (int) – Number of points in the output window. If zero or less, an empty array is returned.

Return type:

Array

Returns:

out (ndarray) – The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd).

scico.numpy.hanning(M)#

Return the Hanning window.

LAX-backend implementation of numpy.hanning.

Original docstring below.

The Hanning window is a taper formed by using a weighted cosine.

Parameters:

M (int) – Number of points in the output window. If zero or less, an empty array is returned.

Return type:

Array

Returns:

out (ndarray, shape(M,)) – The window, with the maximum value normalized to one (the value one appears only if M is odd).

scico.numpy.heaviside(x1, x2, /)#

Compute the Heaviside step function.

LAX-backend implementation of numpy.heaviside.

Original docstring below.

The Heaviside step function is defined as:

                      0   if x1 < 0
heaviside(x1, x2) =  x2   if x1 == 0
                      1   if x1 > 0

where x2 is often taken to be 0.5, but 0 and 1 are also sometimes used.

Parameters:
  • x1 (array_like) – Input values.

  • x2 (array_like) – The value of the function when x1 is 0. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Return type:

Array

Returns:

out (ndarray or scalar) – The output array, element-wise Heaviside step function of x1. This is a scalar if both x1 and x2 are scalars.

scico.numpy.histogram(a, bins=10, range=None, weights=None, density=None)#

Compute the histogram of a dataset.

LAX-backend implementation of numpy.histogram.

Original docstring below.

Parameters:
  • a (array_like) – Input data. The histogram is computed over the flattened array.

  • bins (int or sequence of scalars or str, optional) – If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins is a sequence, it defines a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform bin widths.

  • range ((float, float), optional) – The lower and upper range of the bins. If not provided, range is simply (a.min(), a.max()). Values outside the range are ignored. The first element of the range must be less than or equal to the second. range affects the automatic bin computation as well. While bin width is computed to be optimal based on the actual data within range, the bin count will fill the entire range including portions containing no data.

  • weights (array_like, optional) – An array of weights, of the same shape as a. Each value in a only contributes its associated weight towards the bin count (instead of 1). If density is True, the weights are normalized, so that the integral of the density over the range remains 1.

  • density (bool, optional) – If False, the result will contain the number of samples in each bin. If True, the result is the value of the probability density function at the bin, normalized such that the integral over the range is 1. Note that the sum of the histogram values will not be equal to 1 unless bins of unity width are chosen; it is not a probability mass function.

Return type:

Tuple[Array, Array]

Returns:

  • hist (array) – The values of the histogram. See density and weights for a description of the possible semantics.

  • bin_edges (array of dtype float) – Return the bin edges (length(hist)+1).

scico.numpy.histogram2d(x, y, bins=10, range=None, weights=None, density=None)#

Compute the bi-dimensional histogram of two data samples.

LAX-backend implementation of numpy.histogram2d.

Original docstring below.

Parameters:
  • x (array_like, shape (N,)) – An array containing the x coordinates of the points to be histogrammed.

  • y (array_like, shape (N,)) – An array containing the y coordinates of the points to be histogrammed.

  • bins (int or array_like or [int, int] or [array, array], optional) –

    The bin specification:

    • If int, the number of bins for the two dimensions (nx=ny=bins).

    • If array_like, the bin edges for the two dimensions (x_edges=y_edges=bins).

    • If [int, int], the number of bins in each dimension (nx, ny = bins).

    • If [array, array], the bin edges in each dimension (x_edges, y_edges = bins).

    • A combination [int, array] or [array, int], where int is the number of bins and array is the bin edges.

  • range (array_like, shape(2,2), optional) – The leftmost and rightmost edges of the bins along each dimension (if not specified explicitly in the bins parameters): [[xmin, xmax], [ymin, ymax]]. All values outside of this range will be considered outliers and not tallied in the histogram.

  • density (bool, optional) – If False, the default, returns the number of samples in each bin. If True, returns the probability density function at the bin, bin_count / sample_count / bin_area.

  • weights (array_like, shape(N,), optional) – An array of values w_i weighing each sample (x_i, y_i). Weights are normalized to 1 if density is True. If density is False, the values of the returned histogram are equal to the sum of the weights belonging to the samples falling into each bin.

Return type:

Tuple[Array, Array, Array]

Returns:

  • H (ndarray, shape(nx, ny)) – The bi-dimensional histogram of samples x and y. Values in x are histogrammed along the first dimension and values in y are histogrammed along the second dimension.

  • xedges (ndarray, shape(nx+1,)) – The bin edges along the first dimension.

  • yedges (ndarray, shape(ny+1,)) – The bin edges along the second dimension.

scico.numpy.histogram_bin_edges(a, bins=10, range=None, weights=None)#

Function to calculate only the edges of the bins used by the histogram

LAX-backend implementation of numpy.histogram_bin_edges.

Original docstring below.

function.

Parameters:
  • a (array_like) – Input data. The histogram is computed over the flattened array.

  • bins (int or sequence of scalars or str, optional) –

    If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins is a sequence, it defines the bin edges, including the rightmost edge, allowing for non-uniform bin widths.

    If bins is a string from the list below, histogram_bin_edges will use the method chosen to calculate the optimal bin width and consequently the number of bins (see Notes for more detail on the estimators) from the data that falls within the requested range. While the bin width will be optimal for the actual data in the range, the number of bins will be computed to fill the entire range, including the empty portions. For visualisation, using the ‘auto’ option is suggested. Weighted data is not supported for automated bin size selection.

    ’auto’

    Maximum of the ‘sturges’ and ‘fd’ estimators. Provides good all around performance.

    ’fd’ (Freedman Diaconis Estimator)

    Robust (resilient to outliers) estimator that takes into account data variability and data size.

    ’doane’

    An improved version of Sturges’ estimator that works better with non-normal datasets.

    ’scott’

    Less robust estimator that takes into account data variability and data size.

    ’stone’

    Estimator based on leave-one-out cross-validation estimate of the integrated squared error. Can be regarded as a generalization of Scott’s rule.

    ’rice’

    Estimator does not take variability into account, only data size. Commonly overestimates number of bins required.

    ’sturges’

    R’s default method, only accounts for data size. Only optimal for gaussian data and underestimates number of bins for large non-gaussian datasets.

    ’sqrt’

    Square root (of data size) estimator, used by Excel and other programs for its speed and simplicity.

  • range ((float, float), optional) – The lower and upper range of the bins. If not provided, range is simply (a.min(), a.max()). Values outside the range are ignored. The first element of the range must be less than or equal to the second. range affects the automatic bin computation as well. While bin width is computed to be optimal based on the actual data within range, the bin count will fill the entire range including portions containing no data.

  • weights (array_like, optional) – An array of weights, of the same shape as a. Each value in a only contributes its associated weight towards the bin count (instead of 1). This is currently not used by any of the bin estimators, but may be in the future.

Return type:

Array

Returns:

bin_edges (array of dtype float) – The edges to pass into histogram

scico.numpy.histogramdd(sample, bins=10, range=None, weights=None, density=None)#

Compute the multidimensional histogram of some data.

LAX-backend implementation of numpy.histogramdd.

Original docstring below.

Parameters:
  • sample ((N, D) array, or (N, D) array_like) –

    The data to be histogrammed.

    Note the unusual interpretation of sample when an array_like:

    • When an array, each row is a coordinate in a D-dimensional space - such as histogramdd(np.array([p1, p2, p3])).

    • When an array_like, each element is the list of values for single coordinate - such as histogramdd((X, Y, Z)).

    The first form should be preferred.

  • bins (sequence or int, optional) –

    The bin specification:

    • A sequence of arrays describing the monotonically increasing bin edges along each dimension.

    • The number of bins for each dimension (nx, ny, … =bins)

    • The number of bins for all dimensions (nx=ny=…=bins).

  • range (sequence, optional) – A sequence of length D, each an optional (lower, upper) tuple giving the outer bin edges to be used if the edges are not given explicitly in bins. An entry of None in the sequence results in the minimum and maximum values being used for the corresponding dimension. The default, None, is equivalent to passing a tuple of D None values.

  • density (bool, optional) – If False, the default, returns the number of samples in each bin. If True, returns the probability density function at the bin, bin_count / sample_count / bin_volume.

  • weights ((N,) array_like, optional) – An array of values w_i weighing each sample (x_i, y_i, z_i, …). Weights are normalized to 1 if density is True. If density is False, the values of the returned histogram are equal to the sum of the weights belonging to the samples falling into each bin.

Return type:

Tuple[Array, List[Array]]

Returns:

  • H (ndarray) – The multidimensional histogram of sample x. See density and weights for the different possible semantics.

  • edges (list) – A list of D arrays describing the bin edges for each dimension.

scico.numpy.hsplit(ary, indices_or_sections)#

Split an array into multiple sub-arrays horizontally (column-wise).

LAX-backend implementation of numpy.hsplit.

Original docstring below.

Please refer to the split documentation. hsplit is equivalent to split with axis=1, the array is always split along the second axis except for 1-D arrays, where it is split at axis=0.

Return type:

List[Array]

scico.numpy.hstack(tup, dtype=None)#

Stack arrays in sequence horizontally (column wise).

LAX-backend implementation of numpy.hstack.

Original docstring below.

This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis. Rebuilds arrays divided by hsplit.

This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations.

Parameters:
  • tup (sequence of ndarrays) – The arrays must have the same shape along all but the second axis, except 1-D arrays which can be any length.

  • dtype (str or dtype) – If provided, the destination array will have this dtype. Cannot be provided together with out.

Return type:

Array

Returns:

stacked (ndarray) – The array formed by stacking the given arrays.

scico.numpy.hypot(x1, x2, /)#

Given the “legs” of a right triangle, return its hypotenuse.

LAX-backend implementation of numpy.hypot.

Original docstring below.

Equivalent to sqrt(x1**2 + x2**2), element-wise. If x1 or x2 is scalar_like (i.e., unambiguously cast-able to a scalar type), it is broadcast for use with each element of the other argument. (See Examples)

Parameters:
  • x1 (array_like) – Leg of the triangle(s). If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – Leg of the triangle(s). If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Return type:

Array

Returns:

z (ndarray) – The hypotenuse of the triangle(s). This is a scalar if both x1 and x2 are scalars.

scico.numpy.i0(x)#

Modified Bessel function of the first kind, order 0.

LAX-backend implementation of numpy.i0.

Original docstring below.

Usually denoted \(I_0\).

Parameters:

x (array_like of float) – Argument of the Bessel function.

Return type:

Array

Returns:

out (ndarray, shape = x.shape, dtype = float) – The modified Bessel function evaluated at each of the elements of x.

scico.numpy.identity(n, dtype=None)#

Return the identity array.

LAX-backend implementation of numpy.identity.

Original docstring below.

The identity array is a square array with ones on the main diagonal.

Parameters:
  • n (int) – Number of rows (and columns) in n x n output.

  • dtype (data-type, optional) – Data-type of the output. Defaults to float.

Return type:

Array

Returns:

out (ndarray) – n x n array with its main diagonal set to one, and all other elements 0.

scico.numpy.imag(val, /)#

Return the imaginary part of the complex argument.

LAX-backend implementation of numpy.imag.

Original docstring below.

Parameters:

val (array_like) – Input array.

Return type:

Array

Returns:

out (ndarray or scalar) – The imaginary component of the complex argument. If val is real, the type of val is used for the output. If val has complex elements, the returned type is float.

scico.numpy.in1d(ar1, ar2, assume_unique=False, invert=False)#

Test whether each element of a 1-D array is also present in a second array.

LAX-backend implementation of numpy.in1d.

In the JAX version, the assume_unique argument is not referenced.

Original docstring below.

Returns a boolean array the same length as ar1 that is True where an element of ar1 is in ar2 and False otherwise.

We recommend using isin instead of in1d for new code.

Parameters:
  • ar1 ((M,) array_like) – Input array.

  • ar2 (array_like) – The values against which to test each value of ar1.

  • assume_unique (bool, optional) – If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.

  • invert (bool, optional) – If True, the values in the returned array are inverted (that is, False where an element of ar1 is in ar2 and True otherwise). Default is False. np.in1d(a, b, invert=True) is equivalent to (but is faster than) np.invert(in1d(a, b)).

Return type:

Array

Returns:

in1d ((M,) ndarray, bool) – The values ar1[in1d] are in ar2.

scico.numpy.indices(dimensions, dtype=<class 'jax.numpy.int32'>, sparse=False)#

Return an array representing the indices of a grid.

LAX-backend implementation of numpy.indices.

Original docstring below.

Compute an array where the subarrays contain index values 0, 1, … varying only along the corresponding axis.

Parameters:
  • dimensions (sequence of ints) – The shape of the grid.

  • dtype (dtype, optional) – Data type of the result.

  • sparse (boolean, optional) – Return a sparse representation of the grid instead of a dense representation. Default is False.

Return type:

Union[Array, Tuple[Array, ...]]

Returns:

grid (one ndarray or tuple of ndarrays) –

If sparse is False:

Returns one array of grid indices, grid.shape = (len(dimensions),) + tuple(dimensions).

If sparse is True:

Returns a tuple of arrays, with grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1) with dimensions[i] in the ith place

scico.numpy.inner(a, b, *, precision=None)#

Inner product of two arrays.

LAX-backend implementation of numpy.inner.

In addition to the original NumPy arguments listed below, also supports precision for extra control over matrix-multiplication precision on supported devices. precision may be set to None, which means default precision for the backend, a Precision enum value (Precision.DEFAULT, Precision.HIGH or Precision.HIGHEST) or a tuple of two Precision enums indicating separate precision for each argument.

Original docstring below.

Ordinary inner product of vectors for 1-D arrays (without complex conjugation), in higher dimensions a sum product over the last axes.

Parameters:
  • a (array_like) – If a and b are nonscalar, their last dimensions must match.

  • b (array_like) – If a and b are nonscalar, their last dimensions must match.

Returns:

out (ndarray) – If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. out.shape = (*a.shape[:-1], *b.shape[:-1])

scico.numpy.insert(arr, obj, values, axis=None)#

Insert values along the given axis before the given indices.

LAX-backend implementation of numpy.insert.

Original docstring below.

Parameters:
  • arr (array_like) – Input array.

  • obj (int, slice or sequence of ints) – Object that defines the index or indices before which values is inserted.

  • values (array_like) – Values to insert into arr. If the type of values is different from that of arr, values is converted to the type of arr. values should be shaped so that arr[...,obj,...] = values is legal.

  • axis (int, optional) – Axis along which to insert values. If axis is None then arr is flattened first.

Returns:

out (ndarray) – A copy of arr with values inserted. Note that insert does not occur in-place: a new array is returned. If axis is None, out is a flattened array.

scico.numpy.interp(x, xp, fp, left=None, right=None, period=None)#

One-dimensional linear interpolation for monotonically increasing sample points.

LAX-backend implementation of numpy.interp.

In addition to constant interpolation supported by NumPy, jnp.interp also supports left=’extrapolate’ and right=’extrpolate’ to indicate linear extrpolation instead.

Original docstring below.

Returns the one-dimensional piecewise linear interpolant to a function with given discrete data points (xp, fp), evaluated at x.

Parameters:
  • x (array_like) – The x-coordinates at which to evaluate the interpolated values.

  • xp (1-D sequence of floats) – The x-coordinates of the data points, must be increasing if argument period is not specified. Otherwise, xp is internally sorted after normalizing the periodic boundaries with xp = xp % period.

  • fp (1-D sequence of float or complex) – The y-coordinates of the data points, same length as xp.

  • left (optional float or complex corresponding to fp) – Value to return for x < xp[0], default is fp[0].

  • right (optional float or complex corresponding to fp) – Value to return for x > xp[-1], default is fp[-1].

  • period (None or float, optional) – A period for the x-coordinates. This parameter allows the proper interpolation of angular x-coordinates. Parameters left and right are ignored if period is specified.

Return type:

Array

Returns:

y (float or complex (corresponding to fp) or ndarray) – The interpolated values, same shape as x.

scico.numpy.intersect1d(ar1, ar2, assume_unique=False, return_indices=False)#

Find the intersection of two arrays.

LAX-backend implementation of numpy.intersect1d.

Original docstring below.

Return the sorted, unique values that are in both of the input arrays.

Parameters:
  • ar1 (array_like) – Input arrays. Will be flattened if not already 1D.

  • ar2 (array_like) – Input arrays. Will be flattened if not already 1D.

  • assume_unique (bool) – If True, the input arrays are both assumed to be unique, which can speed up the calculation. If True but ar1 or ar2 are not unique, incorrect results and out-of-bounds indices could result. Default is False.

  • return_indices (bool) – If True, the indices which correspond to the intersection of the two arrays are returned. The first instance of a value is used if there are multiple. Default is False.

Return type:

Union[Array, Tuple[Array, Array, Array]]

Returns:

  • intersect1d (ndarray) – Sorted 1D array of common and unique elements.

  • comm1 (ndarray) – The indices of the first occurrences of the common values in ar1. Only provided if return_indices is True.

  • comm2 (ndarray) – The indices of the first occurrences of the common values in ar2. Only provided if return_indices is True.

scico.numpy.isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)#

Returns a boolean array where two arrays are element-wise equal within a

LAX-backend implementation of numpy.isclose.

Original docstring below.

tolerance.

The tolerance values are positive, typically very small numbers. The relative difference (rtol * abs(b)) and the absolute difference atol are added together to compare against the absolute difference between a and b.

Warning

The default atol is not appropriate for comparing numbers that are much smaller than one (see Notes).

Parameters:
  • a (array_like) – Input arrays to compare.

  • b (array_like) – Input arrays to compare.

  • rtol (float) – The relative tolerance parameter (see Notes).

  • atol (float) – The absolute tolerance parameter (see Notes).

  • equal_nan (bool) – Whether to compare NaN’s as equal. If True, NaN’s in a will be considered equal to NaN’s in b in the output array.

Return type:

Array

Returns:

y (array_like) – Returns a boolean array of where a and b are equal within the given tolerance. If both a and b are scalars, returns a single boolean value.

scico.numpy.iscomplex(x)#

Returns a bool array, where True if input element is complex.

LAX-backend implementation of numpy.iscomplex.

Original docstring below.

What is tested is whether the input has a non-zero imaginary part, not if the input type is complex.

Parameters:

x (array_like) – Input array.

Return type:

Array

Returns:

out (ndarray of bools) – Output array.

scico.numpy.iscomplexobj(x)#

Check for a complex type or an array of complex numbers.

LAX-backend implementation of numpy.iscomplexobj.

Original docstring below.

The type of the input is checked, not the value. Even if the input has an imaginary part equal to zero, iscomplexobj evaluates to True.

Parameters:

x (any) – The input can be of any type and shape.

Return type:

bool

Returns:

iscomplexobj (bool) – The return value, True if x is of a complex type or has at least one complex element.

scico.numpy.isfinite(x, /)#

Test element-wise for finiteness (not infinity and not Not a Number).

LAX-backend implementation of numpy.isfinite.

Original docstring below.

The result is returned as a boolean array.

Parameters:

x (array_like) – Input values.

Return type:

Array

Returns:

y (ndarray, bool) – True where x is not positive infinity, negative infinity, or NaN; false otherwise. This is a scalar if x is a scalar.

scico.numpy.isin(element, test_elements, assume_unique=False, invert=False)#

Calculates element in test_elements, broadcasting over element only.

LAX-backend implementation of numpy.isin.

In the JAX version, the assume_unique argument is not referenced.

Original docstring below.

Returns a boolean array of the same shape as element that is True where an element of element is in test_elements and False otherwise.

Parameters:
  • element (array_like) – Input array.

  • test_elements (array_like) – The values against which to test each value of element. This argument is flattened if it is an array or array_like. See notes for behavior with non-array-like parameters.

  • assume_unique (bool, optional) – If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.

  • invert (bool, optional) – If True, the values in the returned array are inverted, as if calculating element not in test_elements. Default is False. np.isin(a, b, invert=True) is equivalent to (but faster than) np.invert(np.isin(a, b)).

Return type:

Array

Returns:

isin (ndarray, bool) – Has the same shape as element. The values element[isin] are in test_elements.

scico.numpy.isinf(x, /)#

Test element-wise for positive or negative infinity.

LAX-backend implementation of numpy.isinf.

Original docstring below.

Returns a boolean array of the same shape as x, True where x == +/-inf, otherwise False.

Parameters:

x (array_like) – Input values

Return type:

Array

Returns:

y (bool (scalar) or boolean ndarray) – True where x is positive or negative infinity, false otherwise. This is a scalar if x is a scalar.

scico.numpy.isnan(x, /)#

Test element-wise for NaN and return result as a boolean array.

LAX-backend implementation of numpy.isnan.

Original docstring below.

Parameters:

x (array_like) – Input array.

Return type:

Array

Returns:

y (ndarray or bool) – True where x is NaN, false otherwise. This is a scalar if x is a scalar.

scico.numpy.isneginf(x, /, out=None)#

Test element-wise for negative infinity, return result as bool array.

LAX-backend implementation of numpy.isneginf.

Original docstring below.

Parameters:

x (array_like) – The input array.

Returns:

out (ndarray) – A boolean array with the same dimensions as the input. If second argument is not supplied then a numpy boolean array is returned with values True where the corresponding element of the input is negative infinity and values False where the element of the input is not negative infinity.

If a second argument is supplied the result is stored there. If the type of that array is a numeric type the result is represented as zeros and ones, if the type is boolean then as False and True. The return value out is then a reference to that array.

scico.numpy.isposinf(x, /, out=None)#

Test element-wise for positive infinity, return result as bool array.

LAX-backend implementation of numpy.isposinf.

Original docstring below.

Parameters:

x (array_like) – The input array.

Returns:

out (ndarray) – A boolean array with the same dimensions as the input. If second argument is not supplied then a boolean array is returned with values True where the corresponding element of the input is positive infinity and values False where the element of the input is not positive infinity.

If a second argument is supplied the result is stored there. If the type of that array is a numeric type the result is represented as zeros and ones, if the type is boolean then as False and True. The return value out is then a reference to that array.

scico.numpy.isreal(x)#

Returns a bool array, where True if input element is real.

LAX-backend implementation of numpy.isreal.

Original docstring below.

If element has complex type with zero complex part, the return value for that element is True.

Parameters:

x (array_like) – Input array.

Return type:

Array

Returns:

out (ndarray, bool) – Boolean array of same shape as x.

scico.numpy.isrealobj(x)#

Return True if x is a not complex type or an array of complex numbers.

LAX-backend implementation of numpy.isrealobj.

Original docstring below.

The type of the input is checked, not the value. So even if the input has an imaginary part equal to zero, isrealobj evaluates to False if the data type is complex.

Parameters:

x (any) – The input can be of any type and shape.

Return type:

bool

Returns:

y (bool) – The return value, False if x is of a complex type.

scico.numpy.isscalar(element)#

Returns True if the type of element is a scalar type.

LAX-backend implementation of numpy.isscalar.

Original docstring below.

Parameters:

element (any) – Input argument, can be of any type and shape.

Return type:

bool

Returns:

val (bool) – True if element is a scalar type, False if it is not.

scico.numpy.issubdtype(arg1, arg2)#

Returns True if first argument is a typecode lower/equal in type hierarchy.

LAX-backend implementation of numpy.issubdtype.

Original docstring below.

This is like the builtin issubclass, but for dtypes.

Parameters:
  • arg1 (dtype_like) – dtype or object coercible to one

  • arg2 (dtype_like) – dtype or object coercible to one

Return type:

bool

Returns:

out (bool)

scico.numpy.issubsctype(arg1, arg2)#

Determine if the first argument is a subclass of the second argument.

Parameters:
  • arg1 (dtype or dtype specifier) – Data-types.

  • arg2 (dtype or dtype specifier) – Data-types.

Returns:

out (bool) – The result.

See also

issctype, issubdtype, obj2sctype

Examples

>>> np.issubsctype('S8', str)
False
>>> np.issubsctype(np.array([1]), int)
True
>>> np.issubsctype(np.array([1]), float)
False
scico.numpy.iterable(y)#

Check whether or not an object can be iterated over.

Parameters:

y (object) – Input object.

Returns:

b (bool) – Return True if the object has an iterator method or is a sequence and False otherwise.

Examples

>>> np.iterable([1, 2, 3])
True
>>> np.iterable(2)
False

Notes

In most cases, the results of np.iterable(obj) are consistent with isinstance(obj, collections.abc.Iterable). One notable exception is the treatment of 0-dimensional arrays:

>>> from collections.abc import Iterable
>>> a = np.array(1.0)  # 0-dimensional numpy array
>>> isinstance(a, Iterable)
True
>>> np.iterable(a)
False
scico.numpy.ix_(*args)#

Construct an open mesh from multiple sequences.

LAX-backend implementation of numpy.ix_.

Original docstring below.

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)).

Return type:

Tuple[Array, ...]

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.

scico.numpy.kaiser(M, beta)#

Return the Kaiser window.

LAX-backend implementation of numpy.kaiser.

Original docstring below.

The Kaiser window is a taper formed by using a Bessel function.

Parameters:
  • M (int) – Number of points in the output window. If zero or less, an empty array is returned.

  • beta (float) – Shape parameter for window.

Return type:

Array

Returns:

out (array) – The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd).

scico.numpy.kron(a, b)#

Kronecker product of two arrays.

LAX-backend implementation of numpy.kron.

Original docstring below.

Computes the Kronecker product, a composite array made of blocks of the second array scaled by the first.

Parameters:
  • a (array_like) –

  • b (array_like) –

Returns:

out (ndarray)

scico.numpy.lcm(x1, x2)#

Returns the lowest common multiple of |x1| and |x2|

LAX-backend implementation of numpy.lcm.

Original docstring below.

Parameters:
  • x1 (array_like, int) – Arrays of values. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like, int) – Arrays of values. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Return type:

Array

Returns:

y (ndarray or scalar) – The lowest common multiple of the absolute value of the inputs This is a scalar if both x1 and x2 are scalars.

scico.numpy.ldexp(x1, x2, /)#

Returns x1 * 2**x2, element-wise.

LAX-backend implementation of numpy.ldexp.

Original docstring below.

The mantissas x1 and twos exponents x2 are used to construct floating point numbers x1 * 2**x2.

Parameters:
  • x1 (array_like) – Array of multipliers.

  • x2 (array_like, int) – Array of twos exponents. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Return type:

Array

Returns:

y (ndarray or scalar) – The result of x1 * 2**x2. This is a scalar if both x1 and x2 are scalars.

scico.numpy.less(x1, x2, /)#

Return the truth value of (x1 < x2) element-wise.

LAX-backend implementation of numpy.less.

Original docstring below.

Parameters:
  • x1 (array_like) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Returns:

out (ndarray or scalar) – Output array, element-wise comparison of x1 and x2. Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars.

scico.numpy.less_equal(x1, x2, /)#

Return the truth value of (x1 <= x2) element-wise.

LAX-backend implementation of numpy.less_equal.

Original docstring below.

Parameters:
  • x1 (array_like) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Returns:

out (ndarray or scalar) – Output array, element-wise comparison of x1 and x2. Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars.

scico.numpy.lexsort(keys, axis=-1)#

Perform an indirect stable sort using a sequence of keys.

LAX-backend implementation of numpy.lexsort.

Original docstring below.

Given multiple sorting keys, which can be interpreted as columns in a spreadsheet, lexsort returns an array of integer indices that describes the sort order by multiple columns. The last key in the sequence is used for the primary sort order, the second-to-last key for the secondary sort order, and so on. The keys argument must be a sequence of objects that can be converted to arrays of the same shape. If a 2D array is provided for the keys argument, its rows are interpreted as the sorting keys and sorting is according to the last row, second last row etc.

Parameters:
  • keys ((k, N) array or tuple containing k (N,)-shaped sequences) – The k different “columns” to be sorted. The last column (or row if keys is a 2D array) is the primary sort key.

  • axis (int, optional) – Axis to be indirectly sorted. By default, sort over the last axis.

Returns:

indices ((N,) ndarray of ints) – Array of indices that sort the keys along the specified axis.

scico.numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)#

Return evenly spaced numbers over a specified interval.

LAX-backend implementation of numpy.linspace.

Original docstring below.

Returns num evenly spaced samples, calculated over the interval [start, stop].

The endpoint of the interval can optionally be excluded.

Changed in version 1.16.0: Non-scalar start and stop are now supported.

Changed in version 1.20.0: Values are rounded towards -inf instead of 0 when an integer dtype is specified. The old behavior can still be obtained with np.linspace(start, stop, num).astype(int)

Parameters:
  • start (array_like) – The starting value of the sequence.

  • stop (array_like) – The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False.

  • num (int, optional) – Number of samples to generate. Default is 50. Must be non-negative.

  • endpoint (bool, optional) – If True, stop is the last sample. Otherwise, it is not included. Default is True.

  • retstep (bool, optional) – If True, return (samples, step), where step is the spacing between samples.

  • dtype (dtype, optional) – The type of the output array. If dtype is not given, the data type is inferred from start and stop. The inferred dtype will never be an integer; float is chosen even if the arguments would produce an array of integers.

  • axis (int, optional) – The axis in the result to store the samples. Relevant only if start or stop are array-like. By default (0), the samples will be along a new axis inserted at the beginning. Use -1 to get an axis at the end.

Return type:

Union[Array, Tuple[Array, Array]]

Returns:

  • samples (ndarray) – There are num equally spaced samples in the closed interval [start, stop] or the half-open interval [start, stop) (depending on whether endpoint is True or False).

  • step (float, optional) – Only returned if retstep is True

    Size of spacing between samples.

scico.numpy.load(*args, **kwargs)#

Load arrays or pickled objects from .npy, .npz or pickled files.

LAX-backend implementation of numpy.load.

Original docstring below.

Warning

Loading files that contain object arrays uses the pickle module, which is not secure against erroneous or maliciously constructed data. Consider passing allow_pickle=False to load data that is known not to contain object arrays for the safer handling of untrusted sources.

Parameters:
  • file (file-like object, string, or pathlib.Path) – The file to read. File-like objects must support the seek() and read() methods and must always be opened in binary mode. Pickled files require that the file-like object support the readline() method as well.

  • mmap_mode ({None, 'r+', 'r', 'w+', 'c'}, optional) – If not None, then memory-map the file, using the given mode (see numpy.memmap for a detailed description of the modes). A memory-mapped array is kept on disk. However, it can be accessed and sliced like any ndarray. Memory mapping is especially useful for accessing small fragments of large files without reading the entire file into memory.

  • allow_pickle (bool, optional) –

    Allow loading pickled object arrays stored in npy files. Reasons for disallowing pickles include security, as loading pickled data can execute arbitrary code. If pickles are disallowed, loading object arrays will fail. Default: False

    Changed in version 1.16.3: Made default False in response to CVE-2019-6446.

  • fix_imports (bool, optional) – Only useful when loading Python 2 generated pickled files on Python 3, which includes npy/npz files containing object arrays. If fix_imports is True, pickle will try to map the old Python 2 names to the new names used in Python 3.

  • encoding (str, optional) – What encoding to use when reading Python 2 strings. Only useful when loading Python 2 generated pickled files in Python 3, which includes npy/npz files containing object arrays. Values other than ‘latin1’, ‘ASCII’, and ‘bytes’ are not allowed, as they can corrupt numerical data. Default: ‘ASCII’

  • max_header_size (int, optional) – Maximum allowed size of the header. Large headers may not be safe to load securely and thus require explicitly passing a larger value. See ast.literal_eval for details. This option is ignored when allow_pickle is passed. In that case the file is by definition trusted and the limit is unnecessary.

Return type:

Array

Returns:

result (array, tuple, dict, etc.) – Data stored in the file. For .npz files, the returned instance of NpzFile class must be closed to avoid leaking file descriptors.

scico.numpy.log(x, /)#

Natural logarithm, element-wise.

LAX-backend implementation of numpy.log.

Original docstring below.

The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x. The natural logarithm is logarithm in base e.

Parameters:

x (array_like) – Input value.

Returns:

y (ndarray) – The natural logarithm of x, element-wise. This is a scalar if x is a scalar.

scico.numpy.log10(x, /)#

Return the base 10 logarithm of the input array, element-wise.

LAX-backend implementation of numpy.log10.

Original docstring below.

Parameters:

x (array_like) – Input values.

Return type:

Array

Returns:

y (ndarray) – The logarithm to the base 10 of x, element-wise. NaNs are returned where x is negative. This is a scalar if x is a scalar.

scico.numpy.log1p(x, /)#

Return the natural logarithm of one plus the input array, element-wise.

LAX-backend implementation of numpy.log1p.

Original docstring below.

Calculates log(1 + x).

Parameters:

x (array_like) – Input values.

Returns:

y (ndarray) – Natural logarithm of 1 + x, element-wise. This is a scalar if x is a scalar.

scico.numpy.log2(x, /)#

Base-2 logarithm of x.

LAX-backend implementation of numpy.log2.

Original docstring below.

Parameters:

x (array_like) – Input values.

Return type:

Array

Returns:

y (ndarray) – Base-2 logarithm of x. This is a scalar if x is a scalar.

scico.numpy.logical_and(*args)#

Compute the truth value of x1 AND x2 element-wise.

LAX-backend implementation of numpy.logical_and.

Original docstring below.

Parameters:
  • x1 (array_like) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

  • where (array_like, optional) – This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

  • **kwargs – For other keyword-only arguments, see the ufunc docs.

Returns:

y (ndarray or bool) – Boolean result of the logical AND operation applied to the elements of x1 and x2; the shape is determined by broadcasting. This is a scalar if both x1 and x2 are scalars.

scico.numpy.logical_not(*args)#

Compute the truth value of NOT x element-wise.

LAX-backend implementation of numpy.logical_not.

Original docstring below.

Parameters:
  • x (array_like) – Logical NOT is applied to the elements of x.

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

  • where (array_like, optional) – This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

  • **kwargs – For other keyword-only arguments, see the ufunc docs.

Returns:

y (bool or ndarray of bool) – Boolean result with the same shape as x of the NOT operation on elements of x. This is a scalar if x is a scalar.

scico.numpy.logical_or(*args)#

Compute the truth value of x1 OR x2 element-wise.

LAX-backend implementation of numpy.logical_or.

Original docstring below.

Parameters:
  • x1 (array_like) – Logical OR is applied to the elements of x1 and x2. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – Logical OR is applied to the elements of x1 and x2. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

  • where (array_like, optional) – This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

  • **kwargs – For other keyword-only arguments, see the ufunc docs.

Returns:

y (ndarray or bool) – Boolean result of the logical OR operation applied to the elements of x1 and x2; the shape is determined by broadcasting. This is a scalar if both x1 and x2 are scalars.

scico.numpy.logical_xor(*args)#

Compute the truth value of x1 XOR x2, element-wise.

LAX-backend implementation of numpy.logical_xor.

Original docstring below.

Parameters:
  • x1 (array_like) – Logical XOR is applied to the elements of x1 and x2. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – Logical XOR is applied to the elements of x1 and x2. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • out (ndarray, None, or tuple of ndarray and None, optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

  • where (array_like, optional) – This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

  • **kwargs – For other keyword-only arguments, see the ufunc docs.

Returns:

y (bool or ndarray of bool) – Boolean result of the logical XOR operation applied to the elements of x1 and x2; the shape is determined by broadcasting. This is a scalar if both x1 and x2 are scalars.

scico.numpy.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0)#

Return numbers spaced evenly on a log scale.

LAX-backend implementation of numpy.logspace.

Original docstring below.

In linear space, the sequence starts at base ** start (base to the power of start) and ends with base ** stop (see endpoint below).

Changed in version 1.16.0: Non-scalar start and stop are now supported.

Parameters:
  • start (array_like) – base ** start is the starting value of the sequence.

  • stop (array_like) – base ** stop is the final value of the sequence, unless endpoint is False. In that case, num + 1 values are spaced over the interval in log-space, of which all but the last (a sequence of length num) are returned.

  • num (integer, optional) – Number of samples to generate. Default is 50.

  • endpoint (boolean, optional) – If true, stop is the last sample. Otherwise, it is not included. Default is True.

  • base (array_like, optional) – The base of the log space. The step size between the elements in ln(samples) / ln(base) (or log_base(samples)) is uniform. Default is 10.0.

  • dtype (dtype) – The type of the output array. If dtype is not given, the data type is inferred from start and stop. The inferred type will never be an integer; float is chosen even if the arguments would produce an array of integers.

  • axis (int, optional) – The axis in the result to store the samples. Relevant only if start or stop are array-like. By default (0), the samples will be along a new axis inserted at the beginning. Use -1 to get an axis at the end.

Return type:

Array

Returns:

samples (ndarray) – num samples, equally spaced on a log scale.

scico.numpy.mask_indices(*args, **kwargs)#

Return the indices to access (n, n) arrays, given a masking function.

LAX-backend implementation of numpy.mask_indices.

Original docstring below.

Assume mask_func is a function that, for a square array a of size (n, n) with a possible offset argument k, when called as mask_func(a, k) returns a new array with zeros in certain locations (functions like triu or tril do precisely this). Then this function returns the indices where the non-zero values would be located.

Parameters:
  • n (int) – The returned indices will be valid to access arrays of shape (n, n).

  • mask_func (callable) – A function whose call signature is similar to that of triu, tril. That is, mask_func(x, k) returns a boolean array, shaped like x. k is an optional argument to the function.

  • k (scalar) – An optional argument which is passed through to mask_func. Functions like triu, tril take a second argument that is interpreted as an offset.

Returns:

indices (tuple of arrays.) – The n arrays of indices corresponding to the locations where mask_func(np.ones((n, n)), k) is True.

scico.numpy.matmul(a, b, *, precision=None)#

Matrix product of two arrays.

LAX-backend implementation of numpy.matmul.

In addition to the original NumPy arguments listed below, also supports precision for extra control over matrix-multiplication precision on supported devices. precision may be set to None, which means default precision for the backend, a Precision enum value (Precision.DEFAULT, Precision.HIGH or Precision.HIGHEST) or a tuple of two Precision enums indicating separate precision for each argument.

Original docstring below.

Parameters:
  • out (ndarray, optional) – A location into which the result is stored. If provided, it must have a shape that matches the signature (n,k),(k,m)->(n,m). If not provided or None, a freshly-allocated array is returned.

  • **kwargs – For other keyword-only arguments, see the ufunc docs.

Returns:

y (ndarray) – The matrix product of the inputs. This is a scalar only when both x1, x2 are 1-d vectors.

scico.numpy.matrix_transpose(x, /)#

Transposes the last two dimensions of x.

Parameters:

x (array_like) – Input array. Must have x.ndim >= 2.

Return type:

Array

Returns:

xT (Array) – Transposed array.

scico.numpy.max(a, axis=None, out=None, keepdims=False, initial=None, where=None)#

Return the maximum of an array or maximum along an axis.

LAX-backend implementation of numpy.amax.

Original docstring below.

Parameters:
  • a (array_like) – Input data.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which to operate. By default, flattened input is used.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the amax method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • initial (scalar, optional) – The minimum value of an output element. Must be present to allow computation on empty slice. See ~numpy.ufunc.reduce for details.

  • where (array_like of bool, optional) – Elements to compare for the maximum. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

amax (ndarray or scalar) – Maximum of a. If axis is None, the result is a scalar value. If axis is an int, the result is an array of dimension a.ndim - 1. If axis is a tuple, the result is an array of dimension a.ndim - len(axis).

scico.numpy.maximum(x1, x2, /)#

Element-wise maximum of array elements.

LAX-backend implementation of numpy.maximum.

Original docstring below.

Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then that element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated.

Parameters:
  • x1 (array_like) – The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Returns:

y (ndarray or scalar) – The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

scico.numpy.mean(a, axis=None, dtype=None, out=None, keepdims=False, *, where=None)#

Compute the arithmetic mean along the specified axis.

LAX-backend implementation of numpy.mean.

Original docstring below.

Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.

Parameters:
  • a (array_like) – Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

  • dtype (data-type, optional) – Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • where (array_like of bool, optional) – Elements to include in the mean. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

m (ndarray, see dtype parameter above) – If out=None, returns a new array containing the mean values, otherwise a reference to the output array is returned.

scico.numpy.meshgrid(*xi, copy=True, sparse=False, indexing='xy')#

Return coordinate matrices from coordinate vectors.

LAX-backend implementation of numpy.meshgrid.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, given one-dimensional coordinate arrays x1, x2,…, xn.

Changed in version 1.9: 1-D and 0-D cases are allowed.

Parameters:
  • indexing ({'xy', 'ij'}, optional) – Cartesian (‘xy’, default) or matrix (‘ij’) indexing of output. See Notes for more details.

  • sparse (bool, optional) –

    If True the shape of the returned coordinate array for dimension i is reduced from (N1, ..., Ni, ... Nn) to (1, ..., 1, Ni, 1, ..., 1). These sparse coordinate grids are intended to be use with Broadcasting. When all coordinates are used in an expression, broadcasting still leads to a fully-dimensonal result array.

    Default is False.

  • copy (bool, optional) – If False, a view into the original arrays are returned in order to conserve memory. Default is True. Please note that sparse=False, copy=False will likely return non-contiguous arrays. Furthermore, more than one element of a broadcast array may refer to a single memory location. If you need to write to the arrays, make copies first.

Return type:

List[Array]

Returns:

X1, X2,…, XN (ndarray) – For vectors x1, x2,…, xn with lengths Ni=len(xi), returns (N1, N2, N3,..., Nn) shaped arrays if indexing=’ij’ or (N2, N1, N3,..., Nn) shaped arrays if indexing=’xy’ with the elements of xi repeated to fill the matrix along the first dimension for x1, the second for x2 and so on.

scico.numpy.min(a, axis=None, out=None, keepdims=False, initial=None, where=None)#

Return the minimum of an array or minimum along an axis.

LAX-backend implementation of numpy.amin.

Original docstring below.

Parameters:
  • a (array_like) – Input data.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which to operate. By default, flattened input is used.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the amin method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • initial (scalar, optional) – The maximum value of an output element. Must be present to allow computation on empty slice. See ~numpy.ufunc.reduce for details.

  • where (array_like of bool, optional) – Elements to compare for the minimum. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

amin (ndarray or scalar) – Minimum of a. If axis is None, the result is a scalar value. If axis is an int, the result is an array of dimension a.ndim - 1. If axis is a tuple, the result is an array of dimension a.ndim - len(axis).

scico.numpy.minimum(x1, x2, /)#

Element-wise minimum of array elements.

LAX-backend implementation of numpy.minimum.

Original docstring below.

Compare two arrays and returns a new array containing the element-wise minima. If one of the elements being compared is a NaN, then that element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated.

Parameters:
  • x1 (array_like) – The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Returns:

y (ndarray or scalar) – The minimum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

scico.numpy.mod(x1, x2, /)#

Returns the element-wise remainder of division.

LAX-backend implementation of numpy.remainder.

Original docstring below.

Computes the remainder complementary to the floor_divide function. It is equivalent to the Python modulus operator``x1 % x2`` and has the same sign as the divisor x2. The MATLAB function equivalent to np.remainder is mod.

Warning

This should not be confused with:

  • Python 3.7’s math.remainder and C’s remainder, which computes the IEEE remainder, which are the complement to round(x1 / x2).

  • The MATLAB rem function and or the C % operator which is the complement to int(x1 / x2).

Parameters:
  • x1 (array_like) – Dividend array.

  • x2 (array_like) – Divisor array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Return type:

Array

Returns:

y (ndarray) – The element-wise remainder of the quotient floor_divide(x1, x2). This is a scalar if both x1 and x2 are scalars.

scico.numpy.modf(x, /, out=None)#

Return the fractional and integral parts of an array, element-wise.

LAX-backend implementation of numpy.modf.

Original docstring below.

The fractional and integral parts are negative if the given number is negative.

Parameters:

x (array_like) – Input array.

Return type:

Tuple[Array, Array]

Returns:

  • y1 (ndarray) – Fractional part of x. This is a scalar if x is a scalar.

  • y2 (ndarray) – Integral part of x. This is a scalar if x is a scalar.

scico.numpy.moveaxis(a, source, destination)#

Move axes of an array to new positions.

LAX-backend implementation of numpy.moveaxis.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

Other axes remain in their original order.

New in version 1.11.0.

Parameters:
  • a (np.ndarray) – The array whose axes should be reordered.

  • source (int or sequence of int) – Original positions of the axes to move. These must be unique.

  • destination (int or sequence of int) – Destination positions for each of the original axes. These must also be unique.

Return type:

Array

Returns:

result (np.ndarray) – Array with moved axes. This array is a view of the input array.

scico.numpy.multiply(x1, x2, /)#

Multiply arguments element-wise.

LAX-backend implementation of numpy.multiply.

Original docstring below.

Parameters:
  • x1 (array_like) – Input arrays to be multiplied. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – Input arrays to be multiplied. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Returns:

y (ndarray) – The product of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

scico.numpy.nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None)#

Replace NaN with zero and infinity with large finite numbers (default

LAX-backend implementation of numpy.nan_to_num.

Original docstring below.

behaviour) or with the numbers defined by the user using the nan, posinf and/or neginf keywords.

If x is inexact, NaN is replaced by zero or by the user defined value in nan keyword, infinity is replaced by the largest finite floating point values representable by x.dtype or by the user defined value in posinf keyword and -infinity is replaced by the most negative finite floating point values representable by x.dtype or by the user defined value in neginf keyword.

For complex dtypes, the above is applied to each of the real and imaginary components of x separately.

If x is not inexact, then no replacements are made.

Parameters:
  • x (scalar or array_like) – Input data.

  • copy (bool, optional) – Whether to create a copy of x (True) or to replace values in-place (False). The in-place operation only occurs if casting to an array does not require a copy. Default is True.

  • nan (int, float, optional) – Value to be used to fill NaN values. If no value is passed then NaN values will be replaced with 0.0.

  • posinf (int, float, optional) – Value to be used to fill positive infinity values. If no value is passed then positive infinity values will be replaced with a very large number.

  • neginf (int, float, optional) – Value to be used to fill negative infinity values. If no value is passed then negative infinity values will be replaced with a very small (or negative) number.

Return type:

Array

Returns:

out (ndarray) – x, with the non-finite values replaced. If copy is False, this may be x itself.

scico.numpy.nanargmax(a, axis=None, out=None, keepdims=None)#

Return the indices of the maximum values in the specified axis ignoring

LAX-backend implementation of numpy.nanargmax.

Warning: jax.numpy.argmax returns -1 for all-NaN slices and does not raise an error.

Original docstring below.

NaNs. For all-NaN slices ValueError is raised. Warning: the results cannot be trusted if a slice contains only NaNs and -Infs.

Parameters:
  • a (array_like) – Input data.

  • axis (int, optional) – Axis along which to operate. By default flattened input is used.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array.

Returns:

index_array (ndarray) – An array of indices or a single index value.

scico.numpy.nanargmin(a, axis=None, out=None, keepdims=None)#

Return the indices of the minimum values in the specified axis ignoring

LAX-backend implementation of numpy.nanargmin.

Warning: jax.numpy.argmin returns -1 for all-NaN slices and does not raise an error.

Original docstring below.

NaNs. For all-NaN slices ValueError is raised. Warning: the results cannot be trusted if a slice contains only NaNs and Infs.

Parameters:
  • a (array_like) – Input data.

  • axis (int, optional) – Axis along which to operate. By default flattened input is used.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array.

Returns:

index_array (ndarray) – An array of indices or a single index value.

scico.numpy.nancumprod(a, axis=None, dtype=None, out=None)#

Return the cumulative product of array elements over a given axis treating Not a

LAX-backend implementation of numpy.nancumprod.

Original docstring below.

Numbers (NaNs) as one. The cumulative product does not change when NaNs are encountered and leading NaNs are replaced by ones.

Ones are returned for slices that are all-NaN or empty.

New in version 1.12.0.

Parameters:
  • a (array_like) – Input array.

  • axis (int, optional) – Axis along which the cumulative product is computed. By default the input is flattened.

  • dtype (dtype, optional) – Type of the returned array, as well as of the accumulator in which the elements are multiplied. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used instead.

Return type:

Array

Returns:

nancumprod (ndarray) – A new array holding the result is returned unless out is specified, in which case it is returned.

scico.numpy.nancumsum(a, axis=None, dtype=None, out=None)#

Return the cumulative sum of array elements over a given axis treating Not a

LAX-backend implementation of numpy.nancumsum.

Original docstring below.

Numbers (NaNs) as zero. The cumulative sum does not change when NaNs are encountered and leading NaNs are replaced by zeros.

Zeros are returned for slices that are all-NaN or empty.

New in version 1.12.0.

Parameters:
  • a (array_like) – Input array.

  • axis (int, optional) – Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.

  • dtype (dtype, optional) – Type of the returned array and of the accumulator in which the elements are summed. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.

Return type:

Array

Returns:

nancumsum (ndarray.) – A new array holding the result is returned unless out is specified, in which it is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array.

scico.numpy.nanmax(a, axis=None, out=None, keepdims=False, initial=None, where=None)#

Return the maximum of an array or maximum along an axis, ignoring any

LAX-backend implementation of numpy.nanmax.

Original docstring below.

NaNs. When all-NaN slices are encountered a RuntimeWarning is raised and NaN is returned for that slice.

Parameters:
  • a (array_like) – Array containing numbers whose maximum is desired. If a is not an array, a conversion is attempted.

  • axis ({int, tuple of int, None}, optional) – Axis or axes along which the maximum is computed. The default is to compute the maximum of the flattened array.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.

    If the value is anything but the default, then keepdims will be passed through to the max method of sub-classes of ndarray. If the sub-classes methods does not implement keepdims any exceptions will be raised.

  • initial (scalar, optional) – The minimum value of an output element. Must be present to allow computation on empty slice. See ~numpy.ufunc.reduce for details.

  • where (array_like of bool, optional) – Elements to compare for the maximum. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

nanmax (ndarray) – An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, an ndarray scalar is returned. The same dtype as a is returned.

scico.numpy.nanmin(a, axis=None, out=None, keepdims=False, initial=None, where=None)#

Return minimum of an array or minimum along an axis, ignoring any NaNs.

LAX-backend implementation of numpy.nanmin.

Original docstring below.

When all-NaN slices are encountered a RuntimeWarning is raised and Nan is returned for that slice.

Parameters:
  • a (array_like) – Array containing numbers whose minimum is desired. If a is not an array, a conversion is attempted.

  • axis ({int, tuple of int, None}, optional) – Axis or axes along which the minimum is computed. The default is to compute the minimum of the flattened array.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.

    If the value is anything but the default, then keepdims will be passed through to the min method of sub-classes of ndarray. If the sub-classes methods does not implement keepdims any exceptions will be raised.

  • initial (scalar, optional) – The maximum value of an output element. Must be present to allow computation on empty slice. See ~numpy.ufunc.reduce for details.

  • where (array_like of bool, optional) – Elements to compare for the minimum. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

nanmin (ndarray) – An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, an ndarray scalar is returned. The same dtype as a is returned.

scico.numpy.nanprod(a, axis=None, dtype=None, out=None, keepdims=False, initial=None, where=None)#

Return the product of array elements over a given axis treating Not a

LAX-backend implementation of numpy.nanprod.

Original docstring below.

Numbers (NaNs) as ones.

One is returned for slices that are all-NaN or empty.

New in version 1.10.0.

Parameters:
  • a (array_like) – Array containing numbers whose product is desired. If a is not an array, a conversion is attempted.

  • axis ({int, tuple of int, None}, optional) – Axis or axes along which the product is computed. The default is to compute the product of the flattened array.

  • dtype (data-type, optional) – The type of the returned array and of the accumulator in which the elements are summed. By default, the dtype of a is used. An exception is when a has an integer type with less precision than the platform (u)intp. In that case, the default will be either (u)int32 or (u)int64 depending on whether the platform is 32 or 64 bits. For inexact inputs, dtype must be inexact.

  • keepdims (bool, optional) – If True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original arr.

  • initial (scalar, optional) – The starting value for this product. See ~numpy.ufunc.reduce for details.

  • where (array_like of bool, optional) – Elements to include in the product. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

nanprod (ndarray) – A new array holding the result is returned unless out is specified, in which case it is returned.

scico.numpy.nansum(a, axis=None, dtype=None, out=None, keepdims=False, initial=None, where=None)#

Return the sum of array elements over a given axis treating Not a

LAX-backend implementation of numpy.nansum.

Original docstring below.

Numbers (NaNs) as zero.

In NumPy versions <= 1.9.0 Nan is returned for slices that are all-NaN or empty. In later versions zero is returned.

Parameters:
  • a (array_like) – Array containing numbers whose sum is desired. If a is not an array, a conversion is attempted.

  • axis ({int, tuple of int, None}, optional) – Axis or axes along which the sum is computed. The default is to compute the sum of the flattened array.

  • dtype (data-type, optional) – The type of the returned array and of the accumulator in which the elements are summed. By default, the dtype of a is used. An exception is when a has an integer type with less precision than the platform (u)intp. In that case, the default will be either (u)int32 or (u)int64 depending on whether the platform is 32 or 64 bits. For inexact inputs, dtype must be inexact.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.

    If the value is anything but the default, then keepdims will be passed through to the mean or sum methods of sub-classes of ndarray. If the sub-classes methods does not implement keepdims any exceptions will be raised.

  • initial (scalar, optional) – Starting value for the sum. See ~numpy.ufunc.reduce for details.

  • where (array_like of bool, optional) – Elements to include in the sum. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

nansum (ndarray.) – A new array holding the result is returned unless out is specified, in which it is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array.

scico.numpy.ndim(a)#

Return the number of dimensions of an array.

Parameters:

a (array_like) – Input array. If it is not already an ndarray, a conversion is attempted.

Returns:

number_of_dimensions (int) – The number of dimensions in a. Scalars are zero-dimensional.

See also

ndarray.ndim

equivalent method

shape

dimensions of array

ndarray.shape

dimensions of array

Examples

>>> np.ndim([[1,2,3],[4,5,6]])
2
>>> np.ndim(np.array([[1,2,3],[4,5,6]]))
2
>>> np.ndim(1)
0
scico.numpy.negative(x, /)#

Numerical negative, element-wise.

LAX-backend implementation of numpy.negative.

Original docstring below.

Parameters:

x (array_like or scalar) – Input array.

Returns:

y (ndarray or scalar) – Returned array or scalar: y = -x. This is a scalar if x is a scalar.

scico.numpy.nextafter(x1, x2, /)#

Return the next floating-point value after x1 towards x2, element-wise.

LAX-backend implementation of numpy.nextafter.

Note that in some environments flush-denormal-to-zero semantics is used. This means that, around zero, this function returns strictly non-zero values which appear as zero in any operations. Consider this example:

>>> jnp.nextafter(0, 1)  # denormal numbers are representable
Array(1.e-45, dtype=float32, weak_type=True)
>>> jnp.nextafter(0, 1) * 1  # but are flushed to zero
Array(0., dtype=float32, weak_type=True)

For the smallest usable (i.e. normal) float, use tiny of jnp.finfo.

Original docstring below.

Parameters:
  • x1 (array_like) – Values to find the next representable value of.

  • x2 (array_like) – The direction where to look for the next representable value of x1. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Returns:

out (ndarray or scalar) – The next representable values of x1 in the direction of x2. This is a scalar if both x1 and x2 are scalars.

scico.numpy.nonzero(a, *, size=None, fill_value=None)#

Return the indices of the elements that are non-zero.

LAX-backend implementation of numpy.nonzero.

Because the size of the output of nonzero is data-dependent, the function is not typically compatible with JIT. The JAX version adds the optional size argument which must be specified statically for jnp.nonzero to be used within some of JAX’s transformations.

Original docstring below.

Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension. The values in a are always tested and returned in row-major, C-style order.

To group the indices by element, rather than dimension, use argwhere, which returns a row for each non-zero element.

Note

When called on a zero-d array or scalar, nonzero(a) is treated as nonzero(atleast_1d(a)).

Deprecated since version 1.17.0: Use atleast_1d explicitly if this behavior is deliberate.

Parameters:
  • a (array_like) – Input array.

  • size (int, optional) – If specified, the indices of the first size True elements will be returned. If there are fewer unique elements than size indicates, the return value will be padded with fill_value.

  • fill_value (array_like, optional) – When size is specified and there are fewer than the indicated number of elements, the remaining elements will be filled with fill_value, which defaults to zero.

Return type:

Tuple[Array, ...]

Returns:

tuple_of_arrays (tuple) – Indices of elements that are non-zero.

scico.numpy.not_equal(x1, x2, /)#

Return (x1 != x2) element-wise.

LAX-backend implementation of numpy.not_equal.

Original docstring below.

Parameters:
  • x1 (array_like) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Returns:

out (ndarray or scalar) – Output array, element-wise comparison of x1 and x2. Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars.

scico.numpy.ones(shape, dtype=None)#

Return a new array of given shape and type, filled with ones.

LAX-backend implementation of numpy.ones.

Original docstring below.

Parameters:
  • shape (int or sequence of ints) – Shape of the new array, e.g., (2, 3) or 2.

  • dtype (data-type, optional) – The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64.

Return type:

Array

Returns:

out (ndarray) – Array of ones with the given shape, dtype, and order.

scico.numpy.ones_like(a, dtype=None, shape=None)#

Return an array of ones with the same shape and type as a given array.

LAX-backend implementation of numpy.ones_like.

Original docstring below.

Parameters:
  • a (array_like) – The shape and data-type of a define these same attributes of the returned array.

  • dtype (data-type, optional) – Overrides the data type of the result.

  • shape (int or sequence of ints, optional.) – Overrides the shape of the result. If order=’K’ and the number of dimensions is unchanged, will try to keep order, otherwise, order=’C’ is implied.

Return type:

Array

Returns:

out (ndarray) – Array of ones with the same shape and type as a.

scico.numpy.outer(a, b, out=None)#

Compute the outer product of two vectors.

LAX-backend implementation of numpy.outer.

Original docstring below.

Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product is:

[[a0*b0  a0*b1 ... a0*bN ]
 [a1*b0    .
 [ ...          .
 [aM*b0            aM*bN ]]
Parameters:
  • a ((M,) array_like) – First input vector. Input is flattened if not already 1-dimensional.

  • b ((N,) array_like) – Second input vector. Input is flattened if not already 1-dimensional.

Returns:

out ((M, N) ndarray) – out[i, j] = a[i] * b[j]

scico.numpy.pad(array, pad_width, mode='constant', **kwargs)#

Pad an array.

LAX-backend implementation of numpy.pad.

Unlike numpy, JAX “function” mode’s argument (which is another function) should return the modified array. This is because Jax arrays are immutable. (In numpy, “function” mode’s argument should modify a rank 1 array in-place.)

Original docstring below.

Parameters:
  • array (array_like of rank N) – The array to pad.

  • pad_width ({sequence, array_like, int}) – Number of values padded to the edges of each axis. ((before_1, after_1), ... (before_N, after_N)) unique pad widths for each axis. (before, after) or ((before, after),) yields same before and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes.

  • mode (str or function, optional) –

    One of the following string values or a user supplied function.

    ’constant’ (default)

    Pads with a constant value.

    ’edge’

    Pads with the edge values of array.

    ’linear_ramp’

    Pads with the linear ramp between end_value and the array edge value.

    ’maximum’

    Pads with the maximum value of all or part of the vector along each axis.

    ’mean’

    Pads with the mean value of all or part of the vector along each axis.

    ’median’

    Pads with the median value of all or part of the vector along each axis.

    ’minimum’

    Pads with the minimum value of all or part of the vector along each axis.

    ’reflect’

    Pads with the reflection of the vector mirrored on the first and last values of the vector along each axis.

    ’symmetric’

    Pads with the reflection of the vector mirrored along the edge of the array.

    ’wrap’

    Pads with the wrap of the vector along the axis. The first values are used to pad the end and the end values are used to pad the beginning.

    ’empty’

    Pads with undefined values.

  • stat_length (sequence or int, optional) –

    Used in ‘maximum’, ‘mean’, ‘median’, and ‘minimum’. Number of values at edge of each axis used to calculate the statistic value.

    ((before_1, after_1), ... (before_N, after_N)) unique statistic lengths for each axis.

    (before, after) or ((before, after),) yields same before and after statistic lengths for each axis.

    (stat_length,) or int is a shortcut for before = after = statistic length for all axes.

    Default is None, to use the entire axis.

  • constant_values (sequence or scalar, optional) –

    Used in ‘constant’. The values to set the padded values for each axis.

    ((before_1, after_1), ... (before_N, after_N)) unique pad constants for each axis.

    (before, after) or ((before, after),) yields same before and after constants for each axis.

    (constant,) or constant is a shortcut for before = after = constant for all axes.

    Default is 0.

  • end_values (sequence or scalar, optional) –

    Used in ‘linear_ramp’. The values used for the ending value of the linear_ramp and that will form the edge of the padded array.

    ((before_1, after_1), ... (before_N, after_N)) unique end values for each axis.

    (before, after) or ((before, after),) yields same before and after end values for each axis.

    (constant,) or constant is a shortcut for before = after = constant for all axes.

    Default is 0.

  • reflect_type ({'even', 'odd'}, optional) – Used in ‘reflect’, and ‘symmetric’. The ‘even’ style is the default with an unaltered reflection around the edge value. For the ‘odd’ style, the extended part of the array is created by subtracting the reflected values from two times the edge value.

Return type:

Array

Returns:

pad (ndarray) – Padded array of rank equal to array with shape increased according to pad_width.

scico.numpy.partition(a, kth, axis=-1)#

Return a partitioned copy of an array.

LAX-backend implementation of numpy.partition.

The JAX version requires the kth argument to be a static integer rather than a general array. This is implemented via two calls to jax.lax.top_k. If you’re only accessing the top or bottom k values of the output, it may be more efficient to call jax.lax.top_k directly.

The JAX version differs from the NumPy version in the treatment of NaN entries; NaNs which have the negative bit set are sorted to the beginning of the array.

Original docstring below.

Creates a copy of the array with its elements rearranged in such a way that the value of the element in k-th position is in the position the value would be in a sorted array. In the partitioned array, all elements before the k-th element are less than or equal to that element, and all the elements after the k-th element are greater than or equal to that element. The ordering of the elements in the two partitions is undefined.

New in version 1.8.0.

Parameters:
  • a (array_like) – Array to be sorted.

  • kth (int or sequence of ints) –

    Element index to partition by. The k-th value of the element will be in its final sorted position and all smaller elements will be moved before it and all equal or greater elements behind it. The order of all elements in the partitions is undefined. If provided with a sequence of k-th it will partition all elements indexed by k-th of them into their sorted position at once.

    Deprecated since version 1.22.0: Passing booleans as index is deprecated.

  • axis (int or None, optional) – Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.

Return type:

Array

Returns:

partitioned_array (ndarray) – Array of the same type and shape as a.

scico.numpy.piecewise(x, condlist, funclist, *args, **kw)#

Evaluate a piecewise-defined function.

LAX-backend implementation of numpy.piecewise.

Unlike np.piecewise, jax.numpy.piecewise requires functions in funclist to be traceable by JAX, as it is implemented via jax.lax.switch. See the jax.lax.switch documentation for more information.

Original docstring below.

Given a set of conditions and corresponding functions, evaluate each function on the input data wherever its condition is true.

Parameters:
  • x (ndarray or scalar) – The input domain.

  • condlist (list of bool arrays or bool scalars) –

    Each boolean array corresponds to a function in funclist. Wherever condlist[i] is True, funclist[i](x) is used as the output value.

    Each boolean array in condlist selects a piece of x, and should therefore be of the same shape as x.

    The length of condlist must correspond to that of funclist. If one extra function is given, i.e. if len(funclist) == len(condlist) + 1, then that extra function is the default value, used wherever all conditions are false.

  • funclist (list of callables, f(x,*args,**kw), or scalars) – Each function is evaluated over x wherever its corresponding condition is True. It should take a 1d array as input and give an 1d array or a scalar value as output. If, instead of a callable, a scalar is provided then a constant function (lambda x: scalar) is assumed.

  • args (tuple, optional) – Any further arguments given to piecewise are passed to the functions upon execution, i.e., if called piecewise(..., ..., 1, 'a'), then each function is called as f(x, 1, 'a').

  • kw (dict, optional) – Keyword arguments used in calling piecewise are passed to the functions upon execution, i.e., if called piecewise(..., ..., alpha=1), then each function is called as f(x, alpha=1).

Return type:

Array

Returns:

out (ndarray) – The output is the same shape and type as x and is found by calling the functions in funclist on the appropriate portions of x, as defined by the boolean arrays in condlist. Portions not covered by any condition have a default value of 0.

scico.numpy.place(*args, **kwargs)#

Change elements of an array based on conditional and input values.

LAX-backend implementation of numpy.place.

Numpy function numpy.place is not available in JAX and will raise a NotImplementedError, because np.place modifies its arguments in-place, and in JAX arrays are immutable. A JAX-compatible approach to array updates can be found in jax.numpy.ndarray.at.

Original docstring below.

Similar to np.copyto(arr, vals, where=mask), the difference is that place uses the first N elements of vals, where N is the number of True values in mask, while copyto uses the elements where mask is True.

Note that extract does the exact opposite of place.

scico.numpy.polydiv(u, v, *, trim_leading_zeros=False)#

Returns the quotient and remainder of polynomial division.

LAX-backend implementation of numpy.polydiv.

Setting trim_leading_zeros=True makes the output match that of numpy. But prevents the function from being able to be used in compiled code. Due to differences in accumulation of floating point arithmetic errors, the cutoff for values to be considered zero may lead to inconsistent results between NumPy and JAX, and even between different JAX backends. The result may lead to inconsistent output shapes when trim_leading_zeros=True.

Original docstring below.

Note

This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.

The input arrays are the coefficients (including any coefficients equal to zero) of the “numerator” (dividend) and “denominator” (divisor) polynomials, respectively.

Parameters:
  • u (array_like or poly1d) – Dividend polynomial’s coefficients.

  • v (array_like or poly1d) – Divisor polynomial’s coefficients.

Return type:

Tuple[Array, Array]

Returns:

  • q (ndarray) – Coefficients, including those equal to zero, of the quotient.

  • r (ndarray) – Coefficients, including those equal to zero, of the remainder.

scico.numpy.polymul(a1, a2, *, trim_leading_zeros=False)#

Find the product of two polynomials.

LAX-backend implementation of numpy.polymul.

Setting trim_leading_zeros=True makes the output match that of numpy. But prevents the function from being able to be used in compiled code. Due to differences in accumulation of floating point arithmetic errors, the cutoff for values to be considered zero may lead to inconsistent results between NumPy and JAX, and even between different JAX backends. The result may lead to inconsistent output shapes when trim_leading_zeros=True.

Original docstring below.

Note

This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.

Finds the polynomial resulting from the multiplication of the two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree.

Parameters:
  • a1 (array_like or poly1d object) – Input polynomials.

  • a2 (array_like or poly1d object) – Input polynomials.

Return type:

Array

Returns:

out (ndarray or poly1d object) – The polynomial resulting from the multiplication of the inputs. If either inputs is a poly1d object, then the output is also a poly1d object. Otherwise, it is a 1D array of polynomial coefficients from highest to lowest degree.

scico.numpy.positive(x, /)#

Numerical positive, element-wise.

LAX-backend implementation of numpy.positive.

Original docstring below.

New in version 1.13.0.

Parameters:

x (array_like or scalar) – Input array.

Returns:

y (ndarray or scalar) – Returned array or scalar: y = +x. This is a scalar if x is a scalar.

scico.numpy.power(x1, x2, /)#

First array elements raised to powers from second array, element-wise.

LAX-backend implementation of numpy.power.

Original docstring below.

Raise each base in x1 to the positionally-corresponding power in x2. x1 and x2 must be broadcastable to the same shape.

An integer type raised to a negative integer power will raise a ValueError.

Negative values raised to a non-integral value will return nan. To get complex results, cast the input to complex, or specify the dtype to be complex (see the example below).

Parameters:
  • x1 (array_like) – The bases.

  • x2 (array_like) – The exponents. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Return type:

Array

Returns:

y (ndarray) – The bases in x1 raised to the exponents in x2. This is a scalar if both x1 and x2 are scalars.

scico.numpy.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())
scico.numpy.prod(a, axis=None, dtype=None, out=None, keepdims=False, initial=None, where=None, promote_integers=True)#

Return the product of array elements over a given axis.

LAX-backend implementation of numpy.prod.

Original docstring below.

Parameters:
  • a (array_like) – Input data.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which a product is performed. The default, axis=None, will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis.

  • dtype (dtype, optional) – The type of the returned array, as well as of the accumulator in which the elements are multiplied. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the prod method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • initial (scalar, optional) – The starting value for this product. See ~numpy.ufunc.reduce for details.

  • where (array_like of bool, optional) – Elements to include in the product. See ~numpy.ufunc.reduce for details.

  • promote_integers (bool, default=True) – If True, then integer inputs will be promoted to the widest available integer dtype, following numpy’s behavior. If False, the result will have the same dtype as the input. promote_integers is ignored if dtype is specified.

Return type:

Array

Returns:

product_along_axis (ndarray, see dtype parameter above.) – An array shaped as a but with the specified axis removed. Returns a reference to out if specified.

scico.numpy.promote_types(a, b)#

Returns the type to which a binary operation should cast its arguments.

For details of JAX’s type promotion semantics, see Type promotion semantics.

Parameters:
Return type:

dtype

Returns:

A numpy.dtype object.

scico.numpy.ptp(a, axis=None, out=None, keepdims=False)#

Range of values (maximum - minimum) along an axis.

LAX-backend implementation of numpy.ptp.

Original docstring below.

The name of the function comes from the acronym for ‘peak to peak’.

Warning

ptp preserves the data type of the array. This means the return value for an input of signed integers with n bits (e.g. np.int8, np.int16, etc) is also a signed integer with n bits. In that case, peak-to-peak values greater than 2**(n-1)-1 will be returned as negative values. An example with a work-around is shown below.

Parameters:
  • a (array_like) – Input values.

  • axis (None or int or tuple of ints, optional) – Axis along which to find the peaks. By default, flatten the array. axis may be negative, in which case it counts from the last to the first axis.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the ptp method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

Return type:

Array

Returns:

ptp (ndarray or scalar) – The range of a given array - scalar if array is one-dimensional or a new array holding the result along the given axis

scico.numpy.put(*args, **kwargs)#

Replaces specified elements of an array with given values.

LAX-backend implementation of numpy.put.

Numpy function numpy.put is not available in JAX and will raise a NotImplementedError, because np.put modifies its arguments in-place, and in JAX arrays are immutable. A JAX-compatible approach to array updates can be found in jax.numpy.ndarray.at.

Original docstring below.

The indexing works on the flattened target array. put is roughly equivalent to:

a.flat[ind] = v
scico.numpy.rad2deg(x, /)#

Convert angles from radians to degrees.

LAX-backend implementation of numpy.rad2deg.

Original docstring below.

Parameters:

x (array_like) – Angle in radians.

Return type:

Array

Returns:

y (ndarray) – The corresponding angle in degrees. This is a scalar if x is a scalar.

scico.numpy.radians(x, /)#

Convert angles from degrees to radians.

LAX-backend implementation of numpy.deg2rad.

Original docstring below.

Parameters:

x (array_like) – Angles in degrees.

Return type:

Array

Returns:

y (ndarray) – The corresponding angle in radians. This is a scalar if x is a scalar.

scico.numpy.ravel(a, order='C')#

Return a contiguous flattened array.

LAX-backend implementation of numpy.ravel.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

A 1-D array, containing the elements of the input, is returned. A copy is made only if needed.

As of NumPy 1.10, the returned array will have the same type as the input array. (for example, a masked array will be returned for a masked array input)

Parameters:
  • a (array_like) – Input array. The elements in a are read in the order specified by order, and packed as a 1-D array.

  • order ({'C','F', 'A', 'K'}, optional) – The elements of a are read using this index order. ‘C’ means to index the elements in row-major, C-style order, with the last axis index changing fastest, back to the first axis index changing slowest. ‘F’ means to index the elements in column-major, Fortran-style order, with the first index changing fastest, and the last index changing slowest. Note that the ‘C’ and ‘F’ options take no account of the memory layout of the underlying array, and only refer to the order of axis indexing. ‘A’ means to read the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise. ‘K’ means to read the elements in the order they occur in memory, except for reversing the data when strides are negative. By default, ‘C’ index order is used.

Return type:

Array

Returns:

y (array_like) – y is an array of the same subtype as a, with shape (a.size,). Note that matrices are special cased for backward compatibility, if a is a matrix, then y is a 1-D ndarray.

scico.numpy.ravel_multi_index(multi_index, dims, mode='raise', order='C')#

Converts a tuple of index arrays into an array of flat

LAX-backend implementation of numpy.ravel_multi_index.

Original docstring below.

indices, applying boundary modes to the multi-index.

Parameters:
  • multi_index (tuple of array_like) – A tuple of integer arrays, one array for each dimension.

  • dims (tuple of ints) – The shape of array into which the indices from multi_index apply.

  • mode ({'raise', 'wrap', 'clip'}, optional) –

    Specifies how out-of-bounds indices are handled. Can specify either one mode or a tuple of modes, one mode per index.

    • ’raise’ – raise an error (default)

    • ’wrap’ – wrap around

    • ’clip’ – clip to the range

    In ‘clip’ mode, a negative index which would normally wrap will clip to 0 instead.

  • order ({'C', 'F'}, optional) – Determines whether the multi-index should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order.

Return type:

Array

Returns:

raveled_indices (ndarray) – An array of indices into the flattened version of an array of dimensions dims.

scico.numpy.real(val, /)#

Return the real part of the complex argument.

LAX-backend implementation of numpy.real.

Original docstring below.

Parameters:

val (array_like) – Input array.

Return type:

Array

Returns:

out (ndarray or scalar) – The real component of the complex argument. If val is real, the type of val is used for the output. If val has complex elements, the returned type is float.

scico.numpy.reciprocal(x, /)#

Return the reciprocal of the argument, element-wise.

LAX-backend implementation of numpy.reciprocal.

Original docstring below.

Calculates 1/x.

Parameters:

x (array_like) – Input array.

Return type:

Array

Returns:

y (ndarray) – Return array. This is a scalar if x is a scalar.

scico.numpy.remainder(x1, x2, /)#

Returns the element-wise remainder of division.

LAX-backend implementation of numpy.remainder.

Original docstring below.

Computes the remainder complementary to the floor_divide function. It is equivalent to the Python modulus operator``x1 % x2`` and has the same sign as the divisor x2. The MATLAB function equivalent to np.remainder is mod.

Warning

This should not be confused with:

  • Python 3.7’s math.remainder and C’s remainder, which computes the IEEE remainder, which are the complement to round(x1 / x2).

  • The MATLAB rem function and or the C % operator which is the complement to int(x1 / x2).

Parameters:
  • x1 (array_like) – Dividend array.

  • x2 (array_like) – Divisor array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Return type:

Array

Returns:

y (ndarray) – The element-wise remainder of the quotient floor_divide(x1, x2). This is a scalar if both x1 and x2 are scalars.

scico.numpy.repeat(a, repeats, axis=None, *, total_repeat_length=None)#

Repeat elements of an array.

LAX-backend implementation of numpy.repeat.

JAX adds the optional total_repeat_length parameter which specifies the total number of repeat, and defaults to sum(repeats). It must be specified for repeat to be compilable. If sum(repeats) is larger than the specified total_repeat_length the remaining values will be discarded. In the case of sum(repeats) being smaller than the specified target length, the final value will be repeated.

Original docstring below.

Parameters:
  • a (array_like) – Input array.

  • repeats (int or array of ints) – The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.

  • axis (int, optional) – The axis along which to repeat values. By default, use the flattened input array, and return a flat output array.

Return type:

Array

Returns:

repeated_array (ndarray) – Output array which has the same shape as a, except along the given axis.

scico.numpy.reshape(a, newshape, order='C')#

Gives a new shape to an array without changing its data.

LAX-backend implementation of numpy.reshape.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

Parameters:
  • a (array_like) – Array to be reshaped.

  • newshape (int or tuple of ints) – The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

  • order ({'C', 'F', 'A'}, optional) – Read the elements of a using this index order, and place the elements into the reshaped array using this index order. ‘C’ means to read / write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest. ‘F’ means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the ‘C’ and ‘F’ options take no account of the memory layout of the underlying array, and only refer to the order of indexing. ‘A’ means to read / write the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise.

Return type:

Array

Returns:

reshaped_array (ndarray) – This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

scico.numpy.resize(a, new_shape)#

Return a new array with the specified shape.

LAX-backend implementation of numpy.resize.

Original docstring below.

If the new array is larger than the original array, then the new array is filled with repeated copies of a. Note that this behavior is different from a.resize(new_shape) which fills with zeros instead of repeated copies of a.

Parameters:
  • a (array_like) – Array to be resized.

  • new_shape (int or tuple of int) – Shape of resized array.

Return type:

Array

Returns:

reshaped_array (ndarray) – The new array is formed from the data in the old array, repeated if necessary to fill out the required number of elements. The data are repeated iterating over the array in C-order.

scico.numpy.result_type(*args)#

Returns the type that results from applying the NumPy

LAX-backend implementation of numpy.result_type.

Original docstring below.

type promotion rules to the arguments.

Type promotion in NumPy works similarly to the rules in languages like C++, with some slight differences. When both scalars and arrays are used, the array’s type takes precedence and the actual value of the scalar is taken into account.

For example, calculating 3*a, where a is an array of 32-bit floats, intuitively should result in a 32-bit float output. If the 3 is a 32-bit integer, the NumPy rules indicate it can’t convert losslessly into a 32-bit float, so a 64-bit float should be the result type. By examining the value of the constant, ‘3’, we see that it fits in an 8-bit integer, which can be cast losslessly into the 32-bit float.

Return type:

dtype

Returns:

out (dtype) – The result type.

scico.numpy.rint(x, /)#

Round elements of the array to the nearest integer.

LAX-backend implementation of numpy.rint.

Original docstring below.

Parameters:

x (array_like) – Input array.

Return type:

Array

Returns:

out (ndarray or scalar) – Output array is same shape and type as x. This is a scalar if x is a scalar.

scico.numpy.roll(a, shift, axis=None)#

Roll array elements along a given axis.

LAX-backend implementation of numpy.roll.

Original docstring below.

Elements that roll beyond the last position are re-introduced at the first.

Parameters:
  • a (array_like) – Input array.

  • shift (int or tuple of ints) – The number of places by which elements are shifted. If a tuple, then axis must be a tuple of the same size, and each of the given axes is shifted by the corresponding number. If an int while axis is a tuple of ints, then the same value is used for all given axes.

  • axis (int or tuple of ints, optional) – Axis or axes along which elements are shifted. By default, the array is flattened before shifting, after which the original shape is restored.

Return type:

Array

Returns:

res (ndarray) – Output array, with the same shape as a.

scico.numpy.rollaxis(a, axis, start=0)#

Roll the specified axis backwards, until it lies in a given position.

LAX-backend implementation of numpy.rollaxis.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

This function continues to be supported for backward compatibility, but you should prefer moveaxis. The moveaxis function was added in NumPy 1.11.

Parameters:
  • a (ndarray) – Input array.

  • axis (int) – The axis to be rolled. The positions of the other axes do not change relative to one another.

  • start (int, optional) –

    When start <= axis, the axis is rolled back until it lies in this position. When start > axis, the axis is rolled until it lies before this position. The default, 0, results in a “complete” roll. The following table describes how negative values of start are interpreted:

    start

    Normalized start

    -(arr.ndim+1)

    raise AxisError

    -arr.ndim

    0

    -1

    arr.ndim-1

    0

    0

    arr.ndim

    arr.ndim

    arr.ndim + 1

    raise AxisError

Returns:

res (ndarray) – For NumPy >= 1.10.0 a view of a is always returned. For earlier NumPy versions a view of a is returned only if the order of the axes is changed, otherwise the input array is returned.

scico.numpy.roots(p, *, strip_zeros=True)#

Return the roots of a polynomial with coefficients given in p.

LAX-backend implementation of numpy.roots.

Unlike the numpy version of this function, the JAX version returns the roots in a complex array regardless of the values of the roots. Additionally, the jax version of this function adds the strip_zeros function which must be set to False for the function to be compatible with JIT and other JAX transformations. With strip_zeros=False, if your coefficients have leading zeros, the roots will be padded with NaN values:

>>> coeffs = jnp.array([0, 1, 2])

# The default behavior matches numpy and strips leading zeros: >>> jnp.roots(coeffs) Array([-2.+0.j], dtype=complex64)

# With strip_zeros=False, extra roots are set to NaN: >>> jnp.roots(coeffs, strip_zeros=False) Array([-2. +0.j, nan+nanj], dtype=complex64)

Original docstring below.

Note

This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.

The values in the rank-1 array p are coefficients of a polynomial. If the length of p is n+1 then the polynomial is described by:

p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n]
Parameters:
  • p (array_like) – Rank-1 array of polynomial coefficients.

  • strip_zeros (bool, default=True) – If set to True, then leading zeros in the coefficients will be stripped, similar to numpy.roots. If set to False, leading zeros will not be stripped, and undefined roots will be represented by NaN values in the function output. strip_zeros must be set to False for the function to be compatible with jax.jit and other JAX transformations.

Return type:

Array

Returns:

out (ndarray) – An array containing the roots of the polynomial.

scico.numpy.rot90(m, k=1, axes=(0, 1))#

Rotate an array by 90 degrees in the plane specified by axes.

LAX-backend implementation of numpy.rot90.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

Rotation direction is from the first towards the second axis.

Parameters:
  • m (array_like) – Array of two or more dimensions.

  • k (integer) – Number of times the array is rotated by 90 degrees.

  • axes ((2,) array_like) – The array is rotated in the plane defined by the axes. Axes must be different.

Return type:

Array

Returns:

y (ndarray) – A rotated view of m.

scico.numpy.round_(a, decimals=0, out=None)#

Evenly round to the given number of decimals.

LAX-backend implementation of numpy.around.

Original docstring below.

Parameters:
  • a (array_like) – Input data.

  • decimals (int, optional) – Number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point.

Return type:

Array

Returns:

rounded_array (ndarray) – An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned.

The real and imaginary parts of complex numbers are rounded separately. The result of rounding a float is a float.

scico.numpy.row_stack(tup, dtype=None)#

Stack arrays in sequence vertically (row wise).

LAX-backend implementation of numpy.vstack.

Original docstring below.

This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). Rebuilds arrays divided by vsplit.

This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations.

np.row_stack is an alias for vstack. They are the same function.

Parameters:
  • tup (sequence of ndarrays) – The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length.

  • dtype (str or dtype) – If provided, the destination array will have this dtype. Cannot be provided together with out.

Return type:

Array

Returns:

stacked (ndarray) – The array formed by stacking the given arrays, will be at least 2-D.

scico.numpy.save(file, arr, allow_pickle=True, fix_imports=True)#

Save an array to a binary file in NumPy .npy format.

Parameters:
  • file (file, str, or pathlib.Path) – File or filename to which the data is saved. If file is a file-object, then the filename is unchanged. If file is a string or Path, a .npy extension will be appended to the filename if it does not already have one.

  • arr (array_like) – Array data to be saved.

  • allow_pickle (bool, optional) – Allow saving object arrays using Python pickles. Reasons for disallowing pickles include security (loading pickled data can execute arbitrary code) and portability (pickled objects may not be loadable on different Python installations, for example if the stored objects require libraries that are not available, and not all pickled data is compatible between Python 2 and Python 3). Default: True

  • fix_imports (bool, optional) – Only useful in forcing objects in object arrays on Python 3 to be pickled in a Python 2 compatible way. If fix_imports is True, pickle will try to map the new Python 3 names to the old module names used in Python 2, so that the pickle data stream is readable with Python 2.

See also

savez

Save several arrays into a .npz archive

savetxt, load

Notes

For a description of the .npy format, see numpy.lib.format.

Any data saved to the file is appended to the end of the file.

Examples

>>> from tempfile import TemporaryFile
>>> outfile = TemporaryFile()
>>> x = np.arange(10)
>>> np.save(outfile, x)
>>> _ = outfile.seek(0) # Only needed here to simulate closing & reopening file
>>> np.load(outfile)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> with open('test.npy', 'wb') as f:
...     np.save(f, np.array([1, 2]))
...     np.save(f, np.array([1, 3]))
>>> with open('test.npy', 'rb') as f:
...     a = np.load(f)
...     b = np.load(f)
>>> print(a, b)
# [1 2] [1 3]
scico.numpy.savez(file, *args, **kwds)#

Save several arrays into a single file in uncompressed .npz format.

Provide arrays as keyword arguments to store them under the corresponding name in the output file: savez(fn, x=x, y=y).

If arrays are specified as positional arguments, i.e., savez(fn, x, y), their names will be arr_0, arr_1, etc.

Parameters:
  • file (str or file) – Either the filename (string) or an open file (file-like object) where the data will be saved. If file is a string or a Path, the .npz extension will be appended to the filename if it is not already there.

  • args (Arguments, optional) – Arrays to save to the file. Please use keyword arguments (see kwds below) to assign names to arrays. Arrays specified as args will be named “arr_0”, “arr_1”, and so on.

  • kwds (Keyword arguments, optional) – Arrays to save to the file. Each array will be saved to the output file with its corresponding keyword name.

Returns:

None

See also

save

Save a single array to a binary file in NumPy format.

savetxt

Save an array to a file as plain text.

savez_compressed

Save several arrays into a compressed .npz archive

Notes

The .npz file format is a zipped archive of files named after the variables they contain. The archive is not compressed and each file in the archive contains one variable in .npy format. For a description of the .npy format, see numpy.lib.format.

When opening the saved .npz file with load a NpzFile object is returned. This is a dictionary-like object which can be queried for its list of arrays (with the .files attribute), and for the arrays themselves.

Keys passed in kwds are used as filenames inside the ZIP archive. Therefore, keys should be valid filenames; e.g., avoid keys that begin with / or contain ..

When naming variables with keyword arguments, it is not possible to name a variable file, as this would cause the file argument to be defined twice in the call to savez.

Examples

>>> from tempfile import TemporaryFile
>>> outfile = TemporaryFile()
>>> x = np.arange(10)
>>> y = np.sin(x)

Using savez with *args, the arrays are saved with default names.

>>> np.savez(outfile, x, y)
>>> _ = outfile.seek(0) # Only needed here to simulate closing & reopening file
>>> npzfile = np.load(outfile)
>>> npzfile.files
['arr_0', 'arr_1']
>>> npzfile['arr_0']
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

Using savez with **kwds, the arrays are saved with the keyword names.

>>> outfile = TemporaryFile()
>>> np.savez(outfile, x=x, y=y)
>>> _ = outfile.seek(0)
>>> npzfile = np.load(outfile)
>>> sorted(npzfile.files)
['x', 'y']
>>> npzfile['x']
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
scico.numpy.searchsorted(a, v, side='left', sorter=None, *, method='scan')#

Find indices where elements should be inserted to maintain order.

LAX-backend implementation of numpy.searchsorted.

Original docstring below.

Find the indices into a sorted array a such that, if the corresponding elements in v were inserted before the indices, the order of a would be preserved.

Assuming that a is sorted:

side

returned index i satisfies

left

a[i-1] < v <= a[i]

right

a[i-1] <= v < a[i]

Parameters:
  • a (1-D array_like) – Input array. If sorter is None, then it must be sorted in ascending order, otherwise sorter must be an array of indices that sort it.

  • v (array_like) – Values to insert into a.

  • side ({'left', 'right'}, optional) – If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of a).

  • method (str) – One of ‘scan’ (default), ‘sort’ or ‘compare_all’. Controls the method used by the implementation: ‘scan’ tends to be more performant on CPU (particularly when a is very large), ‘sort’ is often more performant on accelerator backends like GPU and TPU (particularly when v is very large), and ‘compare_all’ can be most performant when a is very small.

Return type:

Array

Returns:

indices (int or array of ints) – Array of insertion points with the same shape as v, or an integer if v is a scalar.

scico.numpy.select(condlist, choicelist, default=0)#

Return an array drawn from elements in choicelist, depending on conditions.

LAX-backend implementation of numpy.select.

Original docstring below.

Parameters:
  • condlist (list of bool ndarrays) – The list of conditions which determine from which array in choicelist the output elements are taken. When multiple conditions are satisfied, the first one encountered in condlist is used.

  • choicelist (list of ndarrays) – The list of arrays from which the output elements are taken. It has to be of the same length as condlist.

  • default (scalar, optional) – The element inserted in output when all conditions evaluate to False.

Returns:

output (ndarray) – The output at position m is the m-th element of the array in choicelist where the m-th element of the corresponding array in condlist is True.

scico.numpy.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.

    New in version 1.14.0.

    Changed in version 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.  ])
scico.numpy.setdiff1d(ar1, ar2, assume_unique=False, *, size=None, fill_value=None)#

Find the set difference of two arrays.

LAX-backend implementation of numpy.setdiff1d.

Because the size of the output of setdiff1d is data-dependent, the function is not typically compatible with JIT. The JAX version adds the optional size argument which must be specified statically for jnp.setdiff1d to be used within some of JAX’s transformations.

Original docstring below.

Return the unique values in ar1 that are not in ar2.

Parameters:
  • ar1 (array_like) – Input array.

  • ar2 (array_like) – Input comparison array.

  • assume_unique (bool) – If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.

  • size (int, optional) – If specified, the first size elements of the result will be returned. If there are fewer elements than size indicates, the return value will be padded with fill_value.

  • fill_value (array_like, optional) – When size is specified and there are fewer than the indicated number of elements, the remaining elements will be filled with fill_value, which defaults to zero.

Return type:

Array

Returns:

setdiff1d (ndarray) – 1D array of values in ar1 that are not in ar2. The result is sorted when assume_unique=False, but otherwise only sorted if the input is sorted.

scico.numpy.setxor1d(ar1, ar2, assume_unique=False)#

Find the set exclusive-or of two arrays.

LAX-backend implementation of numpy.setxor1d.

In the JAX version, the input arrays are explicitly flattened regardless of assume_unique value.

Original docstring below.

Return the sorted, unique values that are in only one (not both) of the input arrays.

Parameters:
  • ar1 (array_like) – Input arrays.

  • ar2 (array_like) – Input arrays.

  • assume_unique (bool) – If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.

Return type:

Array

Returns:

setxor1d (ndarray) – Sorted 1D array of unique values that are in only one of the input arrays.

scico.numpy.shape(a)#

Return the shape of an array.

Parameters:

a (array_like) – Input array.

Returns:

shape (tuple of ints) – The elements of the shape tuple give the lengths of the corresponding array dimensions.

See also

len

len(a) is equivalent to np.shape(a)[0] for N-D arrays with N>=1.

ndarray.shape

Equivalent array method.

Examples

>>> np.shape(np.eye(3))
(3, 3)
>>> np.shape([[1, 3]])
(1, 2)
>>> np.shape([0])
(1,)
>>> np.shape(0)
()
>>> a = np.array([(1, 2), (3, 4), (5, 6)],
...              dtype=[('x', 'i4'), ('y', 'i4')])
>>> np.shape(a)
(3,)
>>> a.shape
(3,)
scico.numpy.sign(x, /)#

Returns an element-wise indication of the sign of a number.

LAX-backend implementation of numpy.sign.

Original docstring below.

The sign function returns -1 if x < 0, 0 if x==0, 1 if x > 0. nan is returned for nan inputs.

For complex inputs, the sign function returns sign(x.real) + 0j if x.real != 0 else sign(x.imag) + 0j.

complex(nan, 0) is returned for complex nan inputs.

Parameters:

x (array_like) – Input values.

Return type:

Array

Returns:

y (ndarray) – The sign of x. This is a scalar if x is a scalar.

scico.numpy.signbit(x, /)#

Returns element-wise True where signbit is set (less than zero).

LAX-backend implementation of numpy.signbit.

Original docstring below.

Parameters:

x (array_like) – The input value(s).

Return type:

Array

Returns:

result (ndarray of bool) – Output array, or reference to out if that was supplied. This is a scalar if x is a scalar.

scico.numpy.sin(x, /)#

Trigonometric sine, element-wise.

LAX-backend implementation of numpy.sin.

Original docstring below.

Parameters:

x (array_like) – Angle, in radians (\(2 \pi\) rad equals 360 degrees).

Returns:

y (array_like) – The sine of each element of x. This is a scalar if x is a scalar.

scico.numpy.sinc(x, /)#

Return the normalized sinc function.

LAX-backend implementation of numpy.sinc.

Original docstring below.

The sinc function is equal to \(\sin(\pi x)/(\pi x)\) for any argument \(x\ne 0\). sinc(0) takes the limit value 1, making sinc not only everywhere continuous but also infinitely differentiable.

Note

Note the normalization factor of pi used in the definition. This is the most commonly used definition in signal processing. Use sinc(x / np.pi) to obtain the unnormalized sinc function \(\sin(x)/x\) that is more common in mathematics.

Parameters:

x (ndarray) – Array (possibly multi-dimensional) of values for which to calculate sinc(x).

Return type:

Array

Returns:

out (ndarray) – sinc(x), which has the same shape as the input.

scico.numpy.sinh(x, /)#

Hyperbolic sine, element-wise.

LAX-backend implementation of numpy.sinh.

Original docstring below.

Equivalent to 1/2 * (np.exp(x) - np.exp(-x)) or -1j * np.sin(1j*x).

Parameters:

x (array_like) – Input array.

Returns:

y (ndarray) – The corresponding hyperbolic sine values. This is a scalar if x is a scalar.

scico.numpy.size(a, axis=None)#

Return the number of elements along a given axis.

Parameters:
  • a (array_like) – Input data.

  • axis (int, optional) – Axis along which the elements are counted. By default, give the total number of elements.

Returns:

element_count (int) – Number of elements along the specified axis.

See also

shape

dimensions of array

ndarray.shape

dimensions of array

ndarray.size

number of elements in array

Examples

>>> a = np.array([[1,2,3],[4,5,6]])
>>> np.size(a)
6
>>> np.size(a,1)
3
>>> np.size(a,0)
2
scico.numpy.sort(a, axis=-1, kind='quicksort', order=None)#

Return a sorted copy of an array.

LAX-backend implementation of numpy.sort.

Original docstring below.

Parameters:
  • a (array_like) – Array to be sorted.

  • axis (int or None, optional) – Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.

  • kind ({'quicksort', 'mergesort', 'heapsort', 'stable'}, optional) –

    Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort or radix sort under the covers and, in general, the actual implementation will vary with data type. The ‘mergesort’ option is retained for backwards compatibility.

    Changed in version 1.15.0.: The ‘stable’ option was added.

  • order (str or list of str, optional) – When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.

Returns:

sorted_array (ndarray) – Array of the same type and shape as a.

scico.numpy.sort_complex(a)#

Sort a complex array using the real part first, then the imaginary part.

LAX-backend implementation of numpy.sort_complex.

Original docstring below.

Parameters:

a (array_like) – Input array

Returns:

out (complex ndarray) – Always returns a sorted complex array.

scico.numpy.split(ary, indices_or_sections, axis=0)#

Split an array into multiple sub-arrays as views into ary.

LAX-backend implementation of numpy.split.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

Parameters:
  • ary (ndarray) – Array to be divided into sub-arrays.

  • indices_or_sections (int or 1-D array) –

    If indices_or_sections is an integer, N, the array will be divided into N equal arrays along axis. If such a split is not possible, an error is raised.

    If indices_or_sections is a 1-D array of sorted integers, the entries indicate where along axis the array is split. For example, [2, 3] would, for axis=0, result in

    • ary[:2]

    • ary[2:3]

    • ary[3:]

    If an index exceeds the dimension of the array along axis, an empty sub-array is returned correspondingly.

  • axis (int, optional) – The axis along which to split, default is 0.

Return type:

List[Array]

Returns:

sub-arrays (list of ndarrays) – A list of sub-arrays as views into ary.

scico.numpy.sqrt(x, /)#

Return the non-negative square-root of an array, element-wise.

LAX-backend implementation of numpy.sqrt.

Original docstring below.

Parameters:

x (array_like) – The values whose square-roots are required.

Returns:

y (ndarray) – An array of the same shape as x, containing the positive square-root of each element in x. If any element in x is complex, a complex array is returned (and the square-roots of negative reals are calculated). If all of the elements in x are real, so is y, with negative elements returning nan. If out was provided, y is a reference to it. This is a scalar if x is a scalar.

scico.numpy.square(x, /)#

Return the element-wise square of the input.

LAX-backend implementation of numpy.square.

Original docstring below.

Parameters:

x (array_like) – Input data.

Return type:

Array

Returns:

out (ndarray or scalar) – Element-wise x*x, of the same shape and dtype as x. This is a scalar if x is a scalar.

scico.numpy.squeeze(a, axis=None)#

Remove axes of length one from a.

LAX-backend implementation of numpy.squeeze.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

Parameters:
  • a (array_like) – Input data.

  • axis (None or int or tuple of ints, optional) –

Return type:

Array

Returns:

squeezed (ndarray) – The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into a. Note that if all axes are squeezed, the result is a 0d array and not a scalar.

scico.numpy.stack(arrays, axis=0, out=None, dtype=None)#

Join a sequence of arrays along a new axis.

LAX-backend implementation of numpy.stack.

Original docstring below.

The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension.

New in version 1.10.0.

Parameters:
  • arrays (sequence of array_like) – Each array must have the same shape.

  • axis (int, optional) – The axis in the result array along which the input arrays are stacked.

  • dtype (str or dtype) – If provided, the destination array will have this dtype. Cannot be provided together with out.

Return type:

Array

Returns:

stacked (ndarray) – The stacked array has one more dimension than the input arrays.

scico.numpy.std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=None)#

Compute the standard deviation along the specified axis.

LAX-backend implementation of numpy.std.

Original docstring below.

Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

Parameters:
  • a (array_like) – Calculate the standard deviation of these values.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.

  • dtype (dtype, optional) – Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type.

  • ddof (int, optional) – Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the std method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • where (array_like of bool, optional) – Elements to include in the standard deviation. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

standard_deviation (ndarray, see dtype parameter above.) – If out is None, return a new array containing the standard deviation, otherwise return a reference to the output array.

scico.numpy.subtract(x1, x2, /)#

Subtract arguments, element-wise.

LAX-backend implementation of numpy.subtract.

Original docstring below.

Parameters:
  • x1 (array_like) – The arrays to be subtracted from each other. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • x2 (array_like) – The arrays to be subtracted from each other. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Returns:

y (ndarray) – The difference of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

scico.numpy.sum(a, axis=None, dtype=None, out=None, keepdims=False, initial=None, where=None, promote_integers=True)#

Sum of array elements over a given axis.

LAX-backend implementation of numpy.sum.

Original docstring below.

Parameters:
  • a (array_like) – Elements to sum.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.

  • dtype (dtype, optional) – The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • initial (scalar, optional) – Starting value for the sum. See ~numpy.ufunc.reduce for details.

  • where (array_like of bool, optional) – Elements to include in the sum. See ~numpy.ufunc.reduce for details.

  • promote_integers (bool, default=True) – If True, then integer inputs will be promoted to the widest available integer dtype, following numpy’s behavior. If False, the result will have the same dtype as the input. promote_integers is ignored if dtype is specified.

Return type:

Array

Returns:

sum_along_axis (ndarray) – An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

scico.numpy.swapaxes(a, axis1, axis2)#

Interchange two axes of an array.

LAX-backend implementation of numpy.swapaxes.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

Parameters:
  • a (array_like) – Input array.

  • axis1 (int) – First axis.

  • axis2 (int) – Second axis.

Return type:

Array

Returns:

a_swapped (ndarray) – For NumPy >= 1.10.0, if a is an ndarray, then a view of a is returned; otherwise a new array is created. For earlier NumPy versions a view of a is returned only if the order of the axes is changed, otherwise the input array is returned.

scico.numpy.take(a, indices, axis=None, out=None, mode=None, unique_indices=False, indices_are_sorted=False, fill_value=None)#

Take elements from an array along an axis.

LAX-backend implementation of numpy.take.

By default, JAX assumes that all indices are in-bounds. Alternative out-of-bound index semantics can be specified via the mode parameter (see below).

Original docstring below.

When axis is not None, this function does the same thing as “fancy” indexing (indexing arrays using arrays); however, it can be easier to use if you need elements along a given axis. A call such as np.take(arr, indices, axis=3) is equivalent to arr[:,:,:,indices,...].

Explained without fancy indexing, this is equivalent to the following use of ndindex, which sets each of ii, jj, and kk to a tuple of indices:

Ni, Nk = a.shape[:axis], a.shape[axis+1:]
Nj = indices.shape
for ii in ndindex(Ni):
    for jj in ndindex(Nj):
        for kk in ndindex(Nk):
            out[ii + jj + kk] = a[ii + (indices[jj],) + kk]
Parameters:
  • a (array_like (Ni..., M, Nk...)) – The source array.

  • indices (array_like (Nj...)) – The indices of the values to extract.

  • axis (int, optional) – The axis over which to select values. By default, the flattened input array is used.

  • mode (string, default="fill") – Out-of-bounds indexing mode. The default mode=”fill” returns invalid values (e.g. NaN) for out-of bounds indices (see also fill_value below). For more discussion of mode options, see jax.numpy.ndarray.at.

  • fill_value (optional) – The fill value to return for out-of-bounds slices when mode is ‘fill’. Ignored otherwise. Defaults to NaN for inexact types, the largest negative value for signed types, the largest positive value for unsigned types, and True for booleans.

  • unique_indices (bool, default=False) – If True, the implementation will assume that the indices are unique, which can result in more efficient execution on some backends.

  • indices_are_sorted (bool, default=False) – If True, the implementation will assume that the indices are sorted in ascending order, which can lead to more efficient execution on some backends.

Returns:

out (ndarray (Ni…, Nj…, Nk…)) – The returned array has the same type as a.

scico.numpy.tan(x, /)#

Compute tangent element-wise.

LAX-backend implementation of numpy.tan.

Original docstring below.

Equivalent to np.sin(x)/np.cos(x) element-wise.

Parameters:

x (array_like) – Input array.

Returns:

y (ndarray) – The corresponding tangent values. This is a scalar if x is a scalar.

scico.numpy.tanh(x, /)#

Compute hyperbolic tangent element-wise.

LAX-backend implementation of numpy.tanh.

Original docstring below.

Equivalent to np.sinh(x)/np.cosh(x) or -1j * np.tan(1j*x).

Parameters:

x (array_like) – Input array.

Returns:

y (ndarray) – The corresponding hyperbolic tangent values. This is a scalar if x is a scalar.

scico.numpy.tensordot(a, b, axes=2, *, precision=None)#

Compute tensor dot product along specified axes.

LAX-backend implementation of numpy.tensordot.

In addition to the original NumPy arguments listed below, also supports precision for extra control over matrix-multiplication precision on supported devices. precision may be set to None, which means default precision for the backend, a Precision enum value (Precision.DEFAULT, Precision.HIGH or Precision.HIGHEST) or a tuple of two Precision enums indicating separate precision for each argument.

Original docstring below.

Given two tensors, a and b, and an array_like object containing two array_like objects, (a_axes, b_axes), sum the products of a’s and b’s elements (components) over the axes specified by a_axes and b_axes. The third argument can be a single non-negative integer_like scalar, N; if it is such, then the last N dimensions of a and the first N dimensions of b are summed over.

Parameters:
  • a (array_like) – Tensors to “dot”.

  • b (array_like) – Tensors to “dot”.

  • axes (int or (2,) array_like) –

    • integer_like If an int N, sum over the last N axes of a and the first N axes of b in order. The sizes of the corresponding axes must match.

    • (2,) array_like Or, a list of axes to be summed over, first sequence applying to a, second to b. Both elements array_like must be of the same length.

Returns:

output (ndarray) – The tensor dot product of the input.

scico.numpy.tile(A, reps)#

Construct an array by repeating A the number of times given by reps.

LAX-backend implementation of numpy.tile.

Original docstring below.

If reps has length d, the result will have dimension of max(d, A.ndim).

If A.ndim < d, A is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote A to d-dimensions manually before calling this function.

If A.ndim > d, reps is promoted to A.ndim by pre-pending 1’s to it. Thus for an A of shape (2, 3, 4, 5), a reps of (2, 2) is treated as (1, 1, 2, 2).

Note : Although tile may be used for broadcasting, it is strongly recommended to use numpy’s broadcasting operations and functions.

Parameters:
  • A (array_like) – The input array.

  • reps (array_like) – The number of repetitions of A along each axis.

Return type:

Array

Returns:

c (ndarray) – The tiled output array.

scico.numpy.trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None)#

Return the sum along diagonals of the array.

LAX-backend implementation of numpy.trace.

Original docstring below.

If a is 2-D, the sum along its diagonal with the given offset is returned, i.e., the sum of elements a[i,i+offset] for all i.

If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-arrays whose traces are returned. The shape of the resulting array is the same as that of a with axis1 and axis2 removed.

Parameters:
  • a (array_like) – Input array, from which the diagonals are taken.

  • offset (int, optional) – Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults to 0.

  • axis1 (int, optional) – Axes to be used as the first and second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults are the first two axes of a.

  • axis2 (int, optional) – Axes to be used as the first and second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults are the first two axes of a.

  • dtype (dtype, optional) – Determines the data-type of the returned array and of the accumulator where the elements are summed. If dtype has the value None and a is of integer type of precision less than the default integer precision, then the default integer precision is used. Otherwise, the precision is the same as that of a.

Return type:

Array

Returns:

sum_along_diagonals (ndarray) – If a is 2-D, the sum along the diagonal is returned. If a has larger dimensions, then an array of sums along diagonals is returned.

scico.numpy.transpose(a, axes=None)#

Returns an array with axes transposed.

LAX-backend implementation of numpy.transpose.

The JAX version of this function may in some cases return a copy rather than a view of the input.

Original docstring below.

For a 1-D array, this returns an unchanged view of the original array, as a transposed vector is simply the same vector. To convert a 1-D array into a 2-D column vector, an additional dimension must be added, e.g., np.atleast2d(a).T achieves this, as does a[:, np.newaxis]. For a 2-D array, this is the standard matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided, then transpose(a).shape == a.shape[::-1].

Parameters:
  • a (array_like) – Input array.

  • axes (tuple or list of ints, optional) – If specified, it must be a tuple or list which contains a permutation of [0,1,…,N-1] where N is the number of axes of a. The i’th axis of the returned array will correspond to the axis numbered axes[i] of the input. If not specified, defaults to range(a.ndim)[::-1], which reverses the order of the axes.

Return type:

Array

Returns:

p (ndarray) – a with its axes permuted. A view is returned whenever possible.

scico.numpy.tri(N, M=None, k=0, dtype=None)#

An array with ones at and below the given diagonal and zeros elsewhere.

LAX-backend implementation of numpy.tri.

Original docstring below.

Parameters:
  • N (int) – Number of rows in the array.

  • M (int, optional) – Number of columns in the array. By default, M is taken equal to N.

  • k (int, optional) – The sub-diagonal at and below which the array is filled. k = 0 is the main diagonal, while k < 0 is below it, and k > 0 is above. The default is 0.

  • dtype (dtype, optional) – Data type of the returned array. The default is float.

Return type:

Array

Returns:

tri (ndarray of shape (N, M)) – Array with its lower triangle filled with ones and zero elsewhere; in other words T[i,j] == 1 for j <= i + k, 0 otherwise.

scico.numpy.tril_indices(n, k=0, m=None)#

Return the indices for the lower-triangle of an (n, m) array.

LAX-backend implementation of numpy.tril_indices.

Original docstring below.

Parameters:
  • n (int) – The row dimension of the arrays for which the returned indices will be valid.

  • k (int, optional) – Diagonal offset (see tril for details).

  • m (int, optional) –

Return type:

Tuple[Array, Array]

Returns:

inds (tuple of arrays) – The indices for the triangle. The returned tuple contains two arrays, each with the indices along one dimension of the array.

scico.numpy.tril_indices_from(arr, k=0)#

Return the indices for the lower-triangle of arr.

LAX-backend implementation of numpy.tril_indices_from.

Original docstring below.

See tril_indices for full details.

Parameters:
  • arr (array_like) – The indices will be valid for square arrays whose dimensions are the same as arr.

  • k (int, optional) – Diagonal offset (see tril for details).

Return type:

Tuple[Array, Array]

scico.numpy.trim_zeros(filt, trim='fb')#

Trim the leading and/or trailing zeros from a 1-D array or sequence.

LAX-backend implementation of numpy.trim_zeros.

Original docstring below.

Parameters:
  • filt (1-D array or sequence) – Input array.

  • trim (str, optional) – A string with ‘f’ representing trim from front and ‘b’ to trim from back. Default is ‘fb’, trim zeros from both front and back of the array.

Returns:

trimmed (1-D array or sequence) – The result of trimming the input. The input data type is preserved.

scico.numpy.triu_indices(n, k=0, m=None)#

Return the indices for the upper-triangle of an (n, m) array.

LAX-backend implementation of numpy.triu_indices.

Original docstring below.

Parameters:
  • n (int) – The size of the arrays for which the returned indices will be valid.

  • k (int, optional) – Diagonal offset (see triu for details).

  • m (int, optional) –

Return type:

Tuple[Array, Array]

Returns:

inds (tuple, shape(2) of ndarrays, shape(n)) – The indices for the triangle. The returned tuple contains two arrays, each with the indices along one dimension of the array. Can be used to slice a ndarray of shape(n, n).

scico.numpy.triu_indices_from(arr, k=0)#

Return the indices for the upper-triangle of arr.

LAX-backend implementation of numpy.triu_indices_from.

Original docstring below.

See triu_indices for full details.

Parameters:
  • arr (ndarray, shape(N, N)) – The indices will be valid for square arrays.

  • k (int, optional) – Diagonal offset (see triu for details).

Return type:

Tuple[Array, Array]

Returns:

triu_indices_from (tuple, shape(2) of ndarray, shape(N)) – Indices for the upper-triangle of arr.

scico.numpy.true_divide(x1, x2, /)#

Divide arguments element-wise.

LAX-backend implementation of numpy.divide.

Original docstring below.

Parameters:
  • x1 (array_like) – Dividend array.

  • x2 (array_like) – Divisor array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

Return type:

Array

Returns:

y (ndarray or scalar) – The quotient x1/x2, element-wise. This is a scalar if both x1 and x2 are scalars.

scico.numpy.trunc(x)#

Return the truncated value of the input, element-wise.

LAX-backend implementation of numpy.trunc.

Original docstring below.

The truncated value of the scalar x is the nearest integer i which is closer to zero than x is. In short, the fractional part of the signed number x is discarded.

Parameters:

x (array_like) – Input data.

Return type:

Array

Returns:

y (ndarray or scalar) – The truncated value of each element in x. This is a scalar if x is a scalar.

scico.numpy.union1d(ar1, ar2, *, size=None, fill_value=None)#

Find the union of two arrays.

LAX-backend implementation of numpy.union1d.

Because the size of the output of union1d is data-dependent, the function is not typically compatible with JIT. The JAX version adds the optional size argument which must be specified statically for jnp.union1d to be used within some of JAX’s transformations.

Original docstring below.

Return the unique, sorted array of values that are in either of the two input arrays.

Parameters:
  • ar1 (array_like) – Input arrays. They are flattened if they are not already 1D.

  • ar2 (array_like) – Input arrays. They are flattened if they are not already 1D.

  • size (int, optional) – If specified, the first size elements of the result will be returned. If there are fewer elements than size indicates, the return value will be padded with fill_value.

  • fill_value (array_like, optional) – When size is specified and there are fewer than the indicated number of elements, the remaining elements will be filled with fill_value, which defaults to the minimum value of the union.

Return type:

Array

Returns:

union1d (ndarray) – Unique, sorted union of the input arrays.

scico.numpy.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None, *, size=None, fill_value=None)#

Find the unique elements of an array.

LAX-backend implementation of numpy.unique.

Because the size of the output of unique is data-dependent, the function is not typically compatible with JIT. The JAX version adds the optional size argument which must be specified statically for jnp.unique to be used within some of JAX’s transformations.

Original docstring below.

Returns the sorted unique elements of an array. There are three optional outputs in addition to the unique elements:

  • the indices of the input array that give the unique values

  • the indices of the unique array that reconstruct the input array

  • the number of times each unique value comes up in the input array

Parameters:
  • ar (array_like) – Input array. Unless axis is specified, this will be flattened if it is not already 1-D.

  • return_index (bool, optional) – If True, also return the indices of ar (along the specified axis, if provided, or in the flattened array) that result in the unique array.

  • return_inverse (bool, optional) – If True, also return the indices of the unique array (for the specified axis, if provided) that can be used to reconstruct ar.

  • return_counts (bool, optional) – If True, also return the number of times each unique item appears in ar.

  • size (int, optional) – If specified, the first size unique elements will be returned. If there are fewer unique elements than size indicates, the return value will be padded with fill_value.

  • fill_value (array_like, optional) – When size is specified and there are fewer than the indicated number of elements, the remaining elements will be filled with fill_value. The default is the minimum value along the specified axis of the input.

Returns:

  • unique (ndarray) – The sorted unique values.

  • unique_indices (ndarray, optional) – The indices of the first occurrences of the unique values in the original array. Only provided if return_index is True.

  • unique_inverse (ndarray, optional) – The indices to reconstruct the original array from the unique array. Only provided if return_inverse is True.

  • unique_counts (ndarray, optional) – The number of times each of the unique values comes up in the original array. Only provided if return_counts is True.

    New in version 1.9.0.

scico.numpy.unravel_index(indices, shape)#

Converts a flat index or array of flat indices into a tuple

LAX-backend implementation of numpy.unravel_index.

Unlike numpy’s implementation of unravel_index, negative indices are accepted and out-of-bounds indices are clipped into the valid range.

Original docstring below.

of coordinate arrays.

Parameters:
  • indices (array_like) – An integer array whose elements are indices into the flattened version of an array of dimensions shape. Before version 1.6.0, this function accepted just one index value.

  • shape (tuple of ints) –

    The shape of the array to use for unraveling indices.

    Changed in version 1.16.0: Renamed from dims to shape.

Return type:

Tuple[Array, ...]

Returns:

unraveled_coords (tuple of ndarray) – Each array in the tuple has the same shape as the indices array.

scico.numpy.unwrap(p, discont=None, axis=-1, period=6.283185307179586)#

Unwrap by taking the complement of large deltas with respect to the period.

LAX-backend implementation of numpy.unwrap.

Original docstring below.

This unwraps a signal p by changing elements which have an absolute difference from their predecessor of more than max(discont, period/2) to their period-complementary values.

For the default case where period is \(2\pi\) and discont is \(\pi\), this unwraps a radian phase p such that adjacent differences are never greater than \(\pi\) by adding \(2k\pi\) for some integer \(k\).

Parameters:
  • p (array_like) – Input array.

  • discont (float, optional) – Maximum discontinuity between values, default is period/2. Values below period/2 are treated as if they were period/2. To have an effect different from the default, discont should be larger than period/2.

  • axis (int, optional) – Axis along which unwrap will operate, default is the last axis.

  • period (float, optional) – Size of the range over which the input wraps. By default, it is 2 pi.

Return type:

Array

Returns:

out (ndarray) – Output array.

scico.numpy.var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=None)#

Compute the variance along the specified axis.

LAX-backend implementation of numpy.var.

Original docstring below.

Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis.

Parameters:
  • a (array_like) – Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted.

  • axis (None or int or tuple of ints, optional) – Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array.

  • dtype (data-type, optional) – Type to use in computing the variance. For arrays of integer type the default is float64; for arrays of float types it is the same as the array type.

  • ddof (int, optional) – “Delta Degrees of Freedom”: the divisor used in the calculation is N - ddof, where N represents the number of elements. By default ddof is zero.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the var method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

  • where (array_like of bool, optional) – Elements to include in the variance. See ~numpy.ufunc.reduce for details.

Return type:

Array

Returns:

variance (ndarray, see dtype parameter above) – If out=None, returns a new array containing the variance; otherwise, a reference to the output array is returned.

scico.numpy.vdot(a, b, *, precision=None)#

Return the dot product of two vectors.

LAX-backend implementation of numpy.vdot.

In addition to the original NumPy arguments listed below, also supports precision for extra control over matrix-multiplication precision on supported devices. precision may be set to None, which means default precision for the backend, a Precision enum value (Precision.DEFAULT, Precision.HIGH or Precision.HIGHEST) or a tuple of two Precision enums indicating separate precision for each argument.

Original docstring below.

The vdot(a, b) function handles complex numbers differently than dot(a, b). If the first argument is complex the complex conjugate of the first argument is used for the calculation of the dot product.

Note that vdot handles multidimensional arrays differently than dot: it does not perform a matrix product, but flattens input arguments to 1-D vectors first. Consequently, it should only be used for vectors.

Parameters:
  • a (array_like) – If a is complex the complex conjugate is taken before calculation of the dot product.

  • b (array_like) – Second argument to the dot product.

Returns:

output (ndarray) – Dot product of a and b. Can be an int, float, or complex depending on the types of a and b.

scico.numpy.vectorize(pyfunc, *, excluded=frozenset({}), signature=None)#

Define a vectorized function with broadcasting.

vectorize is a convenience wrapper for defining vectorized functions with broadcasting, in the style of NumPy’s generalized universal functions. It allows for defining functions that are automatically repeated across any leading dimensions, without the implementation of the function needing to be concerned about how to handle higher dimensional inputs.

jax.numpy.vectorize has the same interface as numpy.vectorize, but it is syntactic sugar for an auto-batching transformation (vmap) rather than a Python loop. This should be considerably more efficient, but the implementation must be written in terms of functions that act on JAX arrays.

Parameters:
  • pyfunc – function to vectorize.

  • excluded – optional set of integers representing positional arguments for which the function will not be vectorized. These will be passed directly to pyfunc unmodified.

  • signature – optional generalized universal function signature, e.g., (m,n),(n)->(m) for vectorized matrix-vector multiplication. If provided, pyfunc will be called with (and expected to return) arrays with shapes given by the size of corresponding core dimensions. By default, pyfunc is assumed to take scalars arrays as input and output.

Returns:

Vectorized version of the given function.

Here are a few examples of how one could write vectorized linear algebra routines using vectorize:

>>> from functools import partial
>>> @partial(jnp.vectorize, signature='(k),(k)->(k)')
... def cross_product(a, b):
...   assert a.shape == b.shape and a.ndim == b.ndim == 1
...   return jnp.array([a[1] * b[2] - a[2] * b[1],
...                     a[2] * b[0] - a[0] * b[2],
...                     a[0] * b[1] - a[1] * b[0]])
>>> @partial(jnp.vectorize, signature='(n,m),(m)->(n)')
... def matrix_vector_product(matrix, vector):
...   assert matrix.ndim == 2 and matrix.shape[1:] == vector.shape
...   return matrix @ vector

These functions are only written to handle 1D or 2D arrays (the assert statements will never be violated), but with vectorize they support arbitrary dimensional inputs with NumPy style broadcasting, e.g.,

>>> cross_product(jnp.ones(3), jnp.ones(3)).shape
(3,)
>>> cross_product(jnp.ones((2, 3)), jnp.ones(3)).shape
(2, 3)
>>> cross_product(jnp.ones((1, 2, 3)), jnp.ones((2, 1, 3))).shape
(2, 2, 3)
>>> matrix_vector_product(jnp.ones(3), jnp.ones(3))  
Traceback (most recent call last):
ValueError: input with shape (3,) does not have enough dimensions for all
core dimensions ('n', 'k') on vectorized function with excluded=frozenset()
and signature='(n,k),(k)->(k)'
>>> matrix_vector_product(jnp.ones((2, 3)), jnp.ones(3)).shape
(2,)
>>> matrix_vector_product(jnp.ones((2, 3)), jnp.ones((4, 3))).shape
(4, 2)

Note that this has different semantics than jnp.matmul:

>>> jnp.matmul(jnp.ones((2, 3)), jnp.ones((4, 3)))  
Traceback (most recent call last):
TypeError: dot_general requires contracting dimensions to have the same shape, got [3] and [4].
scico.numpy.vsplit(ary, indices_or_sections)#

Split an array into multiple sub-arrays vertically (row-wise).

LAX-backend implementation of numpy.vsplit.

Original docstring below.

Please refer to the split documentation. vsplit is equivalent to split with axis=0 (default), the array is always split along the first axis regardless of the array dimension.

Return type:

List[Array]

scico.numpy.vstack(tup, dtype=None)#

Stack arrays in sequence vertically (row wise).

LAX-backend implementation of numpy.vstack.

Original docstring below.

This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). Rebuilds arrays divided by vsplit.

This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations.

np.row_stack is an alias for vstack. They are the same function.

Parameters:
  • tup (sequence of ndarrays) – The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length.

  • dtype (str or dtype) – If provided, the destination array will have this dtype. Cannot be provided together with out.

Return type:

Array

Returns:

stacked (ndarray) – The array formed by stacking the given arrays, will be at least 2-D.

scico.numpy.where(condition, x=None, y=None, *, size=None, fill_value=None)#

Return elements chosen from x or y depending on condition.

LAX-backend implementation of numpy.where.

At present, JAX does not support JIT-compilation of the single-argument form of jax.numpy.where because its output shape is data-dependent. The three-argument form does not have a data-dependent shape and can be JIT-compiled successfully. Alternatively, you can use the optional size keyword to statically specify the expected size of the output.

Special care is needed when the x or y input to jax.numpy.where could have a value of NaN. Specifically, when a gradient is taken with jax.grad (reverse-mode differentiation), a NaN in either x or y will propagate into the gradient, regardless of the value of condition. More information on this behavior and workarounds is available in the JAX FAQ: https://jax.readthedocs.io/en/latest/faq.html#gradients-contain-nan-where-using-where

Original docstring below.

Note

When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses. The rest of this documentation covers only the case where all three arguments are provided.

Parameters:
  • condition (array_like, bool) – Where True, yield x, otherwise yield y.

  • x (array_like) – Values from which to choose. x, y and condition need to be broadcastable to some shape.

  • y (array_like) – Values from which to choose. x, y and condition need to be broadcastable to some shape.

  • size (int, optional) – Only referenced when x and y are None. If specified, the indices of the first size elements of the result will be returned. If there are fewer elements than size indicates, the return value will be padded with fill_value.

  • fill_value (array_like, optional) – When size is specified and there are fewer than the indicated number of elements, the remaining elements will be filled with fill_value, which defaults to zero.

Return type:

Union[Array, Tuple[Array, ...]]

Returns:

out (ndarray) – An array with elements from x where condition is True, and elements from y elsewhere.

scico.numpy.zeros(shape, dtype=None)#

Return a new array of given shape and type, filled with zeros.

LAX-backend implementation of numpy.zeros.

Original docstring below.

Parameters:
  • shape (int or tuple of ints) – Shape of the new array, e.g., (2, 3) or 2.

  • dtype (data-type, optional) – The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64.

Return type:

Array

Returns:

out (ndarray) – Array of zeros with the given shape, dtype, and order.

scico.numpy.zeros_like(a, dtype=None, shape=None)#

Return an array of zeros with the same shape and type as a given array.

LAX-backend implementation of numpy.zeros_like.

Original docstring below.

Parameters:
  • a (array_like) – The shape and data-type of a define these same attributes of the returned array.

  • dtype (data-type, optional) – Overrides the data type of the result.

  • shape (int or sequence of ints, optional.) – Overrides the shape of the result. If order=’K’ and the number of dimensions is unchanged, will try to keep order, otherwise, order=’C’ is implied.

Return type:

Array

Returns:

out (ndarray) – Array of zeros with the same shape and type as a.

Modules

scico.numpy.fft

Discrete Fourier Transform functions.

scico.numpy.linalg

Linear algebra functions.

scico.numpy.testing

Test support functions.

scico.numpy.util

Utility functions for working with jax arrays and BlockArrays.