27e98d7d520b0ac511c413145e98814c949ba649
[BK-2020-03.git] / unitproc / python / sleepRand.py
1 #!/usr/bin/env python3
2 # Desc: Pauses a random amount of time. Random distribution is inverse gaussian.
3 # Version: 0.0.2
4 # Depends: python 3.7.3
5 # Usage: ./sleepRand.py arg1
6 # Input: arg1: float seconds (mean of inverse gaussian distribution)
7 # Example: python3 sleepRand.py 4.0
8
9 import math, time, random, sys
10
11 # Define functions
12 def randInvGau(mu, lam):
13 """Returns random variate of inverse gaussian distribution"""
14 # input: mu: mean of inverse gaussian distribution
15 # lam: shape parameter
16 # output: float sampled from inv. gaus. with range 0 to infinity, mean mu
17 # example: sample = float(randInvGau(1.0,4.0));
18 # Ref/Attrib: doi:10.1080/00031305.1976.10479147
19 nu = random.gauss(0,1);
20 y = nu ** 2;
21 xTerm1 = mu;
22 xTerm2 = mu ** 2 * y / (2 * lam);
23 xTerm3 = (- mu / (2 * lam)) * math.sqrt(4 * mu * lam * y + mu ** 2 * y ** 2);
24 x = xTerm1 + xTerm2 + xTerm3;
25 z = random.uniform(0.0,1.0);
26 if z <= (mu / (mu + x)):
27 return x;
28 else:
29 return (mu ** 2 / x);
30
31 # Check input (TODO)
32 arg1 = float(sys.argv[1]); # first argument
33 desMean = arg1;
34
35 # Configure
36 lambdaFactor = 4; # spread factor; inversely proportional to variance
37
38 # Calculate delay
39 delay = randInvGau(desMean, desMean * lambdaFactor);
40 #print('DEBUG:delay:' + str(float(delay)));
41
42 # Sleep
43 time.sleep(float(delay));
44
45 # Author: Steven Baltakatei Sandoal
46 # License: GPLv3+