本文整理匯總了Python中numpy.atleast_1d方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.atleast_1d方法的具體用法?Python numpy.atleast_1d怎麽用?Python numpy.atleast_1d使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.atleast_1d方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: byte_array
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import atleast_1d [as 別名]
def byte_array(pattern):
"""Convert the pattern to a byte array.
Parameters
----------
pattern : ~numpy.ndarray, bytes, int, or iterable of int
Pattern to convert. If a `~numpy.ndarray` or `bytes` instance,
a byte array view is taken. If an (iterable of) int, the integers
need to be unsigned 32 bit and will be interpreted as little-endian.
Returns
-------
byte_array : `~numpy.ndarray` of byte
With any elements of pattern stored in little-endian order.
"""
if isinstance(pattern, (np.ndarray, bytes)):
# Quick turn-around for input that is OK already:
return np.atleast_1d(pattern).view('u1')
pattern = np.array(pattern, ndmin=1)
if (pattern.dtype.kind not in 'uif'
or pattern.min() < 0
or pattern.max() >= 1 << 32):
raise ValueError('values have to fit in 32 bit unsigned int.')
return pattern.astype('<u4').view('u1')
示例2: do
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import atleast_1d [as 別名]
def do(self, a, b, tags):
d = linalg.det(a)
(s, ld) = linalg.slogdet(a)
if asarray(a).dtype.type in (single, double):
ad = asarray(a).astype(double)
else:
ad = asarray(a).astype(cdouble)
ev = linalg.eigvals(ad)
assert_almost_equal(d, multiply.reduce(ev, axis=-1))
assert_almost_equal(s * np.exp(ld), multiply.reduce(ev, axis=-1))
s = np.atleast_1d(s)
ld = np.atleast_1d(ld)
m = (s != 0)
assert_almost_equal(np.abs(s[m]), 1)
assert_equal(ld[~m], -inf)
示例3: blackbody_radiance
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import atleast_1d [as 別名]
def blackbody_radiance(self, T, spectral=True):
"""Calculate integrated radiance for blackbody at temperature T
:param T: Temperature [K]. This can be either a python number, or
a numpy ndarray, on a ureg quantity encompassing either.
:param spectral: Parameter to control whether to return spectral
radiance or radiance. See self.integrate_radiances for
details.
Returns quantity ndarray with blackbody radiance in desired unit.
Note that this is an ndarray with dimension (1,) even if you
passin a scalar.
"""
try:
T = T.to("K")
except AttributeError:
T = ureg.Quantity(T, "K")
T = ureg.Quantity(numpy.atleast_1d(T), T.u)
# fails if T is multidimensional
shp = T.shape
return self.integrate_radiances(
self.frequency, planck_f(
self.frequency[numpy.newaxis, :],
T.reshape((-1,))[:, numpy.newaxis]),
spectral=spectral).reshape(shp)
示例4: normalize_channels_parameter
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import atleast_1d [as 別名]
def normalize_channels_parameter(channels, channel_count):
if channels is None:
if channel_count == 1:
return [0], True
else:
return list(range(channel_count)), False
indices = np.arange(channel_count)
indices = indices[channels]
indices = np.atleast_1d(indices)
if isinstance(channels, slice):
return indices.tolist(), False
channels = np.asarray(channels)
if not np.issubdtype(channels.dtype, np.number):
raise TypeError('`channels` should be None or int or slice or list of int')
if channels.ndim == 0:
assert len(indices) == 1
return indices.tolist(), True
return indices.tolist(), False
示例5: _validate_partition_arguments
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import atleast_1d [as 別名]
def _validate_partition_arguments(a, kth, axis, kind, order, kw):
a = astensor(a)
if axis is None:
a = a.flatten()
axis = 0
else:
axis = validate_axis(a.ndim, axis)
if isinstance(kth, (Base, Entity)):
kth = astensor(kth)
_check_kth_dtype(kth.dtype)
else:
kth = np.atleast_1d(kth)
kth = _validate_kth_value(kth, a.shape[axis])
if kth.ndim > 1:
raise ValueError('object too deep for desired array')
if kind != 'introselect':
raise ValueError('{} is an unrecognized kind of select'.format(kind))
# if a is structure type and order is not None
order = validate_order(a.dtype, order)
need_align = kw.pop('need_align', None)
if len(kw) > 0:
raise TypeError('partition() got an unexpected keyword '
'argument \'{}\''.format(next(iter(kw))))
return a, kth, axis, kind, order, need_align
示例6: lp2lp
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import atleast_1d [as 別名]
def lp2lp(b, a, wo=1.0):
"""
Transform a lowpass filter prototype to a different frequency.
Return an analog low-pass filter with cutoff frequency `wo`
from an analog low-pass filter prototype with unity cutoff frequency, in
transfer function ('ba') representation.
"""
a, b = map(atleast_1d, (a, b))
try:
wo = float(wo)
except TypeError:
wo = float(wo[0])
d = len(a)
n = len(b)
M = max((d, n))
pwo = pow(wo, numpy.arange(M - 1, -1, -1))
start1 = max((n - d, 0))
start2 = max((d - n, 0))
b = b * pwo[start1] / pwo[start2:]
a = a * pwo[start1] / pwo[start1:]
return normalize(b, a)
示例7: _check_func
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import atleast_1d [as 別名]
def _check_func(checker, argname, thefunc, x0, args, numinputs,
output_shape=None):
res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
if (output_shape is not None) and (shape(res) != output_shape):
if (output_shape[0] != 1):
if len(output_shape) > 1:
if output_shape[1] == 1:
return shape(res)
msg = "%s: there is a mismatch between the input and output " \
"shape of the '%s' argument" % (checker, argname)
func_name = getattr(thefunc, '__name__', None)
if func_name:
msg += " '%s'." % func_name
else:
msg += "."
msg += 'Shape should be %s but it is %s.' % (output_shape, shape(res))
raise TypeError(msg)
if issubdtype(res.dtype, inexact):
dt = res.dtype
else:
dt = dtype(float)
return shape(res), dt
示例8: _chk2_asarray
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import atleast_1d [as 別名]
def _chk2_asarray(a, b, axis):
if axis is None:
a = np.ravel(a)
b = np.ravel(b)
outaxis = 0
else:
a = np.asarray(a)
b = np.asarray(b)
outaxis = axis
if a.ndim == 0:
a = np.atleast_1d(a)
if b.ndim == 0:
b = np.atleast_1d(b)
return a, b, outaxis
示例9: _munp
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import atleast_1d [as 別名]
def _munp(self, n, beta, m):
"""
Returns the n-th non-central moment of the crystalball function.
"""
N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) + _norm_pdf_C * _norm_cdf(beta))
def n_th_moment(n, beta, m):
"""
Returns n-th moment. Defined only if n+1 < m
Function cannot broadcast due to the loop over n
"""
A = (m/beta)**m * np.exp(-beta**2 / 2.0)
B = m/beta - beta
rhs = 2**((n-1)/2.0) * sc.gamma((n+1)/2) * (1.0 + (-1)**n * sc.gammainc((n+1)/2, beta**2 / 2))
lhs = np.zeros(rhs.shape)
for k in range(n + 1):
lhs += sc.binom(n, k) * B**(n-k) * (-1)**k / (m - k - 1) * (m/beta)**(-m + k + 1)
return A * lhs + rhs
return N * _lazywhere(np.atleast_1d(n + 1 < m),
(n, beta, m),
np.vectorize(n_th_moment, otypes=[np.float]),
np.inf)
示例10: _parse
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import atleast_1d [as 別名]
def _parse(self):
element = np.atleast_1d(_read_dump('dump.element', 'unicode'))
b = np.atleast_2d(_read_dump('dump.sna'))
db = np.atleast_2d(_read_dump('dump.snad'))
vb = np.atleast_2d(_read_dump('dump.snav'))
return b, db, vb, element
示例11: test_working_type
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import atleast_1d [as 別名]
def test_working_type():
# Which type do input types with slope and inter cast to in numpy?
# Wrapper function because we need to use the dtype str for comparison. We
# need this because of the very confusing np.int32 != np.intp (on 32 bit).
def wt(*args, **kwargs):
return np.dtype(working_type(*args, **kwargs)).str
d1 = np.atleast_1d
for in_type in NUMERIC_TYPES:
in_ts = np.dtype(in_type).str
assert_equal(wt(in_type), in_ts)
assert_equal(wt(in_type, 1, 0), in_ts)
assert_equal(wt(in_type, 1.0, 0.0), in_ts)
in_val = d1(in_type(0))
for slope_type in NUMERIC_TYPES:
sl_val = slope_type(1) # no scaling, regardless of type
assert_equal(wt(in_type, sl_val, 0.0), in_ts)
sl_val = slope_type(2) # actual scaling
out_val = in_val / d1(sl_val)
assert_equal(wt(in_type, sl_val), out_val.dtype.str)
for inter_type in NUMERIC_TYPES:
i_val = inter_type(0) # no scaling, regardless of type
assert_equal(wt(in_type, 1, i_val), in_ts)
i_val = inter_type(1) # actual scaling
out_val = in_val - d1(i_val)
assert_equal(wt(in_type, 1, i_val), out_val.dtype.str)
# Combine scaling and intercept
out_val = (in_val - d1(i_val)) / d1(sl_val)
assert_equal(wt(in_type, sl_val, i_val), out_val.dtype.str)
# Confirm that type codes and dtypes work as well
f32s = np.dtype(np.float32).str
assert_equal(wt('f4', 1, 0), f32s)
assert_equal(wt(np.dtype('f4'), 1, 0), f32s)
示例12: _ftype4scaled_finite
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import atleast_1d [as 別名]
def _ftype4scaled_finite(tst_arr, slope, inter, direction='read',
default=np.float32):
""" Smallest float type for scaling of `tst_arr` that does not overflow
"""
assert direction in ('read', 'write')
if not default in OK_FLOATS and default is np.longdouble:
# Omitted longdouble
return default
def_ind = OK_FLOATS.index(default)
# promote to arrays to avoid numpy scalar casting rules
tst_arr = np.atleast_1d(tst_arr)
slope = np.atleast_1d(slope)
inter = np.atleast_1d(inter)
warnings.filterwarnings('ignore', '.*overflow.*', RuntimeWarning)
try:
for ftype in OK_FLOATS[def_ind:]:
tst_trans = tst_arr.copy()
slope = slope.astype(ftype)
inter = inter.astype(ftype)
if direction == 'read': # as in reading of image from disk
if slope != 1.0:
tst_trans = tst_trans * slope
if inter != 0.0:
tst_trans = tst_trans + inter
elif direction == 'write':
if inter != 0.0:
tst_trans = tst_trans - inter
if slope != 1.0:
tst_trans = tst_trans / slope
if np.all(np.isfinite(tst_trans)):
return ftype
finally:
warnings.filters.pop(0)
raise ValueError('Overflow using highest floating point type')
示例13: create_hdf5
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import atleast_1d [as 別名]
def create_hdf5(self):
'''Creates an HDF5 file to store the data '''
# if the hdf5 file does not exist, create it
file_exists = os.path.exists(self.fn_hdf5)
if file_exists:
raise IOError('Cannot create hdf5 file: {0} '
'it already exists!'.format(self.fn_hdf5))
self.mesh.write_hdf5(self.fn_hdf5, 'mesh/')
self.mesh_roi.write_hdf5(self.fn_hdf5, 'mesh_roi/')
self.poslist._write_conductivity_to_hdf5(self.fn_hdf5)
with h5py.File(self.fn_hdf5, 'a') as f:
f.create_dataset('roi', data=np.atleast_1d(np.array(self.roi, dtype=int)))
示例14: record_data_matrix
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import atleast_1d [as 別名]
def record_data_matrix(self, data, name, group):
''' Appends or create data to the HDF5 file
Parameters:
-------------
data: np.ndarray
Data to be appended. Will be appended along the first dimension
name: str
Name of data seet
group: str
Group where to place data set
'''
data = np.array(data).squeeze()
data = np.atleast_1d(data)
with h5py.File(self.fn_hdf5, 'a') as f:
try:
g = f.create_group(group)
except:
g = f[group]
if name not in g.keys():
g.create_dataset(name,
shape=(0, ) + data.shape,
maxshape=(None, ) + data.shape,
dtype=data.dtype,
chunks=(1, ) + data.shape)
dset = g[name]
dset.resize((dset.shape[0] + 1, ) + data.shape)
dset[-1, ...] = data
示例15: run_simulation
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import atleast_1d [as 別名]
def run_simulation(self, random_vars):
poslist = self._update_poslist(random_vars)
cond = poslist.cond2elmdata(self.mesh)
v = fem.tdcs(
self.mesh, cond, self.el_currents,
self.el_tags, units='mm')
self.mesh.nodedata = [v]
cropped = self.mesh.crop_mesh(self.roi)
v_c = cropped.nodedata[0]
self.mesh.nodedata = []
qois = []
for qoi_name, qoi_f in self.qoi_function.items():
qois.append(qoi_f(v_c, random_vars))
self.record_data_matrix(random_vars, 'random_var_samples', '/')
self.record_data_matrix(v.value, 'v_samples', 'mesh/data_matrices')
self.record_data_matrix(v_c.value, 'v_samples', 'mesh_roi/data_matrices')
for qoi_name, qoi_v in zip(self.qoi_function.keys(), qois):
self.record_data_matrix(
qoi_v, qoi_name + '_samples', 'mesh_roi/data_matrices')
del cropped
del cond
del v
del v_c
return np.atleast_1d(qois[0]).reshape(-1)