本文整理汇总了Python中numpy.digitize方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.digitize方法的具体用法?Python numpy.digitize怎么用?Python numpy.digitize使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.digitize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _radial_wvnum
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import digitize [as 别名]
def _radial_wvnum(k, l, N, nfactor):
""" Creates a radial wavenumber based on two horizontal wavenumbers
along with the appropriate index map
"""
# compute target wavenumbers
k = k.values
l = l.values
K = np.sqrt(k[np.newaxis,:]**2 + l[:,np.newaxis]**2)
nbins = int(N/nfactor)
if k.max() > l.max():
ki = np.linspace(0., l.max(), nbins)
else:
ki = np.linspace(0., k.max(), nbins)
# compute bin index
kidx = np.digitize(np.ravel(K), ki)
# compute number of points for each wavenumber
area = np.bincount(kidx)
# compute the average radial wavenumber for each bin
kr = (np.bincount(kidx, weights=K.ravel())
/ np.ma.masked_where(area==0, area))
return ki, kr[1:-1]
示例2: quantize
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import digitize [as 别名]
def quantize(self, specs, plan_id, star_ind):
r'''Compute the radius, luminosity, and combined bins for a given planet and star.
This is Rhonda's original code. It is here to allow cross-checks but is not used now.
Returns None if the planet/star lies outside the bin boundaries.'''
# return value indicating error
error_rval = (None, None, None)
# extract planet values
Rp_single = strip_units(specs['Rp'][plan_id])
a_single = strip_units(specs['a'][plan_id])
L_star = specs['L'][star_ind]
L_plan = L_star/a_single**2
# bin them
tmpbinplace_Rp = np.digitize(Rp_single, self.Rp_bins)
if tmpbinplace_Rp >= len(self.Rp_bins):
return error_rval # out of range
tmpbinplace_L = np.digitize(L_plan, self.L_bins[tmpbinplace_Rp-1])
if tmpbinplace_L >= len(self.L_bins[tmpbinplace_Rp-1]):
return error_rval # out of range
Rp_bin = tmpbinplace_Rp.item()
L_bin = tmpbinplace_L.item()
RpL_bin = tmpbinplace_L.item() + 10*tmpbinplace_Rp.item()
return Rp_bin, L_bin, RpL_bin
示例3: quantize_final
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import digitize [as 别名]
def quantize_final(self, specs, plan_id, star_ind):
r'''Compute the final radius/luminosity bin, an integer, for a given planet and star.
Returns 0 if the planet/star lies outside the bin boundaries. Returns 1..15 otherwise.'''
# extract planet and star properties
Rp_plan = strip_units(specs['Rp'][plan_id])
a_plan = strip_units(specs['a'][plan_id])
L_star = specs['L'][star_ind]
L_plan = L_star / (a_plan**2) # adjust star luminosity by distance^2 in AU
# Bin by Rp. "too low" maps to 0, and "too high" maps to len(Rp_bins).
Rp_bin = np.digitize(Rp_plan, self.Rp_bins)
# index into L_bins array: if Rp is out-of-range, index is irrelevant
Rp_bin_index = Rp_bin-1 if (Rp_bin > 0) and (Rp_bin < len(self.Rp_bins)) else 0
# bin by L
L_bin = np.digitize(L_plan, self.L_bins[Rp_bin_index])
# map the pair (Rp,L) -> RpL
# Rp_bin and L_bin are np arrays, so need to cast to integers
return self.Rp_L_to_RpL_bin[(int(Rp_bin), int(L_bin))]
示例4: _index_of
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import digitize [as 别名]
def _index_of(arr, lookup):
"""Replace scalars in an array by their indices in a lookup table.
Implicitely assume that:
* All elements of arr and lookup are non-negative integers.
* All elements or arr belong to lookup.
This is not checked for performance reasons.
"""
# Equivalent of np.digitize(arr, lookup) - 1, but much faster.
# TODO: assertions to disable in production for performance reasons.
# TODO: np.searchsorted(lookup, arr) is faster on small arrays with large
# values
lookup = np.asarray(lookup, dtype=np.int32)
m = (lookup.max() if len(lookup) else 0) + 1
tmp = np.zeros(m + 1, dtype=np.int)
# Ensure that -1 values are kept.
tmp[-1] = -1
if len(lookup):
tmp[lookup] = np.arange(len(lookup))
return tmp[arr]
示例5: bin_spikes_trials
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import digitize [as 别名]
def bin_spikes_trials(spikes, trials, bin_size=0.01):
"""
Binarizes the spike times into a raster and assigns a trial number to each bin
:param spikes: spikes object
:type spikes: Bunch
:param trials: trials object
:type trials: Bunch
:param bin_size: size, in s, of the bins
:type bin_size: float
:return: a matrix (bins, SpikeCounts), and a vector of bins size with trial ID,
and a vector bins size with the time that the bins start
"""
binned_spikes, bin_times, _ = bincount2D(spikes['times'], spikes['clusters'], bin_size)
trial_start_times = trials['intervals'][:, 0]
binned_trialIDs = np.digitize(bin_times, trial_start_times)
# correct, as index 0 is whatever happens before the first trial
binned_trialIDs_corrected = binned_trialIDs - 1
return binned_spikes.T, binned_trialIDs_corrected, bin_times
示例6: binned_statistic
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import digitize [as 别名]
def binned_statistic(coords, data, bins, statistic=None):
"""Bin data and calculate statistics on them
As :func:`scipy.stats.binned_statistic` but faster for simple
statistics.
Args:
coords: 1-dimensional numpy.array with the coordinates that should be
binned.
data: A numpy.array on which the statistic should be applied.
bins: The bins used for the binning.
statistic: So far only *mean* is implemented.
Returns:
A numpy array with statistic results.
"""
bin_indices = numpy.digitize(coords, bins)
data_sum = numpy.bincount(bin_indices, weights=data, minlength=bins.size)
data_number = numpy.bincount(bin_indices, minlength=bins.size)
return data_sum / data_number
示例7: _find_multi_iter_group
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import digitize [as 别名]
def _find_multi_iter_group(self, n_iter, master_group_name):
with self.lock:
master_group = self.we_h5file[master_group_name]
master_index = master_group['index'][...]
set_id = numpy.digitize([n_iter], master_index['iter_valid']) - 1
group_ref = master_index[set_id]['group_ref']
# Check if reference is Null
if not bool(group_ref):
return None
# This extra [0] is to work around a bug in h5py
try:
group = self.we_h5file[group_ref]
except AttributeError:
group = self.we_h5file[group_ref[0]]
else:
log.debug('h5py fixed; remove alternate code path')
log.debug('reference {!r} points to group {!r}'.format(group_ref, group))
return group
示例8: Discretize
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import digitize [as 别名]
def Discretize(self, num_points):
num_points_binned = np.digitize(num_points,
self._LogSpacedBinEdgesofPoints())
# index == 0 corresponds to boxes with 0 points. Because we plot everything
# logarithmically, this is a pain in the buttocks. For simplicity, we merely
# accumulate the boxes with 0 points into the first bin.
num_points_binned[num_points_binned == 0] = 1
num_bins = len(self._LogSpacedBinEdgesofPoints())
# index == len(self._LogSpacedBinEdgesofPoints()) corresponds to
# points with to points outside of the range of the last edge. We map
# these points back to the final bucket for simplicity.
num_points_binned[num_points_binned == num_bins] -= 1
# There is an inconsistency between how np.digitize() and np.histogram()
# index their bins and this is due to the fact that index == 0 is reserved
# for examples less than the minimum bin edge.
num_points_binned -= 1
return num_points_binned
示例9: __getitem__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import digitize [as 别名]
def __getitem__(self, index):
img = Image.open(os.path.join(self.data_dir, self.X_train[index] + self.img_ext))
img = img.convert(self.image_mode)
txt_path = os.path.join(self.data_dir, self.y_train[index] + self.annot_ext)
# We get the pose in radians
annot = open(txt_path, 'r')
line = annot.readline().split(' ')
pose = [float(line[1]), float(line[2]), float(line[3])]
# And convert to degrees.
yaw = pose[0] * 180 / np.pi
pitch = pose[1] * 180 / np.pi
roll = pose[2] * 180 / np.pi
# Fix the roll in AFLW
roll *= -1
# Bin values
bins = np.array(range(-99, 102, 3))
labels = torch.LongTensor(np.digitize([yaw, pitch, roll], bins) - 1)
cont_labels = torch.FloatTensor([yaw, pitch, roll])
if self.transform is not None:
img = self.transform(img)
return img, labels, cont_labels, self.X_train[index]
示例10: make_stats
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import digitize [as 别名]
def make_stats(dir, score, name, bounds):
bin_edges = np.linspace(bounds[0], bounds[1], 11)
binned_ind = np.digitize(score, bin_edges)
occurrence, _ = np.histogram(score, bin_edges, density=False)
bin_width = bin_edges[1] - bin_edges[0]
bin_mid = bin_edges + bin_width / 2
plt.figure()
plt.bar(bin_mid[:-1], occurrence, bin_width, facecolor='b', alpha=0.5)
plt.title(name)
plt.xlabel(name)
plt.ylabel('occurences')
plt.savefig(dir + '/' + name + '.png')
plt.close()
f = open(dir + '/{}_histo.txt'.format(name), 'w')
for i in range(bin_edges.shape[0]-1):
f.write('indices for bin {}, {} to {} : {} \n'.format(i, bin_edges[i], bin_edges[i+1], np.where(binned_ind == i+1)[0].tolist()))
示例11: DiscretizeDistMatrix
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import digitize [as 别名]
def DiscretizeDistMatrix(distm, bins=None, invalidDistanceSeparated=False):
assert (bins is not None)
result = np.digitize(distm, bins) - 1
if invalidDistanceSeparated:
## -1 and the maximum distance bin are separated
np.putmask(result, result == -1, len(bins) )
labels = range( len(bins) + 1 )
else:
## -1 and the maximum distance bin are merged into a single bin
np.putmask(result, result == -1, len(bins) -1 )
labels = range( len(bins) )
return result.astype(np.int32), np.int32(labels), bins
## calculate the natural logarithm of a matrix
示例12: discretize
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import digitize [as 别名]
def discretize(self, span=None):
if span is None:
span = self.span
else:
span = self.span = max(span, self._guess_span())
num_bins = power_of_2(int(math.ceil(span / self.epsilon)))
bins = np.linspace(0, span + self.epsilon, num=num_bins)
min_mz = self.peak_set[0].mz
# This ignores the possibility that a peak delta falls outside of span
self.indices = np.digitize([peak.mz - min_mz for peak in self.peak_set], bins)
self.binned_signal = np.zeros(num_bins)
for i, peak in enumerate(self.peak_set):
# The original implementation just set the bin to exp(intensity) of the last
# peak to fall in it, but exp() overflows with numbers higher than ~700.
#
# The absolute magnitude of the value here doesn't matter, just that it is
# non-zero?
self.binned_signal[self.indices[i]] += peak.intensity
示例13: _rejection_sampling
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import digitize [as 别名]
def _rejection_sampling(rng, sampling_d, target_d, bins, hardness, M):
bin_ind = np.digitize(hardness, bins)-1
i = 0
ratio = target_d[bin_ind] / (M*sampling_d[bin_ind])
while i < ratio.size and rng.rand() > ratio[i]:
i = i+1
return i
示例14: bin_points
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import digitize [as 别名]
def bin_points(XYZ_cms, map_size, z_bins, xy_resolution):
"""Bins points into xy-z bins
XYZ_cms is ... x H x W x3
Outputs is ... x map_size x map_size x (len(z_bins)+1)
"""
sh = XYZ_cms.shape
XYZ_cms = XYZ_cms.reshape([-1, sh[-3], sh[-2], sh[-1]])
n_z_bins = len(z_bins)+1
map_center = (map_size-1.)/2.
counts = []
isvalids = []
for XYZ_cm in XYZ_cms:
isnotnan = np.logical_not(np.isnan(XYZ_cm[:,:,0]))
X_bin = np.round(XYZ_cm[:,:,0] / xy_resolution + map_center).astype(np.int32)
Y_bin = np.round(XYZ_cm[:,:,1] / xy_resolution + map_center).astype(np.int32)
Z_bin = np.digitize(XYZ_cm[:,:,2], bins=z_bins).astype(np.int32)
isvalid = np.array([X_bin >= 0, X_bin < map_size, Y_bin >= 0, Y_bin < map_size,
Z_bin >= 0, Z_bin < n_z_bins, isnotnan])
isvalid = np.all(isvalid, axis=0)
ind = (Y_bin * map_size + X_bin) * n_z_bins + Z_bin
ind[np.logical_not(isvalid)] = 0
count = np.bincount(ind.ravel(), isvalid.ravel().astype(np.int32),
minlength=map_size*map_size*n_z_bins)
count = np.reshape(count, [map_size, map_size, n_z_bins])
counts.append(count)
isvalids.append(isvalid)
counts = np.array(counts).reshape(list(sh[:-3]) + [map_size, map_size, n_z_bins])
isvalids = np.array(isvalids).reshape(list(sh[:-3]) + [sh[-3], sh[-2], 1])
return counts, isvalids
示例15: discretize
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import digitize [as 别名]
def discretize(obs):
return tuple([int(numpy.digitize(obs[i], BINS[i])) for i in xrange(4)])