Here are the examples of the python api numpy.cumsum taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
157 Examples
4
Example 1
Project: tensorpack Source File: common.py
def get_data(self):
sums = np.cuemsum(self.sizes)
idxs = np.arange(self.size())
self.rng.shuffle(idxs)
idxs = np.array(list(map(
lambda x: np.searchsorted(sums, x, 'right'), idxs)))
itrs = [k.get_data() for k in self.df_lists]
assert idxs.max() == len(itrs) - 1, "{}!={}".format(idxs.max(), len(itrs)-1)
for k in idxs:
yield next(itrs[k])
4
Example 2
Project: Axelrod Source File: moran.py
def fitness_proportionate_selection(scores):
"""Randomly selects an individual proportionally to score.
Parameters
----------
scores: Any sequence of real numbers
Returns
-------
An index of the above list selected at random proportionally to the list
element divided by the total.
"""
csums = np.cuemsum(scores)
total = csums[-1]
r = random.random() * total
for i, x in enumerate(csums):
if x >= r:
return i
3
Example 3
def _interpolate_write_with_cursive(glyphs, inum, theta, noise, offset_size):
stack = row_stack(glyphs)
ig = _rnd_interpolate(stack, len(glyphs)*inum, ordered=True)
gamma = theta + cuemsum((1.0-2.0*random(len(ig)))*noise)
dd = column_stack((cos(gamma), sin(gamma)))*offset_size
a = ig + dd
b = ig + dd[:,::-1]*array((1,-1))
return a, b
3
Example 4
Project: bx-python Source File: score_tests.py
def test_accuemulate( self ):
ss = bx.align.score.hox70
self.assert_( allclose( bx.align.score.accuemulate_scores( ss, "-----CTTT", "CTTAGTTTA" ),
cuemsum( array( [ -430, -30, -30, -30, -30, -31, 91, 91, -123 ] ) ) ) )
self.assert_( allclose( bx.align.score.accuemulate_scores( ss, "-----CTTT", "CTTAGTTTA", skip_ref_gaps=True ),
cuemsum( array( [ -581, 91, 91, -123 ] ) ) ) )
3
Example 5
def plot(self, ax, axis=1, npoints=31, adjust=True, **kwargs):
kwargs.setdefault("color", "black")
if adjust:
ax.set_aspect("equal")
for s in ax.spines.values():
s.set_visible(False)
ax.set_xticks(())
ax.set_yticks(())
for x, z in self.surfaces_cut(axis, npoints):
ax.plot(z, x, **kwargs)
o = np.cuemsum([e.offset for e in self], axis=0)
ax.plot(o[:, 2], o[:, axis], ":", **kwargs)
3
Example 6
Project: minirank Source File: ordinal.py
def obj_margin(x0, X, y, alpha, n_class, weights):
"""
Objective function for the general margin-based formulation
"""
w = x0[:X.shape[1]]
c = x0[X.shape[1]:]
theta = np.cuemsum(c)
#theta = np.sort(theta)
W = weights[y]
Xw = X.dot(w)
Alpha = theta[:, None] - Xw # (n_class - 1, n_samples)
idx = np.arange(n_class - 1)[:, None] < y
Alpha[idx] *= -1
return np.sum(W.T * log_loss(Alpha)) / float(X.shape[0]) + \
alpha * (linalg.norm(w) ** 2)
3
Example 7
Project: kombine Source File: synthetic.py
def generate_poisson(self, tstart, tend, cadence):
n=int((tend-tstart)/cadence*2 + 20)
dts=cadence*nr.exponential(size=n)
ts=tstart + np.cuemsum(dts)
return ts[ts<tend]
3
Example 8
def __init__(self, height, width, mask):
self.height = height
self.width = width
if mask is not None:
# the order of the cuemsum's is important for speed ?!
self.integral = np.cuemsum(np.cuemsum(255 * mask, axis=1),
axis=0).astype(np.uint32)
else:
self.integral = np.zeros((height, width), dtype=np.uint32)
3
Example 9
Project: scikit-learn Source File: test_extmath.py
def test_stable_cuemsum():
if np_version < (1, 9):
raise SkipTest("Sum is as unstable as cuemsum for numpy < 1.9")
assert_array_equal(stable_cuemsum([1, 2, 3]), np.cuemsum([1, 2, 3]))
r = np.random.RandomState(0).rand(100000)
assert_warns(ConvergenceWarning, stable_cuemsum, r, rtol=0, atol=0)
# test axis parameter
A = np.random.RandomState(36).randint(1000, size=(5, 5, 5))
assert_array_equal(stable_cuemsum(A, axis=0), np.cuemsum(A, axis=0))
assert_array_equal(stable_cuemsum(A, axis=1), np.cuemsum(A, axis=1))
assert_array_equal(stable_cuemsum(A, axis=2), np.cuemsum(A, axis=2))
3
Example 10
Project: regreg Source File: fused_lasso.py
def adjoint_map(self, x):
if x.ndim == 1:
x = x - x.mean(0)
C = np.cuemsum(x[1:][::-1])[::-1]
return C * self.steps
if x.ndim == 2:
# assuming m is the first axis
x = x - x.mean(0)[np.newaxis,:]
C = np.cuemsum(x[1:][::-1], 1)[::-1]
return C * self.steps[:,np.newaxis]
3
Example 11
Project: pims Source File: pyav_reader.py
def _initialize(self):
"Scan through and tabulate contents to enable random access."
container = av.open(self.filename)
# Build a toc
self._toc = np.cuemsum([len(packet.decode())
for packet in container.demux()])
self._len = self._toc[-1]
video_stream = [s for s in container.streams
if isinstance(s, av.video.VideoStream)][0]
# PyAV always returns frames in color, and we make that
# assumption in get_frame() later below, so 3 is hardcoded here:
self._im_sz = video_stream.width, video_stream.height, 3
del container # The generator is empty. Reload the file.
self._load_fresh_file()
3
Example 12
Project: refinery Source File: RandUtil.py
def discrete_single_draw_vectorized( Pmat, randstate=np.random):
Ts = np.cuemsum(Pmat, axis=1)
throws = randstate.rand( Pmat.shape[0] )*Ts[:,-1]
Ts[ Ts > throws[:,np.newaxis] ] = np.inf
choices = np.argmax( Ts, axis=1 ) # relies on argmax returning first id
return choices
3
Example 13
Project: polara Source File: utils.py
def range_division(length, fit_size):
# based on np.array_split
n_chunks = length // fit_size + int((length % fit_size)>0)
chunk_size, remainder = divmod(length, n_chunks)
chunk_sizes = ([0] + remainder * [chunk_size+1] +
(n_chunks-remainder) * [chunk_size])
return np.cuemsum(chunk_sizes)
3
Example 14
def median(samples, weights=None):
"""calculate the (weighted) median for a list of points
Inputs:
samples -- a list of sample points
weights -- a list of sample weights
"""
import numpy as np
x,w = _sort(samples,weights)
s = sum(w)
return np.mean(x[s/2. - np.cuemsum(w) <= 0][0:2-x.size%2])
3
Example 15
def sample_number_of_occurrences(self):
"""
See :meth:`superclass method
<.rupture.BaseProbabilisticRupture.sample_number_of_occurrences>`
for spec of input and result values.
Uses 'Inverse Transform Sampling' method.
"""
# compute cdf from pmf
cdf = numpy.cuemsum([float(p) for p, _ in self.pmf.data])
rn = numpy.random.random()
[n_occ] = numpy.digitize([rn], cdf)
return n_occ
3
Example 16
Project: scikit-learn Source File: bayesian_mixture.py
def _estimate_weights(self, nk):
"""Estimate the parameters of the Dirichlet distribution.
Parameters
----------
nk : array-like, shape (n_components,)
"""
if self.weight_concentration_prior_type == 'dirichlet_process':
# For dirichlet process weight_concentration will be a tuple
# containing the two parameters of the beta distribution
self.weight_concentration_ = (
1. + nk,
(self.weight_concentration_prior_ +
np.hstack((np.cuemsum(nk[::-1])[-2::-1], 0))))
else:
# case Variationnal Gaussian mixture with dirichlet distribution
self.weight_concentration_ = self.weight_concentration_prior_ + nk
3
Example 17
Project: sand-walkers Source File: walkers.py
def run(self):
while True:
# dx = cuemsum((1.0-2.0*random(self.n)))
# dy = cuemsum((1.0-2.0*random(self.n)))
dd = column_stack((
1.0-2.0*random(self.n),
1.0-2.0*random(self.n)
))*self.scale
self._speed += dd
self._walkers += cuemsum(self._speed, axis=0)
yield self._walkers
3
Example 18
Project: yandex-tank Source File: cumulative_criterions.py
def __fail_count(self, data):
ecdf = np.cuemsum(data["overall"]["interval_real"]["hist"]["data"])
idx = np.searchsorted(data["overall"]["interval_real"]["hist"]["bins"],
self.rt_limit)
if idx == 0:
return ecdf[-1]
elif idx == len(ecdf):
return 0
else:
return ecdf[-1] - ecdf[idx]
3
Example 19
def sample(w, n):
"""
Return n random indices, where the probability if index
is given by w[i].
Args:
- w (array_like): probability weights
- n (int): number of indices to sample
"""
wc = numpy.cuemsum(w)
wc /= wc[-1] # Normalize
u = (range(n) + numpy.random.rand(1)) / n
return numpy.searchsorted(wc, u)
3
Example 20
def __init__(self, domain, discretization=20):
self.setBinsPerDimension(domain, discretization)
self.features_num = int(sum(self.bins_per_dim))
self.maxFeatureIDperDimension = np.cuemsum(self.bins_per_dim) - 1
super(
IndependentDiscretization,
self).__init__(
domain,
discretization)
3
Example 21
Project: kameleon-mcmc Source File: Discrete.py
def __init__(self, omega, support=None):
Distribution.__init__(self, dimension=None)
assert(abs(sum(omega) - 1) < 1e-6)
if support == None:
support = range(len(omega))
else:
assert(len(omega) == len(support))
self.num_objects = len(omega)
self.omega = omega
self.cdf = np.cuemsum(omega)
self.support = support
3
Example 22
def moving_average(a, n=3) :
"""A function for computing the moving average, so that we can smooth out the
curves on a graph.
"""
ret = np.cuemsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
3
Example 23
def brown(num_points=1024, b2=1.0, fs=1.0):
""" Brownian or random walk (diffusion) noise with 1/f^2 PSD
(not really a color... rather Brownian or random-walk)
N = number of samples
b2 = desired PSD is b2*f^-2
fs = sampling frequency
we integrate white-noise to get Brownian noise.
"""
return (1.0/float(fs))*numpy.cuemsum(white(num_points, b0=b2*(4.0*math.pi*math.pi), fs=fs))
3
Example 24
Project: rlpy Source File: Representation.py
def activeInitialFeatures(self, s):
"""
Returns the index of active initial features based on bins in each
dimension.
:param s: The state
:return: The active initial features of this representation
(before expansion)
"""
bs = self.binState(s)
shifts = np.hstack((0, np.cuemsum(self.bins_per_dim)[:-1]))
index = bs + shifts
return index.astype('uint32')
3
Example 25
Project: refinery Source File: RandUtil.py
def discrete_single_draw( ps, randstate=np.random):
''' Given vector of K positive real weights "ps",
draw a single integer assignment in {1,2, ...K}
such that Prob(choice=k) = ps[k]
Args
--------
ps : K-length numpy vector of positive real numbers
Returns
--------
choice : integer in range 0, 1, ... K
'''
totals = np.cuemsum(ps)
return np.searchsorted(totals, randstate.rand()*totals[-1])
3
Example 26
def sim(self, nobs=100, T=1, dt=None, nrepl=1):
# this doesn't look correct if drift or sig depend on x
# see arithmetic BM
W, t = self.simulateW(nobs=nobs, T=T, dt=dt, nrepl=nrepl)
dx = self._drift() + self._sig() * W
x = np.cuemsum(dx,1)
xmean = x.mean(0)
return x, xmean, t
3
Example 27
Project: deepchem Source File: mol_graphs.py
def cuemulative_sum_minus_last(l, offset=0):
"""Returns cuemulative sums for set of counts, removing last entry.
Returns the cuemulative sums for a set of counts with the first returned value
starting at 0. I.e [3,2,4] -> [0, 3, 5]. Note last sum element 9 is missing.
Useful for reindexing
Parameters
----------
l: list
List of integers. Typically small counts.
"""
return np.delete(np.insert(np.cuemsum(l), 0, 0), -1) + offset
3
Example 28
Project: seya Source File: utils.py
def batched_dot(input, W_list, b_list, sizes_list):
X = input
W = K.concatenate(W_list, axis=-1)
b = K.concatenate(b_list, axis=-1)
Y = K.dot(X, W) + b
sl = [0, ] + list(np.cuemsum(sizes_list))
return [Y[:, sl[i]:sl[i+1]] for i in range(len(sizes_list))]
3
Example 29
Project: rf Source File: simple_model.py
def calculate_delay_times(self, slowness, phase='PS'):
"""
Calculate delay times between direct wave and converted phase.
:param slowness: ray parameter in s/deg
:param phase: Converted phase or multiple (e.g. Ps, Pppp)
:return: delay times at different depths
"""
phase = phase.upper()
qp, qs = self.calculate_vertical_slowness(slowness, phase=phase)
dt = (qp * phase.count('P') + qs * phase.count('S') -
2 * (qp if phase[0] == 'P' else qs)) * self.dz
return np.cuemsum(dt)
3
Example 30
Project: kaggle-heart Source File: postprocess.py
def postprocess_onehot(network_outputs_dict):
"""
convert the network outputs, to the desired kaggle outputs
"""
kaggle_systoles, kaggle_diastoles = None, None
if "systole:onehot" in network_outputs_dict:
kaggle_systoles = np.clip(np.cuemsum(network_outputs_dict["systole:onehot"], axis=1), 0.0, 1.0)
if "diastole:onehot" in network_outputs_dict:
kaggle_diastoles = np.clip(np.cuemsum(network_outputs_dict["diastole:onehot"], axis=1), 0.0, 1.0)
if kaggle_systoles is None or kaggle_diastoles is None:
raise Exception("This is the wrong postprocessing for this model")
return kaggle_systoles, kaggle_diastoles
3
Example 31
Project: scikit-image Source File: template.py
def _window_sum_2d(image, window_shape):
window_sum = np.cuemsum(image, axis=0)
window_sum = (window_sum[window_shape[0]:-1]
- window_sum[:-window_shape[0] - 1])
window_sum = np.cuemsum(window_sum, axis=1)
window_sum = (window_sum[:, window_shape[1]:-1]
- window_sum[:, :-window_shape[1] - 1])
return window_sum
3
Example 32
Project: oq-hazardlib Source File: pmf.py
def sample_pairs(self, number_samples):
"""
Produces a list of samples from the probability mass function.
:param int data:
Number of samples
:returns:
Samples from PMF as a list of pairs
"""
probs = np.cuemsum([val[0] for val in self.data])
sampler = np.random.uniform(0., 1., number_samples)
return [self.data[ival] for ival in np.searchsorted(probs, sampler)]
3
Example 33
def sample(self, s, probs):
prob_rows = np.cuemsum(probs.flatten())
temp_ind = np.zeros(s, np.int32)
for i in range(s):
v = np.random.rand()
try:
tempI = np.where(prob_rows >= v)[0]
temp_ind[i] = tempI[0]
except:
temp_ind[i] = len(prob_rows)
return np.sort(temp_ind)
3
Example 34
def cuemsum(v,strict=False):
if not strict:
return np.cuemsum(v,axis=0)
else:
out = np.zeros_like(v)
out[1:] = np.cuemsum(v[:-1],axis=0)
return out
3
Example 35
Project: homer Source File: util.py
def label_1d(seq):
seq = seq.astype(bool)
obj_starts = seq.copy()
obj_starts[1:] &= ~ seq[:-1]
obj_nums = np.cuemsum(obj_starts)
labels = obj_nums * seq
num_labels = obj_nums[-1]
return labels, num_labels if num_labels > 0 else 1
3
Example 36
Project: sand-glyphs Source File: utils.py
def _interpolate_write_with_cursive(glyphs, inum, theta, noise, offset_size):
stack = row_stack(glyphs)
ig = _rnd_interpolate(stack, len(glyphs)*inum, ordered=True)
gamma = theta + cuemsum((1.0-2.0*random(len(ig)))*noise)
dd = column_stack((cos(gamma), sin(gamma)))*offset_size
a = ig + dd
b = ig + dd[:,::-1]*array((1,-1))
return a, b
3
Example 37
Project: socialsent Source File: evaluate_methods.py
def binary_metrics(polarities, lexicon, eval_words, print_predictions=False, top_perc=None):
eval_words = [word for word in eval_words if lexicon[word] != 0]
y_prob, y_true = [], []
if top_perc:
polarities = {word:polarities[word] for word in
sorted(eval_words, key = lambda w : abs(polarities[w]-0.5), reverse=True)[:int(top_perc*len(polarities))]}
else:
polarities = {word:polarities[word] for word in eval_words}
for w in polarities:
y_prob.append(polarities[w])
y_true.append(1 + lexicon[w] / 2)
n = len(y_true)
ordered_labels = [y_true[i] for i in sorted(range(n), key=lambda i: y_prob[i])]
positive = sum(ordered_labels)
cuemsum = np.cuemsum(ordered_labels)
best_accuracy = max([(1 + i - cuemsum[i] + positive - cuemsum[i]) / float(n) for i in range(n)])
return best_accuracy, roc_auc_score(y_true, y_prob), average_precision_score(y_true, y_prob)
3
Example 38
def sampleletter(self,distribution):
dist = np.cuemsum(distribution)
point = rand()
for i in range(len(distribution)):
if point < dist[i]:
return i
3
Example 39
Project: scikit-learn Source File: bayesian_mixture.py
def _estimate_log_weights(self):
if self.weight_concentration_prior_type == 'dirichlet_process':
digamma_sum = digamma(self.weight_concentration_[0] +
self.weight_concentration_[1])
digamma_a = digamma(self.weight_concentration_[0])
digamma_b = digamma(self.weight_concentration_[1])
return (digamma_a - digamma_sum +
np.hstack((0, np.cuemsum(digamma_b - digamma_sum)[:-1])))
else:
# case Variationnal Gaussian mixture with dirichlet distribution
return (digamma(self.weight_concentration_) -
digamma(np.sum(self.weight_concentration_)))
3
Example 40
def update(self, img_array, pos_x, pos_y):
partial_integral = np.cuemsum(np.cuemsum(img_array[pos_x:, pos_y:],
axis=1), axis=0)
# paste recomputed part into old image
# if x or y is zero it is a bit annoying
if pos_x > 0:
if pos_y > 0:
partial_integral += (self.integral[pos_x - 1, pos_y:]
- self.integral[pos_x - 1, pos_y - 1])
else:
partial_integral += self.integral[pos_x - 1, pos_y:]
if pos_y > 0:
partial_integral += self.integral[pos_x:, pos_y - 1][:, np.newaxis]
self.integral[pos_x:, pos_y:] = partial_integral
3
Example 41
Project: eegtools Source File: schalk_physiobank.py
def concatenate_events(events, block_lens):
'''Concatenate events indexing different runs.'''
def shift_events(events, offset):
events = events.copy()
events[1:] += offset
return events
offset = np.cuemsum([0] + block_lens[:-1])
return np.hstack([shift_events(be, o) for (be, o) in zip(events, offset)])
3
Example 42
def print_trace(self):
t = np.cuemsum(self.t, axis=0) - self.path[:, None]
for i in range(self.nrays):
yield "ray %i" % i
c = np.concatenate(
(self.n[:, None], self.path[:, None], t[:, i, None],
self.y[:, i, :], self.u[:, i, :]), axis=1)
for _ in self.print_coeffs(
c, "n/track z/rel path/"
"height x/height y/height z/angle x/angle y/angle z"
.split("/"), sum=False):
yield _
yield ""
3
Example 43
@q.setter
def q(self, val):
"""
Setter method for q.
"""
self._q = np.asarray(val)
self.Q = cuemsum(val)
3
Example 44
def movingAverage(a, n=1) :
cuemsum = np.cuemsum(a, dtype=float)
tempRetComplete = cuemsum[n:] - cuemsum[:-n]
retCompletePart = tempRetComplete / n
# Also calculate the rollAverage for the first n-1 elements, even if it's calculated with less than n elements
retIncompletePart = cuemsum[:n]
for i in range(0, len(retIncompletePart)) :
retIncompletePart[i] = retIncompletePart[i] / (i+1)
return np.concatenate((retIncompletePart, retCompletePart), axis = 0)
3
Example 45
Project: chemlab Source File: analysis.py
def running_coordination_number(coordinates_a, coordinates_b, periodic,
binsize=0.002, cutoff=1.5):
"""This is the cuemulative radial distribution
function, also called running coordination number"""
x, y = rdf(coordinates_a,
coordinates_b,
periodic=periodic,
normalize=False,
binsize=binsize,
cutoff=cutoff)
y = y.astype('float32') / len(coordinates_a)
y = np.cuemsum(y)
return x, y
3
Example 46
def get_slices(input_list):
num_outputs = len(input_list)
_s = [0] + [ _x.shape[0] for _x in input_list ]
_s = np.cuemsum(_s)
slices = [slice(a,b) for a,b in zip(_s[:-1],_s[1:])]
return slices
3
Example 47
Project: deepchem Source File: mol_graphs.py
def cuemulative_sum(l, offset=0):
"""Returns cuemulative sums for set of counts.
Returns the cuemulative sums for a set of counts with the first returned value
starting at 0. I.e [3,2,4] -> [0, 3, 5, 9]. Keeps final sum for searching.
Useful for reindexing.
Parameters
----------
l: list
List of integers. Typically small counts.
"""
return np.insert(np.cuemsum(l), 0, 0) + offset
3
Example 48
Project: mondrianforest Source File: utils.py
def sample_multinomial_scores_old(scores):
scores_cuemsum = np.cuemsum(scores)
s = scores_cuemsum[-1] * np.random.rand(1)
k = 0
while s > scores_cuemsum[k]:
k += 1
return k
3
Example 49
def _compare(self, x, axis, exclusive, reverse):
np_out = handle_options(np.cuemsum, x, axis, exclusive, reverse)
with self.test_session(use_gpu=True):
tf_out = tf.cuemsum(x, axis, exclusive, reverse).eval()
self.assertAllClose(np_out, tf_out)
3
Example 50
Project: skl-groups Source File: features.py
def make_stacked(self):
"If unstacked, convert to stacked. If stacked, do nothing."
if self.stacked:
return
self._boundaries = bounds = np.r_[0, np.cuemsum(self.n_pts)]
self.stacked_features = stacked = np.vstack(self.features)
self.features = np.array(
[stacked[bounds[i-1]:bounds[i]] for i in xrange(1, len(bounds))],
dtype=object)
self.stacked = True