Debian Codegraph @

brian2/utils/arrays.py

raw
1 """
2 Helper module containing functions that operate on numpy arrays.
3 """
4
5 import numpy as np
6
7
8 def calc_repeats(delay):
9 """
10 Calculates offsets corresponding to an array, where repeated values are
11 subsequently numbered, i.e. if there n identical values, the returned array
12 will have values from 0 to n-1 at their positions.
13 The code is complex because tricks are needed for vectorisation.
14
15 This function is used in the Python `SpikeQueue` to calculate the offset
16 array for the insertion of spikes with their respective delays into the
17 queue and in the numpy code for synapse creation to calculate how many
18 synapses for each source-target pair exist.
19
20 Examples
21 --------
22 >>> import numpy as np
23 >>> print(calc_repeats(np.array([7, 5, 7, 3, 7, 5])))
24 [0 0 1 0 2 1]
25 """
26 # We use merge sort because it preserves the input order of equal
27 # elements in the sorted output
28 sort_indices = np.argsort(delay, kind="mergesort")
29 xs = delay[sort_indices]
30 J = xs[1:] != xs[:-1]
31 A = np.hstack((0, np.cumsum(J)))
32 B = np.hstack((0, np.cumsum(np.logical_not(J))))
33 BJ = np.hstack((0, B[:-1][J]))
34 ei = B - BJ[A]
35 ofs = np.zeros_like(delay, dtype=np.int32)
36 ofs[sort_indices] = np.array(ei, dtype=ofs.dtype)
37 return ofs