本文整理汇总了Python中numpy.all函数的典型用法代码示例。如果您正苦于以下问题:Python all函数的具体用法?Python all怎么用?Python all使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了all函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_03_03_color_mask
def test_03_03_color_mask(self):
image_set_list = cpi.ImageSetList()
image_set=image_set_list.get_image_set(0)
np.random.seed(0)
pixel_data = np.random.uniform(size=(10,15,3)).astype(np.float32)
image_set.add(IMAGE_NAME, cpi.Image(pixel_data))
masking_image = np.random.uniform(size=(10,15))
image_set.add(MASKING_IMAGE_NAME, cpi.Image(masking_image))
expected_mask = masking_image > .5
pipeline = cpp.Pipeline()
module = M.MaskImage()
module.source_choice.value = M.IO_IMAGE
module.object_name.value = OBJECTS_NAME
module.image_name.value = IMAGE_NAME
module.masking_image_name.value = MASKING_IMAGE_NAME
module.masked_image_name.value = MASKED_IMAGE_NAME
module.invert_mask.value = False
module.module_num = 1
workspace = cpw.Workspace(pipeline, module, image_set, cpo.ObjectSet(),
cpmeas.Measurements(), image_set_list)
module.run(workspace)
masked_image = workspace.image_set.get_image(MASKED_IMAGE_NAME)
self.assertTrue(isinstance(masked_image, cpi.Image))
self.assertTrue(np.all(masked_image.pixel_data[expected_mask,:] ==
pixel_data[expected_mask,:]))
self.assertTrue(np.all(masked_image.pixel_data[~expected_mask,:] == 0))
self.assertTrue(np.all(masked_image.mask == expected_mask))
self.assertFalse(masked_image.has_masking_objects)
开发者ID:JDWarner,项目名称:CellProfiler,代码行数:32,代码来源:test_maskimage.py
示例2: testLoadSave
def testLoadSave(self):
"""Plot with an image: test MaskToolsWidget operations"""
self.plot.addImage(numpy.arange(1024**2).reshape(1024, 1024),
legend='test')
self.qapp.processEvents()
# Draw a polygon mask
toolButton = getQToolButtonFromAction(self.maskWidget.polygonAction)
self.assertIsNot(toolButton, None)
self.mouseClick(toolButton, qt.Qt.LeftButton)
self._drawPolygon()
ref_mask = self.maskWidget.getSelectionMask()
self.assertFalse(numpy.all(numpy.equal(ref_mask, 0)))
with temp_dir() as tmp:
success = self.maskWidget.save(
os.path.join(tmp, 'mask.npy'), 'npy')
self.assertTrue(success)
self.maskWidget.resetSelectionMask()
self.assertTrue(
numpy.all(numpy.equal(self.maskWidget.getSelectionMask(), 0)))
result = self.maskWidget.load(os.path.join(tmp, 'mask.npy'))
self.assertTrue(result)
self.assertTrue(numpy.all(numpy.equal(
self.maskWidget.getSelectionMask(), ref_mask)))
开发者ID:PiRK,项目名称:silx,代码行数:28,代码来源:testMaskToolsWidget.py
示例3: test_dofs
def test_dofs(vector_array):
v = vector_array
np.random.seed(len(v) + 24 + v.dim)
for ind in valid_inds(v):
c = v.copy()
dofs = c[ind].dofs(np.array([], dtype=np.int))
assert isinstance(dofs, np.ndarray)
assert dofs.shape == (v.len_ind(ind), 0)
c = v.copy()
dofs = c[ind].dofs([])
assert isinstance(dofs, np.ndarray)
assert dofs.shape == (v.len_ind(ind), 0)
if v.dim > 0:
for count in (1, 5, 10):
c_ind = np.random.randint(0, v.dim, count)
c = v.copy()
dofs = c[ind].dofs(c_ind)
assert dofs.shape == (v.len_ind(ind), count)
c = v.copy()
dofs2 = c[ind].dofs(list(c_ind))
assert np.all(dofs == dofs2)
c = v.copy()
c.scal(3.)
dofs2 = c[ind].dofs(c_ind)
assert np.allclose(dofs * 3, dofs2)
c = v.copy()
dofs2 = c[ind].dofs(np.hstack((c_ind, c_ind)))
assert np.all(dofs2 == np.hstack((dofs, dofs)))
if hasattr(v, 'data'):
assert np.all(dofs == indexed(v.data, ind)[:, c_ind])
开发者ID:renemilk,项目名称:pyMor,代码行数:32,代码来源:vectorarray.py
示例4: test_1d_array_parameters_1d_array_input
def test_1d_array_parameters_1d_array_input(self):
"""
When the input is an array, if model_set_axis=False then it must
broadcast with the shapes of the parameters (excluding the
model_set_axis).
Otherwise all dimensions must be broadcastable.
"""
t = TModel_1_1([[1, 2, 3], [4, 5, 6]],
[[10, 20, 30], [40, 50, 60]], n_models=2)
with pytest.raises(ValueError):
y1 = t([100, 200, 300])
y1 = t([100, 200])
assert np.shape(y1) == (2, 3)
assert np.all(y1 == [[111, 122, 133], [244, 255, 266]])
with pytest.raises(ValueError):
# Doesn't broadcast with the shape of the parameters, (3,)
y2 = t([100, 200], model_set_axis=False)
y2 = t([100, 200, 300], model_set_axis=False)
assert np.shape(y2) == (2, 3)
assert np.all(y2 == [[111, 222, 333],
[144, 255, 366]])
开发者ID:BTY2684,项目名称:astropy,代码行数:27,代码来源:test_input.py
示例5: test_apply_mne_inverse_raw
def test_apply_mne_inverse_raw():
"""Test MNE with precomputed inverse operator on Raw."""
start = 3
stop = 10
raw = read_raw_fif(fname_raw)
label_lh = read_label(fname_label % 'Aud-lh')
_, times = raw[0, start:stop]
inverse_operator = read_inverse_operator(fname_full)
inverse_operator = prepare_inverse_operator(inverse_operator, nave=1,
lambda2=lambda2, method="dSPM")
for pick_ori in [None, "normal", "vector"]:
stc = apply_inverse_raw(raw, inverse_operator, lambda2, "dSPM",
label=label_lh, start=start, stop=stop, nave=1,
pick_ori=pick_ori, buffer_size=None,
prepared=True)
stc2 = apply_inverse_raw(raw, inverse_operator, lambda2, "dSPM",
label=label_lh, start=start, stop=stop,
nave=1, pick_ori=pick_ori,
buffer_size=3, prepared=True)
if pick_ori is None:
assert_true(np.all(stc.data > 0))
assert_true(np.all(stc2.data > 0))
assert_true(stc.subject == 'sample')
assert_true(stc2.subject == 'sample')
assert_array_almost_equal(stc.times, times)
assert_array_almost_equal(stc2.times, times)
assert_array_almost_equal(stc.data, stc2.data)
开发者ID:claire-braboszcz,项目名称:mne-python,代码行数:30,代码来源:test_inverse.py
示例6: test_01_04_size_color
def test_01_04_size_color(self):
secondary, mask = cpo.size_similarly(np.zeros((10, 20), int),
np.zeros((10, 15, 3), np.float32))
self.assertEqual(tuple(secondary.shape), (10, 20, 3))
self.assertTrue(np.all(mask[:10, :15]))
self.assertTrue(np.all(~mask[:10, 15:]))
self.assertEqual(secondary.dtype, np.dtype(np.float32))
开发者ID:zindy,项目名称:CellProfiler,代码行数:7,代码来源:test_objects.py
示例7: test_mean_std_12bit
def test_mean_std_12bit(self):
# Input 12-bit, with an 8-bit color target
input_scene = np.tile(np.arange(4096)[:, None, None], (1, 1, 3))
color_target = np.tile(np.arange(256)[:, None, None], (1, 1, 3))
luts = hm.mean_std_luts(input_scene.astype(np.uint16),
color_target.astype(np.uint8))
np.testing.assert_array_equal(luts[0], luts[1])
np.testing.assert_array_equal(luts[1], luts[2])
lut = luts[0]
assert np.all(lut[:8] == 0)
assert np.all(lut[-8:] == 4096)
assert np.diff(lut[8:-8]).min() == 1
assert np.diff(lut[8:-8]).max() == 2
# Input 12-bit, with a 12-bit color target
input_scene = np.tile(np.arange(4096)[:, None, None], (1, 1, 3))
color_target = np.tile(np.arange(4096)[:, None, None], (1, 1, 3))
luts = hm.mean_std_luts(input_scene.astype(np.uint16),
color_target.astype(np.uint16))
# Should be a 1 to 1 look-up-table...
np.testing.assert_array_equal(luts[0], np.arange(4097))
开发者ID:huleg,项目名称:color_balance,代码行数:26,代码来源:histogram_match_tests.py
示例8: test_path_no_doubled_point_in_to_polygon
def test_path_no_doubled_point_in_to_polygon():
hand = np.array(
[[1.64516129, 1.16145833],
[1.64516129, 1.59375],
[1.35080645, 1.921875],
[1.375, 2.18229167],
[1.68548387, 1.9375],
[1.60887097, 2.55208333],
[1.68548387, 2.69791667],
[1.76209677, 2.56770833],
[1.83064516, 1.97395833],
[1.89516129, 2.75],
[1.9516129, 2.84895833],
[2.01209677, 2.76041667],
[1.99193548, 1.99479167],
[2.11290323, 2.63020833],
[2.2016129, 2.734375],
[2.25403226, 2.60416667],
[2.14919355, 1.953125],
[2.30645161, 2.36979167],
[2.39112903, 2.36979167],
[2.41532258, 2.1875],
[2.1733871, 1.703125],
[2.07782258, 1.16666667]])
(r0, c0, r1, c1) = (1.0, 1.5, 2.1, 2.5)
poly = Path(np.vstack((hand[:, 1], hand[:, 0])).T, closed=True)
clip_rect = transforms.Bbox([[r0, c0], [r1, c1]])
poly_clipped = poly.clip_to_bbox(clip_rect).to_polygons()[0]
assert np.all(poly_clipped[-2] != poly_clipped[-1])
assert np.all(poly_clipped[-1] == poly_clipped[0])
开发者ID:DanHickstein,项目名称:matplotlib,代码行数:33,代码来源:test_path.py
示例9: __getitem__
def __getitem__(self, key):
if type(key) == slice:
# if all in cache, then use slice, else don't
start, stop, step = key.start, key.stop, key.step
in_cache = self.existence_cache[start:stop:step]
if np.all(in_cache):
return self.cache[self.data_name][start:stop:step]
elif np.all(np.logical_not(in_cache)):
return self.__get_from_data_source(slice(start, stop, step))
key = slice_to_range(key, len(self))
if is_int_like(key):
index = key
if self.existence_cache[index]:
return self.cache[self.data_name][index]
else:
return self.__get_from_data_source(index)
if is_array_like(key):
data = []
for index, in_cache in zip(key, self.existence_cache[key]):
if in_cache:
datum = self.cache[self.data_name][index]
else:
datum = self.__get_from_data_source(index)
data.append(datum)
return np.array(data)
else:
raise RuntimeError('key: {} is not compatible with this datasource'.format(str(key)))
开发者ID:coopie,项目名称:speech_ml,代码行数:34,代码来源:data_sources.py
示例10: test_pickle
def test_pickle():
"""Test that a module can be pickled"""
M = Module()
M.x = (T.dmatrix())
M.y = (T.dmatrix())
a = T.dmatrix()
M.f = Method([a], a + M.x + M.y)
M.g = Method([a], a * M.x * M.y)
mode = get_mode()
m = M.make(x=numpy.zeros((4,5)), y=numpy.ones((2,3)), mode=mode)
m_dup = cPickle.loads(cPickle.dumps(m, protocol=-1))
assert numpy.all(m.x == m_dup.x) and numpy.all(m.y == m_dup.y)
m_dup.x[0,0] = 3.142
assert m_dup.f.input_storage[1].data[0,0] == 3.142
assert m.x[0,0] == 0.0 #ensure that m is not aliased to m_dup
#check that the unpickled version has the same argument/property aliasing
assert m_dup.x is m_dup.f.input_storage[1].data
assert m_dup.y is m_dup.f.input_storage[2].data
assert m_dup.x is m_dup.g.input_storage[1].data
assert m_dup.y is m_dup.g.input_storage[2].data
开发者ID:SinaHonari,项目名称:Theano,代码行数:25,代码来源:test_module.py
示例11: test_tally_results
def test_tally_results(capi_run):
t = openmc.capi.tallies[1]
assert t.num_realizations == 5
assert np.all(t.mean >= 0)
nonzero = (t.mean > 0.0)
assert np.all(t.std_dev[nonzero] >= 0)
assert np.all(t.ci_width()[nonzero] >= 1.95*t.std_dev[nonzero])
开发者ID:mit-crpg,项目名称:openmc,代码行数:7,代码来源:test_capi.py
示例12: test_rand
def test_rand(self):
# Simple distributional checks for sparse.rand.
for random_state in None, 4321, np.random.RandomState():
x = sprand(10, 20, density=0.5, dtype=np.float64,
random_state=random_state)
assert_(np.all(np.less_equal(0, x.data)))
assert_(np.all(np.less_equal(x.data, 1)))
开发者ID:7924102,项目名称:scipy,代码行数:7,代码来源:test_construct.py
示例13: pop_planes
def pop_planes(geometry, kwargs):
# Convert miller index specifications to normal vectors
miller_defs = kwargs.pop("planes_miller", None)
if miller_defs is not None:
if np.any(np.all(abs(miller_defs[:,0:3]) < EPSILON, axis=1)):
error("Emtpy miller index tuple")
miller_defs[:,0:3] = miller_to_normal(
np.dot(geometry.latvecs, geometry.bravais_cell),
miller_defs[:,0:3])
else:
miller_defs = np.zeros((0, 4), dtype=float)
# Convert plane normal vector specifications into cartesian coords.
normal_defs = kwargs.pop("planes_normal", None)
if normal_defs is not None:
normal_defs[:,0:3] = geometry.coord_transform(
normal_defs[:,0:3],
kwargs.pop("planes_normal_coordsys", "lattice"))
if np.any(np.all(abs(normal_defs[:,0:3]) < EPSILON, axis=1)):
error("Emtpy normal vector definition")
else:
normal_defs = np.zeros((0, 4), dtype=float)
# Append two defintions
planes_normal = np.vstack(( miller_defs, normal_defs ))
return planes_normal
开发者ID:aradi,项目名称:nanocut,代码行数:26,代码来源:polyhedron.py
示例14: test_data_scaling
def test_data_scaling(self):
hdr = self.header_class()
hdr.set_data_shape((1,2,3))
hdr.set_data_dtype(np.int16)
S3 = BytesIO()
data = np.arange(6, dtype=np.float64).reshape((1,2,3))
# This uses scaling
hdr.data_to_fileobj(data, S3)
data_back = hdr.data_from_fileobj(S3)
# almost equal
assert_array_almost_equal(data, data_back, 4)
# But not quite
assert_false(np.all(data == data_back))
# This is exactly the same call, just testing it works twice
data_back2 = hdr.data_from_fileobj(S3)
assert_array_equal(data_back, data_back2, 4)
# Rescaling is the default
hdr.data_to_fileobj(data, S3, rescale=True)
data_back = hdr.data_from_fileobj(S3)
assert_array_almost_equal(data, data_back, 4)
assert_false(np.all(data == data_back))
# This doesn't use scaling, and so gets perfect precision
hdr.data_to_fileobj(data, S3, rescale=False)
data_back = hdr.data_from_fileobj(S3)
assert_true(np.all(data == data_back))
开发者ID:adykstra,项目名称:nibabel,代码行数:25,代码来源:test_spm99analyze.py
示例15: test_06_05_ijv_three_overlapping
def test_06_05_ijv_three_overlapping(self):
#
# This is a regression test of a bug where a segmentation consists
# of only one point, labeled three times yielding two planes instead
# of three.
#
ijv = np.array([[4, 5, 1],
[4, 5, 2],
[4, 5, 3]])
x = cpo.Objects()
x.set_ijv(ijv, (8, 9))
labels = []
indices = np.zeros(3, bool)
for l, i in x.get_labels():
labels.append(l)
self.assertEqual(len(i), 1)
self.assertTrue(i[0] in (1, 2, 3))
indices[i[0] - 1] = True
self.assertTrue(np.all(indices))
self.assertEqual(len(labels), 3)
lstacked = np.dstack(labels)
i, j, k = np.mgrid[0:lstacked.shape[0],
0:lstacked.shape[1],
0:lstacked.shape[2]]
self.assertTrue(np.all(lstacked[(i != 4) | (j != 5)] == 0))
self.assertEqual((1, 2, 3), tuple(sorted(lstacked[4, 5, :])))
开发者ID:zindy,项目名称:CellProfiler,代码行数:26,代码来源:test_objects.py
示例16: test_non_quantity_with_unit
def test_non_quantity_with_unit(self):
"""Test that unit attributes in objects get recognized."""
class MyQuantityLookalike(np.ndarray):
pass
a = np.arange(3.)
mylookalike = a.copy().view(MyQuantityLookalike)
mylookalike.unit = 'm'
q1 = u.Quantity(mylookalike)
assert isinstance(q1, u.Quantity)
assert q1.unit is u.m
assert np.all(q1.value == a)
q2 = u.Quantity(mylookalike, u.mm)
assert q2.unit is u.mm
assert np.all(q2.value == 1000.*a)
q3 = u.Quantity(mylookalike, copy=False)
assert np.all(q3.value == mylookalike)
q3[2] = 0
assert q3[2] == 0.
assert mylookalike[2] == 0.
mylookalike = a.copy().view(MyQuantityLookalike)
mylookalike.unit = u.m
q4 = u.Quantity(mylookalike, u.mm, copy=False)
q4[2] = 0
assert q4[2] == 0.
assert mylookalike[2] == 2.
mylookalike.unit = 'nonsense'
with pytest.raises(TypeError):
u.Quantity(mylookalike)
开发者ID:AustereCuriosity,项目名称:astropy,代码行数:33,代码来源:test_quantity.py
示例17: test_07_01_make_ijv_outlines
def test_07_01_make_ijv_outlines(self):
np.random.seed(70)
x = cpo.Objects()
ii, jj = np.mgrid[0:10, 0:20]
masks = [(ii - ic) ** 2 + (jj - jc) ** 2 < r ** 2
for ic, jc, r in ((4, 5, 5), (4, 12, 5), (6, 8, 5))]
i = np.hstack([ii[mask] for mask in masks])
j = np.hstack([jj[mask] for mask in masks])
v = np.hstack([[k + 1] * np.sum(mask) for k, mask in enumerate(masks)])
x.set_ijv(np.column_stack((i, j, v)), ii.shape)
x.parent_image = cpi.Image(np.zeros((10, 20)))
colors = np.random.uniform(size=(3, 3)).astype(np.float32)
image = x.make_ijv_outlines(colors)
i1 = [i for i, color in enumerate(colors) if np.all(color == image[0, 5, :])]
self.assertEqual(len(i1), 1)
i2 = [i for i, color in enumerate(colors) if np.all(color == image[0, 12, :])]
self.assertEqual(len(i2), 1)
i3 = [i for i, color in enumerate(colors) if np.all(color == image[-1, 8, :])]
self.assertEqual(len(i3), 1)
self.assertNotEqual(i1[0], i2[0])
self.assertNotEqual(i2[0], i3[0])
colors = colors[np.array([i1[0], i2[0], i3[0]])]
outlines = np.zeros((10, 20, 3), np.float32)
alpha = np.zeros((10, 20))
for i, (color, mask) in enumerate(zip(colors, masks)):
my_outline = outline(mask)
outlines[my_outline] += color
alpha[my_outline] += 1
alpha[alpha == 0] = 1
outlines /= alpha[:, :, np.newaxis]
np.testing.assert_almost_equal(outlines, image)
开发者ID:zindy,项目名称:CellProfiler,代码行数:32,代码来源:test_objects.py
示例18: test_reset
def test_reset(Simulator, learning_rule, plt, seed, rng):
"""Make sure resetting learning rules resets all state."""
m, activity_p, trans_p = learning_net(
learning_rule, nengo.Network(seed=seed), rng)
sim = Simulator(m)
sim.run(0.1)
sim.run(0.2)
first_t = sim.trange()
first_t_trans = sim.trange(dt=0.01)
first_activity_p = np.array(sim.data[activity_p], copy=True)
first_trans_p = np.array(sim.data[trans_p], copy=True)
sim.reset()
sim.run(0.3)
plt.subplot(2, 1, 1)
plt.ylabel("Neural activity")
plt.plot(first_t, first_activity_p, c='b')
plt.plot(sim.trange(), sim.data[activity_p], c='g')
plt.subplot(2, 1, 2)
plt.ylabel("Connection weight")
plt.plot(first_t_trans, first_trans_p[..., 0], c='b')
plt.plot(sim.trange(dt=0.01), sim.data[trans_p][..., 0], c='g')
assert np.all(sim.trange() == first_t)
assert np.all(sim.trange(dt=0.01) == first_t_trans)
assert np.all(sim.data[activity_p] == first_activity_p)
assert np.all(sim.data[trans_p] == first_trans_p)
开发者ID:epaxon,项目名称:nengo,代码行数:30,代码来源:test_learning_rules.py
示例19: get_resampling_matrix
def get_resampling_matrix(global_grid,local_grid):
"""Build the rectangular matrix that linearly resamples from the global grid to a local grid.
The local grid range must be contained within the global grid range.
Args:
global_grid(numpy.ndarray): Sorted array of n global grid wavelengths.
local_grid(numpy.ndarray): Sorted array of m local grid wavelengths.
Returns:
numpy.ndarray: Array of (m,n) matrix elements that perform the linear resampling.
"""
assert np.all(np.diff(global_grid) > 0),'Global grid is not strictly increasing.'
assert np.all(np.diff(local_grid) > 0),'Local grid is not strictly increasing.'
# Locate each local wavelength in the global grid.
global_index = np.searchsorted(global_grid,local_grid)
assert local_grid[0] >= global_grid[0],'Local grid extends below global grid.'
assert local_grid[-1] <= global_grid[-1],'Local grid extends above global grid.'
# Lookup the global-grid bracketing interval (xlo,xhi) for each local grid point.
# Note that this gives xlo = global_grid[-1] if local_grid[0] == global_grid[0]
# but this is fine since the coefficient of xlo will be zero.
global_xhi = global_grid[global_index]
global_xlo = global_grid[global_index-1]
# Create the rectangular interpolation matrix to return.
alpha = (local_grid - global_xlo)/(global_xhi - global_xlo)
local_index = np.arange(len(local_grid),dtype=int)
matrix = np.zeros((len(local_grid),len(global_grid)))
matrix[local_index,global_index] = alpha
matrix[local_index,global_index-1] = 1 - alpha
return matrix
开发者ID:desihub,项目名称:desispec,代码行数:30,代码来源:coaddition.py
示例20: test_scalar_parameters_1d_array_input
def test_scalar_parameters_1d_array_input(self):
"""
The dimension of the input should match the number of models unless
model_set_axis=False is given, in which case the input is copied across
all models.
"""
t = TModel_1_1([1, 2], [10, 20], n_models=2)
with pytest.raises(ValueError):
y = t(np.arange(5) * 100)
y1 = t([100, 200])
assert np.shape(y1) == (2,)
assert np.all(y1 == [111, 222])
y2 = t([100, 200], model_set_axis=False)
# In this case the value [100, 200, 300] should be evaluated on each
# model rather than evaluating the first model with 100 and the second
# model with 200
assert np.shape(y2) == (2, 2)
assert np.all(y2 == [[111, 211], [122, 222]])
y3 = t([100, 200, 300], model_set_axis=False)
assert np.shape(y3) == (2, 3)
assert np.all(y3 == [[111, 211, 311], [122, 222, 322]])
开发者ID:BTY2684,项目名称:astropy,代码行数:26,代码来源:test_input.py
注:本文中的numpy.all函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论