Simulates multiple Poisson processes
I have N processes, each with a different Poisson rate. I want to simulate the arrival time for all N processes. If N = 1 I can do this
t = 0
N = 1
for i in range(1,10):
t+= random.expovariate(15)
print N, t
But if I have N = 5
and a rate list
rates = [10,1,15,4,2]
I want to somehow get the loop to output the arrival time of all N processes in the correct order. That said, I still want only two numbers per row (process ID and arrival time), but sort globally by arrival time.
I
can make N lists and then merge them, but I want to output the arrival time in the correct order first.
Update. One problem is that if you just take a fixed number of arrival samples from each process, you can only get early time from high-rate processes. So I think I need to sample from a fixed time interval for each process, so the sample size changes depending on the rate.
Solution
If I’m not mistaken:
import random
import itertools
def arrivalGenerator(rate):
t = 0
while True:
t += random.expovariate(rate)
yield t
rates = [10, 1, 15, 4, 2]
t = [(i, 0) for i in range(0, len(rates))]
arrivals = []
for i in range(len(rates)):
t = 0
generator = arrivalGenerator(rates[i])
arrivals += [(i, arrival) \
for arrival in itertools.takewhile(lambda t: t < 100, generator)]
sorted_arrivals = sorted(arrivals, key=lambda x: x[1])
for arrival in sorted_arrivals:
print arrival[0], arrival[1]
Note that your initial logic is to generate a fixed number of arrivals for each process. What you really want is a specific window of time and keep spawning for a given process until you exceed that time window.