Search code examples
pythonarraysnumpyincrement

How to make a numpy.arange with incremental step size?


I want to process data, where the acquisition process slows down gradually as the amount of acquired data grows. In order to relate the index values to an estimated real time value, I estimate an increment function that approximates the real time delta between any two neighboring acquisition indices. Hence, I am looking for an efficient way to generate the array of real times out of the array of increments. As an example, let's assume a linear function for the increments. Then, any time value t(i) could be calculated in a recursive manner as t(i) = (m i + b) + t(i-1), for linearly changing time increments m i+b.

Now, I would like to have a time array instead of the index array. A very convenient way would be something like a numpy.arange function with incremental stepwidths; something like:

np.arange(i_0, i_final, step=[m*i+b])

Unfortunately, numpy doesn't support this. Is there a ready implementation at hand? If not, the simplest solution would be a for-loop over the index array, but since the arrays could be long, I would rather avoid this way, if there are faster ways.

EDIT:

A very simple example would be

i    t    dt (from i-1 to i) 
0    0     
1    1     1
2    5     4
3   11     6
4   19     8
5   29    10
6   41    12

where the increment step size would be simply dt(i) = 2i for any step from index i-1 to i. (However, the step size is usually non-integer.)


Solution

  • Each value of t is equal to the initial value plus the sum of the dts up to that point. So, you can use np.cumsum and add that to the initial value to get your t array. To make sure you get the right initial value, make sure your dt array starts at 0.

    import numpy as np
    
    dt = np.array([0, 1, 4, 6, 8, 10, 12])
    t0 = 0
    t = t0 + np.cumsum(dt)
    print(t)
    

    Output:

    array([ 0,  1,  5, 11, 19, 29, 41])