uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8affe2ad5de8ad038930dae3 | train | function | @_wraps(onp.swapaxes)
def swapaxes(a, axis1, axis2):
perm = onp.arange(ndim(a))
perm[axis1], perm[axis2] = perm[axis2], perm[axis1]
return lax.transpose(a, perm)
| @_wraps(onp.swapaxes)
def swapaxes(a, axis1, axis2):
| perm = onp.arange(ndim(a))
perm[axis1], perm[axis2] = perm[axis2], perm[axis1]
return lax.transpose(a, perm)
| axis % (ndim(a) + 1) # pylint: disable=g-no-augmented-assignment
return lax.reshape(a, shape[:axis] + (1,) + shape[axis:])
@_wraps(onp.swapaxes)
def swapaxes(a, axis1, axis2):
| 63 | 64 | 60 | 20 | 44 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | swapaxes | swapaxes | 648 | 652 | 648 | 649 | 3ea5af7a9ebe8bc82fc4c33c3432a7ccd1de5c94 | bigcode/the-stack | train |
d30b3d72ac967bbd077384b2 | train | function | @_wraps(onp.flipud)
def flipud(m):
return flip(m, 0)
| @_wraps(onp.flipud)
def flipud(m):
| return flip(m, 0)
| , rank)
return lax.rev(m, [axis % rank])
else:
return lax.rev(m, [axis])
@_wraps(onp.fliplr)
def fliplr(m):
return flip(m, 1)
@_wraps(onp.flipud)
def flipud(m):
| 64 | 64 | 22 | 14 | 50 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | flipud | flipud | 555 | 557 | 555 | 556 | 82dc58a444ce7c4dc0af10dbef0442ca2607c39b | bigcode/the-stack | train |
2998d13c8b0990f515184fff | train | function | def _rewriting_take(arr, idx, axis=0):
"""A function like numpy.take that handles boxes and rewrites to LAX."""
# Handle special indexers: (), Ellipsis, slice(None), and None.
# TODO(mattjj): don't compare empty tuple identity (though works for CPython)
if idx is () or idx is Ellipsis or _is_slice_none(idx): ... | def _rewriting_take(arr, idx, axis=0):
| """A function like numpy.take that handles boxes and rewrites to LAX."""
# Handle special indexers: (), Ellipsis, slice(None), and None.
# TODO(mattjj): don't compare empty tuple identity (though works for CPython)
if idx is () or idx is Ellipsis or _is_slice_none(idx): # pylint: disable=literal-comparison
... | .shape) + index_dims - 1))),
collapsed_slice_dims=(axis,),
start_index_map=(axis,))
return lax.gather(a, indices[..., None], dimension_numbers=dnums,
slice_sizes=tuple(slice_sizes))
@_wraps(getattr(onp, "take_along_axis", None))
def take_along_axis(arr, indices, axis):
if axis is None ... | 256 | 256 | 1,570 | 13 | 242 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _rewriting_take | _rewriting_take | 1,952 | 2,077 | 1,952 | 1,952 | dedeaeab0b71b7a3e73e0fe8fc3f0e25c0f7033d | bigcode/the-stack | train |
95a30a0fc2b71f5c5ecfbc4c | train | function | @_wraps(onp.stack)
def stack(arrays, axis=0):
if not arrays:
raise ValueError("Need at least one array to stack.")
shape0 = shape(arrays[0])
axis = _canonicalize_axis(axis, len(shape0) + 1)
new_shape = list(shape0)
new_shape.insert(axis, 1)
new_arrays = []
for a in arrays:
if shape(a) != shape0:
... | @_wraps(onp.stack)
def stack(arrays, axis=0):
| if not arrays:
raise ValueError("Need at least one array to stack.")
shape0 = shape(arrays[0])
axis = _canonicalize_axis(axis, len(shape0) + 1)
new_shape = list(shape0)
new_shape.insert(axis, 1)
new_arrays = []
for a in arrays:
if shape(a) != shape0:
raise ValueError("All input arrays must h... | constant_values[i, 0], widths)
widths[i] = (0, pad_width[i, 1], 0)
array = lax.pad(array, constant_values[i, 1], widths)
return array
@_wraps(onp.stack)
def stack(arrays, axis=0):
| 64 | 64 | 134 | 17 | 46 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | stack | stack | 1,086 | 1,099 | 1,086 | 1,087 | b94f75a1341640279e4c930a3f7c1958b12326ce | bigcode/the-stack | train |
ea0a39fcc377855eb7300c99 | train | function | def _argminmax(op, a, axis):
shape = [1] * a.ndim
shape[axis] = a.shape[axis]
idxs = onp.arange(a.shape[axis]).reshape(shape)
maxval = onp.iinfo(xla_bridge.canonicalize_dtype(idxs.dtype)).max
mask_idxs = where(lax._eq_meet(a, op(a, axis, keepdims=True)), idxs, maxval)
return min(mask_idxs, axis)
| def _argminmax(op, a, axis):
| shape = [1] * a.ndim
shape[axis] = a.shape[axis]
idxs = onp.arange(a.shape[axis]).reshape(shape)
maxval = onp.iinfo(xla_bridge.canonicalize_dtype(idxs.dtype)).max
mask_idxs = where(lax._eq_meet(a, op(a, axis, keepdims=True)), idxs, maxval)
return min(mask_idxs, axis)
| , axis=None):
if axis is None:
a = ravel(a)
axis = 0
return _argminmax(min, a, axis)
# TODO(mattjj): redo this lowering with a call to variadic lax.reduce
def _argminmax(op, a, axis):
| 64 | 64 | 105 | 11 | 52 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _argminmax | _argminmax | 1,825 | 1,831 | 1,825 | 1,825 | 5902e9846757b7634f36979c9b57f99773e17dc8 | bigcode/the-stack | train |
b99276d2e45c4dba41120c2b | train | function | def _movechars(s, src, dst):
"""Helper for einsum string munging, like moveaxis on identifier strings."""
chars = [c for i, c in enumerate(s) if i not in src]
for i, j in sorted(zip(dst, src)):
chars.insert(i, s[j])
return ''.join(chars)
| def _movechars(s, src, dst):
| """Helper for einsum string munging, like moveaxis on identifier strings."""
chars = [c for i, c in enumerate(s) if i not in src]
for i, j in sorted(zip(dst, src)):
chars.insert(i, s[j])
return ''.join(chars)
| .ndim - 1], [rhs.ndim - 1]
dimension_numbers = [(lhs_cont, rhs_cont), (batch_dims, batch_dims)]
result = lax.dot_general(lhs, rhs, dimension_numbers)
return lax.reshape(result, result_shape)
def _movechars(s, src, dst):
| 64 | 64 | 72 | 10 | 54 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _movechars | _movechars | 1,688 | 1,693 | 1,688 | 1,688 | c8e447792488fd9952d9a495ce2e253659ce212d | bigcode/the-stack | train |
ef90cdd2e4af4b6d1429f101 | train | function | @_wraps(onp.atleast_1d)
def atleast_1d(*arys):
if len(arys) == 1:
arr = array(arys[0])
return arr if arr.ndim >= 1 else arr.reshape(-1)
else:
return [atleast_1d(arr) for arr in arys]
| @_wraps(onp.atleast_1d)
def atleast_1d(*arys):
| if len(arys) == 1:
arr = array(arys[0])
return arr if arr.ndim >= 1 else arr.reshape(-1)
else:
return [atleast_1d(arr) for arr in arys]
| v in tup:
arr = array(v)
if arr.ndim < 2:
arr = arr.reshape((-1, 1))
arrays.append(arr)
return concatenate(arrays, 1)
@_wraps(onp.atleast_1d)
def atleast_1d(*arys):
| 64 | 64 | 74 | 20 | 44 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | atleast_1d | atleast_1d | 1,141 | 1,147 | 1,141 | 1,142 | 2202e07cb7e33609c01ff0880a9b68f8c0001cc3 | bigcode/the-stack | train |
28d720fee8952b2ecb8c0571 | train | function | def _check_arraylike(fun_name, *args):
"""Check if all args fit JAX's definition of arraylike (ndarray or scalar)."""
not_array = lambda x: not isinstance(x, ndarray) and not onp.isscalar(x)
if _any(not_array(arg) for arg in args):
pos, arg = next((i, arg) for i, arg in enumerate(args) if not_array(arg))
... | def _check_arraylike(fun_name, *args):
| """Check if all args fit JAX's definition of arraylike (ndarray or scalar)."""
not_array = lambda x: not isinstance(x, ndarray) and not onp.isscalar(x)
if _any(not_array(arg) for arg in args):
pos, arg = next((i, arg) for i, arg in enumerate(args) if not_array(arg))
msg = "{} requires ndarray or scalar ar... | result_dtype(op, *args):
"""Compute result dtype of applying op to arguments with given dtypes."""
args = (onp.ones((0,) * ndim(arg), _dtype(arg)) for arg in args)
return _dtype(op(*args))
def _check_arraylike(fun_name, *args):
| 64 | 64 | 121 | 11 | 53 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _check_arraylike | _check_arraylike | 175 | 181 | 175 | 175 | d4c04fb394b33dbebc3fdc7c57e58d1b60006bef | bigcode/the-stack | train |
aa91c46be227a06a8b8c94cd | train | function | @_wraps(onp.ones_like)
def ones_like(x, dtype=None):
return lax.full_like(x, 1, dtype)
| @_wraps(onp.ones_like)
def ones_like(x, dtype=None):
| return lax.full_like(x, 1, dtype)
| Error("Unexpected input type for array: {}".format(type(object)))
asarray = array
@_wraps(onp.zeros_like)
def zeros_like(x, dtype=None):
return lax.full_like(x, 0, dtype)
@_wraps(onp.ones_like)
def ones_like(x, dtype=None):
| 64 | 64 | 29 | 17 | 47 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | ones_like | ones_like | 1,207 | 1,209 | 1,207 | 1,208 | 1b7fc0135964a60a5d6debb75260c9af4c076c3a | bigcode/the-stack | train |
93e6b1184a75912589097944 | train | function | @_wraps(onp.array)
def array(object, dtype=None, copy=True, order="K", ndmin=0):
del copy # Unused.
if ndmin != 0 or order != "K":
raise NotImplementedError("Only implemented for order='K', ndmin=0.")
if isinstance(object, ndarray):
if dtype and _dtype(object) != dtype:
return lax.convert_element_... | @_wraps(onp.array)
def array(object, dtype=None, copy=True, order="K", ndmin=0):
| del copy # Unused.
if ndmin != 0 or order != "K":
raise NotImplementedError("Only implemented for order='K', ndmin=0.")
if isinstance(object, ndarray):
if dtype and _dtype(object) != dtype:
return lax.convert_element_type(object, dtype)
else:
return object
elif hasattr(object, '__array... | ))
elif ndim(arr) == 2:
arr = arr.reshape(shape(arr) + (1,))
return arr
else:
return [atleast_3d(arr) for arr in arys]
@_wraps(onp.array)
def array(object, dtype=None, copy=True, order="K", ndmin=0):
| 72 | 72 | 242 | 27 | 45 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | array | array | 1,172 | 1,198 | 1,172 | 1,173 | 4a5b19d6ae05ea2653417064e837f91a75341909 | bigcode/the-stack | train |
36d5168415dad1ef360566bc | train | function | @_wraps(onp.matmul)
def matmul(a, b): # pylint: disable=missing-docstring
_check_arraylike("matmul", a, b)
a_is_vec, b_is_vec = (ndim(a) == 1), (ndim(b) == 1)
a = lax.reshape(a, (1,) + shape(a)) if a_is_vec else a
b = lax.reshape(b, shape(b) + (1,)) if b_is_vec else b
a, b = _promote_dtypes(a, b)
batch_sh... | @_wraps(onp.matmul)
def matmul(a, b): # pylint: disable=missing-docstring
| _check_arraylike("matmul", a, b)
a_is_vec, b_is_vec = (ndim(a) == 1), (ndim(b) == 1)
a = lax.reshape(a, (1,) + shape(a)) if a_is_vec else a
b = lax.reshape(b, shape(b) + (1,)) if b_is_vec else b
a, b = _promote_dtypes(a, b)
batch_shape = lax.broadcast_shapes(shape(a)[:-2], shape(b)[:-2])
a = broadcast_to... | contract_dims = ((a_ndim - 1,), (0,))
else:
contract_dims = ((a_ndim - 1,), (b_ndim - 2,))
batch_dims = ((), ())
return lax.dot_general(a, b, (contract_dims, batch_dims))
@_wraps(onp.matmul)
def matmul(a, b): # pylint: disable=missing-docstring
| 86 | 86 | 289 | 25 | 61 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | matmul | matmul | 1,443 | 1,464 | 1,443 | 1,444 | af8b028bf0233057f42d836344ee5f122067ab39 | bigcode/the-stack | train |
ef36a9667aa304cb04e1f452 | train | function | @_wraps(getattr(onp, "lcm", None))
def lcm(x1, x2):
d = gcd(x1, x2)
return where(d == 0, lax._const(d, 0),
lax.div(lax.abs(multiply(x1, x2)), d))
| @_wraps(getattr(onp, "lcm", None))
def lcm(x1, x2):
| d = gcd(x1, x2)
return where(d == 0, lax._const(d, 0),
lax.div(lax.abs(multiply(x1, x2)), d))
| x1, x2 = broadcast_arrays(x1, x2)
gcd, _ = lax.while_loop(cond_fn, body_fn, (x1, x2))
return gcd
@_wraps(getattr(onp, "lcm", None))
def lcm(x1, x2):
| 64 | 64 | 66 | 24 | 39 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | lcm | lcm | 2,176 | 2,180 | 2,176 | 2,177 | a695403be7d879f0d046685dd7b9c2a76b5f9ec2 | bigcode/the-stack | train |
a04c330129d0c870ad048bd2 | train | function | @_wraps(onp.polyval)
def polyval(p, x):
if isinstance(p, onp.poly1d):
p = onp.asarray(p)
if isinstance(x, onp.poly1d):
y = 0
else:
y = zeros_like(x)
for i in range(len(p)):
y = y * x + p[i]
return y
| @_wraps(onp.polyval)
def polyval(p, x):
| if isinstance(p, onp.poly1d):
p = onp.asarray(p)
if isinstance(x, onp.poly1d):
y = 0
else:
y = zeros_like(x)
for i in range(len(p)):
y = y * x + p[i]
return y
| , dtype=bool), v, zeros_like(v))
elif len(v_shape) == 2:
return diagonal(v, offset=k)
else:
raise ValueError("diag input must be 1d or 2d")
@_wraps(onp.polyval)
def polyval(p, x):
| 64 | 64 | 83 | 15 | 49 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | polyval | polyval | 1,401 | 1,411 | 1,401 | 1,402 | f95585860242e64eb85521bb4c65a855c98878e0 | bigcode/the-stack | train |
5c9cbb7284756c604aa6ab67 | train | function | @_wraps(onp.clip)
def clip(a, a_min=None, a_max=None):
if a_min is None and a_max is None:
raise "At most one of a_min and a_max may be None"
if a_min is not None:
if _dtype(a_min) != _dtype(a):
a_min = lax.convert_element_type(a_min, _dtype(a))
a = lax.max(a_min, a)
if a_max is not None:
if... | @_wraps(onp.clip)
def clip(a, a_min=None, a_max=None):
| if a_min is None and a_max is None:
raise "At most one of a_min and a_max may be None"
if a_min is not None:
if _dtype(a_min) != _dtype(a):
a_min = lax.convert_element_type(a_min, _dtype(a))
a = lax.max(a_min, a)
if a_max is not None:
if _dtype(a_max) != _dtype(a):
a_max = lax.convert_... | split_on_axis(onp.vsplit, axis=0)
hsplit = _split_on_axis(onp.hsplit, axis=1)
dsplit = _split_on_axis(onp.dsplit, axis=2)
@_wraps(onp.clip)
def clip(a, a_min=None, a_max=None):
| 64 | 64 | 142 | 20 | 44 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | clip | clip | 763 | 775 | 763 | 764 | 240341fa45215a0eba3069705c0dcd2bfacd7a0d | bigcode/the-stack | train |
6f561de6cf22ab73e6eaa26f | train | function | @_wraps(onp.divmod)
def divmod(x1, x2):
x1, x2 = _promote_args("divmod", x1, x2)
if onp.issubdtype(_dtype(x1), onp.integer):
return floor_divide(x1, x2), remainder(x1, x2)
else:
return _float_divmod(x1, x2)
| @_wraps(onp.divmod)
def divmod(x1, x2):
| x1, x2 = _promote_args("divmod", x1, x2)
if onp.issubdtype(_dtype(x1), onp.integer):
return floor_divide(x1, x2), remainder(x1, x2)
else:
return _float_divmod(x1, x2)
| (lax.mul(x2r, rat1), lax.mul(x2i, rat2))))
return lax.convert_element_type(out, dtype)
else:
return _float_divmod(x1, x2)[0]
@_wraps(onp.divmod)
def divmod(x1, x2):
| 64 | 64 | 89 | 18 | 46 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | divmod | divmod | 373 | 379 | 373 | 374 | 93acbe4b5a7decd10a81471af8f528d0e42b7499 | bigcode/the-stack | train |
7e22da1d3afa627b63f7ca15 | train | function | def _isposneginf(infinity, x):
dtype = _dtype(x)
if issubdtype(dtype, floating):
return lax.eq(x, infinity)
elif issubdtype(dtype, complexfloating):
raise ValueError("isposinf/isneginf are not well defined for complex types")
else:
return full_like(x, False, dtype=bool_)
| def _isposneginf(infinity, x):
| dtype = _dtype(x)
if issubdtype(dtype, floating):
return lax.eq(x, infinity)
elif issubdtype(dtype, complexfloating):
raise ValueError("isposinf/isneginf are not well defined for complex types")
else:
return full_like(x, False, dtype=bool_)
| ubdtype(dtype, complexfloating):
return lax.bitwise_or(lax.eq(lax.abs(real(x)), inf),
lax.eq(lax.abs(imag(x)), inf))
else:
return full_like(x, False, dtype=bool_)
def _isposneginf(infinity, x):
| 63 | 64 | 81 | 12 | 51 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _isposneginf | _isposneginf | 834 | 841 | 834 | 834 | 1768c06aee5d4fa4b0f062d03de9b8b0b9f9f8b2 | bigcode/the-stack | train |
699877b1562aa5384b7e3c26 | train | function | @_wraps(onp.where)
def where(condition, x=None, y=None):
if x is None or y is None:
raise ValueError("Must use the three-argument form of where().")
if not onp.issubdtype(_dtype(condition), onp.bool_):
condition = lax.ne(condition, zeros_like(condition))
condition, x, y = broadcast_arrays(condition, x, y)... | @_wraps(onp.where)
def where(condition, x=None, y=None):
| if x is None or y is None:
raise ValueError("Must use the three-argument form of where().")
if not onp.issubdtype(_dtype(condition), onp.bool_):
condition = lax.ne(condition, zeros_like(condition))
condition, x, y = broadcast_arrays(condition, x, y)
if not onp.size(x):
empty, _ = _promote_dtypes(x, ... | dtype(_dtype(a), complexfloating):
return lax.reshape(out, (1,))
else:
return out
else:
def _maybe_numpy_1_13_isclose_behavior(a, out):
return out
@_wraps(onp.where)
def where(condition, x=None, y=None):
| 64 | 64 | 132 | 18 | 45 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | where | where | 697 | 708 | 697 | 698 | d1c9a3769d18cb974c43193751debbb5775e21d2 | bigcode/the-stack | train |
f208f66d116e7a108ed71785 | train | function | @_wraps(onp.einsum_path)
def einsum_path(subscripts, *operands, **kwargs):
optimize = kwargs.pop('optimize', 'greedy')
# using einsum_call=True here is an internal api for opt_einsum
return opt_einsum.contract_path(subscripts, *operands, optimize=optimize)
| @_wraps(onp.einsum_path)
def einsum_path(subscripts, *operands, **kwargs):
| optimize = kwargs.pop('optimize', 'greedy')
# using einsum_call=True here is an internal api for opt_einsum
return opt_einsum.contract_path(subscripts, *operands, optimize=optimize)
| einsum_call=True, use_blas=True, optimize=optimize)
contractions = tuple(data[:3] for data in contractions)
return _einsum(operands, contractions)
@_wraps(onp.einsum_path)
def einsum_path(subscripts, *operands, **kwargs):
| 64 | 64 | 76 | 25 | 39 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | einsum_path | einsum_path | 1,519 | 1,523 | 1,519 | 1,520 | f32692bc61954afb45ef9ae5ef53a596e833d983 | bigcode/the-stack | train |
c030a532de584b2fcfa85634 | train | class | class _ArrayMeta(type(onp.ndarray)):
"""Metaclass for overriding ndarray isinstance checks."""
def __instancecheck__(self, instance):
try:
return isinstance(instance.aval, _arraylike_types)
except AttributeError:
return isinstance(instance, _arraylike_types)
| class _ArrayMeta(type(onp.ndarray)):
| """Metaclass for overriding ndarray isinstance checks."""
def __instancecheck__(self, instance):
try:
return isinstance(instance.aval, _arraylike_types)
except AttributeError:
return isinstance(instance, _arraylike_types)
| the isinstance behavior directly, without
# having the complexity of multiple inheritance on those classes, by defining
# the ndarray class to have a metaclass with special __instancecheck__ behavior.
_arraylike_types = (onp.ndarray, UnshapedArray, DeviceArray)
class _ArrayMeta(type(onp.ndarray)):
| 64 | 64 | 59 | 9 | 55 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _ArrayMeta | _ArrayMeta | 73 | 80 | 73 | 73 | 7c2441c5e0983586085ee25d38a3768bce12bcb0 | bigcode/the-stack | train |
48c606407d0c45b1d5cbdd4d | train | function | @_wraps(onp.square)
def square(x):
x, = _promote_to_result_dtype(onp.square, x)
return x * x
| @_wraps(onp.square)
def square(x):
| x, = _promote_to_result_dtype(onp.square, x)
return x * x
| , y: lax.rem(x, y))
@_wraps(onp.sqrt)
def sqrt(x):
x, = _promote_to_result_dtype(onp.sqrt, x)
return power(x, _constant_like(x, 0.5))
@_wraps(onp.square)
def square(x):
| 64 | 64 | 34 | 12 | 52 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | square | square | 464 | 467 | 464 | 465 | fed443771cd96c9cd7705cd2e93b0c5f76190af9 | bigcode/the-stack | train |
211ec97bde8300660e0832dc | train | function | def _reshape(a, newshape, order="C"):
dummy_val = onp.broadcast_to(0, shape(a)) # zero strides
computed_newshape = onp.reshape(dummy_val, newshape).shape
if order == "C":
return lax.reshape(a, computed_newshape, None)
elif order == "F":
dims = onp.arange(ndim(a))[::-1]
return lax.reshape(a, comput... | def _reshape(a, newshape, order="C"):
| dummy_val = onp.broadcast_to(0, shape(a)) # zero strides
computed_newshape = onp.reshape(dummy_val, newshape).shape
if order == "C":
return lax.reshape(a, computed_newshape, None)
elif order == "F":
dims = onp.arange(ndim(a))[::-1]
return lax.reshape(a, computed_newshape[::-1], dims).T
elif orde... | )
@_wraps(onp.reshape)
def reshape(a, newshape, order="C"):
try:
return a.reshape(newshape, order=order)
except AttributeError:
return _reshape(a, newshape, order=order)
def _reshape(a, newshape, order="C"):
| 64 | 64 | 144 | 12 | 52 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _reshape | _reshape | 606 | 618 | 606 | 606 | 309ed761457b4c56b2a6b1b4d4d2d9e5c8bf9094 | bigcode/the-stack | train |
cf74d705b48999ef30c472dc | train | function | @_wraps(onp.argsort)
def argsort(a, axis=-1, kind='quicksort', order=None):
if kind != 'quicksort':
warnings.warn("'kind' argument to argsort is ignored.")
if order is not None:
raise ValueError("'order' argument to argsort is not supported.")
if axis is None:
return argsort(a.ravel(), 0)
else:
... | @_wraps(onp.argsort)
def argsort(a, axis=-1, kind='quicksort', order=None):
| if kind != 'quicksort':
warnings.warn("'kind' argument to argsort is ignored.")
if order is not None:
raise ValueError("'order' argument to argsort is not supported.")
if axis is None:
return argsort(a.ravel(), 0)
else:
axis = axis % ndim(a)
iota = lax.broadcasted_iota(onp.int64, shape(a), ... | to sort is not supported.")
if axis is None:
return lax.sort(a.ravel(), 0)
else:
return lax.sort(a, axis % ndim(a))
@_wraps(onp.argsort)
def argsort(a, axis=-1, kind='quicksort', order=None):
| 64 | 64 | 139 | 27 | 37 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | argsort | argsort | 1,847 | 1,860 | 1,847 | 1,848 | f1a5b53f274f61fc5dbd6101c88f52ad84f80ab1 | bigcode/the-stack | train |
4827998dc78753136e221e76 | train | function | @_wraps(onp.identity)
def identity(n, dtype=None):
return eye(n, dtype=dtype)
| @_wraps(onp.identity)
def identity(n, dtype=None):
| return eye(n, dtype=dtype)
| .broadcasted_iota(k_dtype, (N, M), 0)
cols = lax.broadcasted_iota(k_dtype, (N, M), 1)
return lax.convert_element_type(lax.eq(rows, cols), dtype)
@_wraps(onp.identity)
def identity(n, dtype=None):
| 64 | 64 | 24 | 15 | 49 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | identity | identity | 1,256 | 1,258 | 1,256 | 1,257 | 3307334f100ee1cb9ea140747a30c2dd4bc0e25b | bigcode/the-stack | train |
2e0047aadd636ea4dd92eafe | train | function | @_wraps(onp.heaviside)
def heaviside(x, y):
x, y = _promote_to_result_dtype(onp.heaviside, x, y)
zero = lax._const(x, 0)
return where(lax.lt(x, zero), zero,
where(lax.gt(x, zero), lax._const(x, 1), y))
| @_wraps(onp.heaviside)
def heaviside(x, y):
| x, y = _promote_to_result_dtype(onp.heaviside, x, y)
zero = lax._const(x, 0)
return where(lax.lt(x, zero), zero,
where(lax.gt(x, zero), lax._const(x, 1), y))
| x, = _promote_to_result_dtype(onp.rad2deg, x)
return lax.mul(x, lax._const(x, 180 / pi))
degrees = rad2deg
radians = deg2rad
@_wraps(onp.heaviside)
def heaviside(x, y):
| 64 | 64 | 81 | 18 | 45 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | heaviside | heaviside | 486 | 491 | 486 | 487 | f77b04bd1a390e5ec75007af2091d29cb071d9e7 | bigcode/the-stack | train |
7b2389462e29a971fcdf779f | train | function | @_wraps(onp.cross)
def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
if axis is not None:
axisa = axis
axisb = axis
axisc = axis
a_ndims = len(shape(a))
b_ndims = len(shape(b))
axisa = _canonicalize_axis(axisa, a_ndims)
axisb = _canonicalize_axis(axisb, b_ndims)
... | @_wraps(onp.cross)
def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
| if axis is not None:
axisa = axis
axisb = axis
axisc = axis
a_ndims = len(shape(a))
b_ndims = len(shape(b))
axisa = _canonicalize_axis(axisa, a_ndims)
axisb = _canonicalize_axis(axisb, b_ndims)
a = moveaxis(a, axisa, -1)
b = moveaxis(b, axisb, -1)
a_shape = shape... | s(onp.inner)
def inner(a, b):
if ndim(a) == 0 or ndim(b) == 0:
return a * b
return tensordot(a, b, (-1, -1))
@_wraps(onp.outer)
def outer(a, b, out=None):
if out:
raise NotImplementedError("The 'out' argument to outer is not supported.")
return ravel(a)[:, None] * ravel(b)
@_wraps(onp.cross)
def cross... | 132 | 132 | 442 | 32 | 100 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | cross | cross | 1,709 | 1,750 | 1,709 | 1,710 | 2f898a22b6378d5b3c7038435d01c240e76895a5 | bigcode/the-stack | train |
75d8881d46c45fe14a1ed9d6 | train | function | @_wraps(onp.var)
def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
if out is not None:
raise ValueError("var does not support the `out` argument.")
if ddof != 0:
raise NotImplementedError("Only implemented for ddof=0.")
if dtype is None:
if (onp.issubdtype(_dtype(a), onp.bool_) or
... | @_wraps(onp.var)
def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
| if out is not None:
raise ValueError("var does not support the `out` argument.")
if ddof != 0:
raise NotImplementedError("Only implemented for ddof=0.")
if dtype is None:
if (onp.issubdtype(_dtype(a), onp.bool_) or
onp.issubdtype(_dtype(a), onp.integer)):
dtype = xla_bridge.canonicalize... | (a, axis, dtype=dtype, keepdims=keepdims),
lax.convert_element_type(normalizer, dtype))
return lax.convert_element_type(td, dtype)
@_wraps(onp.var)
def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
| 64 | 64 | 187 | 30 | 34 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | var | var | 940 | 954 | 940 | 941 | 2be56b9c9c09f6c2b1a91f3834233018707f6336 | bigcode/the-stack | train |
5dcaa5db5fd7ff25958da282 | train | function | def _wraps(fun):
"""Like functools.wraps but works with numpy.ufuncs."""
def wrap(op):
try:
# Numpy doc comments have the form:
# fn(x, y, z) (optional)
#
# A one-line summary
#
# ... everything else ...
# We (a) move the summary to the top, since it is what th... | def _wraps(fun):
| """Like functools.wraps but works with numpy.ufuncs."""
def wrap(op):
try:
# Numpy doc comments have the form:
# fn(x, y, z) (optional)
#
# A one-line summary
#
# ... everything else ...
# We (a) move the summary to the top, since it is what the Sphinx
# ... | to result type."""
_check_arraylike(op.__name__, *args)
return _promote_shapes(*_promote_to_result_dtype(op, *args))
def _constant_like(x, const):
return onp.array(const, dtype=_dtype(x))
_numpy_signature_re = re.compile(r'^([\w., ]+=)?\s*[\w\.]+\(.*\)$')
def _wraps(fun):
| 86 | 86 | 288 | 6 | 80 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _wraps | _wraps | 201 | 233 | 201 | 201 | 7b889b1dd0a2b62fce3766a810ba785e4eddf8e5 | bigcode/the-stack | train |
643a41a9c1d534bfcf1a3e6e | train | function | @_wraps(onp.atleast_2d)
def atleast_2d(*arys):
if len(arys) == 1:
arr = array(arys[0])
return arr if arr.ndim >= 2 else arr.reshape((1, -1))
else:
return [atleast_2d(arr) for arr in arys]
| @_wraps(onp.atleast_2d)
def atleast_2d(*arys):
| if len(arys) == 1:
arr = array(arys[0])
return arr if arr.ndim >= 2 else arr.reshape((1, -1))
else:
return [atleast_2d(arr) for arr in arys]
| arr = array(arys[0])
return arr if arr.ndim >= 1 else arr.reshape(-1)
else:
return [atleast_1d(arr) for arr in arys]
@_wraps(onp.atleast_2d)
def atleast_2d(*arys):
| 64 | 64 | 77 | 20 | 44 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | atleast_2d | atleast_2d | 1,150 | 1,156 | 1,150 | 1,151 | 9ced29c3f130933685dc6ec6126f1b30910e49ca | bigcode/the-stack | train |
b5a2f821fcad93d2aa858428 | train | function | def _dot_general(lhs, rhs, lhs_cont, rhs_cont, nbatch):
"""Helper for einsum contractions."""
# lax.dot_general has some tight constraints on dimension_numbers that this
# wrapper loosens via transposes and reshapes
assert len(lhs_cont) == len(rhs_cont) > 0
ncont = len(lhs_cont)
lhs_ntensor = lhs.ndim - nba... | def _dot_general(lhs, rhs, lhs_cont, rhs_cont, nbatch):
| """Helper for einsum contractions."""
# lax.dot_general has some tight constraints on dimension_numbers that this
# wrapper loosens via transposes and reshapes
assert len(lhs_cont) == len(rhs_cont) > 0
ncont = len(lhs_cont)
lhs_ntensor = lhs.ndim - nbatch - ncont
rhs_ntensor = rhs.ndim - nbatch - ncont
... | operand = lax.reshape(lhs, lhs_shape) * lax.reshape(rhs, rhs_shape)
else:
raise NotImplementedError # if this is actually reachable, open an issue!
# the resulting 'operand' with axis labels 'names' should be a permutation
# of the desired result
assert len(names) == len(result_names) =... | 156 | 156 | 523 | 17 | 139 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _dot_general | _dot_general | 1,644 | 1,685 | 1,644 | 1,644 | 182b1b34309321ab53b13e8396b5d63bde497ed1 | bigcode/the-stack | train |
e7aff10bed44111b5042423d | train | function | @_wraps(onp.zeros_like)
def zeros_like(x, dtype=None):
return lax.full_like(x, 0, dtype)
| @_wraps(onp.zeros_like)
def zeros_like(x, dtype=None):
| return lax.full_like(x, 0, dtype)
| dtype(out) != dtype:
return lax.convert_element_type(out, dtype)
else:
return out
else:
raise TypeError("Unexpected input type for array: {}".format(type(object)))
asarray = array
@_wraps(onp.zeros_like)
def zeros_like(x, dtype=None):
| 64 | 64 | 29 | 17 | 46 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | zeros_like | zeros_like | 1,202 | 1,204 | 1,202 | 1,203 | 42b14527a6540216b8d10a922b1311f1dd5f1400 | bigcode/the-stack | train |
578c397e7e97100a8a55e677 | train | function | @_wraps(onp.argmin)
def argmin(a, axis=None):
if axis is None:
a = ravel(a)
axis = 0
return _argminmax(min, a, axis)
| @_wraps(onp.argmin)
def argmin(a, axis=None):
| if axis is None:
a = ravel(a)
axis = 0
return _argminmax(min, a, axis)
| @_wraps(onp.argmax)
def argmax(a, axis=None):
if axis is None:
a = ravel(a)
axis = 0
return _argminmax(max, a, axis)
@_wraps(onp.argmin)
def argmin(a, axis=None):
| 64 | 64 | 48 | 17 | 47 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | argmin | argmin | 1,816 | 1,821 | 1,816 | 1,817 | 7f8538c89aa2b4f8a512d52e0c7cc13483b9e422 | bigcode/the-stack | train |
11bbdc7e676a686e070f8bff | train | function | @_wraps(onp.isnan)
def isnan(x):
return lax.bitwise_and(lax.bitwise_not(isfinite(x)),
lax.bitwise_not(isinf(x)))
| @_wraps(onp.isnan)
def isnan(x):
| return lax.bitwise_and(lax.bitwise_not(isfinite(x)),
lax.bitwise_not(isinf(x)))
| _)
isposinf = _wraps(onp.isposinf)(partial(_isposneginf, inf))
isneginf = _wraps(onp.isneginf)(partial(_isposneginf, -inf))
@_wraps(onp.isnan)
def isnan(x):
| 64 | 64 | 37 | 13 | 51 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | isnan | isnan | 846 | 849 | 846 | 847 | 32f40d5410ff8da4a7c78e0ae646a2f361d7201c | bigcode/the-stack | train |
b0d26acf2b988427d7eb8dbe | train | function | def broadcast_arrays(*args):
"""Like Numpy's broadcast_arrays but doesn't return views."""
shapes = [shape(arg) for arg in args]
if len(set(shapes)) == 1:
return [arg if isinstance(arg, ndarray) or isscalar(arg) else array(arg)
for arg in args]
result_shape = lax.broadcast_shapes(*shapes)
retu... | def broadcast_arrays(*args):
| """Like Numpy's broadcast_arrays but doesn't return views."""
shapes = [shape(arg) for arg in args]
if len(set(shapes)) == 1:
return [arg if isinstance(arg, ndarray) or isscalar(arg) else array(arg)
for arg in args]
result_shape = lax.broadcast_shapes(*shapes)
return [broadcast_to(arg, result_... | condition, x, y = broadcast_arrays(condition, x, y)
if not onp.size(x):
empty, _ = _promote_dtypes(x, y)
return empty
else:
return lax.select(condition, *_promote_dtypes(x, y))
def broadcast_arrays(*args):
| 64 | 64 | 93 | 6 | 58 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | broadcast_arrays | broadcast_arrays | 711 | 718 | 711 | 711 | 093abd9902f443a97cefe57687f88ef7b9fb9a9d | bigcode/the-stack | train |
6a6d98d3e908dd48beb31483 | train | function | @_wraps(onp.dstack)
def dstack(tup):
return concatenate([atleast_3d(m) for m in tup], axis=2)
| @_wraps(onp.dstack)
def dstack(tup):
| return concatenate([atleast_3d(m) for m in tup], axis=2)
| ):
arrs = [atleast_1d(m) for m in tup]
if arrs[0].ndim == 1:
return concatenate(arrs, 0)
return concatenate(arrs, 1)
@_wraps(onp.dstack)
def dstack(tup):
| 64 | 64 | 35 | 15 | 49 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | dstack | dstack | 1,125 | 1,127 | 1,125 | 1,126 | 740e175f47580f13874ac9751d902f4087bf61e7 | bigcode/the-stack | train |
8e719e6fb85b47cbf7e91db9 | train | function | @_wraps(onp.atleast_3d)
def atleast_3d(*arys):
if len(arys) == 1:
arr = array(arys[0])
if ndim(arr) <= 1:
arr = arr.reshape((1, -1, 1))
elif ndim(arr) == 2:
arr = arr.reshape(shape(arr) + (1,))
return arr
else:
return [atleast_3d(arr) for arr in arys]
| @_wraps(onp.atleast_3d)
def atleast_3d(*arys):
| if len(arys) == 1:
arr = array(arys[0])
if ndim(arr) <= 1:
arr = arr.reshape((1, -1, 1))
elif ndim(arr) == 2:
arr = arr.reshape(shape(arr) + (1,))
return arr
else:
return [atleast_3d(arr) for arr in arys]
| array(arys[0])
return arr if arr.ndim >= 2 else arr.reshape((1, -1))
else:
return [atleast_2d(arr) for arr in arys]
@_wraps(onp.atleast_3d)
def atleast_3d(*arys):
| 64 | 64 | 106 | 20 | 44 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | atleast_3d | atleast_3d | 1,159 | 1,169 | 1,159 | 1,160 | 05e92fab5c89bce9f64eb2f496ff71cb02388acc | bigcode/the-stack | train |
2e4a49aa48ee581f4a58719a | train | function | def _not_implemented(fun):
@_wraps(fun)
def wrapped(*args, **kwargs):
msg = "Numpy function {} not yet implemented"
raise NotImplementedError(msg.format(fun))
return wrapped
| def _not_implemented(fun):
@_wraps(fun)
| def wrapped(*args, **kwargs):
msg = "Numpy function {} not yet implemented"
raise NotImplementedError(msg.format(fun))
return wrapped
| x2):
d = gcd(x1, x2)
return where(d == 0, lax._const(d, 0),
lax.div(lax.abs(multiply(x1, x2)), d))
### track unimplemented functions
def _not_implemented(fun):
@_wraps(fun)
| 64 | 64 | 47 | 13 | 50 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _not_implemented | _not_implemented | 2,185 | 2,190 | 2,185 | 2,186 | 0b7e90ced09a3d9ef6d850c05396291da3e0f8a6 | bigcode/the-stack | train |
b45ec14954a06a763778a48b | train | function | @_wraps(onp.isinf)
def isinf(x):
dtype = _dtype(x)
if issubdtype(dtype, floating):
return lax.eq(lax.abs(x), inf)
elif issubdtype(dtype, complexfloating):
return lax.bitwise_or(lax.eq(lax.abs(real(x)), inf),
lax.eq(lax.abs(imag(x)), inf))
else:
return full_like(x, False, dt... | @_wraps(onp.isinf)
def isinf(x):
| dtype = _dtype(x)
if issubdtype(dtype, floating):
return lax.eq(lax.abs(x), inf)
elif issubdtype(dtype, complexfloating):
return lax.bitwise_or(lax.eq(lax.abs(real(x)), inf),
lax.eq(lax.abs(imag(x)), inf))
else:
return full_like(x, False, dtype=bool_)
| (x)
elif issubdtype(dtype, complexfloating):
return lax.bitwise_and(lax.is_finite(real(x)), lax.is_finite(imag(x)))
else:
return full_like(x, True, dtype=bool_)
@_wraps(onp.isinf)
def isinf(x):
| 63 | 64 | 95 | 14 | 49 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | isinf | isinf | 823 | 832 | 823 | 824 | c04d4c847c733b7fb50f4c2b2e72450a8e755255 | bigcode/the-stack | train |
af0ab4cc382e083b43349eb3 | train | function | @_wraps(onp.zeros)
def zeros(shape, dtype=onp.dtype("float64")):
shape = (shape,) if onp.isscalar(shape) else shape
return lax.full(shape, 0, dtype)
| @_wraps(onp.zeros)
def zeros(shape, dtype=onp.dtype("float64")):
| shape = (shape,) if onp.isscalar(shape) else shape
return lax.full(shape, 0, dtype)
| return lax.full(shape, fill_value, dtype)
@_wraps(onp.full_like)
def full_like(a, fill_value, dtype=None):
return lax.full_like(a, fill_value, dtype)
@_wraps(onp.zeros)
def zeros(shape, dtype=onp.dtype("float64")):
| 64 | 64 | 50 | 22 | 42 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | zeros | zeros | 1,222 | 1,225 | 1,222 | 1,223 | fc1e374743efbdb22f85089928be79b1aa7d8a31 | bigcode/the-stack | train |
220c17dd0f51ab3f9a45310d | train | function | def _dtype_info(dtype):
"""Helper function for to get dtype info needed for clipping."""
if onp.issubdtype(dtype, onp.integer):
return onp.iinfo(dtype)
return onp.finfo(dtype)
| def _dtype_info(dtype):
| """Helper function for to get dtype info needed for clipping."""
if onp.issubdtype(dtype, onp.integer):
return onp.iinfo(dtype)
return onp.finfo(dtype)
| a = lax.max(a_min, a)
if a_max is not None:
if _dtype(a_max) != _dtype(a):
a_max = lax.convert_element_type(a_max, _dtype(a))
a = lax.min(a_max, a)
return a
def _dtype_info(dtype):
| 64 | 64 | 49 | 6 | 57 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _dtype_info | _dtype_info | 778 | 782 | 778 | 778 | f38452bab1980679cabf7f7875b9c328ca52ead2 | bigcode/the-stack | train |
30d8f19385f6d006bba76974 | train | function | @_wraps(onp.repeat)
def repeat(a, repeats, axis=None):
if not isscalar(repeats):
raise NotImplementedError(
"np.repeat implementation only supports scalar repeats")
if axis is None or isscalar(a):
a = ravel(a)
axis = 0
a_shape = list(shape(a))
num_dims = len(a_shape)
if axis < 0:
axis ... | @_wraps(onp.repeat)
def repeat(a, repeats, axis=None):
| if not isscalar(repeats):
raise NotImplementedError(
"np.repeat implementation only supports scalar repeats")
if axis is None or isscalar(a):
a = ravel(a)
axis = 0
a_shape = list(shape(a))
num_dims = len(a_shape)
if axis < 0:
axis = axis + num_dims
if axis < 0 or axis >= num_dims:
... | # Fall back to instantiating an ndarray in host memory
return onp.arange(*args, **kwargs)
linspace = onp.linspace
logspace = onp.logspace
geomspace = onp.geomspace
meshgrid = onp.meshgrid
@_wraps(onp.repeat)
def repeat(a, repeats, axis=None):
| 72 | 72 | 243 | 17 | 54 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | repeat | repeat | 1,282 | 1,308 | 1,282 | 1,283 | 3b0dd54d9963b8de37c5aca23a8a1c5326a4197b | bigcode/the-stack | train |
d4e944c12db5c04e4042a83a | train | function | @_wraps(onp.squeeze)
def squeeze(a, axis=None):
if 1 not in shape(a):
return a
if axis is None:
newshape = [d for d in shape(a) if d != 1]
else:
axis = frozenset(onp.mod(axis, ndim(a)).reshape(-1))
newshape = [d for i, d in enumerate(shape(a))
if d != 1 or i not in axis]
return l... | @_wraps(onp.squeeze)
def squeeze(a, axis=None):
| if 1 not in shape(a):
return a
if axis is None:
newshape = [d for d in shape(a) if d != 1]
else:
axis = frozenset(onp.mod(axis, ndim(a)).reshape(-1))
newshape = [d for i, d in enumerate(shape(a))
if d != 1 or i not in axis]
return lax.reshape(a, newshape)
| (onp.ravel)
def ravel(a, order="C"):
if order == "K":
raise NotImplementedError("Ravel not implemented for order='K'.")
return reshape(a, (size(a),), order)
@_wraps(onp.squeeze)
def squeeze(a, axis=None):
| 64 | 64 | 109 | 15 | 49 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | squeeze | squeeze | 628 | 638 | 628 | 629 | 22395d48cc4831a2f0faaa2c10b5654f165a2a0f | bigcode/the-stack | train |
28ca33001ac9ac20b39790bb | train | function | @_wraps(onp.exp2)
def exp2(x):
x, = _promote_to_result_dtype(onp.exp2, x)
return lax.exp(lax.mul(lax.log(_constant_like(x, 2)), x))
| @_wraps(onp.exp2)
def exp2(x):
| x, = _promote_to_result_dtype(onp.exp2, x)
return lax.exp(lax.mul(lax.log(_constant_like(x, 2)), x))
| _wraps(onp.log10)
def log10(x):
x, = _promote_to_result_dtype(onp.log10, x)
return lax.div(lax.log(x), lax.log(_constant_like(x, 10)))
@_wraps(onp.exp2)
def exp2(x):
| 62 | 64 | 51 | 14 | 48 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | exp2 | exp2 | 444 | 447 | 444 | 445 | 955d2c260c3ff021d61f5569432ab827bfc3180d | bigcode/the-stack | train |
56aad656c5bc77c18d1b28b4 | train | function | def _is_advanced_int_indexer(idx):
"""Returns True if idx should trigger int array indexing, False otherwise."""
# https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing
if isinstance(idx, (tuple, list)):
# We assume this check comes *after* the check for non-advanced tuple index,
... | def _is_advanced_int_indexer(idx):
| """Returns True if idx should trigger int array indexing, False otherwise."""
# https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing
if isinstance(idx, (tuple, list)):
# We assume this check comes *after* the check for non-advanced tuple index,
# and hence we already know at l... | raise IndexError(msg.format(idx))
def _is_slice_none(idx):
"""Return True if idx is equal to slice(None), False otherwise."""
if isinstance(idx, slice):
return idx.start is None and idx.stop is None and idx.step is None
def _is_advanced_int_indexer(idx):
| 64 | 64 | 139 | 10 | 53 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _is_advanced_int_indexer | _is_advanced_int_indexer | 2,086 | 2,095 | 2,086 | 2,086 | 3257de178e606bbf4c616a34eccafa8840312887 | bigcode/the-stack | train |
74a28d1e0962e0e73edb5b29 | train | function | def _make_nan_reduction(onp_reduction, np_reduction, init_val, nan_if_all_nan):
@_wraps(onp_reduction)
def nan_reduction(a, axis=None, out=None, keepdims=False, **kwargs):
out = np_reduction(where(isnan(a), _reduction_init_val(a, init_val), a),
axis=axis, out=out, keepdims=keepdims, **kwa... | def _make_nan_reduction(onp_reduction, np_reduction, init_val, nan_if_all_nan):
@_wraps(onp_reduction)
| def nan_reduction(a, axis=None, out=None, keepdims=False, **kwargs):
out = np_reduction(where(isnan(a), _reduction_init_val(a, init_val), a),
axis=axis, out=out, keepdims=keepdims, **kwargs)
if nan_if_all_nan:
return where(all(isnan(a), axis=axis, keepdims=keepdims),
... | sum(lax.ne(a, _constant_like(a, 0)), axis=axis,
dtype=xla_bridge.canonicalize_dtype(onp.int_))
def _make_nan_reduction(onp_reduction, np_reduction, init_val, nan_if_all_nan):
@_wraps(onp_reduction)
| 64 | 64 | 141 | 32 | 32 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _make_nan_reduction | _make_nan_reduction | 984 | 995 | 984 | 985 | 83f8642e2e35863f4c6a9886914532b5b7ea7945 | bigcode/the-stack | train |
d22539af5733a8859e60154f | train | function | @_wraps(onp.transpose)
def transpose(x, axis=None):
axis = onp.arange(ndim(x))[::-1] if axis is None else axis
return lax.transpose(x, axis)
| @_wraps(onp.transpose)
def transpose(x, axis=None):
| axis = onp.arange(ndim(x))[::-1] if axis is None else axis
return lax.transpose(x, axis)
| = lax.mul(lax._const(x, pi), x)
return where(lax.eq(x, lax._const(x, 0)),
lax._const(x, 1), lax.div(lax.sin(pi_x), pi_x))
@_wraps(onp.transpose)
def transpose(x, axis=None):
| 64 | 64 | 43 | 15 | 49 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | transpose | transpose | 514 | 517 | 514 | 515 | ce0a503dc2b737e7b2ec77b474883efc2b4fc66b | bigcode/the-stack | train |
9a74b7b9c5eb85728b588ff0 | train | function | @_wraps(onp.arange)
def arange(*args, **kwargs):
dtype = kwargs.pop("dtype", None)
if not args:
raise TypeError("Required argument 'start' (pos 1) not found") # same as numpy error
# If called like np.arange(N), we create a lazy lax._IotaConstant.
if len(args) == 1 and not kwargs:
stop, = args
dty... | @_wraps(onp.arange)
def arange(*args, **kwargs):
| dtype = kwargs.pop("dtype", None)
if not args:
raise TypeError("Required argument 'start' (pos 1) not found") # same as numpy error
# If called like np.arange(N), we create a lazy lax._IotaConstant.
if len(args) == 1 and not kwargs:
stop, = args
dtype = dtype or _dtype(stop)
if onp.issubdtype(... | (N, M), 1)
return lax.convert_element_type(lax.eq(rows, cols), dtype)
@_wraps(onp.identity)
def identity(n, dtype=None):
return eye(n, dtype=dtype)
@_wraps(onp.arange)
def arange(*args, **kwargs):
| 64 | 64 | 157 | 17 | 47 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | arange | arange | 1,261 | 1,275 | 1,261 | 1,262 | 0c90a924f5a351093728e109d233850387df1bee | bigcode/the-stack | train |
0d623846bf1a456ceb2f30b7 | train | function | @_wraps(onp.conjugate)
def conjugate(x):
return lax.conj(x) if iscomplexobj(x) else x
| @_wraps(onp.conjugate)
def conjugate(x):
| return lax.conj(x) if iscomplexobj(x) else x
| [axis])
@_wraps(onp.fliplr)
def fliplr(m):
return flip(m, 1)
@_wraps(onp.flipud)
def flipud(m):
return flip(m, 0)
@_wraps(onp.conjugate)
def conjugate(x):
| 64 | 64 | 31 | 15 | 49 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | conjugate | conjugate | 560 | 562 | 560 | 561 | bef0ea48ef8de8da06c32b7512bf0075f50db400 | bigcode/the-stack | train |
d95d099e846ff6162ea97a2e | train | function | @_wraps(onp.isreal)
def isreal(x):
i = imag(x)
return lax.eq(i, lax._const(i, 0))
| @_wraps(onp.isreal)
def isreal(x):
| i = imag(x)
return lax.eq(i, lax._const(i, 0))
| ):
return lax.real(x) if iscomplexobj(x) else x
@_wraps(onp.iscomplex)
def iscomplex(x):
i = imag(x)
return lax.ne(i, lax._const(i, 0))
@_wraps(onp.isreal)
def isreal(x):
| 64 | 64 | 34 | 14 | 50 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | isreal | isreal | 581 | 584 | 581 | 582 | 7470355e07b5c268d34ae5a5a07fdecccbea8395 | bigcode/the-stack | train |
8b8b37071a57a988a730fd31 | train | function | @_wraps(onp.pad)
def pad(array, pad_width, mode, constant_values=0):
if mode != "constant":
msg = "Only the 'constant' case of np.pad is implemented, got mode={}."
raise NotImplementedError(msg.format(mode))
array = asarray(array)
pad_width = onp.broadcast_to(onp.asarray(pad_width), (array.ndim, 2))
co... | @_wraps(onp.pad)
def pad(array, pad_width, mode, constant_values=0):
| if mode != "constant":
msg = "Only the 'constant' case of np.pad is implemented, got mode={}."
raise NotImplementedError(msg.format(mode))
array = asarray(array)
pad_width = onp.broadcast_to(onp.asarray(pad_width), (array.ndim, 2))
constant_values = broadcast_to(asarray(constant_values), (array.ndim, 2... | if axis < 0 or axis >= num_dims:
raise ValueError(
"axis {} is out of bounds for array of dimension {}".format(
axis, num_dims))
return axis
@_wraps(onp.pad)
def pad(array, pad_width, mode, constant_values=0):
| 64 | 64 | 207 | 22 | 41 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | pad | pad | 1,068 | 1,083 | 1,068 | 1,069 | 703abf72766794ca00153f484eacddc94d6e4b2e | bigcode/the-stack | train |
e52ad2e96c5ab64e55e6d391 | train | function | @_wraps(getattr(onp, "take_along_axis", None))
def take_along_axis(arr, indices, axis):
if axis is None and ndim(arr) != 1:
return take_along_axis(arr.ravel(), indices.ravel(), 0)
elif ndim(arr) == 1:
return lax.index_take(arr, (indices,), (0,))
else:
# TODO(mattjj): if we lower directly to lax.gather... | @_wraps(getattr(onp, "take_along_axis", None))
def take_along_axis(arr, indices, axis):
| if axis is None and ndim(arr) != 1:
return take_along_axis(arr.ravel(), indices.ravel(), 0)
elif ndim(arr) == 1:
return lax.index_take(arr, (indices,), (0,))
else:
# TODO(mattjj): if we lower directly to lax.gather here, we might be able to
# avoid the reshape on the output.
all_indices = [lax... | _slice_dims=(axis,),
start_index_map=(axis,))
return lax.gather(a, indices[..., None], dimension_numbers=dnums,
slice_sizes=tuple(slice_sizes))
@_wraps(getattr(onp, "take_along_axis", None))
def take_along_axis(arr, indices, axis):
| 64 | 64 | 192 | 28 | 36 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | take_along_axis | take_along_axis | 1,932 | 1,946 | 1,932 | 1,933 | 271ff1b3b2c6597bf91ef2a3efe20447436bb8f7 | bigcode/the-stack | train |
07b1e46ce82d54ef7fb26953 | train | function | @_wraps(onp.expand_dims)
def expand_dims(a, axis):
shape = _shape(a)
axis = axis % (ndim(a) + 1) # pylint: disable=g-no-augmented-assignment
return lax.reshape(a, shape[:axis] + (1,) + shape[axis:])
| @_wraps(onp.expand_dims)
def expand_dims(a, axis):
| shape = _shape(a)
axis = axis % (ndim(a) + 1) # pylint: disable=g-no-augmented-assignment
return lax.reshape(a, shape[:axis] + (1,) + shape[axis:])
| (onp.mod(axis, ndim(a)).reshape(-1))
newshape = [d for i, d in enumerate(shape(a))
if d != 1 or i not in axis]
return lax.reshape(a, newshape)
@_wraps(onp.expand_dims)
def expand_dims(a, axis):
| 64 | 64 | 69 | 16 | 48 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | expand_dims | expand_dims | 641 | 645 | 641 | 642 | b271958d6b3b9ea76a014464bea15e0bbfa55754 | bigcode/the-stack | train |
fbfb68981a513cd903240b88 | train | function | @_wraps(onp.rad2deg)
def rad2deg(x):
x, = _promote_to_result_dtype(onp.rad2deg, x)
return lax.mul(x, lax._const(x, 180 / pi))
| @_wraps(onp.rad2deg)
def rad2deg(x):
| x, = _promote_to_result_dtype(onp.rad2deg, x)
return lax.mul(x, lax._const(x, 180 / pi))
| (onp.deg2rad)
def deg2rad(x):
x, = _promote_to_result_dtype(onp.deg2rad, x)
return lax.mul(x, lax._const(x, pi / 180))
@_wraps(onp.rad2deg)
def rad2deg(x):
| 64 | 64 | 50 | 16 | 48 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | rad2deg | rad2deg | 476 | 479 | 476 | 477 | 0d340140db6e4a9fb48d435d6eed5092971b755c | bigcode/the-stack | train |
a4b847ffcd4804738022a540 | train | function | @_wraps(onp.round)
def round(a, decimals=0):
dtype = _dtype(a)
if issubdtype(dtype, integer):
if decimals < 0:
raise NotImplementedError(
"integer np.round not implemented for decimals < 0")
return a # no-op on integer types
def _round_float(x):
if decimals == 0:
return lax.round... | @_wraps(onp.round)
def round(a, decimals=0):
| dtype = _dtype(a)
if issubdtype(dtype, integer):
if decimals < 0:
raise NotImplementedError(
"integer np.round not implemented for decimals < 0")
return a # no-op on integer types
def _round_float(x):
if decimals == 0:
return lax.round(x)
factor = _constant_like(x, 10 ** dec... | _dtype_info(dtype):
"""Helper function for to get dtype info needed for clipping."""
if onp.issubdtype(dtype, onp.integer):
return onp.iinfo(dtype)
return onp.finfo(dtype)
@_wraps(onp.round)
def round(a, decimals=0):
| 64 | 64 | 159 | 16 | 48 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | round | round | 785 | 804 | 785 | 786 | 993ef92154ce34d5b2d5ab7ed840a5c2fb63cc69 | bigcode/the-stack | train |
5a1e2479d1cd01d9f7fab42a | train | function | def _canonicalize_tuple_index(arr, idx):
"""Helper to remove Ellipsis and add in the implicit trailing slice(None)."""
len_without_none = _sum(1 for e in idx if e is not None and e is not Ellipsis)
if len_without_none > arr.ndim:
msg = "Too many indices for array: {} non-None/Ellipsis indices for dim {}."
... | def _canonicalize_tuple_index(arr, idx):
| """Helper to remove Ellipsis and add in the implicit trailing slice(None)."""
len_without_none = _sum(1 for e in idx if e is not None and e is not Ellipsis)
if len_without_none > arr.ndim:
msg = "Too many indices for array: {} non-None/Ellipsis indices for dim {}."
raise IndexError(msg.format(len_without_... | integer dtype, False otherwise."""
return (isinstance(x, int) and not isinstance(x, bool)
or onp.issubdtype(getattr(x, "dtype", None), onp.integer)
or isinstance(x, (list, tuple)) and _all(_is_int_arraylike(e) for e in x))
def _canonicalize_tuple_index(arr, idx):
| 78 | 78 | 263 | 10 | 68 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _canonicalize_tuple_index | _canonicalize_tuple_index | 2,115 | 2,132 | 2,115 | 2,115 | 82cb3a546e1a9aae9a2b7efc20a7a0452d63bf4d | bigcode/the-stack | train |
e3890457b91cf30af96cfc4f | train | function | @_wraps(onp.argmax)
def argmax(a, axis=None):
if axis is None:
a = ravel(a)
axis = 0
return _argminmax(max, a, axis)
| @_wraps(onp.argmax)
def argmax(a, axis=None):
| if axis is None:
a = ravel(a)
axis = 0
return _argminmax(max, a, axis)
| ota = lax.iota(dtype, N)
if not increasing:
iota = lax.sub(lax._const(iota, N - 1), iota)
return power(x[..., None], iota)
### Misc
@_wraps(onp.argmax)
def argmax(a, axis=None):
| 64 | 64 | 47 | 16 | 47 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | argmax | argmax | 1,808 | 1,813 | 1,808 | 1,809 | af501235ad8e3f28ecd76c92295245e8f0fbe7b4 | bigcode/the-stack | train |
5d5da1d526f5019c5de54dc0 | train | function | @_wraps(onp.kron)
def kron(a, b):
a_shape = shape(a)
b_shape = shape(b)
a_ndims = len(a_shape)
b_ndims = len(b_shape)
a = array(a)
b = array(b)
d = _min(a_ndims, b_ndims)
if d == 0:
return a * b
a_broadcast_dims = list(range(a_ndims - d, a_ndims + d, 2))
a_broadcast_shape = onp.ones(a_ndims + d,... | @_wraps(onp.kron)
def kron(a, b):
| a_shape = shape(a)
b_shape = shape(b)
a_ndims = len(a_shape)
b_ndims = len(b_shape)
a = array(a)
b = array(b)
d = _min(a_ndims, b_ndims)
if d == 0:
return a * b
a_broadcast_dims = list(range(a_ndims - d, a_ndims + d, 2))
a_broadcast_shape = onp.ones(a_ndims + d, dtype=onp.int64)
a_broadcast_sh... | ]
b0 = b[..., 0]
b1 = b[..., 1]
b2 = b[..., 2]
c = array([a1 * b2 - a2 * b1,
a2 * b0 - a0 * b2,
a0 * b1 - a1 * b0])
c_ndims = len(shape(c))
axisc = _canonicalize_axis(axisc, c_ndims)
return moveaxis(c, 0, axisc)
@_wraps(onp.kron)
def kron(a, b):
| 122 | 122 | 409 | 15 | 107 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | kron | kron | 1,752 | 1,784 | 1,752 | 1,753 | 51fa3c9fd939efea6fec03d6bed3954650f6fb7a | bigcode/the-stack | train |
d66ca38998b5e4379dfcacfb | train | function | def _result_dtype(op, *args):
"""Compute result dtype of applying op to arguments with given dtypes."""
args = (onp.ones((0,) * ndim(arg), _dtype(arg)) for arg in args)
return _dtype(op(*args))
| def _result_dtype(op, *args):
| """Compute result dtype of applying op to arguments with given dtypes."""
args = (onp.ones((0,) * ndim(arg), _dtype(arg)) for arg in args)
return _dtype(op(*args))
| ote_to_result_dtype(op, *args):
"""Convenience function to promote args directly to the op's result dtype."""
to_dtype = _result_dtype(op, *args)
return [lax.convert_element_type(arg, to_dtype) for arg in args]
def _result_dtype(op, *args):
| 64 | 64 | 55 | 9 | 55 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _result_dtype | _result_dtype | 169 | 172 | 169 | 169 | 910a0aab54c866271c369e6afa57fa5f991f6f10 | bigcode/the-stack | train |
1867a3bbff2a4455d0de5883 | train | function | def _make_reduction(np_fun, op, init_val, preproc=None):
"""Creates reduction function given a binary operation and monoid identity."""
@_wraps(np_fun)
def reduction(a, axis=None, dtype=None, out=None, keepdims=False):
if out is not None:
raise ValueError("reduction does not support the `out` argument.... | def _make_reduction(np_fun, op, init_val, preproc=None):
| """Creates reduction function given a binary operation and monoid identity."""
@_wraps(np_fun)
def reduction(a, axis=None, dtype=None, out=None, keepdims=False):
if out is not None:
raise ValueError("reduction does not support the `out` argument.")
a = a if isinstance(a, ndarray) else asarray(a)
... | nan(x), _constant_like(x, 0), x)
x = where(isposinf(x), _constant_like(x, info.max), x)
x = where(isneginf(x), _constant_like(x, info.min), x)
return x
### Reducers
def _make_reduction(np_fun, op, init_val, preproc=None):
| 77 | 77 | 258 | 17 | 59 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _make_reduction | _make_reduction | 865 | 887 | 865 | 865 | 1536e0f7e6b14cedc9a7bf209047fdaad70a9d49 | bigcode/the-stack | train |
ac44dd0120516a4564551f28 | train | function | @_wraps(onp.ravel)
def ravel(a, order="C"):
if order == "K":
raise NotImplementedError("Ravel not implemented for order='K'.")
return reshape(a, (size(a),), order)
| @_wraps(onp.ravel)
def ravel(a, order="C"):
| if order == "K":
raise NotImplementedError("Ravel not implemented for order='K'.")
return reshape(a, (size(a),), order)
| dims).T
elif order == "A":
raise NotImplementedError("np.reshape order=A is not implemented.")
else:
raise ValueError("Unexpected value for 'order' argument: {}.".format(order))
@_wraps(onp.ravel)
def ravel(a, order="C"):
| 64 | 64 | 53 | 18 | 46 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | ravel | ravel | 621 | 625 | 621 | 622 | 2e189d1614af196f3eac703655d273f521c41d8a | bigcode/the-stack | train |
1eac6070f2c92f8ebd45db79 | train | function | @_wraps(onp.ones)
def ones(shape, dtype=onp.dtype("float64")):
shape = (shape,) if onp.isscalar(shape) else shape
return lax.full(shape, 1, dtype)
| @_wraps(onp.ones)
def ones(shape, dtype=onp.dtype("float64")):
| shape = (shape,) if onp.isscalar(shape) else shape
return lax.full(shape, 1, dtype)
| def zeros(shape, dtype=onp.dtype("float64")):
shape = (shape,) if onp.isscalar(shape) else shape
return lax.full(shape, 0, dtype)
@_wraps(onp.ones)
def ones(shape, dtype=onp.dtype("float64")):
| 64 | 64 | 50 | 22 | 42 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | ones | ones | 1,227 | 1,230 | 1,227 | 1,228 | eb95ee76c5da5fb5a04625e139d9706d77eb0f51 | bigcode/the-stack | train |
d848f416b14f0d2e5215f636 | train | function | @_wraps(onp.remainder)
def remainder(x1, x2):
x1, x2 = _promote_args("remainder", x1, x2)
return lax.rem(lax.add(lax.rem(x1, x2), x2), x2)
| @_wraps(onp.remainder)
def remainder(x1, x2):
| x1, x2 = _promote_args("remainder", x1, x2)
return lax.rem(lax.add(lax.rem(x1, x2), x2), x2)
| (onp.exp2)
def exp2(x):
x, = _promote_to_result_dtype(onp.exp2, x)
return lax.exp(lax.mul(lax.log(_constant_like(x, 2)), x))
@_wraps(onp.remainder)
def remainder(x1, x2):
| 64 | 64 | 60 | 17 | 47 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | remainder | remainder | 450 | 453 | 450 | 451 | f8be2ddf71c72eb4baa9da039e5f7ccb7b23c676 | bigcode/the-stack | train |
a4ba9df208052ebc9e294681 | train | function | @_wraps(onp.split)
def split(ary, indices_or_sections, axis=0):
dummy_val = onp.broadcast_to(0, ary.shape) # zero strides
subarrays = onp.split(dummy_val, indices_or_sections, axis) # shapes
split_indices = onp.cumsum([0] + [onp.shape(sub)[axis] for sub in subarrays])
starts, ends = [0] * ndim(ary), shape(ary... | @_wraps(onp.split)
def split(ary, indices_or_sections, axis=0):
| dummy_val = onp.broadcast_to(0, ary.shape) # zero strides
subarrays = onp.split(dummy_val, indices_or_sections, axis) # shapes
split_indices = onp.cumsum([0] + [onp.shape(sub)[axis] for sub in subarrays])
starts, ends = [0] * ndim(ary), shape(ary)
_subval = lambda x, i, v: lax.subvals(x, [(i, v)])
return ... | = onp.take(shape, new_dims)
squeezed_array = squeeze(arr, diff)
return lax.transpose(lax.broadcast(squeezed_array, broadcast_dims), perm)
else:
return arr
@_wraps(onp.split)
def split(ary, indices_or_sections, axis=0):
| 64 | 64 | 172 | 21 | 42 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | split | split | 742 | 750 | 742 | 743 | 4238588a311d54feeada9cf7cf89a850bd296c03 | bigcode/the-stack | train |
48576ebf07696a687629b605 | train | function | @_wraps(onp.log10)
def log10(x):
x, = _promote_to_result_dtype(onp.log10, x)
return lax.div(lax.log(x), lax.log(_constant_like(x, 10)))
| @_wraps(onp.log10)
def log10(x):
| x, = _promote_to_result_dtype(onp.log10, x)
return lax.div(lax.log(x), lax.log(_constant_like(x, 10)))
| _wraps(onp.log2)
def log2(x):
x, = _promote_to_result_dtype(onp.log2, x)
return lax.div(lax.log(x), lax.log(_constant_like(x, 2)))
@_wraps(onp.log10)
def log10(x):
| 62 | 64 | 50 | 14 | 48 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | log10 | log10 | 438 | 441 | 438 | 439 | 9310e75c700b191f892506f51f020910b6138029 | bigcode/the-stack | train |
266111430bd1d231709e9ee1 | train | function | @_wraps(onp.count_nonzero)
def count_nonzero(a, axis=None):
return sum(lax.ne(a, _constant_like(a, 0)), axis=axis,
dtype=xla_bridge.canonicalize_dtype(onp.int_))
| @_wraps(onp.count_nonzero)
def count_nonzero(a, axis=None):
| return sum(lax.ne(a, _constant_like(a, 0)), axis=axis,
dtype=xla_bridge.canonicalize_dtype(onp.int_))
| @_wraps(onp.allclose)
def allclose(a, b, rtol=1e-05, atol=1e-08):
return all(isclose(a, b, rtol, atol))
@_wraps(onp.count_nonzero)
def count_nonzero(a, axis=None):
| 64 | 64 | 53 | 19 | 45 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | count_nonzero | count_nonzero | 978 | 981 | 978 | 979 | cb3a923f52429b92c01750ca9b4a7be8703eead7 | bigcode/the-stack | train |
9c23f547368e509a622945cb | train | function | @_wraps(onp.imag)
def imag(x):
return lax.imag(x) if iscomplexobj(x) else zeros_like(x)
| @_wraps(onp.imag)
def imag(x):
| return lax.imag(x) if iscomplexobj(x) else zeros_like(x)
| ud)
def flipud(m):
return flip(m, 0)
@_wraps(onp.conjugate)
def conjugate(x):
return lax.conj(x) if iscomplexobj(x) else x
conj = conjugate
@_wraps(onp.imag)
def imag(x):
| 64 | 64 | 29 | 12 | 51 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | imag | imag | 566 | 568 | 566 | 567 | 4702bed3234d5bb4774aaa527d3c76de5f11b6d9 | bigcode/the-stack | train |
7bbd3b63254750771c58bbf7 | train | function | @_wraps(onp.hypot)
def hypot(x, y):
x, y = _promote_to_result_dtype(onp.hypot, x, y)
return lax.sqrt(x*x + y*y)
| @_wraps(onp.hypot)
def hypot(x, y):
| x, y = _promote_to_result_dtype(onp.hypot, x, y)
return lax.sqrt(x*x + y*y)
| ide, x, y)
zero = lax._const(x, 0)
return where(lax.lt(x, zero), zero,
where(lax.gt(x, zero), lax._const(x, 1), y))
@_wraps(onp.hypot)
def hypot(x, y):
| 64 | 64 | 47 | 16 | 48 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | hypot | hypot | 494 | 497 | 494 | 495 | af912e028d9a8aa7fa1132fe2015172ba7d5054f | bigcode/the-stack | train |
bd0d20f4f6cc756388ebae14 | train | function | def _promote_to_result_dtype(op, *args):
"""Convenience function to promote args directly to the op's result dtype."""
to_dtype = _result_dtype(op, *args)
return [lax.convert_element_type(arg, to_dtype) for arg in args]
| def _promote_to_result_dtype(op, *args):
| """Convenience function to promote args directly to the op's result dtype."""
to_dtype = _result_dtype(op, *args)
return [lax.convert_element_type(arg, to_dtype) for arg in args]
| if _dtype(x) != to_dtype else x for x in args]
if six.PY3:
_builtin_numeric_types = (int, float, complex)
else:
_builtin_numeric_types = (int, float, long, complex)
def _promote_to_result_dtype(op, *args):
| 64 | 64 | 58 | 12 | 52 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _promote_to_result_dtype | _promote_to_result_dtype | 163 | 166 | 163 | 163 | 3ccb9e88e7d17d833fa7494ff2321d7ed0ee7011 | bigcode/the-stack | train |
9e12cb0f321b0b0836dcb55d | train | function | @_wraps(getattr(onp, "gcd", None))
def gcd(x1, x2):
if (not issubdtype(lax._dtype(x1), integer) or
not issubdtype(lax._dtype(x2), integer)):
raise ValueError("Arguments to gcd must be integers.")
def cond_fn(xs):
x1, x2 = xs
return any(x2 != 0)
def body_fn(xs):
x1, x2 = xs
x1, x2 = (wher... | @_wraps(getattr(onp, "gcd", None))
def gcd(x1, x2):
| if (not issubdtype(lax._dtype(x1), integer) or
not issubdtype(lax._dtype(x2), integer)):
raise ValueError("Arguments to gcd must be integers.")
def cond_fn(xs):
x1, x2 = xs
return any(x2 != 0)
def body_fn(xs):
x1, x2 = xs
x1, x2 = (where(x2 != 0, x2, x1),
where(x2 != 0, lax... | .blackman
bartlett = onp.bartlett
hamming = onp.hamming
hanning = onp.hanning
kaiser = onp.kaiser # TODO: lower via lax to allow non-constant beta.
@_wraps(getattr(onp, "gcd", None))
def gcd(x1, x2):
| 73 | 73 | 245 | 23 | 50 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | gcd | gcd | 2,157 | 2,173 | 2,157 | 2,158 | 6700d73c47018aa8e36269c9e29aa19a18ec5a06 | bigcode/the-stack | train |
1f7a35a268e2f6fe4b9ab3dd | train | function | def _split_on_axis(onp_fun, axis):
@_wraps(onp_fun)
def f(ary, indices_or_sections):
return split(ary, indices_or_sections, axis=axis)
return f
| def _split_on_axis(onp_fun, axis):
@_wraps(onp_fun)
| def f(ary, indices_or_sections):
return split(ary, indices_or_sections, axis=axis)
return f
| lax.slice(ary, _subval(starts, axis, start), _subval(ends, axis, end))
for start, end in zip(split_indices[:-1], split_indices[1:])]
def _split_on_axis(onp_fun, axis):
@_wraps(onp_fun)
| 63 | 64 | 47 | 19 | 44 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _split_on_axis | _split_on_axis | 752 | 756 | 752 | 753 | 7bfbe80387ed926e610214308bbbb7add30238a2 | bigcode/the-stack | train |
e3007c200bc92793502ad83b | train | function | @_wraps(onp.take)
def take(a, indices, axis=None, out=None, mode=None):
if out:
raise NotImplementedError("The 'out' argument to np.take is not supported.")
a = asarray(a)
indices = asarray(indices)
if axis is None:
a = ravel(a)
axis = 0
axis = _canonicalize_axis(axis, ndim(a))
if mode == "ra... | @_wraps(onp.take)
def take(a, indices, axis=None, out=None, mode=None):
| if out:
raise NotImplementedError("The 'out' argument to np.take is not supported.")
a = asarray(a)
indices = asarray(indices)
if axis is None:
a = ravel(a)
axis = 0
axis = _canonicalize_axis(axis, ndim(a))
if mode == "raise":
# TODO(phawkins): we have no way to report out of bounds error... | slice(None)] * a_ndim
slices[i] = slice(None, -offset)
before = a[tuple(slices)]
slices[i] = slice(-offset, None)
after = a[tuple(slices)]
a = lax.concatenate((after, before), i)
return a
@_wraps(onp.take)
def take(a, indices, axis=None, out=None, mode=None):
| 87 | 87 | 290 | 23 | 63 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | take | take | 1,898 | 1,929 | 1,898 | 1,899 | de34760bc85e68f057238acc83dec9707789864c | bigcode/the-stack | train |
a78da9ba20f44dade0c4dc73 | train | function | def _reduction_dims(a, axis):
if axis is None:
return onp.arange(ndim(a))
elif isinstance(axis, (onp.ndarray, tuple, list)):
return onp.mod(onp.asarray(axis), ndim(a))
elif isinstance(axis, int):
return onp.mod([axis], ndim(a))
else:
raise TypeError("Unexpected type of axis argument: {}".format(... | def _reduction_dims(a, axis):
| if axis is None:
return onp.arange(ndim(a))
elif isinstance(axis, (onp.ndarray, tuple, list)):
return onp.mod(onp.asarray(axis), ndim(a))
elif isinstance(axis, int):
return onp.mod([axis], ndim(a))
else:
raise TypeError("Unexpected type of axis argument: {}".format(type(axis)))
| (1,) * len(dims)))
result = lax.reshape(result, shape_with_singletons)
if dtype and onp.dtype(dtype) != onp.dtype(result_dtype):
result = lax.convert_element_type(result, dtype)
return result
return reduction
def _reduction_dims(a, axis):
| 64 | 64 | 88 | 9 | 54 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _reduction_dims | _reduction_dims | 889 | 897 | 889 | 889 | 0f452df735130f32b069a1fc0aa35c7690412fde | bigcode/the-stack | train |
8405b5a5e7121f0774e6f200 | train | function | @_wraps(onp.ptp)
def ptp(a, axis=None, out=None, keepdims=False):
if out is not None:
raise ValueError("ptp does not support the `out` argument.")
x = amax(a, axis=axis, keepdims=keepdims)
y = amin(a, axis=axis, keepdims=keepdims)
return lax.sub(x, y)
| @_wraps(onp.ptp)
def ptp(a, axis=None, out=None, keepdims=False):
| if out is not None:
raise ValueError("ptp does not support the `out` argument.")
x = amax(a, axis=axis, keepdims=keepdims)
y = amin(a, axis=axis, keepdims=keepdims)
return lax.sub(x, y)
| raise ValueError("std does not support the `out` argument.")
return sqrt(var(a, axis=axis, dtype=dtype, ddof=ddof, keepdims=keepdims))
@_wraps(onp.ptp)
def ptp(a, axis=None, out=None, keepdims=False):
| 64 | 64 | 88 | 24 | 40 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | ptp | ptp | 964 | 970 | 964 | 965 | 52eda3f8777adda4b81cdc01a5b47e1ea8cf5269 | bigcode/the-stack | train |
8bcd3a15fe9903ef50af3553 | train | function | @_wraps(onp.angle)
def angle(x):
re = real(x)
im = imag(x)
dtype = _dtype(re)
if not issubdtype(dtype, inexact) or (
issubdtype(_dtype(x), floating) and ndim(x) == 0):
dtype = xla_bridge.canonicalize_dtype(float64)
re = lax.convert_element_type(re, dtype)
im = lax.convert_element_type(im, dtyp... | @_wraps(onp.angle)
def angle(x):
| re = real(x)
im = imag(x)
dtype = _dtype(re)
if not issubdtype(dtype, inexact) or (
issubdtype(_dtype(x), floating) and ndim(x) == 0):
dtype = xla_bridge.canonicalize_dtype(float64)
re = lax.convert_element_type(re, dtype)
im = lax.convert_element_type(im, dtype)
return lax.atan2(im, re)
| = imag(x)
return lax.ne(i, lax._const(i, 0))
@_wraps(onp.isreal)
def isreal(x):
i = imag(x)
return lax.eq(i, lax._const(i, 0))
@_wraps(onp.angle)
def angle(x):
| 64 | 64 | 106 | 12 | 52 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | angle | angle | 586 | 596 | 586 | 587 | 3f755b6eac589fe8cb1c54d14d9aef52e1e885b6 | bigcode/the-stack | train |
817f41dd6c89e9f9705cdf96 | train | function | @_wraps(onp.logaddexp)
def logaddexp(x1, x2):
x1, x2 = _promote_shapes(*_promote_to_result_dtype(onp.logaddexp, x1, x2))
amax = lax.max(x1, x2)
return lax.add(amax, lax.log(lax.add(lax.exp(lax.sub(x1, amax)),
lax.exp(lax.sub(x2, amax)))))
| @_wraps(onp.logaddexp)
def logaddexp(x1, x2):
| x1, x2 = _promote_shapes(*_promote_to_result_dtype(onp.logaddexp, x1, x2))
amax = lax.max(x1, x2)
return lax.add(amax, lax.log(lax.add(lax.exp(lax.sub(x1, amax)),
lax.exp(lax.sub(x2, amax)))))
| (acc, x1), acc)
x1 = lax.mul(x1, x1)
x2 = lax.shift_right_logical(x2, _constant_like(x2, 1))
return acc
@_wraps(onp.logaddexp)
def logaddexp(x1, x2):
| 64 | 64 | 98 | 20 | 43 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | logaddexp | logaddexp | 416 | 421 | 416 | 417 | 57e61e208b47925ec75bed8be3b96c3c0af4c2ae | bigcode/the-stack | train |
8979eb233092a82e1be7cfa0 | train | function | @_wraps(onp.deg2rad)
def deg2rad(x):
x, = _promote_to_result_dtype(onp.deg2rad, x)
return lax.mul(x, lax._const(x, pi / 180))
| @_wraps(onp.deg2rad)
def deg2rad(x):
| x, = _promote_to_result_dtype(onp.deg2rad, x)
return lax.mul(x, lax._const(x, pi / 180))
| power(x, _constant_like(x, 0.5))
@_wraps(onp.square)
def square(x):
x, = _promote_to_result_dtype(onp.square, x)
return x * x
@_wraps(onp.deg2rad)
def deg2rad(x):
| 64 | 64 | 52 | 17 | 46 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | deg2rad | deg2rad | 470 | 473 | 470 | 471 | b5a7dfe2efa7bef3edb0f13cd87f63f58c2cbe49 | bigcode/the-stack | train |
ab162b2a2903f24879ce13f4 | train | function | @_wraps(onp.fliplr)
def fliplr(m):
return flip(m, 1)
| @_wraps(onp.fliplr)
def fliplr(m):
| return flip(m, 1)
| assert axis >= -rank, "axis={} is invalid for the {}-dimensional input array".format(axis, rank)
return lax.rev(m, [axis % rank])
else:
return lax.rev(m, [axis])
@_wraps(onp.fliplr)
def fliplr(m):
| 64 | 64 | 24 | 16 | 48 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | fliplr | fliplr | 550 | 552 | 550 | 551 | fac857fda87225140594400ba52c7a070eb42af1 | bigcode/the-stack | train |
e435583a52c31cd328ce6be5 | train | function | def _promote_shapes(*args):
"""Prepend implicit leading singleton dimensions for Numpy broadcasting."""
if len(args) < 2:
return args
else:
shapes = [shape(arg) for arg in args]
nd = len(lax.broadcast_shapes(*shapes))
return [lax.reshape(arg, (1,) * (nd - len(shp)) + shp)
if len(shp) !... | def _promote_shapes(*args):
| """Prepend implicit leading singleton dimensions for Numpy broadcasting."""
if len(args) < 2:
return args
else:
shapes = [shape(arg) for arg in args]
nd = len(lax.broadcast_shapes(*shapes))
return [lax.reshape(arg, (1,) * (nd - len(shp)) + shp)
if len(shp) != nd else arg for arg, shp i... | onp.finfo
issubdtype = onp.issubdtype
issubsctype = onp.issubsctype
ComplexWarning = onp.ComplexWarning
array_str = onp.array_str
array_repr = onp.array_repr
### utility functions
def _promote_shapes(*args):
| 64 | 64 | 103 | 8 | 55 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _promote_shapes | _promote_shapes | 136 | 144 | 136 | 136 | df9f798a83996148b4302e91c7daf29e6550662e | bigcode/the-stack | train |
57a3f9d6dde7058da45faefe | train | function | def _logical_op(np_op, bitwise_op):
@_wraps(np_op)
def op(*args):
zero = lambda x: lax.full_like(x, shape=(), fill_value=0)
args = (x if onp.issubdtype(_dtype(x), onp.bool_) else lax.ne(x, zero(x))
for x in args)
return bitwise_op(*_promote_args(np_op.__name__, *args))
return op
| def _logical_op(np_op, bitwise_op):
@_wraps(np_op)
| def op(*args):
zero = lambda x: lax.full_like(x, shape=(), fill_value=0)
args = (x if onp.issubdtype(_dtype(x), onp.bool_) else lax.ne(x, zero(x))
for x in args)
return bitwise_op(*_promote_args(np_op.__name__, *args))
return op
| .greater_equal, lax.ge)
greater = _comparison_op(onp.greater, lax.gt)
less_equal = _comparison_op(onp.less_equal, lax.le)
less = _comparison_op(onp.less, lax.lt)
def _logical_op(np_op, bitwise_op):
@_wraps(np_op)
| 64 | 64 | 99 | 18 | 46 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _logical_op | _logical_op | 315 | 322 | 315 | 316 | 780f3c8c3089fe0e7314e69c516694a4bca24031 | bigcode/the-stack | train |
fa9486f1ec869599a81da74c | train | function | @_wraps(onp.append)
def append(arr, values, axis=None):
if axis is None:
return concatenate([ravel(arr), ravel(values)], 0)
else:
return concatenate([arr, values], axis=axis)
| @_wraps(onp.append)
def append(arr, values, axis=None):
| if axis is None:
return concatenate([ravel(arr), ravel(values)], 0)
else:
return concatenate([arr, values], axis=axis)
| isinstance(x, onp.poly1d):
y = 0
else:
y = zeros_like(x)
for i in range(len(p)):
y = y * x + p[i]
return y
@_wraps(onp.append)
def append(arr, values, axis=None):
| 64 | 64 | 53 | 17 | 46 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | append | append | 1,414 | 1,419 | 1,414 | 1,415 | 4f3e38b1cfc48528bc6e61958aa0ee45d83eed15 | bigcode/the-stack | train |
34dcef271597c940417966da | train | function | def _canonicalize_axis(axis, num_dims):
"""Canonicalize an axis in (-num_dims, num_dims) to [0, num_dims)."""
axis = int(axis)
if axis < 0:
axis = axis + num_dims
if axis < 0 or axis >= num_dims:
raise ValueError(
"axis {} is out of bounds for array of dimension {}".format(
axi... | def _canonicalize_axis(axis, num_dims):
| """Canonicalize an axis in (-num_dims, num_dims) to [0, num_dims)."""
axis = int(axis)
if axis < 0:
axis = axis + num_dims
if axis < 0 or axis >= num_dims:
raise ValueError(
"axis {} is out of bounds for array of dimension {}".format(
axis, num_dims))
return axis
| squash_nan=True)
nancumprod = _make_cumulative_reduction(
onp.nancumprod, lax._reduce_window_prod, 1, squash_nan=True)
### Array-creation functions
# TODO(phawkins): use this helper everywhere.
def _canonicalize_axis(axis, num_dims):
| 64 | 64 | 95 | 10 | 54 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | _canonicalize_axis | _canonicalize_axis | 1,056 | 1,065 | 1,056 | 1,056 | 4cbeda09a133a2b6c8d5c0e1be64f225e60d7fc9 | bigcode/the-stack | train |
380e3daf1e608d7052f45916 | train | function | @_wraps(onp.vstack)
def vstack(tup):
return concatenate([atleast_2d(m) for m in tup], axis=0)
| @_wraps(onp.vstack)
def vstack(tup):
| return concatenate([atleast_2d(m) for m in tup], axis=0)
| array to concatenate.")
if ndim(arrays[0]) == 0:
raise ValueError("Zero-dimensional arrays cannot be concatenated.")
return lax.concatenate(_promote_dtypes(*arrays), axis % ndim(arrays[0]))
@_wraps(onp.vstack)
def vstack(tup):
| 63 | 64 | 34 | 14 | 49 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | vstack | vstack | 1,111 | 1,113 | 1,111 | 1,112 | 6393031a46ba0ac62a32d960b8b9aa385b0b0e3e | bigcode/the-stack | train |
e1d57e9d7de1f35915ce80bf | train | function | @_wraps(onp.einsum)
def einsum(*operands, **kwargs):
optimize = kwargs.pop('optimize', 'auto')
optimize = 'greedy' if optimize is True else optimize
if kwargs:
msg = 'invalid keyword arguments for einsum: {}'
raise TypeError(msg.format(', '.join(kwargs)))
# using einsum_call=True here is an internal api... | @_wraps(onp.einsum)
def einsum(*operands, **kwargs):
| optimize = kwargs.pop('optimize', 'auto')
optimize = 'greedy' if optimize is True else optimize
if kwargs:
msg = 'invalid keyword arguments for einsum: {}'
raise TypeError(msg.format(', '.join(kwargs)))
# using einsum_call=True here is an internal api for opt_einsum
operands, contractions = opt_einsum... | , num_axes)
msg = ("tensordot axes argument must be an int, a pair of ints, or a pair of "
"lists/tuples of ints.")
raise TypeError(msg)
@_wraps(onp.einsum)
def einsum(*operands, **kwargs):
| 64 | 64 | 148 | 20 | 44 | navneet-nmk/jax | jax/numpy/lax_numpy.py | Python | einsum | einsum | 1,506 | 1,517 | 1,506 | 1,507 | 2a95a928cb92d5d894c9f2f2e54f0c5f5194f6a2 | bigcode/the-stack | train |
9860665d679a7d4df9ea9b69 | train | function | @dext_jinja2.jinjaglobal
def region_url(turn=None):
return logic.region_url(turn=turn)
| @dext_jinja2.jinjaglobal
def region_url(turn=None):
| return logic.region_url(turn=turn)
|
import smart_imports
smart_imports.all()
@dext_jinja2.jinjaglobal
def region_url(turn=None):
| 28 | 64 | 26 | 17 | 11 | devapromix/the-tale | src/the_tale/the_tale/game/map/jinjaglobals.py | Python | region_url | region_url | 7 | 9 | 7 | 8 | 2d7ce5237fffdce05bb1d2b64a54eae6f4d796f1 | bigcode/the-stack | train |
1fee1ceee9e1030261843416 | train | class | class TestDFN(unittest.TestCase):
def test_well_posed(self):
options = {"thermal": "isothermal"}
model = pybamm.lithium_ion.DFN(options)
model.check_well_posedness()
def test_well_posed_2plus1D(self):
options = {"current collector": "potential pair", "dimensionality": 1}
... | class TestDFN(unittest.TestCase):
| def test_well_posed(self):
options = {"thermal": "isothermal"}
model = pybamm.lithium_ion.DFN(options)
model.check_well_posedness()
def test_well_posed_2plus1D(self):
options = {"current collector": "potential pair", "dimensionality": 1}
model = pybamm.lithium_ion.DFN(op... | #
# Tests for the lithium-ion DFN model
#
import pybamm
import unittest
class TestDFN(unittest.TestCase):
| 28 | 256 | 1,020 | 8 | 19 | DrSOKane/PyBaMM | tests/unit/test_models/test_full_battery_models/test_lithium_ion/test_dfn.py | Python | TestDFN | TestDFN | 8 | 124 | 8 | 8 | 0d5ed01ab09399c36cbee6898f18d6c3d94d1536 | bigcode/the-stack | train |
32177f7b95aec1b4617432a0 | train | class | class TestDFNWithCrack(unittest.TestCase):
def test_well_posed_none_crack(self):
options = {"particle": "Fickian diffusion", "particle cracking": None}
model = pybamm.lithium_ion.DFN(options)
model.check_well_posedness()
def test_well_posed_no_cracking(self):
options = {"particl... | class TestDFNWithCrack(unittest.TestCase):
| def test_well_posed_none_crack(self):
options = {"particle": "Fickian diffusion", "particle cracking": None}
model = pybamm.lithium_ion.DFN(options)
model.check_well_posedness()
def test_well_posed_no_cracking(self):
options = {"particle": "Fickian diffusion", "particle cracking... | amm.lithium_ion.DFN(options)
model.check_well_posedness()
def test_well_posed_ec_reaction_limited(self):
options = {"sei": "ec reaction limited", "sei porosity change": True}
model = pybamm.lithium_ion.DFN(options)
model.check_well_posedness()
class TestDFNWithCrack(unittest.TestCas... | 87 | 87 | 293 | 11 | 76 | DrSOKane/PyBaMM | tests/unit/test_models/test_full_battery_models/test_lithium_ion/test_dfn.py | Python | TestDFNWithCrack | TestDFNWithCrack | 164 | 188 | 164 | 164 | a284ee81284d15b94957727f3ed47f26c6f0d471 | bigcode/the-stack | train |
44f2f6debbeea4b481099aab | train | class | class TestDFNWithSEI(unittest.TestCase):
def test_well_posed_constant(self):
options = {"sei": "constant"}
model = pybamm.lithium_ion.DFN(options)
model.check_well_posedness()
def test_well_posed_reaction_limited(self):
options = {"sei": "reaction limited"}
model = pybam... | class TestDFNWithSEI(unittest.TestCase):
| def test_well_posed_constant(self):
options = {"sei": "constant"}
model = pybamm.lithium_ion.DFN(options)
model.check_well_posedness()
def test_well_posed_reaction_limited(self):
options = {"sei": "reaction limited"}
model = pybamm.lithium_ion.DFN(options)
model.... | test_surface_form_algebraic(self):
options = {"surface form": "algebraic"}
model = pybamm.lithium_ion.DFN(options)
model.check_well_posedness()
def test_electrolyte_options(self):
options = {"electrolyte conductivity": "integrated"}
with self.assertRaisesRegex(pybamm.Option... | 112 | 112 | 375 | 11 | 101 | DrSOKane/PyBaMM | tests/unit/test_models/test_full_battery_models/test_lithium_ion/test_dfn.py | Python | TestDFNWithSEI | TestDFNWithSEI | 127 | 161 | 127 | 127 | 4129dae8b518eb9b20d102a3627212f862c28fd5 | bigcode/the-stack | train |
d98c3096c9bf25713e589b30 | train | class | class SRUCell(tf.keras.layers.AbstractRNNCell):
"""Statistical Recurrent Unit Cell.
Attributes:
mavg_alphas: List of summary statistics tracked.
num_stats: output size for each summary statistic.
The output size of the RNN is determined by len(mavg_alphas * num_stats).
... | class SRUCell(tf.keras.layers.AbstractRNNCell):
| """Statistical Recurrent Unit Cell.
Attributes:
mavg_alphas: List of summary statistics tracked.
num_stats: output size for each summary statistic.
The output size of the RNN is determined by len(mavg_alphas * num_stats).
recur_dims: Number of previous states that are t... | 1, 1, self.num_stats))
# Calculation: mu_t = mask*mu_{t-1} + cos(2*pi*w*t/T + 2*pi*phase)*phi_t
angle1 = (2. * math.pi / self.sequence_length) * cur_time_step * self.freqs
angle2 = 2. * math.pi * self.phases
first_term = self.freqs_mask * state_tensor
second_term = (1 / self.seq... | 256 | 256 | 887 | 12 | 243 | Selozhd/UngatedRNN | fru_cell.py | Python | SRUCell | SRUCell | 132 | 227 | 132 | 132 | e59e75b57bcc0746d7574644e2a0ead3234b61d9 | bigcode/the-stack | train |
c79468f578ac4e7dd1bf0fa2 | train | class | class FRU(tf.keras.layers.RNN):
"""Fourier Recurrent Unit."""
def __init__(self,
num_stats,
freqs,
recur_dims,
freqs_mask=1.,
linear_out=False,
include_input=False,
activation=tf.nn.gelu,
... | class FRU(tf.keras.layers.RNN):
| """Fourier Recurrent Unit."""
def __init__(self,
num_stats,
freqs,
recur_dims,
freqs_mask=1.,
linear_out=False,
include_input=False,
activation=tf.nn.gelu,
initializer = tf.initialize... | 1, self.num_stats))
output_tensor = self.mavg_alphas * state_tensor + (1 - self.mavg_alphas) * stats_tensor
out_state = tf.reshape(output_tensor, shape=(-1, self.state_size))
# Compute the output.
if self.include_input:
output_vars = [out_state, inputs]
else:
... | 173 | 174 | 583 | 9 | 164 | Selozhd/UngatedRNN | fru_cell.py | Python | FRU | FRU | 230 | 321 | 230 | 230 | e80703070e5e45195fed27a8d8ee747c9cc81c94 | bigcode/the-stack | train |
fb12464a866dc44cbc00e3d3 | train | class | class FRUCell(tf.keras.layers.Layer):
"""Fourier Recurrent Unit."""
def __init__(self,
num_stats,
freqs,
recur_dims,
freqs_mask=1., # I don't understand the point of this.
linear_out=False,
include_input=False... | class FRUCell(tf.keras.layers.Layer):
| """Fourier Recurrent Unit."""
def __init__(self,
num_stats,
freqs,
recur_dims,
freqs_mask=1., # I don't understand the point of this.
linear_out=False,
include_input=False,
activation=tf.nn.ge... | standing long range dependencies. For the official repositories see
[3] and [4] for SRU and FRU respectively.
References:
[1] Oliva, J. B., Póczos, B., & Schneider, J. (2017, July). The statistical recurrent unit.
In International Conference on Machine Learning (pp. 2671-2680). PMLR.
[2] Zhang, J., Li... | 256 | 256 | 1,104 | 9 | 246 | Selozhd/UngatedRNN | fru_cell.py | Python | FRUCell | FRUCell | 29 | 129 | 29 | 29 | 1cabf922f06165937a19b3c46657deec37a7c72f | bigcode/the-stack | train |
d48d9b06e42524ecfa4064d3 | train | function | def _linear(args, matrix, bias):
"""Helper function for an affine transformation w.r.t matrix."""
if isinstance(args, (tuple, list)):
return tf.matmul(tf.concat(args, axis=1), matrix) + bias
else:
return tf.matmul(args, matrix) + bias
| def _linear(args, matrix, bias):
| """Helper function for an affine transformation w.r.t matrix."""
if isinstance(args, (tuple, list)):
return tf.matmul(tf.concat(args, axis=1), matrix) + bias
else:
return tf.matmul(args, matrix) + bias
| (pp. 5815-5823). PMLR.
[3] https://github.com/mirandawork/sru.
[4] https://github.com/limbo018/FRU.
"""
import math
import tensorflow as tf
def _linear(args, matrix, bias):
| 64 | 64 | 63 | 9 | 54 | Selozhd/UngatedRNN | fru_cell.py | Python | _linear | _linear | 21 | 26 | 21 | 21 | aa16f658e45f30fc9e71f2e43d2ff6d1f6bc4042 | bigcode/the-stack | train |
1fcd94564b24edc1c8962485 | train | function | def build_augmenter(with_labels=True, dim=[360, 640], CFG=None):
def augment(img, dim=dim):
if random_float()<CFG.transform_prob:
img = transform(img,DIM=dim,
ROT=CFG.rot,SHR=CFG.shr,
H_ZOOM=CFG.hzoom, V_ZOOM=CFG.vzoom,
... | def build_augmenter(with_labels=True, dim=[360, 640], CFG=None):
| def augment(img, dim=dim):
if random_float()<CFG.transform_prob:
img = transform(img,DIM=dim,
ROT=CFG.rot,SHR=CFG.shr,
H_ZOOM=CFG.hzoom, V_ZOOM=CFG.vzoom,
H_SHIFT=CFG.hshift, V_SHIFT=CFG.vshift,
... | .remove_border:
img = RandomBorder(img, target_size=target_size,mode='constant',
fill_border=CFG.fill_border,remove_symbol=CFG.remove_symbol)
img = tf.cast(img, tf.float32)
# normalization
img = img / 255.0
img = tf.reshape(img, [*target_size, ... | 136 | 136 | 455 | 19 | 116 | awsaf49/deep-chimpact-1st-place-solution | dataset/dataset.py | Python | build_augmenter | build_augmenter | 54 | 92 | 54 | 54 | 2a5855258894dbd3dd9d78045ed36b9fd0f674bd | bigcode/the-stack | train |
6db1a5e8cc62a2e4741b40ad | train | function | def build_dataset(paths, labels=None, batch_size=32, cache=True,
decode_fn=None, augment_fn=None,
augment=True, repeat=True, shuffle=1024,
cache_dir="", drop_remainder=False, CFG=None):
if cache_dir != "" and cache is True:
os.makedirs(cache_dir, exist_... | def build_dataset(paths, labels=None, batch_size=32, cache=True,
decode_fn=None, augment_fn=None,
augment=True, repeat=True, shuffle=1024,
cache_dir="", drop_remainder=False, CFG=None):
| if cache_dir != "" and cache is True:
os.makedirs(cache_dir, exist_ok=True)
if decode_fn is None:
decode_fn = build_decoder(labels is not None,target_size=CFG.img_size,
CFG=CFG)
if augment_fn is None:
augment_fn = build_augmenter(labels is ... | 1)
img = tf.reshape(img, [*dim, 3])
return img
def augment_with_labels(img, label):
return augment(img), label
return augment_with_labels if with_labels else augment
def build_dataset(paths, labels=None, batch_size=32, cache=True,
decode_fn=None, augmen... | 100 | 100 | 336 | 50 | 49 | awsaf49/deep-chimpact-1st-place-solution | dataset/dataset.py | Python | build_dataset | build_dataset | 95 | 128 | 95 | 98 | a1ac12e0943c5774ab51a2c21bbed15f53633d3f | bigcode/the-stack | train |
f65f80fa8f2d7494233cabc7 | train | function | def build_decoder(with_labels=True, target_size=[360, 640], CFG=None, ext='png'):
def decode(path):
file_bytes = tf.io.read_file(path)
if ext == 'png':
img = tf.image.decode_png(file_bytes, channels=3)
elif ext in ['jpg', 'jpeg']:
img = tf.image.decode_jpeg(file_bytes... | def build_decoder(with_labels=True, target_size=[360, 640], CFG=None, ext='png'):
| def decode(path):
file_bytes = tf.io.read_file(path)
if ext == 'png':
img = tf.image.decode_png(file_bytes, channels=3)
elif ext in ['jpg', 'jpeg']:
img = tf.image.decode_jpeg(file_bytes, channels=3)
else:
raise ValueError("Image extension not supp... | EDING
def seeding(CFG):
SEED = CFG.seed
np.random.seed(SEED)
random.seed(SEED)
os.environ['PYTHONHASHSEED'] = str(SEED)
tf.random.set_seed(SEED)
print('> SEEDING DONE')
# DATA PIPELINE
def build_decoder(with_labels=True, target_size=[360, 640], CFG=None, ext='png'):
| 88 | 88 | 294 | 22 | 65 | awsaf49/deep-chimpact-1st-place-solution | dataset/dataset.py | Python | build_decoder | build_decoder | 20 | 51 | 20 | 20 | 8c402f79f5f8b256558552bfbedf7b3557c43036 | bigcode/the-stack | train |
0f011b35ba821c0cceb00cfa | train | function | def seeding(CFG):
SEED = CFG.seed
np.random.seed(SEED)
random.seed(SEED)
os.environ['PYTHONHASHSEED'] = str(SEED)
tf.random.set_seed(SEED)
print('> SEEDING DONE')
| def seeding(CFG):
| SEED = CFG.seed
np.random.seed(SEED)
random.seed(SEED)
os.environ['PYTHONHASHSEED'] = str(SEED)
tf.random.set_seed(SEED)
print('> SEEDING DONE')
| np
import random
import os
import tensorflow as tf
from dataset.augment import transform, RandomBorder, dropout, RandomFlip, RandomJitter
from dataset.augment import OpticalDistortion, GridDistortion
from dataset.augment import random_float
# SEEDING
def seeding(CFG):
| 64 | 64 | 58 | 6 | 57 | awsaf49/deep-chimpact-1st-place-solution | dataset/dataset.py | Python | seeding | seeding | 11 | 17 | 11 | 11 | c0a009923c7a64067fcdc7e7f976e7fe841d746f | bigcode/the-stack | train |
0ebcf93f818aaa0b8876375f | train | class | @python_2_unicode_compatible
class Similarity(RecommendsBaseModel):
"""How much an object is similar to another"""
score = models.FloatField(null=True, blank=True, default=None)
related_object_ctype = models.PositiveIntegerField()
related_object_id = models.PositiveIntegerField()
related_object_si... | @python_2_unicode_compatible
class Similarity(RecommendsBaseModel):
| """How much an object is similar to another"""
score = models.FloatField(null=True, blank=True, default=None)
related_object_ctype = models.PositiveIntegerField()
related_object_id = models.PositiveIntegerField()
related_object_site = models.PositiveIntegerField()
related_object = generic.Gene... | commendsManager()
class Meta:
abstract = True
unique_together = ('object_ctype', 'object_id', 'object_site')
def __str__(self):
return "RecommendsBaseModel"
@python_2_unicode_compatible
class Similarity(RecommendsBaseModel):
| 64 | 64 | 181 | 17 | 47 | coagulant/django-recommends | recommends/storages/djangoorm/models.py | Python | Similarity | Similarity | 26 | 45 | 26 | 27 | d0631cba0d6039a5130f5f2d1d76ac5b53420f4a | bigcode/the-stack | train |
60bece4e52038fb588c6a83d | train | class | @python_2_unicode_compatible
class Recommendation(RecommendsBaseModel):
"""Recommended an object for a particular user"""
user = models.PositiveIntegerField()
score = models.FloatField(null=True, blank=True, default=None)
objects = RecommendationManager()
class Meta:
unique_together = ('ob... | @python_2_unicode_compatible
class Recommendation(RecommendsBaseModel):
| """Recommended an object for a particular user"""
user = models.PositiveIntegerField()
score = models.FloatField(null=True, blank=True, default=None)
objects = RecommendationManager()
class Meta:
unique_together = ('object_ctype', 'object_id', 'user')
ordering = ['-score']
def... | _object_ctype', 'related_object_id', 'related_object_site')
ordering = ['-score']
def __str__(self):
return "Similarity between %s and %s" % (self.object, self.related_object)
@python_2_unicode_compatible
class Recommendation(RecommendsBaseModel):
| 64 | 64 | 104 | 16 | 48 | coagulant/django-recommends | recommends/storages/djangoorm/models.py | Python | Recommendation | Recommendation | 48 | 61 | 48 | 49 | 6479187ff02f8e7cb60233d95f16d6921e976499 | bigcode/the-stack | train |
45d9025350aa0f4a4c0db31d | train | class | @python_2_unicode_compatible
class RecommendsBaseModel(models.Model):
"""(RecommendsBaseModel description)"""
object_ctype = models.PositiveIntegerField()
object_id = models.PositiveIntegerField()
object_site = models.PositiveIntegerField()
object = generic.GenericForeignKey('object_ctype', 'object_... | @python_2_unicode_compatible
class RecommendsBaseModel(models.Model):
| """(RecommendsBaseModel description)"""
object_ctype = models.PositiveIntegerField()
object_id = models.PositiveIntegerField()
object_site = models.PositiveIntegerField()
object = generic.GenericForeignKey('object_ctype', 'object_id')
objects = RecommendsManager()
class Meta:
abstr... | import unicode_literals
from django.db import models
from django.contrib.contenttypes import generic
from .managers import RecommendsManager, SimilarityManager, RecommendationManager
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class RecommendsBaseModel(models.Model):
| 64 | 64 | 123 | 17 | 46 | coagulant/django-recommends | recommends/storages/djangoorm/models.py | Python | RecommendsBaseModel | RecommendsBaseModel | 8 | 23 | 8 | 9 | 1008184f57cf02e9b3f36c72ffbeaa651c501034 | bigcode/the-stack | train |
6d9b1fc2297211f8dcd4909d | train | class | class BinanceChainSocketConn(object):
"""
Binance Chain Abstract Base Socket Connections,
As per https://github.com/websocket-client/websocket-client, provide 2 ways to connect to socket:
- Long-lived connection
- Short-lived one-off send-receive
"""
def __init__(self, ws_url):
web... | class BinanceChainSocketConn(object):
| """
Binance Chain Abstract Base Socket Connections,
As per https://github.com/websocket-client/websocket-client, provide 2 ways to connect to socket:
- Long-lived connection
- Short-lived one-off send-receive
"""
def __init__(self, ws_url):
websocket.enableTrace(True)
self.... | ws4py
All above works fine
decided to adopt "websocket" because its simple as per zen of python: "Simple is better than complex"
"""
import ssl
import asyncio
import websocket
try:
import thread
except ImportError:
import _thread as thread
from websocket import create_connection
class BinanceChainSocketConn(... | 73 | 73 | 246 | 7 | 65 | RafaelHMachado/Cioffis_Automation | venv/Lib/site-packages/binance_dex/lib/sockets.py | Python | BinanceChainSocketConn | BinanceChainSocketConn | 21 | 54 | 21 | 21 | 9c7fd924451421669dc2f68d6b6fef0583b76b33 | bigcode/the-stack | train |
6953adab9a10d11c836d58a4 | train | function | def _on_open(ws):
def run(*args):
pass
thread.start_new_thread(run, ())
| def _on_open(ws):
| def run(*args):
pass
thread.start_new_thread(run, ())
| print('!!! Here is default callback function, '
'please pass in your own customized callback function to handle received data !!!')
print(args[1])
def _on_error(ws, error):
print(error)
def _on_close(ws):
print("### closed ###")
def _on_open(ws):
| 64 | 64 | 23 | 6 | 58 | RafaelHMachado/Cioffis_Automation | venv/Lib/site-packages/binance_dex/lib/sockets.py | Python | _on_open | _on_open | 73 | 76 | 73 | 73 | 83d820757e7245851f43795a78e96ff2600590a8 | bigcode/the-stack | train |
f184d0490eee9ab8187e76d7 | train | function | def _on_close(ws):
print("### closed ###")
| def _on_close(ws):
| print("### closed ###")
| free to override by yourself
def _on_message(*args):
print('!!! Here is default callback function, '
'please pass in your own customized callback function to handle received data !!!')
print(args[1])
def _on_error(ws, error):
print(error)
def _on_close(ws):
| 64 | 64 | 13 | 6 | 58 | RafaelHMachado/Cioffis_Automation | venv/Lib/site-packages/binance_dex/lib/sockets.py | Python | _on_close | _on_close | 69 | 70 | 69 | 69 | f99aae84e503b5c655b85c13205a52194440ab6a | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.