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)
python类logical_or()的实例源码
def outer(self, a, b):
"""
Return the function applied to the outer product of a and b.
"""
(da, db) = (getdata(a), getdata(b))
d = self.f.outer(da, db)
ma = getmask(a)
mb = getmask(b)
if ma is nomask and mb is nomask:
m = nomask
else:
ma = getmaskarray(a)
mb = getmaskarray(b)
m = umath.logical_or.outer(ma, mb)
if (not m.ndim) and m:
return masked
if m is not nomask:
np.copyto(d, da, where=m)
if not d.shape:
return d
masked_d = d.view(get_masked_subclass(a, b))
masked_d._mask = m
masked_d._update_from(d)
return masked_d
def construct_embedding_matrix(self):
min_delay = numpy.min(self.delays)
max_delay = numpy.max(self.delays)
t_list = []
embedding_list = []
for i in range(self.x.shape[0]):
if (i - max_delay < 0) or (i - min_delay) >= self.x.shape[0]:
continue
delay_vector = numpy.array([self.x[i - delay] for delay in self.delays])
if numpy.any(numpy.logical_or(numpy.isnan(delay_vector), numpy.isinf(delay_vector))):
continue
t_list.append(i)
embedding_list.append(delay_vector)
if len(embedding_list) == 0:
self.t = numpy.array(t_list, dtype=float)
self.embedding_mat = numpy.zeros((0, len(self.delays)), dtype=float)
else:
self.t = numpy.array(t_list)
self.embedding_mat = numpy.array(embedding_list)
assert self.embedding_mat.shape[1] == len(self.delays)
def correlation_valid(x, y):
invalid = numpy.logical_or(numpy.isnan(x), numpy.isnan(y))
valid = numpy.logical_not(invalid)
valid_count = valid.sum()
if valid_count == 0:
corr = float('nan')
sd_x = float('nan')
sd_y = float('nan')
else:
sd_x = numpy.std(x[valid])
sd_y = numpy.std(y[valid])
if sd_x == 0 and sd_y == 0:
corr = 1.0
elif sd_x == 0 or sd_y == 0:
corr = 0.0
else:
corr = numpy.corrcoef(x[valid], y[valid])[0,1]
return corr, valid_count, sd_x, sd_y
def correlation_valid(x, y):
invalid = numpy.logical_or(numpy.isnan(x), numpy.isnan(y))
valid = numpy.logical_not(invalid)
valid_count = valid.sum()
if valid_count == 0:
corr = float('nan')
sd_x = float('nan')
sd_y = float('nan')
else:
sd_x = numpy.std(x[valid])
sd_y = numpy.std(y[valid])
if sd_x == 0 and sd_y == 0:
corr = 1.0
elif sd_x == 0 or sd_y == 0:
corr = 0.0
else:
corr = numpy.corrcoef(x[valid], y[valid])[0,1]
return corr, valid_count, sd_x, sd_y
def sutton_chen(x):
x = x.reshape((int(x.size/3), 3))
idx = np.array(list(np.arange(0, x.shape[0])) * x.shape[0])
jdx = np.concatenate([[a] * x.shape[0] for a in range(
0, x.shape[0])])
index = np.column_stack((idx, jdx))
index = index[index[:, 0] < index[:, 1], :]
rij = np.zeros(index.shape[0])
for i in range(index.shape[0]):
rij[i] = np.sqrt(np.sum((x[index[i, 0], :] - x[
index[i, 1], :]) ** 2))
f1s = np.zeros(index.shape[0])
rhos = np.zeros(index.shape[0])
for i in range(0, x.shape[0]):
idx = np.logical_or(index[:, 0] == i, index[:, 1] == i)
f1s[i] = 0.5 * (A**K) * np.sum(1/rij[idx] ** K)
rhos[i] = (A**M) * sum(1/(rij[idx]) ** M)
return np.sum(f1s - C * np.sqrt(rhos))
def gradient(self, x):
g = np.zeros(x.size, np.float64)
for i in range(x.size):
x1 = np.array(x)
x2 = np.array(x)
respl = self.reps
respr = self.reps
x1[i] = x[i] + respr
if x1[i] > self.upper[i]:
x1[i] = self.upper[i]
respr = x1[i] - x[i]
x2[i] = x[i] - respl
if x2[i] < self.lower[i]:
x2[i] = self.lower[i]
respl = x[i] - x2[i]
f1 = self.func_wrapper(x1)
f2 = self.func_wrapper(x2)
g[i] = ((f1 - f2)) / (respl + respr)
idx = np.logical_or(np.isnan(g), np.isinf(g))
g[idx] = 101.0
return g
def _idvalid(data, isinvalid=None, minval=None, maxval=None):
"""Identifies valid entries in an array and returns the corresponding
indices
Invalid values are NaN and Inf. Other invalid values can be passed using
the isinvalid keyword argument.
Parameters
----------
data : :class:`numpy:numpy.ndarray` of floats
isinvalid : list of what is considered an invalid value
"""
if isinvalid is None:
isinvalid = [-99., 99, -9999., -9999]
ix = np.ma.masked_invalid(data).mask
for el in isinvalid:
ix = np.logical_or(ix, np.ma.masked_where(data == el, data).mask)
if minval is not None:
ix = np.logical_or(ix, np.ma.masked_less(data, minval).mask)
if maxval is not None:
ix = np.logical_or(ix, np.ma.masked_greater(data, maxval).mask)
return np.where(np.logical_not(ix))[0]
sculpture_gen.py 文件源码
项目:Simple-User-Input-Sculpture-Generation
作者: ClaireKincaid
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def m_menu(self):
"""Runs the Mathmatically defined sculpture menu item."""
sin, cos = np.sin, np.cos
res = raw_input("Enter a functional definition of a volume (x**2+y**2+z**2 < 1) \n")
self.user_text = res
self.volume_data = self.bool_ops()
self.create_iso_surface(.7)
while True:
res = raw_input("Enter another functional definition of a volume (x**2+y**2+z**2 < 1) \n")
self.user_text = res
self.sec_volume_data = self.bool_ops()
self.create_iso_surface(.7, second=True)
res = raw_input("Enter a boolean operation to do with the previous solid (a = and, o = or, n = not, x = xor):\n")
if res == "a":
self.sec_volume_data = 0+ np.logical_and(my_sculpture.volume_data, my_sculpture.bool_ops())
elif res == "o":
self.sec_volume_data = 0+ np.logical_or(my_sculpture.volume_data, my_sculpture.bool_ops())
elif res == "n":
self.sec_volume_data = 0+ np.logical_not(my_sculpture.volume_data, my_sculpture.bool_ops())
elif res == "x":
self.sec_volume_data = 0+ np.logical_xor(my_sculpture.volume_data, my_sculpture.bool_ops())
self.create_iso_surface(.7, second=True)
def indexSearch(self, indexes):
"""Filters the data by a list of indexes.
Args:
indexes (list of int): List of index numbers to return.
Returns:
list: A list containing all indexes with filtered data. Matches
will be `True`, the remaining items will be `False`. If the
dataFrame is empty, an empty list will be returned.
"""
if not self._dataFrame.empty:
filter0 = self._dataFrame.index == -9999
for index in indexes:
filter1 = self._dataFrame.index == index
filter0 = np.logical_or(filter0, filter1)
return filter0
else:
return []
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)
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 outer(self, a, b):
"""
Return the function applied to the outer product of a and b.
"""
(da, db) = (getdata(a), getdata(b))
d = self.f.outer(da, db)
ma = getmask(a)
mb = getmask(b)
if ma is nomask and mb is nomask:
m = nomask
else:
ma = getmaskarray(a)
mb = getmaskarray(b)
m = umath.logical_or.outer(ma, mb)
if (not m.ndim) and m:
return masked
if m is not nomask:
np.copyto(d, da, where=m)
if not d.shape:
return d
masked_d = d.view(get_masked_subclass(a, b))
masked_d._mask = m
return masked_d
def simpleMask(config):
#params = ugali.utils.(config, kwargs)
roi = ugali.observation.roi.ROI(config)
# De-project the bin centers to get magnitude depths
mesh_x, mesh_y = numpy.meshgrid(roi.centers_x, roi.centers_y)
r = numpy.sqrt(mesh_x**2 + mesh_y**2) # Think about x, y conventions here
#z = (0. * (r > 1.)) + (21. * (r < 1.))
#z = 21. - r
#z = (21. - r) * (mesh_x > 0.) * (mesh_y < 0.)
z = (21. - r) * numpy.logical_or(mesh_x > 0., mesh_y > 0.)
return MaskBand(z, roi)
############################################################
def loaddata(filename):
if filename.find(ext)==-1: filename += ext
data = None
hdulist = pf.open(filename)
# extract data hdu per hdu
for item in hdulist:
if item.header.get(card)=='DATA':
if data is None: # first set
data = Oidata(src=item.header.get('SRC'), flatten=item.header.get('FLATTEN'), degrees=item.header.get('DEGREES'), significant_figures=item.header.get('SIG_FIG'), **{item.header.get('DATATYPE'):item.data})
else:
data.addData(src=item.header.get('SRC'), flatten=item.header.get('FLATTEN'), degrees=item.header.get('DEGREES'), significant_figures=item.header.get('SIG_FIG'), **{item.header.get('DATATYPE'):item.data})
# apply data mode per mode
for item in hdulist:
if item.header.get(card)=='DATAMASK':
theoldmask = getattr(data, item.header.get('DATATYPE')).mask
if theoldmask.shape != item.data.shape:
print("Error while applying data mask on "+item.header.get('DATATYPE'))
else:
getattr(data, item.header.get('DATATYPE')).mask = np.logical_or(theoldmask, item.data.astype(bool))
return data
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)
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 outer(self, a, b):
"""
Return the function applied to the outer product of a and b.
"""
(da, db) = (getdata(a), getdata(b))
d = self.f.outer(da, db)
ma = getmask(a)
mb = getmask(b)
if ma is nomask and mb is nomask:
m = nomask
else:
ma = getmaskarray(a)
mb = getmaskarray(b)
m = umath.logical_or.outer(ma, mb)
if (not m.ndim) and m:
return masked
if m is not nomask:
np.copyto(d, da, where=m)
if not d.shape:
return d
masked_d = d.view(get_masked_subclass(a, b))
masked_d._mask = m
return masked_d