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
python类nanargmax()的实例源码
def phase_shift( shotGather, num_vel=2048, min_frequency=5, max_frequency=100, min_velocity=1, max_velocity=1000 ):
# Ensure that min_velocity is greater than zero for numerical stability
if min_velocity < 1:
min_velocity = 1
# Frequency vector
freq = np.arange(0, shotGather.fnyq, shotGather.df)
# FFT of timeHistories (Equation 1 of Park et al. 1998).....................
U = np.fft.fft(shotGather.timeHistories, axis=0)
# Remove frequencies above/below specificied max/min frequencies and downsample (if required by zero padding)
fminID = np.argmin( np.absolute(freq-min_frequency) )
fmaxID = np.argmin( np.absolute(freq-max_frequency) )
freq_id = range(fminID,(fmaxID+1), shotGather.multiple)
freq = freq[freq_id]
U = U[freq_id, :]
# Trial velocities
v_vals = np.linspace( min_velocity, max_velocity, num_vel )
# Initialize variables
v_peak = np.zeros( np.shape(freq) )
V = np.zeros( (np.shape(v_vals)[0], len(freq)) )
pnorm = np.zeros( np.shape(V) )
# Transformation ...........................................................
# Loop through frequencies
for c in range( len(freq) ):
# Loop through trial velocities at each frequency
for r in range( np.shape(v_vals)[0] ):
# Set power equal to NaN at wavenumbers > kres
if v_vals[r] < (2*np.pi*freq[c]/shotGather.kres):
V[r,c] = float( 'nan' )
# (Equation 4 in Park et al. 1998)
else:
V[r,c] = np.abs( np.sum( U[c,:]/np.abs(U[c,:]) * np.exp( 1j*2*np.pi*freq[c]*shotGather.position / v_vals[r] ) ) )
# Identify index associated with peak power at current frequency
max_id = np.nanargmax( V[:,c] )
pnorm[:,c] = V[:,c] / V[max_id,c]
v_peak[c] = v_vals[max_id]
# Create instance of DispersionPower class..................................
dispersionPower = dctypes.DispersionPower( freq, v_peak, v_vals, 'velocity', shotGather.kres, pnorm )
return dispersionPower
#*******************************************************************************
# Slant-stack transform
def compose_ko(radargrids, qualitygrids):
"""Composes grids according to quality information using quality \
information as a knockout criterion.
The value of the composed pixel is taken from the radargrid whose
quality grid has the highest value.
Parameters
----------
radargrids : list of arrays
radar data to be composited. Each item in the list corresponds to the
data of one radar location. All items must have the same shape.
qualitygrids : list of arrays
quality data to decide upon which radar site will contribute its pixel
to the composite. Then length of this list must be the same as that
of `radargrids`. All items must have the same shape and be aligned with
the items in `radargrids`.
Returns
-------
composite : array
"""
# first add a fallback array for all pixels having missing values in all
# radargrids
radarfallback = (np.repeat(np.nan, np.prod(radargrids[0].shape))
.reshape(radargrids[0].shape))
radargrids.append(radarfallback)
radarinfo = np.array(radargrids)
# then do the same for the quality grids
qualityfallback = (np.repeat(-np.inf, np.prod(radargrids[0].shape))
.reshape(radargrids[0].shape))
qualitygrids.append(qualityfallback)
qualityinfo = np.array(qualitygrids)
select = np.nanargmax(qualityinfo, axis=0)
composite = (radarinfo.reshape((radarinfo.shape[0], -1))
[select.ravel(), np.arange(np.prod(radarinfo.shape[1:]))]
.reshape(radarinfo.shape[1:]))
radargrids.pop()
qualitygrids.pop()
return composite
def cum_beam_block_frac(pbb):
"""Cumulative beam blockage fraction along a beam.
Computes the cumulative beam blockage (cbb) along a beam from the partial
beam blockage (pbb) fraction of each bin along that beam. CBB in one bin
along a beam will always be at least as high as the maximum PBB of the
preceeding bins.
.. versionadded:: 0.10.0
Parameters
----------
pbb : :class:`numpy:numpy.ndarray`
2-D array of floats of shape (num beams, num range bins)
Partial beam blockage fraction of a bin along a beam [m]
Returns
-------
cbb : :class:`numpy:numpy.ndarray`
Array of floats of the same shape as pbb
Cumulative partial beam blockage fraction [unitless]
Examples
--------
>>> PBB = beam_block_frac(Th,Bh,a) #doctest: +SKIP
>>> CBB = cum_beam_block_frac(PBB) #doctest: +SKIP
See :ref:`notebooks/beamblockage/wradlib_beamblock.ipynb`.
"""
# This is the index of the maximum PBB along each beam
maxindex = np.nanargmax(pbb, axis=1)
cbb = np.copy(pbb)
# Iterate over all beams
for ii, index in enumerate(maxindex):
premax = 0.
for jj in range(index):
# Only iterate to max index to make this faster
if pbb[ii, jj] > premax:
cbb[ii, jj] = pbb[ii, jj]
premax = pbb[ii, jj]
else:
cbb[ii, jj] = premax
# beyond max index, everything is max anyway
cbb[ii, index:] = pbb[ii, index]
return cbb
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 _auto_low_rank_model(data, mode, n_jobs, method_params, cv,
stop_early=True, verbose=None):
"""compute latent variable models."""
method_params = cp.deepcopy(method_params)
iter_n_components = method_params.pop('iter_n_components')
if iter_n_components is None:
iter_n_components = np.arange(5, data.shape[1], 5)
from sklearn.decomposition import PCA, FactorAnalysis
if mode == 'factor_analysis':
est = FactorAnalysis
elif mode == 'pca':
est = PCA
else:
raise ValueError('Come on, this is not a low rank estimator: %s' %
mode)
est = est(**method_params)
est.n_components = 1
scores = np.empty_like(iter_n_components, dtype=np.float64)
scores.fill(np.nan)
# make sure we don't empty the thing if it's a generator
max_n = max(list(cp.deepcopy(iter_n_components)))
if max_n > data.shape[1]:
warn('You are trying to estimate %i components on matrix '
'with %i features.' % (max_n, data.shape[1]))
for ii, n in enumerate(iter_n_components):
est.n_components = n
try: # this may fail depending on rank and split
score = _cross_val(data=data, est=est, cv=cv, n_jobs=n_jobs)
except ValueError:
score = np.inf
if np.isinf(score) or score > 0:
logger.info('... infinite values encountered. stopping estimation')
break
logger.info('... rank: %i - loglik: %0.3f' % (n, score))
if score != -np.inf:
scores[ii] = score
if (ii >= 3 and np.all(np.diff(scores[ii - 3:ii]) < 0.) and
stop_early is True):
# early stop search when loglik has been going down 3 times
logger.info('early stopping parameter search.')
break
# happens if rank is too low right form the beginning
if np.isnan(scores).all():
raise RuntimeError('Oh no! Could not estimate covariance because all '
'scores were NaN. Please contact the MNE-Python '
'developers.')
i_score = np.nanargmax(scores)
best = est.n_components = iter_n_components[i_score]
logger.info('... best model at rank = %i' % best)
runtime_info = {'ranks': np.array(iter_n_components),
'scores': scores,
'best': best,
'cv': cv}
return est, runtime_info
def get_multievent_sg(cum_trace, tmin, tmax, tstart,
threshold_inside_tmin_tmax_percent,
threshold_inside_tmin_tmax_sec, threshold_after_tmax_percent):
"""
Returns the tuple (or a list of tuples, if the first argument is a stream) of the
values (score, UTCDateTime of arrival)
where scores is: 0: no double event, 1: double event inside tmin_tmax,
2: double event after tmax, 3: both double event previously defined are detected
If score is 2 or 3, the second argument is the UTCDateTime denoting the occurrence of the
first sample triggering the double event after tmax
:param trace: the input obspy.core.Trace
"""
tmin = utcdatetime(tmin)
tmax = utcdatetime(tmax)
tstart = utcdatetime(tstart)
# split traces between tmin and tmax and after tmax
traces = [cum_trace.slice(tmin, tmax), cum_trace.slice(tmax, None)]
# calculate second derivative and normalize:
second_derivs = []
max_ = np.nan
for ttt in traces:
ttt.taper(type='cosine', max_percentage=0.05)
sec_der = savitzky_golay(ttt.data, 31, 2, deriv=2)
sec_der_abs = np.abs(sec_der)
idx = np.nanargmax(sec_der_abs)
# get max (global) for normalization:
max_ = np.nanmax([max_, sec_der_abs[idx]])
second_derivs.append(sec_der_abs)
# normalize second derivatives:
for der in second_derivs:
der /= max_
result = 0
# case A: see if after tmax we exceed a threshold
indices = np.where(second_derivs[1] >= threshold_after_tmax_percent)[0]
if len(indices):
result = 2
# case B: see if inside tmin tmax we exceed a threshold, and in case check the duration
deltatime = 0
indices = np.where(second_derivs[0] >= threshold_inside_tmin_tmax_percent)[0]
starttime = endtime = None
if len(indices) >= 2:
idx0 = indices[0]
idx1 = indices[-1]
starttime = timeof(traces[0], idx0)
endtime = timeof(traces[0], idx1)
deltatime = endtime - starttime
if deltatime >= threshold_inside_tmin_tmax_sec:
result += 1
return result, deltatime, starttime, endtime
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