Here are the examples of the python api numpy.asanyarray taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
734 Examples
3
Source : test_subclassing.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def __new__(cls,arr,info={}):
x = np.asanyarray(arr).view(cls)
x.info = info.copy()
return x
def __array_finalize__(self, obj):
3
Source : test_distance.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def _chk_asarrays(arrays, axis=None):
arrays = [np.asanyarray(a) for a in arrays]
if axis is None:
# np < 1.10 ravel removes subclass from arrays
arrays = [np.ravel(a) if a.ndim != 1 else a
for a in arrays]
axis = 0
arrays = tuple(np.atleast_1d(a) for a in arrays)
if axis < 0:
if not all(a.ndim == arrays[0].ndim for a in arrays):
raise ValueError("array ndim must be the same for neg axis")
axis = range(arrays[0].ndim)[axis]
return arrays + (axis,)
def _chk_weights(arrays, weights=None, axis=None,
3
Source : test_distance.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def _weight_masked(arrays, weights, axis):
if axis is None:
axis = 0
weights = np.asanyarray(weights)
for a in arrays:
axis_mask = np.ma.getmask(a)
if axis_mask is np.ma.nomask:
continue
if a.ndim > 1:
not_axes = tuple(i for i in range(a.ndim) if i != axis)
axis_mask = axis_mask.any(axis=not_axes)
weights *= 1 - axis_mask.astype(int)
return weights
def within_tol(a, b, tol):
3
Source : mstats_basic.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def _betai(a, b, x):
x = np.asanyarray(x)
x = ma.where(x < 1.0, x, 1.0) # if x > 1 then return 1.0
return special.betainc(a, b, x)
def msign(x):
3
Source : collections.py
with MIT License
from alvarobartt
with MIT License
from alvarobartt
def set_offsets(self, offsets):
"""
Set the offsets for the collection. *offsets* can be a scalar
or a sequence.
ACCEPTS: float or sequence of floats
"""
offsets = np.asanyarray(offsets, float)
if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else.
offsets = offsets[None, :]
# This decision is based on how they are initialized above in __init__.
if self._uniform_offsets is None:
self._offsets = offsets
else:
self._uniform_offsets = offsets
self.stale = True
def get_offsets(self):
3
Source : collections.py
with MIT License
from alvarobartt
with MIT License
from alvarobartt
def add_positions(self, position):
'''
add one or more events at the specified positions
'''
if position is None or (hasattr(position, 'len') and
len(position) == 0):
return
positions = self.get_positions()
positions = np.hstack([positions, np.asanyarray(position)])
self.set_positions(positions)
extend_positions = append_positions = add_positions
3
Source : colors.py
with MIT License
from alvarobartt
with MIT License
from alvarobartt
def autoscale(self, A):
"""
Set *vmin*, *vmax* to min, max of *A*.
"""
A = np.asanyarray(A)
self.vmin = A.min()
self.vmax = A.max()
def autoscale_None(self, A):
3
Source : colors.py
with MIT License
from alvarobartt
with MIT License
from alvarobartt
def autoscale_None(self, A):
"""autoscale only None-valued vmin or vmax."""
A = np.asanyarray(A)
if self.vmin is None and A.size:
self.vmin = A.min()
if self.vmax is None and A.size:
self.vmax = A.max()
def scaled(self):
3
Source : colors.py
with MIT License
from alvarobartt
with MIT License
from alvarobartt
def autoscale_None(self, A):
"""autoscale only None-valued vmin or vmax."""
if self.vmin is not None and self.vmax is not None:
pass
A = np.asanyarray(A)
if self.vmin is None and A.size:
self.vmin = A.min()
if self.vmax is None and A.size:
self.vmax = A.max()
self._transform_vmin_vmax()
class PowerNorm(Normalize):
3
Source : colors.py
with MIT License
from alvarobartt
with MIT License
from alvarobartt
def autoscale_None(self, A):
"""autoscale only None-valued vmin or vmax."""
A = np.asanyarray(A)
if self.vmin is None and A.size:
self.vmin = A.min()
if self.vmin < 0:
self.vmin = 0
warnings.warn("Power-law scaling on negative values is "
"ill-defined, clamping to 0.")
if self.vmax is None and A.size:
self.vmax = A.max()
class BoundaryNorm(Normalize):
3
Source : art3d.py
with MIT License
from alvarobartt
with MIT License
from alvarobartt
def set_segments(self, segments):
'''
Set 3D segments
'''
self._segments3d = np.asanyarray(segments)
LineCollection.set_segments(self, [])
def do_3d_projection(self, renderer):
3
Source : testing.py
with MIT License
from alvarobartt
with MIT License
from alvarobartt
def _assert_allclose(actual, desired, rtol=1e-7, atol=0,
err_msg='', verbose=True):
actual, desired = np.asanyarray(actual), np.asanyarray(desired)
if np.allclose(actual, desired, rtol=rtol, atol=atol):
return
msg = ('Array not equal to tolerance rtol=%g, atol=%g: '
'actual %s, desired %s') % (rtol, atol, actual, desired)
raise AssertionError(msg)
if hasattr(np.testing, 'assert_allclose'):
3
Source : validation.py
with MIT License
from alvarobartt
with MIT License
from alvarobartt
def _assert_all_finite(X):
"""Like assert_all_finite, but only for ndarray."""
if _get_config()['assume_finite']:
return
X = np.asanyarray(X)
# First try an O(n) time, O(1) space solution for the common case that
# everything is finite; fall back to O(n) space np.isfinite to prevent
# false positives from overflow in sum method.
if (X.dtype.char in np.typecodes['AllFloat'] and not np.isfinite(X.sum())
and not np.isfinite(X).all()):
raise ValueError("Input contains NaN, infinity"
" or a value too large for %r." % X.dtype)
def assert_all_finite(X):
3
Source : compressor_magnitude.py
with MIT License
from AP-Atul
with MIT License
from AP-Atul
def compress(self, data):
"""
Apply thresholding techniques to remove the signal below the magnitude
Parameters
----------
data: array_like
input data signal, mostly coefficients output of the decompose
Returns
-------
array_like
thresholded data/ coefficients
"""
data = np.asanyarray(data)
self.__magnitude = np.sum(data.flatten(), axis=0)
return self.__compressor.compress(data, (self.__magnitude / len(data)))
def getCompressionRate(self, data):
3
Source : utility.py
with MIT License
from AP-Atul
with MIT License
from AP-Atul
def snr(data, axis=0, ddof=0):
"""
Signal to Noise ratio
simply given by mean / standard deviation
"""
a = np.asanyarray(data)
m = a.mean(axis)
sd = a.std(axis=axis, ddof=ddof)
return np.where(sd == 0 or m == 0, 0, m / sd)
def rmse(y):
3
Source : cbook.py
with GNU General Public License v3.0
from Artikash
with GNU General Public License v3.0
from Artikash
def safe_masked_invalid(x):
x = np.asanyarray(x)
try:
xm = np.ma.masked_invalid(x, copy=False)
xm.shrink_mask()
except TypeError:
return x
return xm
class MemoryMonitor:
3
Source : core.py
with GNU General Public License v3.0
from Artikash
with GNU General Public License v3.0
from Artikash
def compressed(x):
"""
Return all the non-masked data as a 1-D array.
This function is equivalent to calling the "compressed" method of a
`MaskedArray`, see `MaskedArray.compressed` for details.
See Also
--------
MaskedArray.compressed
Equivalent method.
"""
if getmask(x) is nomask:
return np.asanyarray(x)
else:
return x.compressed()
def concatenate(arrays, axis=0):
3
Source : create_video.py
with MIT License
from autonomousvision
with MIT License
from autonomousvision
def process_fn(episode):
writer = skvideo.io.FFmpegWriter(os.path.join(sys.argv[2], episode.split('/')[-1]+'_'+sys.argv[3].replace("/", "_")+'.mp4'), inputdict={'-r':sys.argv[4]},
outputdict={'-r':sys.argv[4], '-acodec':'aac', '-c:v': 'libx264', '-preset': 'slow', '-pix_fmt': 'yuv420p'})
print ('path: ', os.path.join(sys.argv[1], episode, sys.argv[3]))
for image_path in sorted(os.listdir(os.path.join(sys.argv[1], episode, sys.argv[3]))):
img = Image.open(os.path.join(sys.argv[1], episode, sys.argv[3], image_path))
d = ImageDraw.Draw(img)
writer.writeFrame(np.asanyarray(img).copy())
writer.close()
if __name__ == '__main__':
3
Source : cross_val.py
with MIT License
from birforce
with MIT License
from birforce
def split(train_indexes, test_indexes, *args):
"""
For each arg return a train and test subsets defined by indexes provided
in train_indexes and test_indexes
"""
ret = []
for arg in args:
arg = np.asanyarray(arg)
arg_train = arg[train_indexes]
arg_test = arg[test_indexes]
ret.append(arg_train)
ret.append(arg_test)
return ret
'''
3
Source : texture.py
with MIT License
from brain-slam
with MIT License
from brain-slam
def update_darray(self, darray):
"""
Update darray and dtype, shape accordingly.
:param darray:
:return: Current TextureND
"""
self.darray = np.asanyarray(darray)
self.dtype = self.darray.dtype
self.shape = self.darray.shape
if self.shape is not None:
self.is_empty = False
def copy(self):
3
Source : collections.py
with MIT License
from buds-lab
with MIT License
from buds-lab
def set_offsets(self, offsets):
"""
Set the offsets for the collection.
Parameters
----------
offsets : float or sequence of floats
"""
offsets = np.asanyarray(offsets, float)
if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else.
offsets = offsets[None, :]
# This decision is based on how they are initialized above in __init__.
if self._uniform_offsets is None:
self._offsets = offsets
else:
self._uniform_offsets = offsets
self.stale = True
def get_offsets(self):
3
Source : colors.py
with MIT License
from buds-lab
with MIT License
from buds-lab
def autoscale(self, A):
"""Set *vmin*, *vmax* to min, max of *A*."""
A = np.asanyarray(A)
self.vmin = A.min()
self.vmax = A.max()
def autoscale_None(self, A):
3
Source : colors.py
with MIT License
from buds-lab
with MIT License
from buds-lab
def autoscale_None(self, A):
"""Autoscale only None-valued vmin or vmax."""
A = np.asanyarray(A)
if self.vmin is None and A.size:
self.vmin = A.min()
if self.vmax is None and A.size:
self.vmax = A.max()
def scaled(self):
3
Source : art3d.py
with MIT License
from buds-lab
with MIT License
from buds-lab
def set_segments(self, segments):
"""
Set 3D segments.
"""
self._segments3d = np.asanyarray(segments)
LineCollection.set_segments(self, [])
def do_3d_projection(self, renderer):
3
Source : audio.py
with MIT License
from CPJKU
with MIT License
from CPJKU
def to_float(data, out=None):
"""
Converts integer samples to float samples, dividing by the datatype's
maximum on the way. If the data is in floating point already, just
converts to float32 if needed.
"""
data = np.asanyarray(data)
if np.issubdtype(data.dtype, np.floating):
if out is None:
return np.asarray(data, dtype=np.float32)
else:
out[:] = data
else:
return np.divide(data, np.iinfo(data.dtype).max, dtype=np.float32,
out=out)
def normalize(data, low=-1, high=1):
3
Source : __init__.py
with MIT License
from CPJKU
with MIT License
from CPJKU
def loop(array, length):
"""
Loops a given `array` along its first axis to reach a length of `length`.
"""
if len(array) < length:
array = np.asanyarray(array)
if len(array) == 0:
return np.zeros((length,) + array.shape[1:], dtype=array.dtype)
factor = length // len(array)
if factor > 1:
array = np.tile(array, (factor,) + (1,) * (array.ndim - 1))
missing = length - len(array)
if missing:
array = np.concatenate((array, array[:missing:]))
return array
def crop(array, length, deterministic=False):
3
Source : __init__.py
with MIT License
from CPJKU
with MIT License
from CPJKU
def __getitem__(self, idx):
item = dict(self.dataset[idx])
data = item[self.key]
if self.transpose:
data = np.asanyarray(data).T
item[self.key] = audio.to_float(data)
return item
class MixBackgroundNoise(Dataset):
3
Source : collections.py
with Apache License 2.0
from dashanji
with Apache License 2.0
from dashanji
def set_offsets(self, offsets):
"""
Set the offsets for the collection.
Parameters
----------
offsets : array-like (N, 2) or (2,)
"""
offsets = np.asanyarray(offsets, float)
if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else.
offsets = offsets[None, :]
# This decision is based on how they are initialized above in __init__.
if self._uniform_offsets is None:
self._offsets = offsets
else:
self._uniform_offsets = offsets
self.stale = True
def get_offsets(self):
3
Source : collections.py
with Apache License 2.0
from dashanji
with Apache License 2.0
from dashanji
def add_positions(self, position):
"""Add one or more events at the specified positions."""
if position is None or (hasattr(position, 'len') and
len(position) == 0):
return
positions = self.get_positions()
positions = np.hstack([positions, np.asanyarray(position)])
self.set_positions(positions)
extend_positions = append_positions = add_positions
3
Source : colors.py
with Apache License 2.0
from dashanji
with Apache License 2.0
from dashanji
def autoscale_None(self, A):
"""If vmin or vmax are not set, use the min/max of *A* to set them."""
A = np.asanyarray(A)
if self.vmin is None and A.size:
self.vmin = A.min()
if self.vmax is None and A.size:
self.vmax = A.max()
def scaled(self):
3
Source : test_decomp.py
with Apache License 2.0
from dashanji
with Apache License 2.0
from dashanji
def clear_fuss(ar, fuss_binary_bits=7):
"""Clears trailing `fuss_binary_bits` of mantissa of a floating number"""
x = np.asanyarray(ar)
if np.iscomplexobj(x):
return clear_fuss(x.real) + 1j * clear_fuss(x.imag)
significant_binary_bits = np.finfo(x.dtype).nmant
x_mant, x_exp = np.frexp(x)
f = 2.0**(significant_binary_bits - fuss_binary_bits)
x_mant *= f
np.rint(x_mant, out=x_mant)
x_mant /= f
return np.ldexp(x_mant, x_exp)
# XXX: This function should be available through numpy.testing
def assert_dtype_equal(act, des):
3
Source : _index.py
with Apache License 2.0
from dashanji
with Apache License 2.0
from dashanji
def _maybe_bool_ndarray(idx):
"""Returns a compatible array if elements are boolean.
"""
idx = np.asanyarray(idx)
if idx.dtype.kind == 'b':
return idx
return None
def _first_element_bool(idx, max_dim=2):
3
Source : colors.py
with MIT License
from davidglavas
with MIT License
from davidglavas
def autoscale_None(self, A):
"""autoscale only None-valued vmin or vmax."""
A = np.asanyarray(A)
if self.vmin is None and A.size:
self.vmin = A.min()
if self.vmax is None and A.size:
self.vmax = A.max()
class BoundaryNorm(Normalize):
3
Source : scf.py
with GNU Lesser General Public License v3.0
from deepmodeling
with GNU Lesser General Public License v3.0
from deepmodeling
def make_eig(self, dm=None):
"""return eigenvalues of projected density matrix"""
if dm is None:
dm = self.make_rdm1()
dm = np.asanyarray(dm)
if dm.ndim >= 3 and isinstance(self, scf.uhf.UHF):
dm = dm.sum(0)
t_dm = torch.from_numpy(dm).double()
t_eig = t_make_eig(t_dm, self._t_ovlp_shells)
return t_eig.detach().cpu().numpy()
def proj_intor(self, intor):
3
Source : collections.py
with GNU General Public License v3.0
from dnn-security
with GNU General Public License v3.0
from dnn-security
def set_offsets(self, offsets):
"""
Set the offsets for the collection.
Parameters
----------
offsets : (N, 2) or (2,) array-like
"""
offsets = np.asanyarray(offsets, float)
if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else.
offsets = offsets[None, :]
# This decision is based on how they are initialized above in __init__.
if self._uniform_offsets is None:
self._offsets = offsets
else:
self._uniform_offsets = offsets
self.stale = True
def get_offsets(self):
3
Source : colors.py
with GNU General Public License v3.0
from dnn-security
with GNU General Public License v3.0
from dnn-security
def autoscale(self, A):
"""
Set *halfrange* to ``max(abs(A-vcenter))``, then set *vmin* and *vmax*.
"""
A = np.asanyarray(A)
self._halfrange = max(self._vcenter-A.min(),
A.max()-self._vcenter)
self._set_vmin_vmax()
def autoscale_None(self, A):
3
Source : colors.py
with GNU General Public License v3.0
from dnn-security
with GNU General Public License v3.0
from dnn-security
def autoscale_None(self, A):
"""Set *vmin* and *vmax*."""
A = np.asanyarray(A)
if self._halfrange is None and A.size:
self.autoscale(A)
@property
3
Source : widgets.py
with GNU General Public License v3.0
from dnn-security
with GNU General Public License v3.0
from dnn-security
def _stepped_value(self, val):
"""Return *val* coerced to closest number in the ``valstep`` grid."""
if isinstance(self.valstep, Number):
val = (self.valmin
+ round((val - self.valmin) / self.valstep) * self.valstep)
elif self.valstep is not None:
valstep = np.asanyarray(self.valstep)
if valstep.ndim != 1:
raise ValueError(
f"valstep must have 1 dimension but has {valstep.ndim}"
)
val = valstep[np.argmin(np.abs(valstep - val))]
return val
def disconnect(self, cid):
3
Source : snippet.py
with Apache License 2.0
from dockerizeme
with Apache License 2.0
from dockerizeme
def _finv(y, N, a, b, c, u=0, v=0):
# a * x**3 + b*x**1.5 + c * log x + log y - log N
ya = np.asanyarray(y)
xa = np.ones_like(ya)
flag = (ya>0)
logyn = np.log(ya[flag]/N)
xa[~flag] = np.inf
for i in range(3):
ca = np.log(xa[flag])*c + logyn - np.log1p(u/xa[flag]**1.5 + v/xa[flag]**3)
xa[flag] = ((np.sqrt(b*b-4.*a*ca) -b)/(a*2.) if a else ca/(-b))**(2./3.)
return xa
class TracyWidom:
3
Source : snippet.py
with Apache License 2.0
from dockerizeme
with Apache License 2.0
from dockerizeme
def pdf(self, x):
"""
Return the probability distribution function at x.
pdf(x) = d P(TW < x) / dx.
Parameters
----------
x : float or array-like
Returns
-------
y : float or array-like
y = pdf(x)
"""
xa = np.asanyarray(x)
return derivative(self.cdf, xa, dx=0.08, order=5)
def cdfinv(self, x):
3
Source : 2D_backend_analysis.py
with MIT License
from enokjun
with MIT License
from enokjun
def area_np(x, y):
import numpy as np
x = np.asanyarray(x)
y = np.asanyarray(y)
n = len(x)
shift_up = np.arange(-n+1, 1)
shift_down = np.arange(-1, n-1)
return abs((x * (y.take(shift_up) - y.take(shift_down))).sum() / 2.0)
'''2D LEM Slope Analysis - compute R, f, x and e for moment arm for moment equilibrium '''
3
Source : sampler.py
with Apache License 2.0
from eugene-yang
with Apache License 2.0
from eugene-yang
def sampleDocs(self, nask: int, ledger: Ledger, scores, **kwargs):
scores = np.asanyarray(scores)
if len(scores.shape) == 1:
assert scores.min() >= 0 and scores.max() < = 1
scores = np.abs(scores - 0.5)
elif len(scores.shape) == 2:
scores = np.max(scores, axis=1)
else:
raise ValueError("Scores should be either probabilities of positive ",
"or probabilities of all classes. ")
return _removeKnownDocs(np.argsort(scores), ledger)[:nask]
def freeze(self):
3
Source : sampler.py
with Apache License 2.0
from eugene-yang
with Apache License 2.0
from eugene-yang
def sampleDocs(self, nask: int, ledger: Ledger, scores, **kwargs):
scores = getOneDimScores(np.asanyarray(scores))
return _removeKnownDocs(np.argsort(scores)[::-1], ledger)[:nask]
class RandomSampler(Sampler):
3
Source : mesh_colouring.py
with GNU General Public License v3.0
from expertanalytics
with GNU General Public License v3.0
from expertanalytics
def add_slope_colors(*,
normals: triangulate_dem.point3_vector,
colors: np.ndarray) -> np.ndarray:
slopes = np.asanyarray(triangulate_dem.compute_slopes(normals))
colors[slopes >= 55/180*np.pi] = [0.2, 0.2, 0.2]
return colors
def color_field_by_slope(*,
3
Source : mesh_colouring.py
with GNU General Public License v3.0
from expertanalytics
with GNU General Public License v3.0
from expertanalytics
def color_field_by_slope(*,
normals: triangulate_dem.point3_vector) -> np.ndarray:
slopes = np.asanyarray(triangulate_dem.compute_slopes(normals))
colors = np.empty((len(slopes), 3))
colors[slopes < 5.0e-2] = [0, 0, 1]
colors[slopes > 5.0e-2] = [1, 1, 1]
colors[slopes > 30/180*np.pi] = [1, 0, 0]
return colors
def color_field_by_avalanche_danger(*,
3
Source : mesh_colouring.py
with GNU General Public License v3.0
from expertanalytics
with GNU General Public License v3.0
from expertanalytics
def color_field_by_aspect(*, normals: triangulate_dem.point3_vector)->np.ndarray:
palette = sns.color_palette("pastel", n_colors=len(varsom_angles))
aspects = np.asanyarray(triangulate_dem.compute_aspects(normals))
colors = np.empty((len(aspects), 3))
for angle, col in zip(varsom_angles, palette):
range = np.logical_and(aspects >= angle[0]/180*np.pi, aspects < angle[1]/180*np.pi)
colors[range] = col
return colors
3
Source : export_getting_started_to_pkl.py
with MIT License
from gboehl
with MIT License
from gboehl
def basic_type_or_list(obj):
"""Check type of object."""
return not np.asanyarray(obj).dtype.hasobject
def flatten_to_dict(obj):
3
Source : export_getting_started_to_pkl.py
with MIT License
from gboehl
with MIT License
from gboehl
def to_ndarray(obj):
"""Convert to numpy array."""
if isinstance(obj, dict):
return {k: np.asanyarray(v) for k, v in obj.items()}
elif isinstance(obj, (list, tuple, set)) and not basic_type_or_list(obj):
return [np.asanyarray(v) for v in obj]
else:
return np.asanyarray(obj)
def is_path(path):
3
Source : special.py
with MIT License
from GeoStat-Framework
with MIT License
from GeoStat-Framework
def reshape(self, result):
"""Reshape a time-rad result according to the input shape."""
np.asanyarray(result)
if self.struc_grid:
result = result.reshape(self.time_shape + self.rad_shape)
elif self.rad_shape:
result = np.diag(result).reshape(self.rad_shape)
if self.time_scalar and self.rad_scalar:
result = result.item()
return result
def step_f(rad, r_part, f_part):
3
Source : varlib.py
with MIT License
from GeoStat-Framework
with MIT License
from GeoStat-Framework
def value(self, value):
if issubclass(np.asanyarray(value).dtype.type, numbers.Real):
if np.ndim(np.squeeze(value)) == 0:
self.__value = float(np.squeeze(value))
else:
self.__value = np.squeeze(np.array(value, dtype=float))
elif issubclass(np.asanyarray(value).dtype.type, numbers.Integral):
if np.ndim(np.squeeze(value)) == 0:
self.__value = int(np.squeeze(value))
else:
self.__value = np.squeeze(np.array(value, dtype=int))
else:
raise ValueError("Variable: 'value' is neither integer nor float")
def __repr__(self):
See More Examples