def compute_integral(self, x_s, y_s):
if len(x_s) == 0:
return np.zeros((y_s.shape[0],)) * np.nan
closer = np.nanargmin(abs(x_s - self.limits[0]))
return y_s[:, closer]
python类nanargmin()的实例源码
def compute_draw_info(self, x, ys):
bs = self.compute_baseline(x, ys)
im = np.array([np.nanargmin(abs(x - self.limits[0]))])
dx = [self.limits[0], self.limits[0]]
dys = np.hstack((bs[:, im], ys[:, im]))
return [("curve", (dx, dys, INTEGRATE_DRAW_EDGE_PENARGS)), # line to value
("dot", (x[im], ys[:, im]))]
def update(self, arx, xarchive=None, arf=None, evals=None):
"""checks for better solutions in list `arx`.
Based on the smallest corresponding value in `arf`,
alternatively, `update` may be called with a `BestSolution`
instance like ``update(another_best_solution)`` in which case
the better solution becomes the current best.
`xarchive` is used to retrieve the genotype of a solution.
"""
if isinstance(arx, BestSolution):
if self.evalsall is None:
self.evalsall = arx.evalsall
elif arx.evalsall is not None:
self.evalsall = max((self.evalsall, arx.evalsall))
if arx.f is not None and arx.f < np.inf:
self.update([arx.x], xarchive, [arx.f], arx.evals)
return self
assert arf is not None
# find failsave minimum
minidx = np.nanargmin(arf)
if minidx is np.nan:
return
minarf = arf[minidx]
# minarf = reduce(lambda x, y: y if y and y is not np.nan
# and y < x else x, arf, np.inf)
if minarf < np.inf and (minarf < self.f or self.f is None):
self.x, self.f = arx[minidx], arf[minidx]
if xarchive is not None and xarchive.get(self.x) is not None:
self.x_geno = xarchive[self.x].get('geno')
else:
self.x_geno = None
self.evals = None if not evals else evals - len(arf) + minidx + 1
self.evalsall = evals
elif evals:
self.evalsall = evals
self.last.x = arx[minidx]
self.last.f = minarf
def test_nanargmin(self):
tgt = np.argmin(self.mat)
for mat in self.integer_arrays():
assert_equal(np.nanargmin(mat), tgt)
def nanmedoid(a, axis=1, indexonly=False):
"""
Compute the medoid along the specified axis, omitting
observations containing NaNs.
Returns the medoid of the array elements.
Parameters
----------
a : array_like
Input array or object that can be converted to an array.
axis : int
Axis along which the medoid is computed. The default
is to compute the median along the last axis of the array.
indexonly : bool, optional
If this is set to True, only the index of the medoid is returned.
Returns
-------
medoid : ndarray or int
"""
if axis == 1:
diff = a.T[:, None, :] - a.T
ssum = np.einsum('ijk,ijk->ij', diff, diff)
dist = np.nansum(np.sqrt(ssum), axis=1)
mask = np.isnan(a).any(axis=0)
dist[mask] = np.nan
idx = np.nanargmin(dist)
if indexonly:
return idx
else:
return a[:, idx]
if axis == 0:
diff = a[:, None, :] - a
ssum = np.einsum('ijk,ijk->ij', diff, diff)
dist = np.nansum(np.sqrt(ssum), axis=1)
mask = np.isnan(a).any(axis=1)
dist[mask] = np.nan
idx = np.nanargmin(dist)
if indexonly:
return idx
else:
return a[idx, :]
raise IndexError("axis {} out of bounds".format(axis))
def nanargmin(a, axis=None):
"""
Return the indices of the minimum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results
cannot be trusted if a slice contains only NaNs and Infs.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
Returns
-------
index_array : ndarray
An array of indices or a single index value.
See Also
--------
argmin, nanargmax
Examples
--------
>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmin(a)
0
>>> np.nanargmin(a)
2
>>> np.nanargmin(a, axis=0)
array([1, 1])
>>> np.nanargmin(a, axis=1)
array([1, 0])
"""
a, mask = _replace_nan(a, np.inf)
res = np.argmin(a, axis=axis)
if mask is not None:
mask = np.all(mask, axis=axis)
if np.any(mask):
raise ValueError("All-NaN slice encountered")
return res
def nanargmax(a, axis=None):
"""
Return the indices of the maximum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the
results cannot be trusted if a slice contains only NaNs and -Infs.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
Returns
-------
index_array : ndarray
An array of indices or a single index value.
See Also
--------
argmax, nanargmin
Examples
--------
>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmax(a)
0
>>> np.nanargmax(a)
1
>>> np.nanargmax(a, axis=0)
array([1, 0])
>>> np.nanargmax(a, axis=1)
array([1, 1])
"""
a, mask = _replace_nan(a, -np.inf)
res = np.argmax(a, axis=axis)
if mask is not None:
mask = np.all(mask, axis=axis)
if np.any(mask):
raise ValueError("All-NaN slice encountered")
return res
def nanargmin(a, axis=None):
"""
Return the indices of the minimum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results
cannot be trusted if a slice contains only NaNs and Infs.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
Returns
-------
index_array : ndarray
An array of indices or a single index value.
See Also
--------
argmin, nanargmax
Examples
--------
>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmin(a)
0
>>> np.nanargmin(a)
2
>>> np.nanargmin(a, axis=0)
array([1, 1])
>>> np.nanargmin(a, axis=1)
array([1, 0])
"""
a, mask = _replace_nan(a, np.inf)
res = np.argmin(a, axis=axis)
if mask is not None:
mask = np.all(mask, axis=axis)
if np.any(mask):
raise ValueError("All-NaN slice encountered")
return res
def nanargmax(a, axis=None):
"""
Return the indices of the maximum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the
results cannot be trusted if a slice contains only NaNs and -Infs.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
Returns
-------
index_array : ndarray
An array of indices or a single index value.
See Also
--------
argmax, nanargmin
Examples
--------
>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmax(a)
0
>>> np.nanargmax(a)
1
>>> np.nanargmax(a, axis=0)
array([1, 0])
>>> np.nanargmax(a, axis=1)
array([1, 1])
"""
a, mask = _replace_nan(a, -np.inf)
res = np.argmax(a, axis=axis)
if mask is not None:
mask = np.all(mask, axis=axis)
if np.any(mask):
raise ValueError("All-NaN slice encountered")
return res
def nicecolorbar(self,
axcb=None,
reflevel=None,
label=None,
vmax=None,
vmin=None,
data=None,
loc='head right',
fontsize=8,
ticks = None):
if not axcb:
axcb = matplotlib.pyplot.gca()
divider = make_axes_locatable(axcb)
# this code is from
# http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html#axes-grid1
cax = divider.append_axes("right", size="2%", pad=0.15)
levels = numpy.asarray([0.001,0.0025,0.005,0.01,0.025,0.05,0.1,0.25,0.5,1,2.5,5,10,25,50,100,250,500,1000])
if vmax!= None and vmin != None:
level = levels[numpy.nanargmin(abs((vmax - vmin)/5 - levels))]
ticks = numpy.arange(vmin, vmax, level)
elif vmax :
level = levels[numpy.nanargmin(abs((vmax - numpy.nanmin(data))/5 - levels))]
ticks = numpy.arange(numpy.nanmin(data), vmax, level)
elif data is not None:
level = None #levels[numpy.nanargmin(abs((numpy.nanmax(data) - numpy.nanmin(data))/5 - levels))]
ticks = None #numpy.arange(numpy.nanmin(data), numpy.nanmax(data), level)
#ticks -= numpy.nanmin(abs(ticks))
cb = matplotlib.pyplot.colorbar(self,
cax=cax,
label=label,
orientation='vertical',
extend='both',
spacing='uniform',
ticks=ticks)
if vmax!= None and vmin != None:
#print(ticks,vmin,vmax)
cb.set_clim(vmin, vmax)
cb.ax.yaxis.set_ticks_position('right')
cb.ax.yaxis.set_label_position('right')
cb.ax.set_yticklabels(cb.ax.get_yticklabels(), rotation='vertical',fontsize=fontsize)
#if reflevel:
# cb.ax.axhline((reflevel-min(cb.get_clim()))/numpy.diff(cb.get_clim()),zorder=999,color='k',linewidth=2)
return cb
def nanargmin(a, axis=None):
"""
Return the indices of the minimum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results
cannot be trusted if a slice contains only NaNs and Infs.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
Returns
-------
index_array : ndarray
An array of indices or a single index value.
See Also
--------
argmin, nanargmax
Examples
--------
>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmin(a)
0
>>> np.nanargmin(a)
2
>>> np.nanargmin(a, axis=0)
array([1, 1])
>>> np.nanargmin(a, axis=1)
array([1, 0])
"""
a, mask = _replace_nan(a, np.inf)
res = np.argmin(a, axis=axis)
if mask is not None:
mask = np.all(mask, axis=axis)
if np.any(mask):
raise ValueError("All-NaN slice encountered")
return res
def nanargmax(a, axis=None):
"""
Return the indices of the maximum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the
results cannot be trusted if a slice contains only NaNs and -Infs.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
Returns
-------
index_array : ndarray
An array of indices or a single index value.
See Also
--------
argmax, nanargmin
Examples
--------
>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmax(a)
0
>>> np.nanargmax(a)
1
>>> np.nanargmax(a, axis=0)
array([1, 0])
>>> np.nanargmax(a, axis=1)
array([1, 1])
"""
a, mask = _replace_nan(a, -np.inf)
res = np.argmax(a, axis=axis)
if mask is not None:
mask = np.all(mask, axis=axis)
if np.any(mask):
raise ValueError("All-NaN slice encountered")
return res
def nanargmin(a, axis=None):
"""
Return the indices of the minimum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results
cannot be trusted if a slice contains only NaNs and Infs.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
Returns
-------
index_array : ndarray
An array of indices or a single index value.
See Also
--------
argmin, nanargmax
Examples
--------
>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmin(a)
0
>>> np.nanargmin(a)
2
>>> np.nanargmin(a, axis=0)
array([1, 1])
>>> np.nanargmin(a, axis=1)
array([1, 0])
"""
a, mask = _replace_nan(a, np.inf)
res = np.argmin(a, axis=axis)
if mask is not None:
mask = np.all(mask, axis=axis)
if np.any(mask):
raise ValueError("All-NaN slice encountered")
return res
def nanargmax(a, axis=None):
"""
Return the indices of the maximum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the
results cannot be trusted if a slice contains only NaNs and -Infs.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
Returns
-------
index_array : ndarray
An array of indices or a single index value.
See Also
--------
argmax, nanargmin
Examples
--------
>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmax(a)
0
>>> np.nanargmax(a)
1
>>> np.nanargmax(a, axis=0)
array([1, 0])
>>> np.nanargmax(a, axis=1)
array([1, 1])
"""
a, mask = _replace_nan(a, -np.inf)
res = np.argmax(a, axis=axis)
if mask is not None:
mask = np.all(mask, axis=axis)
if np.any(mask):
raise ValueError("All-NaN slice encountered")
return res
def nanargmin(a, axis=None):
"""
Return the indices of the minimum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results
cannot be trusted if a slice contains only NaNs and Infs.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
Returns
-------
index_array : ndarray
An array of indices or a single index value.
See Also
--------
argmin, nanargmax
Examples
--------
>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmin(a)
0
>>> np.nanargmin(a)
2
>>> np.nanargmin(a, axis=0)
array([1, 1])
>>> np.nanargmin(a, axis=1)
array([1, 0])
"""
a, mask = _replace_nan(a, np.inf)
res = np.argmin(a, axis=axis)
if mask is not None:
mask = np.all(mask, axis=axis)
if np.any(mask):
raise ValueError("All-NaN slice encountered")
return res
def nanargmax(a, axis=None):
"""
Return the indices of the maximum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the
results cannot be trusted if a slice contains only NaNs and -Infs.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
Returns
-------
index_array : ndarray
An array of indices or a single index value.
See Also
--------
argmax, nanargmin
Examples
--------
>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmax(a)
0
>>> np.nanargmax(a)
1
>>> np.nanargmax(a, axis=0)
array([1, 0])
>>> np.nanargmax(a, axis=1)
array([1, 1])
"""
a, mask = _replace_nan(a, -np.inf)
res = np.argmax(a, axis=axis)
if mask is not None:
mask = np.all(mask, axis=axis)
if np.any(mask):
raise ValueError("All-NaN slice encountered")
return res
def get_ray_lengths(self,x=None,y=None,PositionTol = 3,Coords='Display'):
# Work out ray lengths for all raytraced pixels
RayLength = np.sqrt(np.sum( (self.ray_end_coords - self.ray_start_coords) **2,axis=-1))
# If no x and y given, return them all
if x is None and y is None:
if self.fullchip:
if Coords.lower() == 'display':
return RayLength
else:
return self.transform.display_to_original_image(RayLength,binning=self.binning)
else:
return RayLength
else:
if self.x is None or self.y is None:
raise Exception('This ray data does not have x and y pixel indices!')
# Otherwise, return the ones at given x and y pixel coords.
if np.shape(x) != np.shape(y):
raise ValueError('x and y arrays must be the same shape!')
else:
if Coords.lower() == 'original':
x,y = self.transform.original_to_display_coords(x,y)
orig_shape = np.shape(x)
x = np.reshape(x,np.size(x),order='F')
y = np.reshape(y,np.size(y),order='F')
RL = np.zeros(np.shape(x))
RayLength = RayLength.flatten()
xflat = self.x.flatten()
yflat = self.y.flatten()
for pointno in range(x.size):
if np.isnan(x[pointno]) or np.isnan(y[pointno]):
RL[pointno] = np.nan
continue
deltaX = xflat - x[pointno]
deltaY = yflat - y[pointno]
deltaR = np.sqrt(deltaX**2 + deltaY**2)
if np.nanmin(deltaR) <= PositionTol:
RL[pointno] = RayLength[np.nanargmin(deltaR)]
else:
raise Exception('No ray-traced pixel within PositionTol of requested pixel!')
return np.reshape(RL,orig_shape,order='F')
# Return unit vectors of sight-line direction for each pixel.
def _compute_projection_pick(artist, path, xy):
"""Project *xy* on *path* to obtain a `Selection` for *artist*.
*path* is first transformed to screen coordinates using the artist
transform, and the target of the returned `Selection` is transformed
back to data coordinates using the artist *axes* inverse transform. The
`Selection` `index` is returned as a float. This function returns ``None``
for degenerate inputs.
The caller is responsible for converting the index to the proper class if
needed.
"""
transform = artist.get_transform().frozen()
tpath = (path.cleaned(transform) if transform.is_affine
# `cleaned` only handles affine transforms.
else transform.transform_path(path).cleaned())
# `cleaned` should return a path where the first element is `MOVETO`, the
# following are `LINETO` or `CLOSEPOLY`, and the last one is `STOP`, i.e.
# codes = path.codes
# assert (codes[0], codes[-1]) == (path.MOVETO, path.STOP)
# assert np.in1d(codes[1:-1], [path.LINETO, path.CLOSEPOLY]).all()
vertices = tpath.vertices[:-1]
codes = tpath.codes[:-1]
vertices[codes == tpath.CLOSEPOLY] = vertices[0]
# Unit vectors for each segment.
us = vertices[1:] - vertices[:-1]
ls = np.hypot(*us.T)
with np.errstate(invalid="ignore"):
# Results in 0/0 for repeated consecutive points.
us /= ls[:, None]
# Vectors from each vertex to the event (overwritten below).
vs = xy - vertices[:-1]
# Clipped dot products -- `einsum` cannot be done in place, `clip` can.
dot = np.clip(np.einsum("ij,ij->i", vs, us), 0, ls, out=vs[:, 0])
# Projections.
projs = vertices[:-1] + dot[:, None] * us
ds = np.hypot(*(xy - projs).T, out=vs[:, 1])
try:
argmin = np.nanargmin(ds)
dmin = ds[argmin]
except (ValueError, IndexError): # See above re: exceptions caught.
return
else:
target = AttrArray(
artist.axes.transData.inverted().transform_point(projs[argmin]))
target.index = (
(argmin + dot[argmin] / ls[argmin])
/ (path._interpolation_steps / tpath._interpolation_steps))
return Selection(artist, target, dmin, None, None)
def _(artist, event):
# No need to call `line.contains` because we're going to redo
# the work anyways (and it was broken for step plots up to
# matplotlib/matplotlib#6645).
# Always work in screen coordinates, as this is how we need to compute
# distances. Note that the artist transform may be different from the axes
# transform (e.g., for axvline).
xy = event.x, event.y
data_xy = artist.get_xydata()
sels = []
# If markers are visible, find the closest vertex.
if artist.get_marker() not in ["None", "none", " ", "", None]:
ds = np.hypot(*(xy - artist.get_transform().transform(data_xy)).T)
try:
argmin = np.nanargmin(ds)
dmin = ds[argmin]
except (ValueError, IndexError):
# numpy 1.7.0's `nanargmin([nan])` returns nan, so
# `ds[argmin]` raises IndexError. In later versions of numpy,
# `nanargmin([nan])` raises ValueError (the release notes for 1.8.0
# are incorrect on this topic).
pass
else:
# More precise than transforming back.
target = with_attrs(artist.get_xydata()[argmin], index=argmin)
sels.append(Selection(artist, target, dmin, None, None))
# If lines are visible, find the closest projection.
if (artist.get_linestyle() not in ["None", "none", " ", "", None]
and len(artist.get_xydata()) > 1):
sel = _compute_projection_pick(artist, artist.get_path(), xy)
if sel is not None:
sel.target.index = {
"_draw_lines": lambda _, index: index,
"_draw_steps_pre": Index.pre_index,
"_draw_steps_mid": Index.mid_index,
"_draw_steps_post": Index.post_index}[
Line2D.drawStyles[artist.get_drawstyle()]](
len(data_xy), sel.target.index)
sels.append(sel)
sel = min(sels, key=lambda sel: sel.dist, default=None)
return sel if sel and sel.dist < artist.get_pickradius() else None
def mouseMoved(self, evt):
pos = evt[0]
if self.plot.sceneBoundingRect().contains(pos):
mousePoint = self.plot.vb.mapSceneToView(pos)
posx, posy = mousePoint.x(), mousePoint.y()
labels = []
for a, vs in sorted(self.reports.items()):
for v in vs:
if isinstance(v, tuple) and len(v) == 2:
if v[0] == "x":
labels.append(("%0." + str(self.important_decimals[0]) + "f") % v[1])
continue
labels.append(str(v))
labels = " ".join(labels)
self.crosshair_hidden = bool(labels)
if self.location and not labels:
fs = "%0." + str(self.important_decimals[0]) + "f %0." + str(self.important_decimals[1]) + "f"
labels = fs % (posx, posy)
self.label.setText(labels, color=(0, 0, 0))
if self.curves and len(self.curves[0][0]): # need non-zero x axis!
cache = {}
bd = None
if self.markclosest and self.plot.vb.action != ZOOMING:
xpixel, ypixel = self.plot.vb.viewPixelSize()
distances = distancetocurves(self.curves[0], posx, posy, xpixel, ypixel, r=self.MOUSE_RADIUS,
cache=cache)
try:
mindi = np.nanargmin(distances)
if distances[mindi] < self.MOUSE_RADIUS:
bd = mindi
except ValueError: # if all distances are NaN
pass
if self.highlighted != bd:
QToolTip.hideText()
if self.highlighted is not None and bd is None:
self.highlighted = None
self.highlighted_curve.hide()
if bd is not None:
self.highlighted = bd
x = self.curves[0][0]
y = self.curves[0][1][self.highlighted]
self.highlighted_curve.setData(x=x, y=y)
self.highlighted_curve.show()
self.vLine.setPos(posx)
self.hLine.setPos(posy)
self.viewhelpers_show()
else:
self.viewhelpers_hide()