本文整理汇总了Python中numpy.alltrue函数的典型用法代码示例。如果您正苦于以下问题:Python alltrue函数的具体用法?Python alltrue怎么用?Python alltrue使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了alltrue函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: testIter
def testIter(self):
# Override testIter.
index = self.cls(texts, self.w2v_model)
for sims in index:
self.assertTrue(numpy.alltrue(sims >= 0.0))
self.assertTrue(numpy.alltrue(sims <= 1.0))
开发者ID:RaRe-Technologies,项目名称:gensim,代码行数:7,代码来源:test_similarities.py
示例2: test_local_max
def test_local_max(self):
bd = BlobDetection(self.img)
bd._one_octave(shrink=False, refine=False, n_5=False)
self.assert_(numpy.alltrue(_blob.local_max(bd.dogs, bd.cur_mask, False) == \
local_max(bd.dogs, bd.cur_mask, False)), "max test, 3x3x3")
self.assert_(numpy.alltrue(_blob.local_max(bd.dogs, bd.cur_mask, True) == \
local_max(bd.dogs, bd.cur_mask, True)), "max test, 3x5x5")
开发者ID:SulzmannFr,项目名称:pyFAI,代码行数:7,代码来源:test_blob_detection.py
示例3: testWeightedModelMatrix
def testWeightedModelMatrix(self):
linearModel = LinearModel(
self.regressorList, self.regressorNames, self.covMatrixObserv2, regressorsAreWeighted=True
)
self.assertTrue(np.alltrue(linearModel.designMatrix() == self.unweightedDesignMatrix))
linearModel = LinearModel(
self.regressorList, self.regressorNames, self.covMatrixObserv2, regressorsAreWeighted=False
)
self.assertFalse(np.alltrue(linearModel.designMatrix() == self.unweightedDesignMatrix))
expectedWeightedDesignMatrix = np.array(
[
[3.16227766e00, 4.73643073e-15],
[4.23376727e-01, 2.79508497e00],
[-2.67843095e-01, 3.79299210e00],
[-5.45288776e-01, 4.39760881e00],
[-6.78144517e-01, 4.84809047e00],
[-7.46997591e-01, 5.21965041e00],
[-7.83412990e-01, 5.54374745e00],
[-8.01896636e-01, 5.83605564e00],
[-8.09868157e-01, 6.10538773e00],
[-8.11425366e-01, 6.35716086e00],
]
)
self.assertTrue(
np.allclose(linearModel.designMatrix(), expectedWeightedDesignMatrix, rtol=1.0e-6, atol=1.0e-08)
)
开发者ID:robinlombaert,项目名称:IvSPythonRepository,代码行数:30,代码来源:testlinearregression.py
示例4: set_weights
def set_weights(self, weight_dict):
"""Update weights with a dictionary keyed by test_mi, whose values are
either:
(1) dicts of feature -> scalar weight.
(2) a scalar which will apply to all features of that model interface
Features and model interfaces must correspond to those declared for the
context.
"""
for test_mi, fs in weight_dict.items():
try:
flist = list(self.metric_features[test_mi]['features'].keys())
except KeyError:
raise AssertionError("Invalid test model interface")
if isinstance(fs, common._num_types):
feat_dict = {}.fromkeys(flist, fs)
elif isinstance(fs, dict):
assert npy.alltrue([isinstance(w, common._num_types) for \
w in fs.values()]), "Invalid scalar weight"
assert npy.alltrue([f in flist for f in fs.keys()]), \
"Invalid features given for this test model interface"
feat_dict = fs
for f, w in feat_dict.items():
self.feat_weights[(test_mi, f)] = w
# update weight value
start_ix, end_ix = self.weight_index_mapping[test_mi][f]
self.weights[start_ix:end_ix] = w
开发者ID:FedericoV,项目名称:pydstool,代码行数:26,代码来源:ModelContext.py
示例5: nested_equal
def nested_equal(self, val1, val2):
"""Test for equality in a nested list or ndarray
"""
if isinstance(val1, list):
for (subval1, subval2) in zip(val1, val2):
if isinstance(subval1, list):
self.nested_equal(subval1, subval2)
elif isinstance(subval1, np.ndarray):
try:
np.allclose(subval1, subval2)
except NotImplementedError:
import sys
print >> sys.stderr, '****', subval1, subval1.size
print >> sys.stderr, subval2, subval2.shape
print >> sys.stderr, '******\n'
else:
self.assertEqual(subval1, subval2)
elif isinstance(val1, np.ndarray):
np.allclose(val1, np.array(val2))
elif isinstance(val1, basestring):
self.assertEqual(val1, val2)
else:
try:
assert (np.alltrue(np.isnan(val1)) and
np.alltrue(np.isnan(val2)))
except (AssertionError, NotImplementedError):
self.assertEqual(val1, val2)
开发者ID:filmor,项目名称:oct2py,代码行数:27,代码来源:test_oct2py.py
示例6: test_capacitor
def test_capacitor():
"""Verify simple capacitance model"""
class Capacitor(Behavioural):
instparams = [Parameter(name="c", desc="Capacitance", unit="F")]
@staticmethod
def analog(plus, minus):
b = Branch(plus, minus)
return (Contribution(b.I, dtt(c * b.V)),)
C = sympy.Symbol("C")
cap = Capacitor(c=C)
v1, v2 = sympy.symbols(("v1", "v2"))
assert cap.i([v1, v2]) == [0, 0]
assert cap.q([v1, v2]) == [C * (v1 - v2), -C * (v1 - v2)]
assert np.alltrue(cap.C([v1, v2]) == np.array([[C, -C], [-C, C]]))
assert np.alltrue(cap.G([v1, v2]) == np.zeros((2, 2)))
assert np.alltrue(cap.CY([v1, v2]) == np.zeros((2, 2)))
开发者ID:hohe,项目名称:pycircuit,代码行数:26,代码来源:test_hdl.py
示例7: pixfun_inv_c
def pixfun_inv_c():
if not numpy_available:
return 'skip'
filename = 'data/pixfun_inv_c.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
if ds is None:
gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
return 'fail'
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/cint_sar.tif'
refds = gdal.Open(reffilename)
if refds is None:
gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
return 'fail'
refdata = refds.GetRasterBand(1).ReadAsArray()
refdata = refdata.astype('complex')
delta = data - 1./refdata
if not numpy.alltrue(abs(delta.real) < 1e-13):
return 'fail'
if not numpy.alltrue(abs(delta.imag) < 1e-13):
return 'fail'
return 'success'
开发者ID:Mavrx-inc,项目名称:gdal,代码行数:27,代码来源:pixfun.py
示例8: test_1d_weight_array
def test_1d_weight_array(self):
""""""
sample_size = 5
# check the individual gridcells
# This is a stochastic model, so it may legitimately fail occassionally.
index1 = where(self.households.get_attribute("lucky"))[0]
index2 = where(self.gridcells.get_attribute("filter"))[0]
weight=self.gridcells.get_attribute("weight")
for icc in [0,1]: #include_chosen_choice?
#icc = sample([0,1],1)
sampler_ret = weighted_sampler().run(dataset1=self.households, dataset2=self.gridcells, index1=index1,
index2=index2, sample_size=sample_size, weight="weight",include_chosen_choice=icc)
# get results
sampled_index = sampler_ret.get_2d_index()
chosen_choices = UNPLACED_ID * ones(index1.size, dtype="int32")
where_chosen = where(sampler_ret.get_attribute("chosen_choice"))
chosen_choices[where_chosen[0]]=where_chosen[1]
sample_results = sampled_index, chosen_choices
sampled_index = sample_results[0]
self.assertEqual(sampled_index.shape, (index1.size, sample_size))
if icc:
placed_agents_index = self.gridcells.try_get_id_index(
self.households.get_attribute("grid_id")[index1],UNPLACED_ID)
chosen_choice_index = resize(array([UNPLACED_ID], dtype="int32"), index1.shape)
w = where(chosen_choices>=0)[0]
# for 64 bit machines, need to coerce the type to int32 -- on a
# 32 bit machine the astype(int32) doesn't do anything
chosen_choice_index[w] = sampled_index[w, chosen_choices[w]].astype(int32)
self.assert_( alltrue(equal(placed_agents_index, chosen_choice_index)) )
sampled_index = sampled_index[:,1:]
self.assert_( alltrue(lookup(sampled_index.ravel(), index2, index_if_not_found=UNPLACED_ID)!=UNPLACED_ID) )
self.assert_( all(not_equal(weight[sampled_index], 0.0)) )
开发者ID:christianurich,项目名称:VIBe2UrbanSim,代码行数:34,代码来源:weighted_sampler.py
示例9: __contains__
def __contains__(self, point):
"""
:param Point point: the box of the problem
"""
l = np.alltrue(point.x >= self.box[:, 0])
u = np.alltrue(point.x <= self.box[:, 1])
return l and u
开发者ID:haraldschilly,项目名称:panobbgo,代码行数:7,代码来源:lib.py
示例10: test_bitsShaders
def test_bitsShaders():
#a dict of dicts for expected vals
for mode in ['bits++', 'mono++', 'color++']:
bits.mode=mode
for finalVal in [255.0, 1024, 65535]:
thisExpected = expectedVals[mode][finalVal]
#print bits.mode, finalVal
intended = np.linspace(0.0,1,256)*255.0/finalVal
stim.image = np.resize(intended,[256,256])*2-1 #NB psychopy uses -1:1
stim.draw()
#fr = np.array(win._getFrame('back').transpose(Image.ROTATE_270))
#print 'pre r', fr[0:10,-1,0], fr[250:256,-1,0]
#print 'pre g', fr[0:10,-1,1], fr[250:256,-1,0]
win.flip()
fr = np.array(win._getFrame('front').transpose(Image.ROTATE_270))
if not _travisTesting:
assert np.alltrue(thisExpected['lowR'] == fr[0:10,-1,0])
assert np.alltrue(thisExpected['lowG'] == fr[0:10,-1,1])
assert np.alltrue(thisExpected['highR'] == fr[250:256,-1,0])
assert np.alltrue(thisExpected['highG'] == fr[250:256,-1,1])
if not _travisTesting:
print 'R', repr(fr[0:10,-1,0]), repr(fr[250:256,-1,0])
print 'G', repr(fr[0:10,-1,1]), repr(fr[250:256,-1,0])
开发者ID:NSalem,项目名称:psychopy,代码行数:26,代码来源:test_CRS_bitsShaders.py
示例11: test_call_with_normalisation_precision
def test_call_with_normalisation_precision(self):
'''The normalisation should use a double precision scaling.
'''
# Should be the case for double inputs...
_input_array = empty_aligned((256, 512), dtype='complex128', n=16)
self.fft()
ifft = FFTW(self.output_array, _input_array,
direction='FFTW_BACKWARD')
ref_output = ifft(normalise_idft=False).copy()/numpy.float64(ifft.N)
test_output = ifft(normalise_idft=True).copy()
self.assertTrue(numpy.alltrue(ref_output == test_output))
# ... and single inputs.
_input_array = empty_aligned((256, 512), dtype='complex64', n=16)
ifft = FFTW(numpy.array(self.output_array, _input_array.dtype),
_input_array,
direction='FFTW_BACKWARD')
ref_output = ifft(normalise_idft=False).copy()/numpy.float64(ifft.N)
test_output = ifft(normalise_idft=True).copy()
self.assertTrue(numpy.alltrue(ref_output == test_output))
开发者ID:grlee77,项目名称:pyFFTW,代码行数:26,代码来源:test_pyfftw_call.py
示例12: test_integrate
def test_integrate(self):
h = 1.
x0 = np.array([0, 0, 1.])
dt, vu0, uu = .01, .01, .5
self.s.electrode("rf").rf = uu*h**2
t, x, v = [], [], []
for ti, xi, vi in self.s.trajectory(
x0, np.array([0, 0, vu0*uu*h]), axis=(1, 2),
t1=20*2*np.pi, dt=dt*2*np.pi):
t.append(ti)
x.append(xi)
v.append(vi)
t = np.array(t)
x = np.array(x)
v = np.array(v)
self.assertEqual(np.alltrue(utils.norm(x, axis=1)<3), True)
self.assertEqual(np.alltrue(utils.norm(v, axis=1)<1), True)
avg = int(1/dt)
kin = (((x[:-avg]-x[avg:])/(2*np.pi))**2).sum(axis=-1)/2*4 # 4?
pot = self.s.potential(np.array([x0[0]+0*x[:,0], x[:,0], x[:,1]]).T)
pot = pot[avg/2:-avg/2]
t = t[avg/2:-avg/2]
do_avg = lambda ar: ar[:ar.size/avg*avg].reshape(
(-1, avg)).mean(axis=-1)
t, kin, pot = map(do_avg, (t, kin, pot))
self.assertEqual(np.alltrue(np.std(kin+pot)/np.mean(kin+pot)<.01),
True)
开发者ID:dhslichter,项目名称:electrode,代码行数:31,代码来源:test_traps.py
示例13: test_multib0_dsi
def test_multib0_dsi():
data, gtab = dsi_voxels()
# Create a new data-set with a b0 measurement:
new_data = np.concatenate([data, data[..., 0, None]], -1)
new_bvecs = np.concatenate([gtab.bvecs, np.zeros((1, 3))])
new_bvals = np.concatenate([gtab.bvals, [0]])
new_gtab = gradient_table(new_bvals, new_bvecs)
ds = DiffusionSpectrumModel(new_gtab)
sphere = get_sphere('repulsion724')
dsfit = ds.fit(new_data)
pdf = dsfit.pdf()
dsfit.odf(sphere)
assert_equal(new_data.shape[:-1] + (17, 17, 17), pdf.shape)
assert_equal(np.alltrue(np.isreal(pdf)), True)
# And again, with one more b0 measurement (two in total):
new_data = np.concatenate([data, data[..., 0, None]], -1)
new_bvecs = np.concatenate([gtab.bvecs, np.zeros((1, 3))])
new_bvals = np.concatenate([gtab.bvals, [0]])
new_gtab = gradient_table(new_bvals, new_bvecs)
ds = DiffusionSpectrumModel(new_gtab)
dsfit = ds.fit(new_data)
pdf = dsfit.pdf()
dsfit.odf(sphere)
assert_equal(new_data.shape[:-1] + (17, 17, 17), pdf.shape)
assert_equal(np.alltrue(np.isreal(pdf)), True)
开发者ID:albayenes,项目名称:dipy,代码行数:26,代码来源:test_dsi.py
示例14: test_capacitor
def test_capacitor():
"""Verify simple capacitance model"""
class Capacitor(Behavioural):
instparams = [Parameter(name='c', desc='Capacitance', unit='F')]
@staticmethod
def analog(plus, minus):
b = Branch(plus, minus)
return Contribution(b.I, ddt(c * b.V)),
C = sympy.Symbol('C')
cap = Capacitor(c=C)
v1,v2 = sympy.symbols(('v1', 'v2'))
assert cap.i([v1,v2]) == [0, 0]
assert cap.q([v1,v2]) == [C*(v1-v2), -C*(v1-v2)]
assert np.alltrue(cap.C([v1,v2]) ==
np.array([[C, -C], [-C, C]]))
assert np.alltrue(cap.G([v1,v2]) == np.zeros((2,2)))
assert np.alltrue(cap.CY([v1,v2]) == np.zeros((2,2)))
开发者ID:AshitaPrasad,项目名称:pycircuit,代码行数:26,代码来源:test_hdl.py
示例15: test_array_alpha
def test_array_alpha(self):
if not arraytype:
self.fail("no array package installed")
if arraytype == 'numeric':
# This is known to fail with Numeric (differing values for
# get_rgb and array element for 16 bit surfaces).
return
palette = [(0, 0, 0, 0),
(10, 50, 100, 255),
(60, 120, 240, 130),
(64, 128, 255, 0),
(255, 128, 0, 65)]
targets = [self._make_src_surface(8, palette=palette),
self._make_src_surface(16, palette=palette),
self._make_src_surface(16, palette=palette, srcalpha=True),
self._make_src_surface(24, palette=palette),
self._make_src_surface(32, palette=palette),
self._make_src_surface(32, palette=palette, srcalpha=True)]
for surf in targets:
p = palette
if surf.get_bitsize() == 16:
p = [surf.unmap_rgb(surf.map_rgb(c)) for c in p]
arr = pygame.surfarray.array_alpha(surf)
if surf.get_masks()[3]:
for (x, y), i in self.test_points:
self.failUnlessEqual(arr[x, y], p[i][3],
("%i != %i, posn: (%i, %i), "
"bitsize: %i" %
(arr[x, y], p[i][3],
x, y,
surf.get_bitsize())))
else:
self.failUnless(alltrue(arr == 255))
# No per-pixel alpha when blanket alpha is None.
for surf in targets:
blacket_alpha = surf.get_alpha()
surf.set_alpha(None)
arr = pygame.surfarray.array_alpha(surf)
self.failUnless(alltrue(arr == 255),
"bitsize: %i, flags: %i" %
(surf.get_bitsize(), surf.get_flags()))
surf.set_alpha(blacket_alpha)
# Bug for per-pixel alpha surface when blanket alpha 0.
for surf in targets:
blanket_alpha = surf.get_alpha()
surf.set_alpha(0)
arr = pygame.surfarray.array_alpha(surf)
if surf.get_masks()[3]:
self.failIf(alltrue(arr == 255),
"bitsize: %i, flags: %i" %
(surf.get_bitsize(), surf.get_flags()))
else:
self.failUnless(alltrue(arr == 255),
"bitsize: %i, flags: %i" %
(surf.get_bitsize(), surf.get_flags()))
surf.set_alpha(blanket_alpha)
开发者ID:123jefferson,项目名称:MiniBloq-Sparki,代码行数:60,代码来源:surfarray_test.py
示例16: __add__
def __add__(self, other):
selection = ['atom', 'bond_with', 'angle_with', 'dihedral_with']
coords = ['bond', 'angle', 'dihedral']
new = self.copy()
new._metadata['absolute_zmat'] = (self._metadata['absolute_zmat']
and other._metadata['absolute_zmat'])
try:
assert (self.index == other.index).all()
# TODO default values for _metadata
if new._metadata['absolute_zmat']:
assert np.alltrue(self[:, selection] == other[:, selection])
else:
self[:, selection].isnull()
tested_where_equal = (self[:, selection] == other[:, selection])
tested_where_nan = (self[:, selection].isnull()
| other[:, selection].isnull())
for column in selection:
tested_where_equal[tested_where_nan[column], column] = True
assert np.alltrue(tested_where_equal)
new[:, coords] = self[:, coords] + other[:, coords]
except AssertionError:
raise PhysicalMeaningError("You can add only those zmatrices that \
have the same index, use the same buildlist, have the same ordering... \
The only allowed difference is ['bond', 'angle', 'dihedral']")
return new
开发者ID:mcocdawc,项目名称:chemcoord,代码行数:26,代码来源:zmat_functions.py
示例17: pixfun_imag_c
def pixfun_imag_c():
if not numpy_available:
return 'skip'
filename = 'data/pixfun_imag_c.vrt'
ds = gdal.OpenShared(filename, gdal.GA_ReadOnly)
if ds is None:
gdaltest.post_reason('Unable to open "%s" dataset.' % filename)
return 'fail'
data = ds.GetRasterBand(1).ReadAsArray()
reffilename = 'data/cint_sar.tif'
refds = gdal.Open(reffilename)
if refds is None:
gdaltest.post_reason('Unable to open "%s" dataset.' % reffilename)
return 'fail'
refdata = refds.GetRasterBand(1).ReadAsArray()
if not numpy.alltrue(data == refdata.imag):
gdaltest.post_reason('fail')
return 'fail'
# Test bugfix of #6599
copied_ds = gdal.Translate('', filename, format = 'MEM')
data_ds = copied_ds.GetRasterBand(1).ReadAsArray()
copied_ds = None
if not numpy.alltrue(data == data_ds):
gdaltest.post_reason('fail')
return 'fail'
return 'success'
开发者ID:Mavrx-inc,项目名称:gdal,代码行数:33,代码来源:pixfun.py
示例18: check_callable
def check_callable(callables, n_scales):
r"""
Checks the callable type per level.
Parameters
----------
callables : `callable` or `list` of `callables`
The callable to be used per scale.
n_scales : `int`
The number of scales.
Returns
-------
callable_list : `list`
A `list` of callables.
Raises
------
ValueError
callables must be a callable or a list/tuple of callables with the same
length as the number of scales
"""
if callable(callables):
return [callables] * n_scales
elif len(callables) == 1 and np.alltrue([callable(f) for f in callables]):
return list(callables) * n_scales
elif len(callables) == n_scales and np.alltrue([callable(f)
for f in callables]):
return list(callables)
else:
raise ValueError("callables must be a callable or a list/tuple of "
"callables with the same length as the number "
"of scales")
开发者ID:KeeganRen,项目名称:menpofit,代码行数:33,代码来源:checks.py
示例19: test_join_by_rows_for_char_arrays
def test_join_by_rows_for_char_arrays(self):
from numpy import alltrue
storage = StorageFactory().get_storage('dict_storage')
storage.write_table(
table_name='dataset1',
table_data={
'id':array([2,4,6,8]),
'attr':array(['4','7','2','1'])
}
)
storage.write_table(
table_name='dataset2',
table_data={
'id':array([1,5,9]),
'attr':array(['55','66','100'])
}
)
ds1 = Dataset(in_storage=storage, in_table_name='dataset1', id_name='id')
ds2 = Dataset(in_storage=storage, in_table_name='dataset2', id_name='id')
ds1.join_by_rows(ds2)
self.assert_(alltrue(ds1.get_attribute('attr') == array(['4','7','2','1','55','66','100'])))
self.assert_(alltrue(ds2.get_attribute('attr') == array(['55','66','100'])))
开发者ID:christianurich,项目名称:VIBe2UrbanSim,代码行数:26,代码来源:test_dataset.py
示例20: testsegmarker
def testsegmarker(self):
holelist = []
regionlist = []
points = [(0.0,0.0),(0.0,10.0),(3.0,0.0),(3.0,10.0)]
pointattlist = [[],[],[],[]]
regionlist.append( (1.2,1.2,5.0) )
seglist = [(0,1),(1,3),(3,2),(2,0)]
segattlist = [1.0,2.0,3.0,4.0]
mode = "Qzp"
data = generate_mesh(points,seglist,holelist,regionlist,
pointattlist,segattlist, mode, points)
correct = num.array([(1, 0, 2), (2, 3, 1)])
self.assertTrue(num.alltrue(data['generatedtrianglelist'].flat == \
correct.flat),
'trianglelist is wrong!')
correct = num.array([(0, 1), (1, 3), (3, 2), (2, 0)])
self.assertTrue(num.alltrue(data['generatedsegmentlist'].flat == \
correct.flat),
'segmentlist is wrong!')
correct = num.array([(0.0, 0.0), (0.0, 10.0),
(3.0, 0.0), (3.0, 10.0)])
self.assertTrue(num.allclose(data['generatedpointlist'].flat, \
correct.flat),
'Failed')
self.assertTrue(num.alltrue(data['generatedsegmentmarkerlist'] == \
num.array([1,2,3,4])),
'Failed!')
开发者ID:GeoscienceAustralia,项目名称:anuga_core,代码行数:33,代码来源:test_generate_mesh.py
注:本文中的numpy.alltrue函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论