def test_truth_table_logical(self):
# 2, 3 and 4 serves as true values
input1 = [0, 0, 3, 2]
input2 = [0, 4, 0, 2]
typecodes = (np.typecodes['AllFloat']
+ np.typecodes['AllInteger']
+ '?') # boolean
for dtype in map(np.dtype, typecodes):
arg1 = np.asarray(input1, dtype=dtype)
arg2 = np.asarray(input2, dtype=dtype)
# OR
out = [False, True, True, True]
for func in (np.logical_or, np.maximum):
assert_equal(func(arg1, arg2).astype(bool), out)
# AND
out = [False, False, False, True]
for func in (np.logical_and, np.minimum):
assert_equal(func(arg1, arg2).astype(bool), out)
# XOR
out = [False, True, True, False]
for func in (np.logical_xor, np.not_equal):
assert_equal(func(arg1, arg2).astype(bool), out)
python类logical_and()的实例源码
def test_object_logical(self):
a = np.array([3, None, True, False, "test", ""], dtype=object)
assert_equal(np.logical_or(a, None),
np.array([x or None for x in a], dtype=object))
assert_equal(np.logical_or(a, True),
np.array([x or True for x in a], dtype=object))
assert_equal(np.logical_or(a, 12),
np.array([x or 12 for x in a], dtype=object))
assert_equal(np.logical_or(a, "blah"),
np.array([x or "blah" for x in a], dtype=object))
assert_equal(np.logical_and(a, None),
np.array([x and None for x in a], dtype=object))
assert_equal(np.logical_and(a, True),
np.array([x and True for x in a], dtype=object))
assert_equal(np.logical_and(a, 12),
np.array([x and 12 for x in a], dtype=object))
assert_equal(np.logical_and(a, "blah"),
np.array([x and "blah" for x in a], dtype=object))
assert_equal(np.logical_not(a),
np.array([not x for x in a], dtype=object))
assert_equal(np.logical_or.reduce(a), 3)
assert_equal(np.logical_and.reduce(a), None)
def test_NotImplemented_not_returned(self):
# See gh-5964 and gh-2091. Some of these functions are not operator
# related and were fixed for other reasons in the past.
binary_funcs = [
np.power, np.add, np.subtract, np.multiply, np.divide,
np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
np.logical_and, np.logical_or, np.logical_xor, np.maximum,
np.minimum, np.mod
]
# These functions still return NotImplemented. Will be fixed in
# future.
# bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]
a = np.array('1')
b = 1
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
def _make_counts(emin, emax):
def _counts(field, data):
e = data["event_energy"].in_units("keV")
mask = np.logical_and(e >= emin, e < emax)
x = data["event_x"][mask]
y = data["event_y"][mask]
z = np.ones(x.shape)
pos = np.array([x,y,z]).transpose()
img = data.deposit(pos, method="count")
if data.has_field_parameter("sigma"):
sigma = data.get_field_parameter("sigma")
else:
sigma = None
if sigma is not None and sigma > 0.0:
kern = _astropy.conv.Gaussian2DKernel(stddev=sigma)
img[:,:,0] = _astropy.conv.convolve(img[:,:,0], kern)
return data.ds.arr(img, "counts/pixel")
return _counts
def test_particle_filter_dependency():
"""
Test dataset add_particle_filter which should automatically add
the dependency of the filter.
"""
@particle_filter(filtered_type='all', requires=['particle_type'])
def stars(pfilter, data):
filter = data[(pfilter.filtered_type, "particle_type")] == 2
return filter
@particle_filter(filtered_type='stars', requires=['creation_time'])
def young_stars(pfilter, data):
age = data.ds.current_time - data[pfilter.filtered_type, "creation_time"]
filter = np.logical_and(age.in_units('Myr') <= 5, age >= 0)
return filter
ds = yt.load(iso_galaxy)
ds.add_particle_filter('young_stars')
assert 'young_stars' in ds.particle_types
assert 'stars' in ds.particle_types
assert ('deposit', 'young_stars_cic') in ds.derived_field_list
assert ('deposit', 'stars_cic') in ds.derived_field_list
def bbox_filter(left, right, domain_width):
def myfilter(chunk, mask=None):
pos = np.array([chunk['x'], chunk['y'], chunk['z']]).T
# This hurts, but is useful for periodicity. Probably should check
# first if it is even needed for a given left/right
for i in range(3):
pos[:, i] = np.mod(pos[:, i] - left[i], domain_width[i]) + left[i]
# Now get all particles that are within the bbox
if mask is None:
mask = np.all(pos >= left, axis=1)
np.logical_and(mask, np.all(pos < right, axis=1), mask)
else:
np.logical_and(mask, np.all(pos >= left, axis=1), mask)
np.logical_and(mask, np.all(pos < right, axis=1), mask)
return mask
return myfilter
def get_transitions(states):
"""
Computes transitions given a state array
Args:
states : numpy array
States array of the form
...,4,1,1,...,1,2,2,...,2,3,3,....,3,4,...,4,1,...
Returns:
transitions : numpy array
Contains indices of all the transitions in the states array
"""
states = np.squeeze(states)
# Edge cases when starts in 1 and/or ends in 4
if states[0] == 1:
states = np.concatenate(([4], states))
if states[-1] == 4:
states = np.concatenate((states, [1]))
transitions = np.where(np.diff(states) != 0)[0] + 1
first = np.where(states == 1)[0][0]
last = np.where(states == 4)[0][-1] + 1
transitions = transitions[np.logical_and(transitions >= first, transitions <= last)]
return transitions
def get_transitions(states):
"""
Computes transitions given a state array
Args:
states : numpy array
States array of the form
...,4,1,1,...,1,2,2,...,2,3,3,....,3,4,...,4,1,...
Returns:
transitions : numpy array
Contains indices of all the transitions in the states array
"""
states = np.squeeze(states)
# Edge cases when starts in 1 and/or ends in 4
if states[0] == 1:
states = np.concatenate(([4], states))
if states[-1] == 4:
states = np.concatenate((states, [1]))
transitions = np.where(np.diff(states) != 0)[0] + 1
first = np.where(states == 1)[0][0]
last = np.where(states == 4)[0][-1] + 1
transitions = transitions[np.logical_and(transitions >= first, transitions <= last)]
return transitions
def _compute_count_purity(counts0, counts1):
""" Compute fraction of counts in putative single-cell GEMs
originating from the non-cell transcriptome """
gem_occupancy = MultiGenomeAnalysis._classify_gems(counts0, counts1)
frac0 = counts0.astype(float) / (counts0 + counts1).astype(float)
purity0 = frac0[gem_occupancy == cr_constants.GEM_CLASS_GENOME0]
purity1 = 1 - frac0[gem_occupancy == cr_constants.GEM_CLASS_GENOME1]
overall_purity = np.concatenate([purity0, purity1])
# Compute number of purity outliers
threshold0, threshold1 = 1.0, 1.0
fit_purity0 = purity0[np.logical_and(purity0 > 0, purity0 < 1)]
fit_purity1 = purity1[np.logical_and(purity1 > 0, purity1 < 1)]
if len(fit_purity0) > 1 and len(fit_purity1) > 1:
try:
alpha0, beta0, _, _ = scipy.stats.beta.fit(fit_purity0, floc=0, fscale=1)
alpha1, beta1, _, _ = scipy.stats.beta.fit(fit_purity1, floc=0, fscale=1)
threshold0 = scipy.stats.beta.ppf(cr_constants.COUNT_PURITY_OUTLIER_PROB_THRESHOLD, alpha0, beta0)
threshold1 = scipy.stats.beta.ppf(cr_constants.COUNT_PURITY_OUTLIER_PROB_THRESHOLD, alpha1, beta1)
except scipy.stats._continuous_distns.FitSolverError as e:
print >> sys.stderr, e
threshold0, threshold1 = 1.0, 1.0
except scipy.stats._continuous_distns.FitDataError as e:
print >> sys.stderr, e
threshold0, threshold1 = 1.0, 1.0
outlier0 = np.logical_and(gem_occupancy == cr_constants.GEM_CLASS_GENOME0,
frac0 < threshold0)
outlier1 = np.logical_and(gem_occupancy == cr_constants.GEM_CLASS_GENOME1,
(1-frac0) < threshold1)
n_outlier0 = sum(outlier0)
n_outlier1 = sum(outlier1)
frac_outlier0 = tk_stats.robust_divide(n_outlier0, len(purity0))
frac_outlier1 = tk_stats.robust_divide(n_outlier1, len(purity1))
is_outlier = np.logical_or(outlier0, outlier1).astype(int)
return (purity0.mean(), purity1.mean(), overall_purity.mean(),
n_outlier0, n_outlier1, frac_outlier0, frac_outlier1,
is_outlier)
def numpy_logical_and_list(list_of_logicals):
assert(len(list_of_logicals) >= 2)
output = list_of_logicals[0]
for i in range(1,len(list_of_logicals)):
output = np.logical_and(output, list_of_logicals[i])
return output
def clean_contour(in_contour, is_prob=False):
if is_prob:
pred = (in_contour >= 0.5).astype(np.float32)
else:
pred = in_contour
labels = measure.label(pred)
area = []
for l in range(1, np.amax(labels) + 1):
area.append(np.sum(labels == l))
out_contour = in_contour
out_contour[np.logical_and(labels > 0, labels != np.argmax(area) + 1)] = 0
return out_contour
def dice(im1, im2):
"""
Computes the Dice coefficient, a measure of set similarity.
Parameters
----------
im1 : array-like, bool
Any array of arbitrary size. If not boolean, will be converted.
im2 : array-like, bool
Any other array of identical size. If not boolean, will be converted.
Returns
-------
dice : float
Dice coefficient as a float on range [0,1].
Maximum similarity = 1
No similarity = 0
Notes
-----
The order of inputs for `dice` is irrelevant. The result will be
identical if `im1` and `im2` are switched.
"""
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
# Compute Dice coefficient
intersection = np.logical_and(im1, im2)
return (2. * intersection.sum() + np.finfo('float').eps) / (im1.sum() + im2.sum() + np.finfo('float').eps)
def dice(im1, im2):
"""
Computes the Dice coefficient, a measure of set similarity.
Parameters
----------
im1 : array-like, bool
Any array of arbitrary size. If not boolean, will be converted.
im2 : array-like, bool
Any other array of identical size. If not boolean, will be converted.
Returns
-------
dice : float
Dice coefficient as a float on range [0,1].
Maximum similarity = 1
No similarity = 0
Notes
-----
The order of inputs for `dice` is irrelevant. The result will be
identical if `im1` and `im2` are switched.
"""
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
# Compute Dice coefficient
intersection = np.logical_and(im1, im2)
return 2. * (intersection.sum() + np.finfo('float').eps) / (im1.sum() + im2.sum() + 2*np.finfo('float').eps)
def dice(im1, im2):
"""
Computes the Dice coefficient, a measure of set similarity.
Parameters
----------
im1 : array-like, bool
Any array of arbitrary size. If not boolean, will be converted.
im2 : array-like, bool
Any other array of identical size. If not boolean, will be converted.
Returns
-------
dice : float
Dice coefficient as a float on range [0,1].
Maximum similarity = 1
No similarity = 0
Notes
-----
The order of inputs for `dice` is irrelevant. The result will be
identical if `im1` and `im2` are switched.
"""
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
# Compute Dice coefficient
intersection = np.logical_and(im1, im2)
return 2. * (intersection.sum() + np.finfo('float').eps) / (im1.sum() + im2.sum() + 2*np.finfo('float').eps)
def dice(im1, im2):
"""
Computes the Dice coefficient, a measure of set similarity.
Parameters
----------
im1 : array-like, bool
Any array of arbitrary size. If not boolean, will be converted.
im2 : array-like, bool
Any other array of identical size. If not boolean, will be converted.
Returns
-------
dice : float
Dice coefficient as a float on range [0,1].
Maximum similarity = 1
No similarity = 0
Notes
-----
The order of inputs for `dice` is irrelevant. The result will be
identical if `im1` and `im2` are switched.
"""
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
# Compute Dice coefficient
intersection = np.logical_and(im1, im2)
return 2. * (intersection.sum() + np.finfo('float').eps) / (im1.sum() + im2.sum() + 2 * np.finfo('float').eps)
def dice(im1, im2):
"""
Computes the Dice coefficient, a measure of set similarity.
Parameters
----------
im1 : array-like, bool
Any array of arbitrary size. If not boolean, will be converted.
im2 : array-like, bool
Any other array of identical size. If not boolean, will be converted.
Returns
-------
dice : float
Dice coefficient as a float on range [0,1].
Maximum similarity = 1
No similarity = 0
Notes
-----
The order of inputs for `dice` is irrelevant. The result will be
identical if `im1` and `im2` are switched.
"""
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
# Compute Dice coefficient
intersection = np.logical_and(im1, im2)
return 2. * (intersection.sum() + np.finfo('float').eps) / (im1.sum() + im2.sum() + 2*np.finfo('float').eps)
def dice(im1, im2):
"""
Computes the Dice coefficient, a measure of set similarity.
Parameters
----------
im1 : array-like, bool
Any array of arbitrary size. If not boolean, will be converted.
im2 : array-like, bool
Any other array of identical size. If not boolean, will be converted.
Returns
-------
dice : float
Dice coefficient as a float on range [0,1].
Maximum similarity = 1
No similarity = 0
Notes
-----
The order of inputs for `dice` is irrelevant. The result will be
identical if `im1` and `im2` are switched.
"""
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
# Compute Dice coefficient
intersection = np.logical_and(im1, im2)
return 2. * intersection.sum() / (im1.sum() + im2.sum())
def dice(im1, im2):
"""
Computes the Dice coefficient, a measure of set similarity.
Parameters
----------
im1 : array-like, bool
Any array of arbitrary size. If not boolean, will be converted.
im2 : array-like, bool
Any other array of identical size. If not boolean, will be converted.
Returns
-------
dice : float
Dice coefficient as a float on range [0,1].
Maximum similarity = 1
No similarity = 0
Notes
-----
The order of inputs for `dice` is irrelevant. The result will be
identical if `im1` and `im2` are switched.
"""
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
# Compute Dice coefficient
intersection = np.logical_and(im1, im2)
return (2. * intersection.sum() + np.finfo('float').eps) / (im1.sum() + im2.sum() + np.finfo('float').eps)
def __indexs_select_pk2(self,pk2_roi_pos):
x_min = pk2_roi_pos[:,0].min()
x_max = pk2_roi_pos[:,0].max()
y_min = pk2_roi_pos[:,1].min()
y_max = pk2_roi_pos[:,1].max()
pca_1,pca_2 = self.PCAusedList.currentText().split("-")
pca_1 = np.int(pca_1)-1
pca_2 = np.int(pca_2)-1
x = np.logical_and(self.wavePCAs[:,pca_1]>x_min, \
self.wavePCAs[:,pca_1]<x_max)
y = np.logical_and(self.wavePCAs[:,pca_2]>y_min, \
self.wavePCAs[:,pca_2]<y_max)
ind_0 = np.logical_and(x, y)
ind_0 = np.where(ind_0 == True)[0]
ind_0 = np.array(ind_0,dtype=np.int32)
if ind_0.shape[0]>0:
segments = []
for i in range(pk2_roi_pos.shape[0]-1):
segments.append([pk2_roi_pos[i],pk2_roi_pos[i+1]])
segments.append([pk2_roi_pos[-1],pk2_roi_pos[0]])
segments = np.array(segments)
temp_pcas = self.wavePCAs[ind_0]
temp_pcas = temp_pcas[:,[pca_1,pca_2]]
is_intersect = np.apply_along_axis(self.__intersect_roi2,1,temp_pcas,segments,pca_1)
return ind_0[is_intersect]
else:
return np.array([],dtype=np.int32)
def __indexs_select_pk2(self,pk2_roi_pos):
x_min = pk2_roi_pos[:,0].min()
x_max = pk2_roi_pos[:,0].max()
y_min = pk2_roi_pos[:,1].min()
y_max = pk2_roi_pos[:,1].max()
pca_1,pca_2 = self.PCAusedList.currentText().split("-")
pca_1 = np.int(pca_1)-1
pca_2 = np.int(pca_2)-1
x = np.logical_and(self.wavePCAs[:,pca_1]>x_min, \
self.wavePCAs[:,pca_1]<x_max)
y = np.logical_and(self.wavePCAs[:,pca_2]>y_min, \
self.wavePCAs[:,pca_2]<y_max)
ind_0 = np.logical_and(x, y)
ind_0 = np.where(ind_0 == True)[0]
ind_0 = np.array(ind_0,dtype=np.int32)
if ind_0.shape[0]>0:
segments = []
for i in range(pk2_roi_pos.shape[0]-1):
segments.append([pk2_roi_pos[i],pk2_roi_pos[i+1]])
segments.append([pk2_roi_pos[-1],pk2_roi_pos[0]])
segments = np.array(segments)
temp_pcas = self.wavePCAs[ind_0]
temp_pcas = temp_pcas[:,[pca_1,pca_2]]
is_intersect = np.apply_along_axis(self.__intersect_roi2,1,temp_pcas,segments,pca_1)
return ind_0[is_intersect]
else:
return np.array([],dtype=np.int32)