本文整理汇总了Python中numpy.broadcast函数的典型用法代码示例。如果您正苦于以下问题:Python broadcast函数的具体用法?Python broadcast怎么用?Python broadcast使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了broadcast函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: indices
def indices(self):
if self.ndim == 2:
return list(np.broadcast(*np.ogrid[
:self.shape[1], :self.shape[0]]))
else:
return list(np.broadcast(*np.ogrid[
:self.shape[2], :self.shape[1], :self.shape[0]]))
开发者ID:albeanth,项目名称:openmc,代码行数:7,代码来源:lattice.py
示例2: _validate_mask_and_error
def _validate_mask_and_error(self):
"""
Raises ValueError if they don't match (using ~numpy.broadcast)
"""
try:
if self.mask is not None:
np.broadcast(self.data, self.mask)
maskmatch = True
except ValueError:
maskmatch = False
try:
if self.error is not None:
np.broadcast(self.data, self.error)
errmatch = True
except ValueError:
errmatch = False
if not errmatch and not maskmatch:
raise ValueError('NDData error and mask do not match data')
elif not errmatch:
raise ValueError('NDData error does not match data')
elif not maskmatch:
raise ValueError('NDData mask does not match data')
开发者ID:lmoustakas,项目名称:astropy,代码行数:25,代码来源:nddata.py
示例3: classify
def classify(self, lattice):
"""Determine lattice element indices which might contain the TRISO particle.
Parameters
----------
lattice : openmc.RectLattice
Lattice to check
Returns
-------
list of tuple
(z,y,x) lattice element indices which might contain the TRISO
particle.
"""
ll, ur = self.region.bounding_box
if lattice.ndim == 2:
(i_min, j_min), p = lattice.find_element(ll)
(i_max, j_max), p = lattice.find_element(ur)
return list(np.broadcast(*np.ogrid[
j_min:j_max+1, i_min:i_max+1]))
else:
(i_min, j_min, k_min), p = lattice.find_element(ll)
(i_max, j_max, k_max), p = lattice.find_element(ur)
return list(np.broadcast(*np.ogrid[
k_min:k_max+1, j_min:j_max+1, i_min:i_max+1]))
开发者ID:mit-crpg,项目名称:openmc,代码行数:27,代码来源:triso.py
示例4: check_mean_sigma_keepdims
def check_mean_sigma_keepdims(a, axis):
mu1, sigma1 = mean_sigma(a, axis, keepdims=False)
mu2, sigma2 = mean_sigma(a, axis, keepdims=True)
assert_array_equal(mu1.ravel(), mu2.ravel())
assert_array_equal(sigma1.ravel(), sigma2.ravel())
assert_array_equal(np.broadcast(a, mu2).shape, a.shape)
assert_array_equal(np.broadcast(a, sigma2).shape, a.shape)
开发者ID:BTY2684,项目名称:astroML,代码行数:9,代码来源:test_stats.py
示例5: _set_error
def _set_error(self, value):
if value is not None:
try:
np.broadcast(self.data, value)
except ValueError:
raise ValueError("dimensions of `error` do not match data")
else:
self._error = value
else:
self._error = value
开发者ID:fgrollier,项目名称:astropy,代码行数:10,代码来源:nddata.py
示例6: logsubtrexp
def logsubtrexp(minuend, subtrahend, sign_minuend = None, sign_subtrahend = None):
if sign_minuend is None:
sign_minuend = np.ones(minuend.shape)
if sign_subtrahend is None:
sign_subtrahend = np.ones(subtrahend.shape)
if not (minuend.shape == sign_minuend.shape and subtrahend.shape == sign_subtrahend.shape):
raise ValueError("sign arguments expected be of same shape as corresponding log-matrices")
if not (np.abs(sign_minuend).all() and np.abs(sign_subtrahend).all()):
raise ValueError("sign arguments expected to contain only +1 or -1 elements")
b = np.broadcast(minuend, subtrahend)
s_b = np.broadcast(sign_minuend, sign_subtrahend)
abs_res = np.empty(b.shape)
sign_res = np.empty(b.shape)
for i in range(b.size):
(m, s) = b.next()
(sign_m, sign_s) = s_b.next()
if sign_m > sign_s: # sign_m == 1 and sign_s == -1
# this is equivalent to logsumexp(m, s)
#print("sign_m > sign_s")
sign_res.flat[i] = 1
abs_res.flat[i] = logsumexp((m,s))
elif sign_m < sign_s: # sign_m == -1 and sign_s == 1
#print("sign_m < sign_s")
sign_res.flat[i] = -1
abs_res.flat[i] = logsumexp((m,s))
else:
#signs are eqal
if m == s:
sign_res.flat[i] = 1
abs_res.flat[i] = log(0)
else:
if sign_m == -1:
if m > s:
#print("m >= s")
sign_res.flat[i] = -1
abs_res.flat[i] = log(1 - exp(s - m)) + m
elif m < s:
#print("m < s")
sign_res.flat[i] = 1
abs_res.flat[i] = log(1 - exp(m - s)) + s
else:# sign_m == 1
if m > s:
#print("m >= s")
sign_res.flat[i] = 1
abs_res.flat[i] = log(1 - exp(s - m)) + m
elif m < s:
#print("m < s")
sign_res.flat[i] = -1
abs_res.flat[i] = log(1 - exp(m - s)) + s
#print(sign_m*exp(m), sign_s*exp(s), sign_m*exp(m) - sign_s*exp(s), sign_res.flat[i] * exp(abs_res.flat[i]))
return (abs_res, sign_res)
开发者ID:ingmarschuster,项目名称:ModelSelection,代码行数:55,代码来源:estimator_statistics.py
示例7: getPsfAtPoints
def getPsfAtPoints(self, bandnum, x, y):
'''
Reconstruct the SDSS model PSF from KL basis functions.
x,y can be scalars or 1-d numpy arrays.
Return value:
if x,y are scalars: a PSF image
if x,y are arrays: a list of PSF images
'''
rtnscalar = np.isscalar(x) and np.isscalar(y)
x = np.atleast_1d(x)
y = np.atleast_1d(y)
psf = fits_table(self.hdus[bandnum+1].data)
psfimgs = None
(outh, outw) = (None,None)
# From the IDL docs:
# http://photo.astro.princeton.edu/photoop_doc.html#SDSS_PSF_RECON
# acoeff_k = SUM_i{ SUM_j{ (0.001*ROWC)^i * (0.001*COLC)^j * C_k_ij } }
# psfimage = SUM_k{ acoeff_k * RROWS_k }
for k in range(len(psf)):
nrb = psf.nrow_b[k]
ncb = psf.ncol_b[k]
c = psf.c[k].reshape(5, 5)
c = c[:nrb,:ncb]
(gridi,gridj) = np.meshgrid(range(nrb), range(ncb))
if psfimgs is None:
psfimgs = [np.zeros_like(psf.rrows[k]) for xy
in np.broadcast(x,y)]
(outh,outw) = (psf.rnrow[k], psf.rncol[k])
else:
assert(psf.rnrow[k] == outh)
assert(psf.rncol[k] == outw)
for i,(xi,yi) in enumerate(np.broadcast(x,y)):
#print 'xi,yi', xi,yi
acoeff_k = np.sum(((0.001 * xi)**gridi * (0.001 * yi)**gridj * c))
if False: # DEBUG
print 'coeffs:', (0.001 * xi)**gridi * (0.001 * yi)**gridj
print 'c:', c
for (coi,ci) in zip(((0.001 * xi)**gridi * (0.001 * yi)**gridj).ravel(), c.ravel()):
print 'co %g, c %g' % (coi,ci)
print 'acoeff_k', acoeff_k
#print 'acoeff_k', acoeff_k.shape, acoeff_k
#print 'rrows[k]', psf.rrows[k].shape, psf.rrows[k]
psfimgs[i] += acoeff_k * psf.rrows[k]
psfimgs = [img.reshape((outh,outw)) for img in psfimgs]
if rtnscalar:
return psfimgs[0]
return psfimgs
开发者ID:astrometry,项目名称:pysdss,代码行数:54,代码来源:common.py
示例8: test_mean_sigma_keepdims
def test_mean_sigma_keepdims(axis):
np.random.seed(0)
a = np.random.random((4, 5, 6))
mu1, sigma1 = mean_sigma(a, axis, keepdims=False)
mu2, sigma2 = mean_sigma(a, axis, keepdims=True)
assert_array_equal(mu1.ravel(), mu2.ravel())
assert_array_equal(sigma1.ravel(), sigma2.ravel())
assert_array_equal(np.broadcast(a, mu2).shape, a.shape)
assert_array_equal(np.broadcast(a, sigma2).shape, a.shape)
开发者ID:astroML,项目名称:astroML,代码行数:11,代码来源:test_stats.py
示例9: _assert_incompatible_broadcast
def _assert_incompatible_broadcast(self, shape1, shape2):
if shape1.dims is not None and shape2.dims is not None:
zeros1 = np.zeros(shape1.as_list())
zeros2 = np.zeros(shape2.as_list())
with self.assertRaises(ValueError):
np.broadcast(zeros1, zeros2)
with self.assertRaises(ValueError):
np.broadcast(zeros2, zeros1)
with self.assertRaises(ValueError):
common_shapes.broadcast_shape(shape1, shape2)
with self.assertRaises(ValueError):
common_shapes.broadcast_shape(shape2, shape1)
开发者ID:AlbertXiebnu,项目名称:tensorflow,代码行数:12,代码来源:common_shapes_test.py
示例10: test_broadcastable
def test_broadcastable():
for ndim1 in range(1, 4):
for ndim2 in range(1, 4):
for shape1 in itertools.permutations(range(1, 4), ndim1):
for shape2 in itertools.permutations(range(1, 4), ndim2):
try:
np.broadcast(np.zeros(shape1),
np.zeros(shape2))
result = True
except ValueError:
result = False
assert result == broadcastable(shape1, shape2)
开发者ID:jmcq,项目名称:SciDB-Py,代码行数:12,代码来源:test_utils.py
示例11: _set_flags
def _set_flags(self, value):
if value is not None:
if isinstance(value, np.ndarray):
try:
np.broadcast(self.data, value)
except ValueError:
raise ValueError("dimensions of `flags` do not match data")
else:
self._flags = value
else:
raise TypeError("`flags` should be a Numpy array")
else:
self._flags = value
开发者ID:fgrollier,项目名称:astropy,代码行数:13,代码来源:nddata.py
示例12: __init__
def __init__(self, w, mu, *args, **kwargs):
_, sd = get_tau_sd(tau=kwargs.pop('tau', None),
sd=kwargs.pop('sd', None))
distshape = np.broadcast(mu, sd).shape
self.mu = mu = tt.as_tensor_variable(mu)
self.sd = sd = tt.as_tensor_variable(sd)
if not distshape:
distshape = np.broadcast(mu.tag.test_value, sd.tag.test_value).shape
super(NormalMixture, self).__init__(w, Normal.dist(mu, sd=sd, shape=distshape),
*args, **kwargs)
开发者ID:mwibrow,项目名称:pymc3,代码行数:13,代码来源:mixture.py
示例13: near
def near(x, l, h):
#RESULT: array(3) & array([3, 4])
a = broadcast(x,l,h)
has_iterable = a.shape
x,l,h = tuple(atleast_1d(i) for i in (x,l,h))
b = broadcast(x,l,h)
_x,_l,_h = (empty(b.shape), empty(b.shape), empty(b.shape))
_x.flat = [i for i in x]
_l.flat = [i for i in l]
_h.flat = [i for i in h]
result = asarray(map(_near, x, l, h))
if not has_iterable:
result = asarray(result[0])
return result
开发者ID:agamdua,项目名称:mystic,代码行数:14,代码来源:constraints.py
示例14: _natural_indices
def _natural_indices(self):
"""Iterate over all possible (x,y) or (x,y,z) lattice element indices.
This property is used when constructing distributed cell and material
paths. Most importantly, the iteration order matches that used on the
Fortran side.
"""
if self.ndim == 2:
nx, ny = self.shape
return np.broadcast(*np.ogrid[:nx, :ny])
else:
nx, ny, nz = self.shape
return np.broadcast(*np.ogrid[:nx, :ny, :nz])
开发者ID:mit-crpg,项目名称:openmc,代码行数:14,代码来源:lattice.py
示例15: _assert_broadcast
def _assert_broadcast(self, expected, shape1, shape2):
if shape1.dims is not None and shape2.dims is not None:
expected_np = expected.as_list()
zeros1 = np.zeros(shape1.as_list())
zeros2 = np.zeros(shape2.as_list())
self.assertAllEqual(expected_np, np.broadcast(zeros1, zeros2).shape)
self.assertAllEqual(expected_np, np.broadcast(zeros2, zeros1).shape)
self.assertEqual(
expected, common_shapes.broadcast_shape(shape1, shape2))
self.assertEqual(
expected, common_shapes.broadcast_shape(shape2, shape1))
else:
self.assertEqual(expected, common_shapes.broadcast_shape(shape1, shape2))
self.assertEqual(expected, common_shapes.broadcast_shape(shape2, shape1))
开发者ID:AlbertXiebnu,项目名称:tensorflow,代码行数:14,代码来源:common_shapes_test.py
示例16: __call__
def __call__(self, p, cols='all'):
if cols is 'all':
icols = np.arange(self.n_columns)
else:
icols = np.array([self.column_index[col] for col in cols])
args = (p, self.grid, icols, self.index_columns)
if self.ndim == 2:
args = (p[0], p[1], self.grid, icols,
self.index_columns[0], self.index_columns[1])
if ((isinstance(p[0], float) or isinstance(p[0], int)) and
(isinstance(p[1], float) or isinstance(p[1], int))):
values = interp_value_2d(*args)
else:
b = np.broadcast(*p)
pp = [np.atleast_1d(np.resize(x, b.shape)).astype(float) for x in p]
args = (*pp, self.grid, icols, *self.index_columns)
# print([(a, type(a)) for a in args])
values = interp_values_2d(*args)
if self.ndim == 3:
args = (p[0], p[1], p[2], self.grid, icols,
self.index_columns[0], self.index_columns[1],
self.index_columns[2])
if ((isinstance(p[0], float) or isinstance(p[0], int)) and
(isinstance(p[1], float) or isinstance(p[1], int)) and
(isinstance(p[2], float) or isinstance(p[2], int))):
values = interp_value_3d(*args)
else:
b = np.broadcast(*p)
pp = [np.atleast_1d(np.resize(x, b.shape)).astype(float) for x in p]
args = (*pp, self.grid, icols, *self.index_columns)
# print([(a, type(a)) for a in args])
values = interp_values_3d(*args)
elif self.ndim == 4:
args = (p[0], p[1], p[2], p[3], self.grid, icols,
self.index_columns[0], self.index_columns[1],
self.index_columns[2], self.index_columns[3])
if ((isinstance(p[0], float) or isinstance(p[0], int)) and
(isinstance(p[1], float) or isinstance(p[1], int)) and
(isinstance(p[2], float) or isinstance(p[2], int)) and
(isinstance(p[3], float) or isinstance(p[3], int))):
values = interp_value_4d(*args)
else:
b = np.broadcast(*p)
pp = [np.atleast_1d(np.resize(x, b.shape)).astype(float) for x in p]
values = interp_values_4d(*pp, self.grid, icols, *self.index_columns)
return values
开发者ID:timothydmorton,项目名称:isochrones,代码行数:48,代码来源:interp.py
示例17: kernel_reconstruct
def kernel_reconstruct(kernels_theta, kernels_phi, weights,
grid_theta, grid_phi, kernel, N=8):
"""Kernel reconstruction of the PDF, on a grid on the sphere.
Parameters
----------
kernels_theta, kernels_phi : (N,) ndarray
Positions of the kernels.
weights : (N,) ndarray
Weights of the kernels.
grid_theta : (M,) ndarray
Inclination angles of grid.
grid_phi : (N,) ndarray
Azimuth angles of grid.
kernel : callable
Kernel function used in the reconstruction.
N : int
Maximum order of kernel polynomials.
Returns
-------
pdf : (M, N) ndarray
Reconstruction of the PDF on the specified grid.
"""
PDF_recon = np.zeros(np.broadcast(grid_theta, grid_phi).shape)
for (k_theta, k_phi, w) in zip(kernels_theta, kernels_phi, weights):
cos_theta = cos_inc_angle(grid_theta, grid_phi,
k_theta, k_phi)
PDF_recon += w * kernel(cos_theta, N)
return PDF_recon
开发者ID:coryahrens,项目名称:spheredwi,代码行数:34,代码来源:kernel_model.py
示例18: testHarmonicOscillator
def testHarmonicOscillator(self):
"""
Check the semiclassical trajectory for a harmonic oscillator.
"""
ps = np.linspace(-hp['init_p_max'], hp['init_p_max'], 7) # g nm/ps mol
qs = np.linspace(-hp['init_q_max'], hp['init_q_max'], 11) # nm
init_ps, init_qs = meshgrid(ps, qs)
shape = np.broadcast(init_ps, init_qs).shape
ho_fs = harmonic(m=hp['mass'], omega=hp['omega'])
ts = np.linspace(0., 4. * np.pi / hp['omega'], 6000) # ps
dt = ts[1] - ts[0] # ps
omts = hp['omega'] * ts # 1
traj = SemiclassicalTrajectory(hp['gamma'], hp['mass'], dt, ho_fs, init_ps, init_qs, max_steps=len(ts))
calculated_p = np.empty((len(ts), len(ps), len(qs))) # g nm/ps mol
calculated_q = np.empty_like(calculated_p) # nm
calculated_R = np.empty_like(calculated_p, dtype=complex) # 1
calculated_S = np.empty_like(calculated_p) # kJ ps/mol
for i, step in enumerate(traj):
_, calculated_p[i], calculated_q[i], calculated_R[i], calculated_S[i] = step
exact_ps, exact_qs, exact_Rs, exact_Ss = harmonic_trajectory(hp['mass'], hp['omega'], hp['gamma'], ts, init_ps, init_qs)
assert_array_almost_equal(calculated_p, exact_ps)
assert_array_almost_equal(calculated_q, exact_qs)
assert_array_almost_equal(calculated_R, exact_Rs)
assert_array_almost_equal(calculated_S, exact_Ss)
开发者ID:0,项目名称:realtimepork,代码行数:32,代码来源:test_semiclassical.py
示例19: busday_count_mask_NaT
def busday_count_mask_NaT(begindates, enddates, out=None):
"""
Simple of numpy.busday_count that returns `float` arrays rather than int
arrays, and handles `NaT`s by returning `NaN`s where the inputs were `NaT`.
Doesn't support custom weekdays or calendars, but probably should in the
future.
See Also
--------
np.busday_count
"""
if out is None:
out = empty(broadcast(begindates, enddates).shape, dtype=float)
beginmask = begindates == NaTD
endmask = enddates == NaTD
out = busday_count(
# Temporarily fill in non-NaT values.
where(beginmask, _notNaT, begindates),
where(endmask, _notNaT, enddates),
out=out,
)
# Fill in entries where either comparison was NaT with nan in the output.
out[beginmask | endmask] = nan
return out
开发者ID:rsr2425,项目名称:zipline,代码行数:28,代码来源:numpy_utils.py
示例20: movetext
def movetext(textid, x=None, y=None, dx=None, dy=None):
'''Convert textid to a list of matplotlib Text instances.
textid -- integer zero based index or a matplotlib Text instance.
Can be also a list of indices or Text objects.
When 'all', use all text objects in the current axis.
x, y -- new x, y positions of the specified text objects,
floating point numbers or arrays.
Positions are not changed when None.
dx, dy -- offsets in the x or y directions, numbers or arrays.
These are applied after setting the x, y coordinates.
Return a list of Text instances.
'''
import numpy
texthandles = findtexts(textid)
for hti, xi, yi, dxi, dyi in numpy.broadcast(texthandles, x, y, dx, dy):
xt, yt = hti.get_position()
if xi is not None:
xt = xi
if dxi is not None:
xt += dxi
if yi is not None:
yt = yi
if dyi is not None:
yt += dyi
hti.set_position((xt, yt))
if texthandles:
_redraw()
return
开发者ID:CJ-Wright,项目名称:ipython_ophyd,代码行数:30,代码来源:pylab_utilities.py
注:本文中的numpy.broadcast函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论