def dataBounds(self, ax, frac=1.0, orthoRange=None):
if frac >= 1.0 and orthoRange is None and self.bounds[ax] is not None:
return self.bounds[ax]
#self.prepareGeometryChange()
if self.data is None or len(self.data) == 0:
return (None, None)
if ax == 0:
d = self.data['x']
d2 = self.data['y']
elif ax == 1:
d = self.data['y']
d2 = self.data['x']
if orthoRange is not None:
mask = (d2 >= orthoRange[0]) * (d2 <= orthoRange[1])
d = d[mask]
d2 = d2[mask]
if frac >= 1.0:
self.bounds[ax] = (np.nanmin(d) - self._maxSpotWidth*0.7072, np.nanmax(d) + self._maxSpotWidth*0.7072)
return self.bounds[ax]
elif frac <= 0.0:
raise Exception("Value for parameter 'frac' must be > 0. (got %s)" % str(frac))
else:
mask = np.isfinite(d)
d = d[mask]
return np.percentile(d, [50 * (1 - frac), 50 * (1 + frac)])
python类nanmin()的实例源码
def quickMinMax(self, data):
"""
Estimate the min/max values of *data* by subsampling.
"""
while data.size > 1e6:
ax = np.argmax(data.shape)
sl = [slice(None)] * data.ndim
sl[ax] = slice(None, None, 2)
data = data[sl]
return nanmin(data), nanmax(data)
def normalize_data(self, values):
normalized_values = copy.deepcopy(values)
data = np.array(values, dtype=float)[:, 0:5]
data_min = np.nanmin(data, 0)
data_max = np.nanmax(data, 0)
print data_min
print data_max
for i in range(len(values)):
for j in range(5):
normalized_values[i][j] = np.abs(values[i][j] - data_min[j]) / np.abs(data_max[j] - data_min[j])
return normalized_values, data_min, data_max
def writeBinData(out_file, i, GenotypeData, ScoreList, NumInfoSites):
num_lines = len(GenotypeData.accessions)
(likeliScore, likeliHoodRatio) = snpmatch.calculate_likelihoods(ScoreList, NumInfoSites)
if len(likeliScore) > 0:
NumAmb = np.where(likeliHoodRatio < snpmatch.lr_thres)[0]
if len(NumAmb) >= 1 and len(NumAmb) < num_lines:
try:
nextLikeli = np.nanmin(likeliHoodRatio[np.where(likeliHoodRatio > snpmatch.lr_thres)[0]])
except:
nextLikeli = 1
for k in NumAmb:
score = float(ScoreList[k])/NumInfoSites[k]
out_file.write("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (GenotypeData.accessions[k], int(ScoreList[k]), NumInfoSites[k], score, likeliScore[k], nextLikeli, len(NumAmb), i+1))
def image_as_uint8(im):
""" Convert the given image to uint8
If the dtype is already uint8, it is returned as-is. If the image
is float, and all values are between 0 and 1, the values are
multiplied by 255. In all other situations, the values are scaled
such that the minimum value becomes 0 and the maximum value becomes
255.
"""
if not isinstance(im, np.ndarray):
raise ValueError('image must be a numpy array')
dtype_str = str(im.dtype)
# Already uint8?
if dtype_str == 'uint8':
return im
# Handle float
mi, ma = np.nanmin(im), np.nanmax(im)
if dtype_str.startswith('float'):
if mi >= 0 and ma <= 1:
mi, ma = 0, 1
# Now make float copy before we scale
im = im.astype('float32')
# Scale the values between 0 and 255
if np.isfinite(mi) and np.isfinite(ma):
if mi:
im -= mi
if ma != 255:
im *= 255.0 / (ma - mi)
assert np.nanmax(im) < 256
return im.astype(np.uint8)
# currently not used ... the only use it to easly provide the global meta info
def test_masked(self):
mat = np.ma.fix_invalid(_ndat)
msk = mat._mask.copy()
for f in [np.nanmin]:
res = f(mat, axis=1)
tgt = f(_ndat, axis=1)
assert_equal(res, tgt)
assert_equal(mat._mask, msk)
assert_(not np.isinf(mat).any())
def test_nanmin(self):
tgt = np.min(self.mat)
for mat in self.integer_arrays():
assert_equal(np.nanmin(mat), tgt)
def data(self, data):
""" :type: numppy.ndarray """
self._assert_shape(data, self._x_indexes, self._y_indexes)
data[data == -np.inf] = 0.0
data[data == np.inf] = 0.0
self._data = data
self._min_value = np.nanmin(self.data)
self._max_value = np.nanmax(self.data)
self._data_x_indexes = list(range(data.shape[0]))
self._data_y_indexes = list(range(data.shape[1]))
self._dirty = False
def sanitize_array(array):
''' Replace NaN and Inf (there should not be any!)'''
a=np.ravel(array)
maxi = np.nanmax((filter(lambda x: x != float('inf'), a))) # Max except NaN and Inf
mini = np.nanmin((filter(lambda x: x != float('-inf'), a))) # Mini except NaN and Inf
array[array==float('inf')]=maxi
array[array==float('-inf')]=mini
mid = (maxi + mini)/2
array[np.isnan(array)]=mid
return array
def sanitize_array(array):
''' Replace NaN and Inf (there should not be any!)'''
a=np.ravel(array)
maxi = np.nanmax((filter(lambda x: x != float('inf'), a))) # Max except NaN and Inf
mini = np.nanmin((filter(lambda x: x != float('-inf'), a))) # Mini except NaN and Inf
array[array==float('inf')]=maxi
array[array==float('-inf')]=mini
mid = (maxi + mini)/2
array[np.isnan(array)]=mid
return array
def _evaluate(self,x):
'''
Returns the level of the function at each value in x as the minimum among
all of the functions. Only called internally by HARKinterpolator1D.__call__.
'''
if _isscalar(x):
y = np.nanmin([f(x) for f in self.functions])
else:
m = len(x)
fx = np.zeros((m,self.funcCount))
for j in range(self.funcCount):
fx[:,j] = self.functions[j](x)
y = np.nanmin(fx,axis=1)
return y
def _evaluate(self,x,y):
'''
Returns the level of the function at each value in (x,y) as the minimum
among all of the functions. Only called internally by
HARKinterpolator2D.__call__.
'''
if _isscalar(x):
f = np.nanmin([f(x,y) for f in self.functions])
else:
m = len(x)
temp = np.zeros((m,self.funcCount))
for j in range(self.funcCount):
temp[:,j] = self.functions[j](x,y)
f = np.nanmin(temp,axis=1)
return f
def _evaluate(self,x,y,z):
'''
Returns the level of the function at each value in (x,y,z) as the minimum
among all of the functions. Only called internally by
HARKinterpolator3D.__call__.
'''
if _isscalar(x):
f = np.nanmin([f(x,y,z) for f in self.functions])
else:
m = len(x)
temp = np.zeros((m,self.funcCount))
for j in range(self.funcCount):
temp[:,j] = self.functions[j](x,y,z)
f = np.nanmin(temp,axis=1)
return f
def replot(self, val):
'''
'''
# Update plot
self.cadence = int(val)
self.implot.set_data(self.images[int(val)])
self.implot.set_clim(vmin = np.nanmin(self.images[int(val)]), vmax = np.nanmax(self.images[int(val)]))
self.tracker1.set_xdata([self.time[self.cadence], self.time[self.cadence]])
self.tracker2.set_xdata([self.time[self.cadence], self.time[self.cadence]])
self.update_bkg()
self.update_lc()
self.update_lcbkg()
self.fig.canvas.draw()
def vmin(self):
return self._vmin if self._vmin else np.nanmin(self.hic_matrix)
def _plot(self, region=None, cax=None):
da_sub, regions_sub = sub_data_regions(self.da, self.regions, region)
da_sub_masked = np.ma.MaskedArray(da_sub, mask=np.isnan(da_sub))
bin_coords = np.r_[[(x.start - 1) for x in regions_sub], regions_sub[-1].end]
x, y = np.meshgrid(bin_coords, self.window_sizes)
self.mesh = self.ax.pcolormesh(x, y, da_sub_masked, cmap=self.colormap, vmax=self.vmax)
self.colorbar = plt.colorbar(self.mesh, cax=cax, orientation="vertical")
self.window_size_line = self.ax.axhline(self.current_window_size, color='red')
if self.log_y:
self.ax.set_yscale("log")
self.ax.set_ylim((np.nanmin(self.window_sizes), np.nanmax(self.window_sizes)))
def _plot(self, region=None, cax=None):
self._new_region(region)
bin_coords = [(x.start - 1) for x in self.sr]
ds = self.da_sub[self.init_row]
self.line, = self.ax.plot(bin_coords, ds)
if not self.is_symmetric:
self.current_cutoff = (self.ax.get_ylim()[1] - self.ax.get_ylim()[0]) / 2 + self.ax.get_ylim()[0]
else:
self.current_cutoff = self.ax.get_ylim()[1]/ 2
self.ax.axhline(0.0, linestyle='dashed', color='grey')
self.cutoff_line = self.ax.axhline(self.current_cutoff, color='r')
if self.is_symmetric:
self.cutoff_line_mirror = self.ax.axhline(-1*self.current_cutoff, color='r')
self.ax.set_ylim((np.nanmin(ds), np.nanmax(ds)))
def update(self, ix=None, cutoff=None, region=None, update_canvas=True):
if region is not None:
self._new_region(region)
if ix is not None and ix != self.current_ix:
ds = self.da_sub[ix]
self.current_ix = ix
self.line.set_ydata(ds)
self.ax.set_ylim((np.nanmin(ds), np.nanmax(ds)))
if cutoff is None:
if not self.is_symmetric:
self.update(cutoff=(self.ax.get_ylim()[1]-self.ax.get_ylim()[0])/2 + self.ax.get_ylim()[0],
update_canvas=False)
else:
self.update(cutoff=self.ax.get_ylim()[1] / 2, update_canvas=False)
if update_canvas:
self.fig.canvas.draw()
if cutoff is not None and cutoff != self.current_cutoff:
if self.is_symmetric:
self.current_cutoff = abs(cutoff)
else:
self.current_cutoff = cutoff
self.cutoff_line.set_ydata(self.current_cutoff)
if self.is_symmetric:
self.cutoff_line_mirror.set_ydata(-1*self.current_cutoff)
if update_canvas:
self.fig.canvas.draw()
def define_levels(self, nb_class, disc_func):
pot = self.pot
_min = np.nanmin(pot)
if not nb_class:
nb_class = int(get_opt_nb_class(len(pot)) - 2)
if not disc_func or "prog_geom" in disc_func:
levels = [_min] + [
np.nanmax(pot) / i for i in range(1, nb_class + 1)][::-1]
elif "equal_interval" in disc_func:
_bin = np.nanmax(pot) / nb_class
levels = [_min] + [_bin * i for i in range(1, nb_class+1)]
elif "percentiles" in disc_func:
levels = np.percentile(
np.concatenate((pot[pot.nonzero()], np.array([_min]))),
np.linspace(0.0, 100.0, nb_class+1))
elif "jenks" in disc_func:
levels = list(jenks_breaks(np.concatenate(
([_min], pot[pot.nonzero()])), nb_class))
levels[0] = levels[0] - _min * 0.01
elif "head_tail" in disc_func:
levels = head_tail_breaks(np.concatenate(
([_min], pot[pot.nonzero()])))
elif "maximal_breaks" in disc_func:
levels = maximal_breaks(np.concatenate(
([_min], pot[pot.nonzero()])), nb_class)
else:
raise ValueError
return levels
def set_range(self, x_data, y_data):
min_x, max_x = np.nanmin(x_data), np.nanmax(x_data)
min_y, max_y = np.nanmin(y_data), np.nanmax(y_data)
self.plotview.setRange(
QRectF(min_x, min_y, max_x - min_x, max_y - min_y),
padding=0.025)
self.plotview.replot()