Here are the examples of the python api numpy.any taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
169 Examples
5
Example 1
Project: attention-lvcsr Source File: test_opt.py
def test_no_shared_var_graph():
"""Test that the InputToGpuOptimizer optimizer make graph that don't have shared variable compiled too.
"""
a = tensor.fmatrix()
b = tensor.fmatrix()
f = theano.function([a, b], [a + b], mode=mode_with_gpu)
l = f.maker.fgraph.toposort()
assert len(l) == 4
assert numpy.any(isinstance(x.op, cuda.GpuElemwise) for x in l)
assert numpy.any(isinstance(x.op, cuda.GpuFromHost) for x in l)
assert numpy.any(isinstance(x.op, cuda.HostFromGpu) for x in l)
4
Example 2
def fitness(self, T_k, N_k):
# Eq. 75 of Scargle 2012
M_k = T_k / self.dt
N_over_M = N_k * 1. / M_k
eps = 1E-8
if np.any(N_over_M > 1 + eps):
import warnings
warnings.warn('regular events: N/M > 1. '
'Is the time step correct?')
one_m_NM = 1 - N_over_M
N_over_M[N_over_M <= 0] = 1
one_m_NM[one_m_NM <= 0] = 1
return N_k * np.log(N_over_M) + (M_k - N_k) * np.log(one_m_NM)
3
Example 3
Project: robothon Source File: extras.py
def flatnotmasked_edges(a):
"""Find the indices of the first and last not masked values in a
1D masked array. If all values are masked, returns None.
"""
m = getmask(a)
if m is nomask or not np.any(m):
return [0,-1]
unmasked = np.flatnonzero(~m)
if len(unmasked) > 0:
return unmasked[[0,-1]]
else:
return None
3
Example 4
Project: engarde Source File: generic.py
def verify_any(df, check, *args, **kwargs):
"""
Verify that any of the entries in ``check(df, *args, **kwargs)``
is true
"""
result = check(df, *args, **kwargs)
try:
assert np.any(result)
except AssertionError as e:
msg = '{} not true for any'.format(check.__name__)
e.args = (msg, df)
raise
return df
3
Example 5
Project: pylearn2 Source File: pca.py
def _update_cutoff(self):
"""
Update component cutoff shared var, based on current parameters.
"""
assert self.num_components is not None and self.num_components > 0, \
'Number of components requested must be >= 1'
v = self.v.get_value(borrow=True)
var_mask = v / v.sum() > self.min_variance
assert numpy.any(var_mask), \
'No components exceed the given min. variance'
var_cutoff = 1 + numpy.where(var_mask)[0].max()
self.component_cutoff.set_value(min(var_cutoff, self.num_components))
3
Example 6
def is_empty(self):
'''
Check if the current HyperLogLog is empty - at the state of just
initialized.
'''
if np.any(self.reg):
return False
return True
3
Example 7
Project: aospy Source File: model.py
def set_grid_data(self):
"""Populate the attrs that hold grid data."""
if self.grid_data_is_set:
return
self._set_mult_grid_attr()
if not np.any(getattr(self, 'sfc_area', None)):
try:
sfc_area = self.grid_sfc_area(self.lon, self.lat,
self.lon_bounds, self.lat_bounds)
except AttributeError:
sfc_area = self.grid_sfc_area(self.lon, self.lat)
self.sfc_area = sfc_area
try:
self.levs_thick = level_thickness(self.level)
except AttributeError:
self.level = None
self.levs_thick = None
self.grid_data_is_set = True
3
Example 8
Project: veusz Source File: axisfunction.py
def _linearInterpolWarning(self, vals, xcoords, ycoords):
'''Linear interpolation, giving out of bounds warning.'''
if N.any(vals < xcoords[0]) or N.any(vals > xcoords[-1]):
self.docuement.log(
_('Warning: values exceed bounds in axis-function'))
return N.interp(vals, xcoords, ycoords)
3
Example 9
Project: scikit-learn Source File: bicluster_newsgroups.py
def bicluster_ncut(i):
rows, cols = cocluster.get_indices(i)
if not (np.any(rows) and np.any(cols)):
import sys
return sys.float_info.max
row_complement = np.nonzero(np.logical_not(cocluster.rows_[i]))[0]
col_complement = np.nonzero(np.logical_not(cocluster.columns_[i]))[0]
# Note: the following is identical to X[rows[:, np.newaxis], cols].sum() but
# much faster in scipy <= 0.16
weight = X[rows][:, cols].sum()
cut = (X[row_complement][:, cols].sum() +
X[rows][:, col_complement].sum())
return cut / weight
3
Example 10
def _step6(state):
"""
Add the value found in Step 4 to every element of each covered row,
and subtract it from every element of each uncovered column.
Return to Step 4 without altering any stars, primes, or covered lines.
"""
# the smallest uncovered value in the matrix
if np.any(state.row_uncovered) and np.any(state.col_uncovered):
minval = np.min(state.C[state.row_uncovered], axis=0)
minval = np.min(minval[state.col_uncovered])
state.C[np.logical_not(state.row_uncovered)] += minval
state.C[:, state.col_uncovered] -= minval
return _step4
3
Example 11
def _step3(state):
"""
Cover each column containing a starred zero. If n columns are covered,
the starred zeros describe a complete set of unique assignments.
In this case, Go to DONE, otherwise, Go to Step 4.
"""
marked = (state.marked == 1)
state.col_uncovered[np.any(marked, axis=0)] = False
if marked.sum() < state.C.shape[0]:
return _step4
3
Example 12
def invHermMat2D(a_00, a_01, a_11):
"""This inverts a set of 2x2 Hermitian matrices
better check :py:func:`inv_herm_mat_2d` instead, and replace all
reference to this by the former.
"""
det = a_00 * a_11 - np.abs(a_01)**2
if np.any(det==0):
warnings.warn("The matrix is probably non invertible! %s"
%str(det[det==0]))
return a_11/det, -a_01/det, a_00/det
3
Example 13
def lnprob(p):
# Trivial prior: uniform in the log.
if np.any((-10 > p) + (p > 10)):
return -np.inf
lnprior = 0.0
# Update the kernel and compute the lnlikelihood.
kernel.pars = np.exp(p)
return lnprior + gp.lnlikelihood(y, quiet=True)
3
Example 14
def _load(self, group):
"""
Load the state of the node from a HDF5 file.
"""
# TODO/FIXME: Check that the shapes are correct!
for i in range(len(self.u)):
ui = group['u%d' % i][...]
self.u[i] = ui
old_observed = self.observed
self.observed = group['observed'][...]
# Update masks if necessary
if np.any(old_observed != self.observed):
self._update_mask()
3
Example 15
def __contains__(self, other):
"""Allow tests of the form "geom in s"
Tests whether a GeoSeries contains a geometry.
Note: This is not the same as the geometric method "contains".
"""
if isinstance(other, BaseGeometry):
return np.any(self.geom_equals(other))
else:
return False
3
Example 16
Project: root_numpy Source File: tests.py
def check_hist2array_THnSparse(hist):
hist_thnsparse = ROOT.THnSparse.CreateSparse("", "", hist)
array = rnp.hist2array(hist)
array_thnsparse = rnp.hist2array(hist_thnsparse)
# non-zero elements
assert_true(np.any(array))
# arrays should be identical
assert_array_equal(array, array_thnsparse)
3
Example 17
Project: neupy Source File: test_bam.py
def test_argument_in_predict_method(self):
dhnet = algorithms.DiscreteBAM(mode='async', n_times=1)
dhnet.train(self.data, self.hints)
self.assertTrue(np.any(one != dhnet.predict_output(half_one)[0]))
np.testing.assert_array_almost_equal(
one,
dhnet.predict_output(half_one, n_times=100)[0]
)
3
Example 18
def hstack(datasets):
"""
Wrapper for hstack method from numpy or scipy. If any of the input
datasets are sparse, then sparse.hstack is used instead of np.hstack
Args:
datasets: datasets to be stacked, all must have same shape along axis 0
Returns:
a sparse CSR matrix if any dataset in datasets is sparse
a numpy array otherwise
"""
if np.any([sparse.issparse(d) for d in datasets]):
stack = lambda x: sparse.hstack(x).tocsr()
else:
stack = np.hstack
return stack(datasets)
3
Example 19
def latexify(self, var=None, idx=''):
template_dict = self.objective_vars.copy()
template_dict['idx'] = idx
if var is not None:
template_dict['var'] = var
if self.offset is not None and np.any(self.offset == 0):
template_dict['var'] = (r'%(offset)s_{%(idx)s}' % template_dict) + var
obj = self.objective_template % template_dict
template_dict['obj'] = obj
if self.lagrange is not None:
obj = r'\lambda_{%(idx)s} %(obj)s' % template_dict
else:
obj = r'I^{\infty}(%(obj)s \leq \delta_{%(idx)s})' % template_dict
if not self.quadratic.iszero:
return ' + '.join([self.quadratic.latexify(var=var, idx=idx), obj])
return obj
3
Example 20
@doc_template_user
def seminorm(self, arg, lagrange=None, check_feasibility=False):
lagrange = seminorm.seminorm(self, arg,
check_feasibility=check_feasibility,
lagrange=lagrange)
anyneg = np.any(arg < 0 + self.tol)
v = lagrange * np.max(arg)
if not anyneg or not check_feasibility:
return v
return np.inf
3
Example 21
def can_write(self, version, symbol, data):
if isinstance(data, Panel):
frame = data.to_frame(filter_observations=False)
if np.any(frame.dtypes.values == 'object'):
return self.SERIALIZER.can_convert_to_records_without_objects(frame, symbol)
return True
return False
3
Example 22
@frequency.setter
def frequency(self, val):
if hasattr(self, '_frequency') and self._frequency is not None:
# they are updating the frequency, we may have to do somethign
attrs_to_test = [self._gamma, self._Z0, self._z0]
if any([has_len(k) for k in attrs_to_test]):
raise NotImplementedError('updating a Media frequency, with non-constant gamma/Z0/z0 is not worked out yet')
self._frequency = val
3
Example 23
Project: pyphi Source File: concept.py
def damaged_by_cut(self, subsystem):
"""Return True if this |Mice| is affected by the subsystem's cut.
The cut affects the |Mice| if it either splits the |Mice|'s
mechanism or splits the connections between the purview and
mechanism.
"""
return (subsystem.cut.splits_mechanism(self.mechanism) or
np.any(self._relevant_connections(subsystem) *
subsystem.cut_matrix == 1))
3
Example 24
def __eq__(self, other):
if isinstance(other, self.__class__):
for (lr2traj, other_lr2traj) in [(self.lr2arm_traj, other.lr2arm_traj), (self.lr2finger_traj, other.lr2finger_traj),
(self.lr2ee_traj, other.lr2ee_traj),
(self.lr2open_finger_traj, other.lr2open_finger_traj), (self.lr2close_finger_traj, other.lr2close_finger_traj)]:
if lr2traj is None:
if other_lr2traj is None:
continue
else:
return False
if set(lr2traj.keys()) != set(other_lr2traj.keys()):
return False
for lr in lr2traj.keys():
if np.any(lr2traj[lr] != other_lr2traj[lr]):
return False
return True
else:
return False
3
Example 25
def find_intersections(self, frame, ray_bundle):
"""
Extends the parent flat geometry manager by discarding in advance
impact points outside a centered rectangle.
"""
ray_prms = FiniteFlatGM.find_intersections(self, frame, ray_bundle)
ray_prms[N.any(abs(self._local[:2]) > self._half_dims, axis=0)] = N.inf
del self._local
return ray_prms
3
Example 26
Project: iris Source File: _interpolation.py
def _account_for_inverted(self, data):
if np.any(self._coord_decreasing):
dim_slices = [slice(None)] * data.ndim
for interp_dim, flip in zip(self._interp_dims,
self._coord_decreasing):
if flip:
dim_slices[interp_dim] = slice(-1, None, -1)
data = data[dim_slices]
return data
3
Example 27
def _any(arg):
if arg is True:
return True
if arg is False:
return False
return any(arg)
3
Example 28
Project: astrodendro Source File: test_is_independent.py
def test_position_criterion(self):
def position(structure, index=None, value=None):
return (np.any(structure.indices()[0] == 6) or
np.any(structure.indices()[0] == 8))
d = Dendrogram.compute(self.data, is_independent=position)
branches = [s for s in d.all_structures if s.is_branch]
leaves = [s for s in d.all_structures if s.is_leaf]
assert len(branches) == 1
assert len(leaves) == 2
# Check that leaf that used to contain pixels 1, 2, and 3 is now just
# part of the main branch.
assert np.all(branches[0].indices(subtree=False) == np.array([0, 1, 2, 3, 4, 7, 9]))
3
Example 29
Project: sherpa Source File: test_ui.py
def test_covar_as_none(self):
for stat in self.right_stats - {'wstat'}:
ui.set_stat(stat)
ui.fit()
ui.covar()
niter = 10
stat, accept, params = ui.get_draws(niter=niter)
self.assertEqual(niter + 1, stat.size)
self.assertEqual(niter + 1, accept.size)
self.assertEqual((2, niter + 1), params.shape)
self.assertTrue(numpy.any(accept))
3
Example 30
Project: py-sdm Source File: np_divs.py
def get_cross_divs(self):
self.status_fn('\nGetting cross-bag distances and divergences...')
# If anything needs its transpose also, then we just compute everything
# with the transpose; we'll nan out the unnecessary bits later.
# TODO: only compute the things we need transposed...
mask = self.mask
self.should_mask = False
if any(req.needs_transpose for f in self.metas
for req in f.needs_results):
if np.any(mask != mask.T):
mask = mask + mask.T
self.should_mask = True
self.outputs = _estimate_cross_divs(
self.features, self.indices, self.rhos,
mask.view(np.uint8), self.funcs,
self.Ks, self.max_K, self.save_all_Ks,
self.specs, self.n_meta_only,
self.progressbar, self.flann_args['cores'], self.min_dist)
3
Example 31
Project: root_numpy Source File: tests.py
def check_hist2array_THn(hist):
hist_thn = ROOT.THn.CreateHn("", "", hist)
array = rnp.hist2array(hist)
array_thn = rnp.hist2array(hist_thn)
# non-zero elements
assert_true(np.any(array))
# arrays should be identical
assert_array_equal(array, array_thn)
3
Example 32
def is_empty(self):
'''
Check if the current MinHash is empty - at the state of just
initialized.
'''
if np.any(self.hashvalues != _max_hash):
return False
return True
3
Example 33
Project: aospy Source File: calc.py
def _get_pressure_from_p_coords(self, ps, name='p', n=0):
"""Get pressure or pressure thickness array for data on p-coords."""
if np.any(self.pressure):
pressure = self.pressure
else:
pressure = self.model[n].level
if name == 'p':
return pressure
if name == 'dp':
return dp_from_p(pressure, ps)
raise ValueError("name must be 'p' or 'dp':"
"'{}'".format(name))
3
Example 34
def __init__(self, points, radius=None, center=None):
self.points = points
if np.any(center):
self.center = center
else:
self.center = np.zeros(3)
if radius:
self.radius = radius
else:
self.radius = 1
self.vertices = None
self.regions = None
self._tri = None
self._calc_vertices_regions()
3
Example 35
@Operation.factory(attrs=("keep_dims",))
def Any(a, reduction_indices, keep_dims):
"""
Any reduction op.
"""
return np.any(a, axis=tuple(reduction_indices), keepdims=keep_dims),
3
Example 36
Project: pyNCS Source File: pyST_unittest.py
def testNormalizeAER(self):
events=self.STcsSeq.exportAER(self.ch_events)
events_imported=self.STcsSeq.importAER(events,isi=True)
stnorm=self.STcsSeq.normalizeAER(events_imported)
for i in stnorm.iterkeys():
self.assert_(stnorm[i].get_nev()==events_imported[i].get_nev())
st=self.STcsSeq.generateST(events_imported,normalize=True)
self.assert_(np.any([st[0].t_start==0,st[1].t_start==0]))
3
Example 37
def __new__(cls, name, data=None,
dtype=None, shape=(), length=0,
description=None, unit=None, format=None, meta=None, copy=False):
if isinstance(data, MaskedColumn) and np.any(data.mask):
raise TypeError("Cannot convert a MaskedColumn with masked value to a Column")
self = super(IdiColumn, cls).__new__(cls, data=data, name=name, dtype=dtype,
shape=shape, length=length, description=description,
unit=unit, format=format, meta=meta)
return self
3
Example 38
Project: vasputil Source File: supercell.py
def check_cells(cell1, cell2):
"""Check to which extent two cells are compatible.
Return value -- a tuple where the first element is a boolean specifying
whether the lattices are compatible, that is, comparing the basis vectors *
lattice constants. The second element is a boolean specifying whether the
cells contain an equal amount of atoms.
"""
# First check that lattice constant * basis vectors are compatible.
latt = np.any(cell1.get_cell() \
- cell2.get_cell() < 1e-15)
# Then check that there are an equal number of atoms.
nat = natoms(cell1) == natoms(cell2)
return (latt, nat)
3
Example 39
Project: empca Source File: empca.py
def solve_coeffs(self):
"""
Solve for c[i,k] such that data[i] ~= Sum_k: c[i,k] eigvec[k]
"""
for i in range(self.nobs):
#- Only do weighted solution if really necessary
if N.any(self.weights[i] != self.weights[i,0]):
self.coeff[i] = _solve(self.eigvec.T, self.data[i], self.weights[i])
else:
self.coeff[i] = N.dot(self.eigvec, self.data[i])
self.solve_model()
3
Example 40
Project: pychemqt Source File: UI_baghouse.py
def rellenarInput(self):
UI_equip.rellenarInput(self)
if self.Equipment.kwargs["entrada"].solido:
diametros = []
for d in self.Equipment.kwargs["entrada"].solido.diametros:
diametros.append(d.config("ParticleDiameter"))
self.efic.setColumn(0, diametros)
if any(self.Equipment.kwargs["rendimientos"]):
self.efic.setColumn(1, self.Equipment.kwargs["rendimientos"])
3
Example 41
Project: deep_recommend_system Source File: exponential_test.py
def testExponentialSample(self):
with self.test_session():
lam = tf.constant([3.0, 4.0])
lam_v = [3.0, 4.0]
n = tf.constant(100000)
exponential = tf.contrib.distributions.Exponential(lam=lam)
samples = exponential.sample(n, seed=137)
sample_values = samples.eval()
self.assertEqual(sample_values.shape, (100000, 2))
self.assertFalse(np.any(sample_values < 0.0))
for i in range(2):
self.assertLess(
stats.kstest(
sample_values[:, i], stats.expon(scale=1.0/lam_v[i]).cdf)[0],
0.01)
3
Example 42
def __call__(self, *args, **kw):
# Check if is array
self.array = np.any([hasattr(a, '__iter__') for a in args])
# Check if is masked
self.masked = np.any([np.ma.isMaskedArray(a) for a in args])
newargs = [np.ma.atleast_1d(np.ma.masked_invalid(a)) for a in args]
newargs = [a.astype(np.float) for a in newargs]
ret = self.func(*newargs, **kw)
if not self.masked: # Return a filled array if not masked.
ret = np.ma.filled(ret, np.nan)
if not self.array: # Return scalar if not array.
ret = ret[0]
return ret
3
Example 43
def can_write(self, version, symbol, data):
if isinstance(data, DataFrame):
if np.any(data.dtypes.values == 'object'):
return self.SERIALIZER.can_convert_to_records_without_objects(data, symbol)
return True
return False
3
Example 44
Project: kombine Source File: twoD.py
def lnprior(self, X):
"""
Use a uniform, bounded prior.
"""
if np.any(X < self._lower_left) or np.any(X > self._upper_right):
return -np.inf
else:
return 0.0
3
Example 45
Project: lifetimes Source File: estimation.py
@staticmethod
def _negative_log_likelihood(params, frequency, avg_monetary_value, penalizer_coef=0):
if any(i < 0 for i in params):
return np.inf
p, q, v = params
x = frequency
m = avg_monetary_value
negative_log_likelihood_values = (special.gammaln(p * x + q) -
special.gammaln(p * x) -
special.gammaln(q) +
q * np.log(v) +
(p * x - 1) * np.log(m) +
(p * x) * np.log(x) -
(p * x + q) * np.log(x * m + v))
penalizer_term = penalizer_coef * log(params).sum()
return -np.sum(negative_log_likelihood_values) + penalizer_term
3
Example 46
Project: ncpol2sdpa Source File: chordal_extension.py
def find_clique_index(variables, polynomial, clique_set):
support = np.any(get_support(variables, polynomial), axis=0)
support[np.nonzero(support)[0]] = 1
for i, clique in enumerate(clique_set):
if np.dot(support, clique) == len(np.nonzero(support)[0]):
return i
return -1
3
Example 47
def isInvalid(devs, error):
"""
Check if the reduced observables differ from the original
observables more than the parameter error threshold.
"""
invalid = np.any(devs > error)
return invalid
3
Example 48
def isTerminal(self):
s = self.state
if np.any(self.statespace_limits_full[:9, 0] > s[:9]) or np.any(self.statespace_limits_full[:9, 1] < s[:9]):
return True
if len(s) <= 12:
w = np.sqrt(1. - np.sum(s[9:12] ** 2))
else:
w = s[9]
return np.abs(w) < self.MIN_QW_BEFORE_HITTING_TERMINAL_STATE
3
Example 49
Project: sherpa Source File: test_ui.py
def test_covar_as_argument(self):
for stat in self.right_stats - {'wstat'}:
ui.set_stat(stat)
ui.fit()
matrix = [[0.00064075, 0.01122127], [0.01122127, 0.20153251]]
niter = 10
stat, accept, params = ui.get_draws(niter=niter, covar_matrix=matrix)
self.assertEqual(niter + 1, stat.size)
self.assertEqual(niter + 1, accept.size)
self.assertEqual((2, niter + 1), params.shape)
self.assertTrue(numpy.any(accept))
3
Example 50
def _check_inputs(frequency, recency=None, T=None, monetary_value=None):
if recency is not None:
if T is not None and np.any(recency > T):
raise ValueError("Some values in recency vector are larger than T vector.")
if np.any(recency[frequency == 0] != 0):
raise ValueError("There exist non-zero recency values when frequency is zero.")
if np.sum((frequency - frequency.astype(int)) ** 2) != 0:
raise ValueError("There exist non-integer values in the frequency vector.")
if monetary_value is not None and np.any(monetary_value <= 0):
raise ValueError("There exist non-positive values in the monetary_value vector.")