def test_testTakeTransposeInnerOuter(self):
# Test of take, transpose, inner, outer products
x = arange(24)
y = np.arange(24)
x[5:6] = masked
x = x.reshape(2, 3, 4)
y = y.reshape(2, 3, 4)
assert_(eq(np.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1))))
assert_(eq(np.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1)))
assert_(eq(np.inner(filled(x, 0), filled(y, 0)),
inner(x, y)))
assert_(eq(np.outer(filled(x, 0), filled(y, 0)),
outer(x, y)))
y = array(['abc', 1, 'def', 2, 3], object)
y[2] = masked
t = take(y, [0, 3, 4])
assert_(t[0] == 'abc')
assert_(t[1] == 2)
assert_(t[2] == 3)
python类take()的实例源码
test_old_ma.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 36
收藏 0
点赞 0
评论 0
timer_comparison.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def test_4(self):
"""
Test of take, transpose, inner, outer products.
"""
x = self.arange(24)
y = np.arange(24)
x[5:6] = self.masked
x = x.reshape(2, 3, 4)
y = y.reshape(2, 3, 4)
assert self.allequal(np.transpose(y, (2, 0, 1)), self.transpose(x, (2, 0, 1)))
assert self.allequal(np.take(y, (2, 0, 1), 1), self.take(x, (2, 0, 1), 1))
assert self.allequal(np.inner(self.filled(x, 0), self.filled(y, 0)),
self.inner(x, y))
assert self.allequal(np.outer(self.filled(x, 0), self.filled(y, 0)),
self.outer(x, y))
y = self.array(['abc', 1, 'def', 2, 3], object)
y[2] = self.masked
t = self.take(y, [0, 3, 4])
assert t[0] == 'abc'
assert t[1] == 2
assert t[2] == 3
def get_patch_values(point, target_image, radius=5, shape='circle', morfo_mask=None):
"""
To obtain the list of the values below a maks.
:param point:
:param target_image:
:param radius:
:param shape:
:param morfo_mask: To avoid computing the morphological mask at each iteration if this method is called in a loop, this can be provided as input.
:return:
"""
if morfo_mask is None:
morfo_mask = get_morphological_mask(point, target_image.shape, radius=radius, shape=shape)
coord = np.nonzero(morfo_mask.flatten())[0]
return np.take(target_image.flatten(), coord)
# def midpoint_circle_algorithm(center=(0, 0, 0), radius=4):
# x, y, z = center
# # TODO generalise the midpoint circle algorithm and use it for get_shell_for_given_radius
# pass
def glassoBonaFidePartial(gl,X,TrueCov):
#take a
ep=EmpiricalCovariance().fit(X)
emp_cov=ep.covariance_
_,precs=graph_lasso_path(X, gl.cv_alphas_)
best_score = -np.inf
best_ind=0
for i in xrange(len(gl.cv_alphas_)):
try:
this_score = log_likelihood(TrueCov, precs[i])
if this_score >= .1 / np.finfo(np.float64).eps:
this_score = np.nan
if(this_score>best_score):
best_score=this_score
best_ind=i
except:
print 'exited:',best_score
continue
covariance_, precision_, n_iter_ = graph_lasso(
emp_cov, alpha=gl.cv_alphas_[best_ind], mode=gl.mode, tol=gl.tol*5., max_iter=gl.max_iter, return_n_iter=True)
return np.abs(toPartialCorr(precision_))
def __init__(self, x, y, ival=0., sorted=False, side='left'):
if side.lower() not in ['right', 'left']:
msg = "side can take the values 'right' or 'left'"
raise ValueError(msg)
self.side = side
_x = np.asarray(x)
_y = np.asarray(y)
if _x.shape != _y.shape:
msg = "x and y do not have the same shape"
raise ValueError(msg)
if len(_x.shape) != 1:
msg = 'x and y must be 1-dimensional'
raise ValueError(msg)
self.x = np.r_[-np.inf, _x]
self.y = np.r_[ival, _y]
if not sorted:
asort = np.argsort(self.x)
self.x = np.take(self.x, asort, 0)
self.y = np.take(self.y, asort, 0)
self.n = self.x.shape[0]
def project_radii(radii, spacing, r_min, r_max):
""" Projects given radii to values between r_min and r_max; good spacing ~ 1000 """
radii_norm = radii / np.max(radii) # Normalize radii
# Determine min and max of array and generate spacing
radii_to_proj = np.around(np.linspace(np.min(radii_norm), np.max(radii_norm), spacing), 3)
values_to_proj = np.around(np.linspace(r_min, r_max, spacing), 3)
# Determine respective array positions
pos = np.array([np.argmin(np.abs(radii_to_proj -
radii_norm[entry])) for entry in range(len(radii_norm))], dtype=np.int)
# Determine new radii
return np.take(values_to_proj, pos)
###############################################################################
# HUNGARIAN (MUNKRES) ALGORITHM - TAKEN FROM SCIPY
###############################################################################
def get_wigner_seitz_radii(self, calc_for='mol1'):
""" Calculate Wigner-Seitz radii from nuclear charges """
if calc_for == 'mol1':
chg = self.chg_mol1
else:
chg = self.chg_mol2
# Wigner-Seitz Radius in A
w_s_r = (((3.0 * chg) /
(4.0 * np.pi * np.take(pse_mass_dens, chg - 1) * NA)) ** (1.0 / 3.0) * 0.01) / 1.0E-10
# Return result(s)
return w_s_r
def get_xsf_stored(self, logger, charge, xsf_type='MoKa'):
# Set up dictionary of the prestored scattering factors
xsf_dict = {'MoKa': (pse_mo_xsf_1, pse_mo_xsf_2), 'CuKa': (pse_cu_xsf_1, pse_cu_xsf_2),
'CoKa': (pse_co_xsf_1, pse_co_xsf_2), 'FeKa': (pse_fe_xsf_1, pse_fe_xsf_2),
'CrKa': (pse_cr_xsf_1, pse_cr_xsf_2)}
if not xsf_type in ['MoKa', 'CuKa', 'CoKa', 'FeKa', 'CrKa']: # Check for valid user input
logger.pt_xsf_wrong_source()
xsf_type = 'MoKa'
# Get scattering factors from nuclear charge
chosen_xsf_1, chosen_xsf_2 = xsf_dict[xsf_type]
xsf1, xsf2 = np.take(chosen_xsf_1, charge - 1), np.take(chosen_xsf_2, charge - 1)
# Return value(s)
return xsf1, xsf2
def test_TakeTransposeInnerOuter(self):
# Test of take, transpose, inner, outer products
x = arange(24)
y = np.arange(24)
x[5:6] = masked
x = x.reshape(2, 3, 4)
y = y.reshape(2, 3, 4)
assert_equal(np.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1)))
assert_equal(np.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1))
assert_equal(np.inner(filled(x, 0), filled(y, 0)),
inner(x, y))
assert_equal(np.outer(filled(x, 0), filled(y, 0)),
outer(x, y))
y = array(['abc', 1, 'def', 2, 3], object)
y[2] = masked
t = take(y, [0, 3, 4])
assert_(t[0] == 'abc')
assert_(t[1] == 2)
assert_(t[2] == 3)
def test_generic_methods(self):
# Tests some MaskedArray methods.
a = array([1, 3, 2])
assert_equal(a.any(), a._data.any())
assert_equal(a.all(), a._data.all())
assert_equal(a.argmax(), a._data.argmax())
assert_equal(a.argmin(), a._data.argmin())
assert_equal(a.choose(0, 1, 2, 3, 4), a._data.choose(0, 1, 2, 3, 4))
assert_equal(a.compress([1, 0, 1]), a._data.compress([1, 0, 1]))
assert_equal(a.conj(), a._data.conj())
assert_equal(a.conjugate(), a._data.conjugate())
m = array([[1, 2], [3, 4]])
assert_equal(m.diagonal(), m._data.diagonal())
assert_equal(a.sum(), a._data.sum())
assert_equal(a.take([1, 2]), a._data.take([1, 2]))
assert_equal(m.transpose(), m._data.transpose())
def test_testTakeTransposeInnerOuter(self):
# Test of take, transpose, inner, outer products
x = arange(24)
y = np.arange(24)
x[5:6] = masked
x = x.reshape(2, 3, 4)
y = y.reshape(2, 3, 4)
assert_(eq(np.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1))))
assert_(eq(np.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1)))
assert_(eq(np.inner(filled(x, 0), filled(y, 0)),
inner(x, y)))
assert_(eq(np.outer(filled(x, 0), filled(y, 0)),
outer(x, y)))
y = array(['abc', 1, 'def', 2, 3], object)
y[2] = masked
t = take(y, [0, 3, 4])
assert_(t[0] == 'abc')
assert_(t[1] == 2)
assert_(t[2] == 3)
def test_testArrayMethods(self):
a = array([1, 3, 2])
self.assertTrue(eq(a.any(), a._data.any()))
self.assertTrue(eq(a.all(), a._data.all()))
self.assertTrue(eq(a.argmax(), a._data.argmax()))
self.assertTrue(eq(a.argmin(), a._data.argmin()))
self.assertTrue(eq(a.choose(0, 1, 2, 3, 4),
a._data.choose(0, 1, 2, 3, 4)))
self.assertTrue(eq(a.compress([1, 0, 1]), a._data.compress([1, 0, 1])))
self.assertTrue(eq(a.conj(), a._data.conj()))
self.assertTrue(eq(a.conjugate(), a._data.conjugate()))
m = array([[1, 2], [3, 4]])
self.assertTrue(eq(m.diagonal(), m._data.diagonal()))
self.assertTrue(eq(a.sum(), a._data.sum()))
self.assertTrue(eq(a.take([1, 2]), a._data.take([1, 2])))
self.assertTrue(eq(m.transpose(), m._data.transpose()))
def test_4(self):
"""
Test of take, transpose, inner, outer products.
"""
x = self.arange(24)
y = np.arange(24)
x[5:6] = self.masked
x = x.reshape(2, 3, 4)
y = y.reshape(2, 3, 4)
assert self.allequal(np.transpose(y, (2, 0, 1)), self.transpose(x, (2, 0, 1)))
assert self.allequal(np.take(y, (2, 0, 1), 1), self.take(x, (2, 0, 1), 1))
assert self.allequal(np.inner(self.filled(x, 0), self.filled(y, 0)),
self.inner(x, y))
assert self.allequal(np.outer(self.filled(x, 0), self.filled(y, 0)),
self.outer(x, y))
y = self.array(['abc', 1, 'def', 2, 3], object)
y[2] = self.masked
t = self.take(y, [0, 3, 4])
assert t[0] == 'abc'
assert t[1] == 2
assert t[2] == 3
def take(self, indices, axis=None, out=None, mode='raise'):
"""
"""
(_data, _mask) = (self._data, self._mask)
cls = type(self)
# Make sure the indices are not masked
maskindices = getattr(indices, '_mask', nomask)
if maskindices is not nomask:
indices = indices.filled(0)
# Get the data
if out is None:
out = _data.take(indices, axis=axis, mode=mode).view(cls)
else:
np.take(_data, indices, axis=axis, mode=mode, out=out)
# Get the mask
if isinstance(out, MaskedArray):
if _mask is nomask:
outmask = maskindices
else:
outmask = _mask.take(indices, axis=axis, mode=mode)
outmask |= maskindices
out.__setmask__(outmask)
return out
# Array methods
def get_test_set(self):
""" Return the test set (the same for each inc. batch). """
scen = self.scenario
run = self.run
test_idx_list = self.LUP[scen][run][-1]
if self.preload:
test_x = np.take(self.x, test_idx_list, axis=0).astype(np.float32)
else:
# test paths
test_paths = []
for idx in test_idx_list:
test_paths.append(os.path.join(self.root, self.paths[idx]))
# test imgs
test_x = self.get_batch_from_paths(test_paths).astype(np.float32)
test_y = self.labels[scen][run][-1]
test_y = np.asarray(test_y, dtype=np.float32)
return test_x, test_y
def imcrop_tosquare(img):
"""Make any image a square image.
Parameters
----------
img : np.ndarray
Input image to crop, assumed at least 2d.
Returns
-------
crop : np.ndarray
Cropped image.
"""
size = np.min(img.shape[:2])
extra = img.shape[:2] - size
crop = img
for i in np.flatnonzero(extra):
crop = np.take(crop, extra[i] // 2 + np.r_[:size], axis=i)
return crop
def imcrop_tosquare(img):
"""Make any image a square image.
Parameters
----------
img : np.ndarray
Input image to crop, assumed at least 2d.
Returns
-------
crop : np.ndarray
Cropped image.
"""
size = np.min(img.shape[:2])
extra = img.shape[:2] - size
crop = img
for i in np.flatnonzero(extra):
crop = np.take(crop, extra[i] // 2 + np.r_[:size], axis=i)
return crop
def _get_labels(self, mask):
"""Transform a mask of class index into a mask containing actual classification labels.
Parameters
----------
mask: ndarray (shape: [width, height])
An NumPy representation of a segmentation mask. Each pixel should be a class index (see
`SemanticSegmenter.segment` function docstring).
Returns
-------
mask: ndarray (shape: [width, height])
A NumPy representation of the mask containing the true labels of the image
Raises
------
ValueError: if the true labels were not defined
"""
if self.classes is None:
raise ValueError("Class labels are not defined.")
return np.take(self.classes, mask)
def test_TakeTransposeInnerOuter(self):
# Test of take, transpose, inner, outer products
x = arange(24)
y = np.arange(24)
x[5:6] = masked
x = x.reshape(2, 3, 4)
y = y.reshape(2, 3, 4)
assert_equal(np.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1)))
assert_equal(np.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1))
assert_equal(np.inner(filled(x, 0), filled(y, 0)),
inner(x, y))
assert_equal(np.outer(filled(x, 0), filled(y, 0)),
outer(x, y))
y = array(['abc', 1, 'def', 2, 3], object)
y[2] = masked
t = take(y, [0, 3, 4])
assert_(t[0] == 'abc')
assert_(t[1] == 2)
assert_(t[2] == 3)
def test_generic_methods(self):
# Tests some MaskedArray methods.
a = array([1, 3, 2])
assert_equal(a.any(), a._data.any())
assert_equal(a.all(), a._data.all())
assert_equal(a.argmax(), a._data.argmax())
assert_equal(a.argmin(), a._data.argmin())
assert_equal(a.choose(0, 1, 2, 3, 4), a._data.choose(0, 1, 2, 3, 4))
assert_equal(a.compress([1, 0, 1]), a._data.compress([1, 0, 1]))
assert_equal(a.conj(), a._data.conj())
assert_equal(a.conjugate(), a._data.conjugate())
m = array([[1, 2], [3, 4]])
assert_equal(m.diagonal(), m._data.diagonal())
assert_equal(a.sum(), a._data.sum())
assert_equal(a.take([1, 2]), a._data.take([1, 2]))
assert_equal(m.transpose(), m._data.transpose())