Simulate decaying function

139 Views Asked by At

Lets t be the time tick i.e. 1,2,3,4,5....

I want to calculate and plot a cumulative decaying function f(inits[],peaks[],peak-ticks,zero-ticks). Preferably in python

Where :

- inits[] is a list of points at time/tick t where a new 'signal' is introduced
- peaks[] is a list of values which must be reached after peak-ticks. (corresponding to inits)
- peak-ticks is how many ticks it takes to reach the next peak value
- zero-ticks is how many ticks it takes to reach zero from the peak

For example :

 f(inits=[10,15,18], peaks=[1,1,1], peak-ticks=1, zero-ticks=10)

in this case decay takes 10 ticks i.e. 0.1 per tick.

at tick:

 10! result is 0
 11. = 1
 12. = 0.9
 .....
 15! = 0.6 + 0 = 0.6
 16. = 0.5 + 1 = 1.5
 17. = 0.4 + 0.9 = 1.3
 18! = 0.3 + 0.8 + 0 = 1.1
 19. = 0.2 + 0.7 + 1 = 1.9
 20. = 0.1 + 0.6 + 0.9 = 1.6
 .....

PS> As a complication, what if the decay is exponential like 1/x ?

1

There are 1 best solutions below

1
On BEST ANSWER

For the base case you mentioned, it is actually pretty simple, you just need to define a triangular function that returns the contribution of a specific singal at the current tick t.

Then, just sum the contribution of all signals at tick t, that is your answer.

In the code below, I implemented the decaying function as an infinite generator, so I have to use islice to define how many ticks to compute (or maybe the start and end ticks). You could also implement it as a normal function, you'd just have to pass in the start and end ticks.

from itertools import count, islice

def fdecay(inits, peaks, ptks, ztks):
  for t in count():
    yield sum(triang(p, i, i+ptks, i+ptks+ztks, t) for i, p in zip(inits, peaks))

def triang(ymax, xa, xb, xc, x):
  if x < xa: return 0
  if x < xb: return ymax * (x-xa) / (xb-xa)
  if x < xc: return ymax * (xc-x) / (xc-xb)
  return 0

x = list(islice(fdecay([10,15,18], [1,1,1], 1, 10), 30))
print(x)
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0, 0.9, 0.8, 0.7, 0.6, 1.5, 1.3, 1.1, 1.9, 1.6, 1.3, 1.1, 0.9, 0.7, 0.5, 0.3, 0.2, 0.1, 0]

If you want exponential decay, just switch the triangular function to the exponential function at time t (with the appropriate params).