本文整理汇总了Python中numpy.searchsorted方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.searchsorted方法的具体用法?Python numpy.searchsorted怎么用?Python numpy.searchsorted使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.searchsorted方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _interp_ebv
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import searchsorted [as 别名]
def _interp_ebv(self, datum, dist):
"""
Calculate samples of E(B-V) at an arbitrary distance (in kpc) for one
test coordinate.
"""
dm = 5. * (np.log10(dist) + 2.)
idx_ceil = np.searchsorted(datum['DM_bin_edges'], dm)
if idx_ceil == 0:
dist_0 = 10.**(datum['DM_bin_edges'][0]/5. - 2.)
return dist/dist_0 * datum['samples'][:,0]
elif idx_ceil == len(datum['DM_bin_edges']):
return datum['samples'][:,-1]
else:
dm_ceil = datum['DM_bin_edges'][idx_ceil]
dm_floor = datum['DM_bin_edges'][idx_ceil-1]
a = (dm_ceil - dm) / (dm_ceil - dm_floor)
return (
(1.-a) * datum['samples'][:,idx_ceil]
+ a * datum['samples'][:,idx_ceil-1]
)
示例2: get_real_index
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import searchsorted [as 别名]
def get_real_index(self, relativeIndex):
"""
Compute real index of the given relativeIndex considering
already collected indexes.
:Parameters:
#. relativeIndex (int): Atom relative index to already collected
indexes.
:Parameters:
#. index (int): Atom real index.
"""
### THIS IS NOT TESTED YET.
indexes = np.array( sorted(self.indexes) )
shift = np.searchsorted(a=indexes, v=relativeIndex, side='left')
index = relativeIndex+shift
for idx in indexes[shift:]:
if idx > index:
break
index += 1
return index
示例3: collect
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import searchsorted [as 别名]
def collect(self, index, dataDict, check=True):
"""
Collect atom given its index.
:Parameters:
#. index (int): The atom index to collect.
#. dataDict (dict): The atom data dict to collect.
#. check (boolean): Whether to check dataDict keys before
collecting. If set to False, user promises that collected
data is a dictionary and contains the needed keys.
"""
assert not self.is_collected(index), LOGGER.error("attempting to collect and already collected atom of index '%i'"%index)
# add data
if check:
assert isinstance(dataDict, dict), LOGGER.error("dataDict must be a dictionary of data where keys are dataKeys")
assert tuple(sorted(dataDict)) == self.__dataKeys, LOGGER.error("dataDict keys don't match promised dataKeys")
self.__collectedData[index] = dataDict
# set indexes sorted array
idx = np.searchsorted(a=self.__indexesSortedArray, v=index, side='left')
self.__indexesSortedArray = np.insert(self.__indexesSortedArray, idx, index)
# set state
self.__state = str(uuid.uuid1())
示例4: release
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import searchsorted [as 别名]
def release(self, index):
"""
Release atom from list of collected atoms and return its
collected data.
:Parameters:
#. index (int): The atom index to release.
:Returns:
#. dataDict (dict): The released atom collected data.
"""
if not self.is_collected(index):
LOGGER.warn("Attempting to release atom %i that is not collected."%index)
return
index = self.__collectedData.pop(index)
# set indexes sorted array
idx = np.searchsorted(a=self.__indexesSortedArray, v=index, side='left')
self.__indexesSortedArray = np.insert(self.__indexesSortedArray, idx, index)
# set state
self.__state = str(uuid.uuid1())
# return
return index
示例5: move
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import searchsorted [as 别名]
def move(self, coordinates):
"""
Move coordinates.
:Parameters:
#. coordinates (np.ndarray): The coordinates on which to apply
the transformation.
:Returns:
#. coordinates (np.ndarray): The new coordinates after applying
the transformation.
"""
if self.__randomize:
index = INT_TYPE( np.searchsorted(self.__selectionScheme, generate_random_float()) )
moveGenerator = self.__collection[ index ]
else:
moveGenerator = self.__collection[self.__step]
self.__step = (self.__step+1)%len(self.__collection)
# perform the move
return moveGenerator.move(coordinates)
示例6: sample_categorical
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import searchsorted [as 别名]
def sample_categorical(prob, rng):
"""Sample from independent categorical distributions
Each batch is an independent categorical distribution.
Parameters
----------
prob : numpy.ndarray
Probability of the categorical distribution. Shape --> (batch_num, category_num)
rng : numpy.random.RandomState
Returns
-------
ret : numpy.ndarray
Sampling result. Shape --> (batch_num,)
"""
ret = numpy.empty(prob.shape[0], dtype=numpy.float32)
for ind in range(prob.shape[0]):
ret[ind] = numpy.searchsorted(numpy.cumsum(prob[ind]), rng.rand()).clip(min=0.0,
max=prob.shape[
1] - 0.5)
return ret
示例7: sample_doc
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import searchsorted [as 别名]
def sample_doc(self, current_idx, sentence_weighted=True):
# Uses the current iteration counter to ensure we don't sample the same doc twice
if sentence_weighted:
# With sentence weighting, we sample docs proportionally to their sentence length
if self.doc_cumsum is None or len(self.doc_cumsum) != len(self.doc_lengths):
self._precalculate_doc_weights()
rand_start = self.doc_cumsum[current_idx]
rand_end = rand_start + self.cumsum_max - self.doc_lengths[current_idx]
sentence_index = randrange(rand_start, rand_end) % self.cumsum_max
sampled_doc_index = np.searchsorted(self.doc_cumsum, sentence_index, side='right')
else:
# If we don't use sentence weighting, then every doc has an equal chance to be chosen
sampled_doc_index = (current_idx + randrange(1, len(self.doc_lengths))) % len(self.doc_lengths)
assert sampled_doc_index != current_idx
if self.reduce_memory:
return self.document_shelf[str(sampled_doc_index)]
else:
return self.documents[sampled_doc_index]
示例8: residual_resample
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import searchsorted [as 别名]
def residual_resample(weights):
n = len(weights)
indices = np.zeros(n, np.uint32)
# take int(N*w) copies of each weight
num_copies = (n * weights).astype(np.uint32)
k = 0
for i in range(n):
for _ in range(num_copies[i]): # make n copies
indices[k] = i
k += 1
# use multinormial resample on the residual to fill up the rest.
residual = weights - num_copies # get fractional part
residual /= np.sum(residual)
cumsum = np.cumsum(residual)
cumsum[-1] = 1
indices[k:n] = np.searchsorted(cumsum, np.random.uniform(0, 1, n - k))
return indices
示例9: select
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import searchsorted [as 别名]
def select(self, population: Population, n: int = 1) -> Sequence[Individual]:
"""Return `n` individuals from the population.
Parameters
----------
population
A Population of Individuals.
n : int
The number of parents to select from the population. Default is 1.
Returns
-------
Sequence[Individual]
The selected Individuals.
"""
super().select(population, n)
population_total_errors = np.array([i.total_error for i in population])
sum_of_total_errors = np.sum(population_total_errors)
probabilities = 1.0 - (population_total_errors / sum_of_total_errors)
selected_ndxs = np.searchsorted(np.cumsum(probabilities), random(n))
return [population[ndx] for ndx in selected_ndxs]
示例10: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import searchsorted [as 别名]
def __init__(self, ts, granularity, start=None):
# NOTE(sileht): The whole class assumes ts is ordered and don't have
# duplicate timestamps, it uses numpy.unique that sorted list, but
# we always assume the orderd to be the same as the input.
self.granularity = granularity
self.can_derive = isinstance(granularity, numpy.timedelta64)
self.start = start
if start is None:
self._ts = ts
self._ts_for_derive = ts
else:
self._ts = ts[numpy.searchsorted(ts['timestamps'], start):]
if self.can_derive:
start_derive = start - granularity
self._ts_for_derive = ts[
numpy.searchsorted(ts['timestamps'], start_derive):
]
if self.can_derive:
self.indexes = round_timestamp(self._ts['timestamps'], granularity)
elif calendar.GROUPINGS.get(granularity):
self.indexes = calendar.GROUPINGS.get(granularity)(
self._ts['timestamps'])
self.tstamps, self.counts = numpy.unique(self.indexes,
return_counts=True)
示例11: __getitem__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import searchsorted [as 别名]
def __getitem__(self, key):
if isinstance(key, numpy.datetime64):
idx = numpy.searchsorted(self.timestamps, key)
if self.timestamps[idx] == key:
return self[idx]
raise KeyError(key)
if isinstance(key, slice):
if isinstance(key.start, numpy.datetime64):
start = numpy.searchsorted(self.timestamps, key.start)
else:
start = key.start
if isinstance(key.stop, numpy.datetime64):
stop = numpy.searchsorted(self.timestamps, key.stop)
else:
stop = key.stop
key = slice(start, stop, key.step)
return self.ts[key]
示例12: set_values
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import searchsorted [as 别名]
def set_values(self, values, before_truncate_callback=None):
"""Set the timestamps and values in this timeseries.
:param values: A sorted timeseries array.
:param before_truncate_callback: A callback function to call before
truncating the BoundTimeSerie to its
maximum size.
:return: None of the return value of before_truncate_callback
"""
if self.block_size is not None and len(self.ts) != 0:
index = numpy.searchsorted(values['timestamps'],
self.first_block_timestamp())
values = values[index:]
super(BoundTimeSerie, self).set_values(values)
if before_truncate_callback:
return_value = before_truncate_callback(self)
else:
return_value = None
self._truncate()
return return_value
示例13: truncate
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import searchsorted [as 别名]
def truncate(self, oldest_point=None):
"""Truncate the time series up to oldest_point excluded.
:param oldest_point: Oldest point to keep from, this excluded.
Default is the aggregation timespan.
:type oldest_point: numpy.datetime64 or numpy.timedelta64
:return: The oldest point that could have been kept.
"""
last = self.last
if last is None:
return
if oldest_point is None:
oldest_point = self.aggregation.timespan
if oldest_point is None:
return
if isinstance(oldest_point, numpy.timedelta64):
oldest_point = last - oldest_point
index = numpy.searchsorted(self.ts['timestamps'], oldest_point,
side='right')
self.ts = self.ts[index:]
return oldest_point
示例14: branch
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import searchsorted [as 别名]
def branch(configs, weights):
"""
Perform branching on a set of walkers by stochastic reconfiguration
Walkers are resampled with probability proportional to the weights, and the new weights are all set to be equal to the average weight.
Args:
configs: (nconfig,nelec,3) walker coordinates
weights: (nconfig,) walker weights
Returns:
configs: resampled walker configurations
weights: (nconfig,) all weights are equal to average weight
"""
nconfig = configs.configs.shape[0]
wtot = np.sum(weights)
probability = np.cumsum(weights / wtot)
base = np.random.rand()
newinds = np.searchsorted(probability, (base + np.arange(nconfig) / nconfig) % 1.0)
configs.resample(newinds)
weights.fill(wtot / nconfig)
return configs, weights
示例15: encode_edges
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import searchsorted [as 别名]
def encode_edges(edges, nodes):
"""Encode data with dictionary
Args:
edges (np.ndarray): np array of the form [node1, node2].
nodes (np.array): list of unique nodes
Returns:
np.ndarray: relabeled edges
Examples:
>>> import numpy as np
>>> edges = np.array([['A', 'B'], ['A', 'C']])
>>> nodes = np.array(['C', 'B', 'A'])
>>> print(encode_edges(edges, nodes))
[[2 1]
[2 0]]
"""
sidx = nodes.argsort()
relabeled_edges = sidx[np.searchsorted(nodes, edges, sorter=sidx)]
return relabeled_edges