def lindley(m=55000, d=5000): ''' Estimates waiting time with m customers, discarding the first d customers Lindley approximation for waiting time in a M/G/1 queue ''' replications = 10 lindley = [] for rep in range(replications): y = 0 SumY = 0 for i in range(1, d): # Random number variable generation from scipy.stats # shape = 0, rate =1, 1 value a = expon.rvs(0, 1) # rate = .8/3, shape = 3 x = erlang.rvs(3, scale=0.8 / 3, size=1) y = max(0, y + x - a) for i in range(d, m): a = expon.rvs(0, 1) # rate = .8/3, shape = 3 x = erlang.rvs(3, scale=0.8 / 3, size=1) y = max(0, y + x - a) SumY += y result = SumY / (m - d) lindley.append(result) return lindley
async def iot_handler(websocket, path): await websocket.send(motd) # mode_query = "What kind of sensor would you like? (temperature,occupancy)" # await websocket.send(mode_query) # mode = await websocket.recv() mode = "all" rooms = get_simulated_rooms() while True: await asyncio.sleep(erlang.rvs(1, 0, size=1)) room = random.choice(list(rooms.keys())) dat = {"time": datetime.now().isoformat()} if mode.startswith(("all", "tem")): dat["temperature"] = cauchy.rvs(loc=rooms[room]["loc"], scale=rooms[room]["scale"], size=1).tolist() if mode.startswith(("all", "occ")): dat["occupancy"] = poisson.rvs(rooms[room]["occ"], size=1).tolist() if mode.startswith(("all", "co")): dat["co2"] = gamma.rvs(rooms[room]["co"], size=1).tolist() await websocket.send(json.dumps({room: dat}))
def Consumed_Bin (self): # With, Item spot = I_N and Time put on board = T_N with N integer from scipy.stats import erlang self.Time = 1 while self.Time <= 24: # Data will be of the form [[I_1,T_1], [I_2, T_2], ...] if self.Lead_Time[0] == True and self.Lead_Finish == self.Time: # Function should have a while loop self.Lead_Time [0] = False for item in self.Virtual_Board: self.Board.append (item) self.Track_Virtual.append (len (self.Virtual_Board)) self.Virtual_Board = [] Random_Variables = erlang.rvs (self.Demand, size = len (self.Bins)) count = 0 for element in Random_Variables: # For loop will continue to give the same few numbers starting numbers, or pattern of numbers if element > self.Demand: self.Bins_Consumed.append ([count, self.Time]) # Function empties the next one (want to empty 43, will empty 44) <--- Fine item2 will come up as index 1 count += 1 for element in self.Bins_Consumed: self.Empty_Bin (element[0]) self.Bins_Consumed = [] if self.Need_Replenishment: self.Replenishment() # Out of supplies triggers replenishment self.Lead_Time[0] = True # ***********Still need to deactivate lead_time*********** self.Lead_Finish = self.Time + self.Lead_Time[1] self.Time += 1
async def iot_handler(websocket, path): """ generate simulated data for each room and sensor """ await websocket.send(motd) mode = "all" rooms = get_simulated_rooms() print("IoT simulator connected to", websocket.remote_address) while True: await asyncio.sleep(erlang.rvs(1, 0, size=1).item()) room = random.choice(list(rooms.keys())) dat = {"time": datetime.now().isoformat()} if mode.startswith(("all", "tem")): dat["temperature"] = cauchy.rvs( loc=rooms[room]["loc"], scale=rooms[room]["scale"], size=1 ).tolist() if mode.startswith(("all", "occ")): dat["occupancy"] = poisson.rvs(rooms[room]["occ"], size=1).tolist() if mode.startswith(("all", "co")): dat["co2"] = gamma.rvs(rooms[room]["co"], size=1).tolist() try: await websocket.send(json.dumps({room: dat})) except websockets.exceptions.ConnectionClosedOK: print("Closing connection to", websocket.remote_address) break
def visit(self, b): arrive = self.sim.now() yield Sim.request, self, b wait = self.sim.now() - arrive tib = erlang.rvs(G.phases, scale=float(G.timeReceptionist) / G.phases, size=1) yield Sim.hold, self, tib #2 yield Sim.release, self, b
def monte_carlo(dist, traffic): # dist is distribution type, traffic is the offered traffic for the simulation mc_gos = [] # empty list to hold Grad of Service values for simulation for i in traffic: num_lines = 56 # fixed calls = [] # list to hold 56 calls on the "channels" # choosing distribution for call durations (normal, erlang, exponential) mean 2 minutes, spread 30 seconds if dist == 1: durations = numpy.random.normal(120, 30, i).astype(int) elif dist == 2: durations = expon.rvs(120, 30, i).astype(int) elif dist == 3: durations = erlang.rvs(a=4, loc=120, scale=30, size=i).astype(int) call_times = numpy.random.randint(0, 3601, i) # call times in the hour call_times.sort() # set variables to 0 at beginning of loop call = 0 calls_dropped = 0 call_success = 0 for j in range(1, 3601): # one hour in seconds for c in calls: if c <= j: calls.pop(calls.index(c)) if call < i and j in call_times: if len(calls) < num_lines: calls.append(durations[call] + j) call_success += 1 call += 1 else: calls_dropped += 1 call += 1 gos = (call - call_success)/call # calculate Grade of Service mc_gos.append(gos) # add calculated GoS to list to return at end of method return mc_gos
async def iot_handler(websocket, path): """ generate simulated data for each room and sensor """ await websocket.send(motd) rooms = get_simulated_rooms() print("Connected:", websocket.remote_address) while True: await asyncio.sleep(erlang.rvs(1, 0, size=1).item()) room = random.choice(list(rooms.keys())) try: await websocket.send(json.dumps({room: generate_data(rooms[room])})) except websockets.exceptions.ConnectionClosedOK: break print("Closed:", websocket.remote_address)
def customer_sample(self): """ Function to draw bernoulli sample from Poisson dist. Used for arrival """ if self.customer_arrival_dist == 'expon': #time_step = poisson.rvs(self.mean_customer_arrival) time_step = self.exp_dist() elif self.customer_arrival_dist == 'erlang': time_step = erlang.rvs(self.mean_customer_arrival) elif self.customer_arrival_dist == 'hyperexp': rand1 = random.random() rand2 = random.random() if rand1 < self.mean_customer_arrival[0][0]: time_step = -1 / self.mean_customer_arrival[0][1] * log(rand2) else: time_step = -1 / self.mean_customer_arrival[1][1] * log(rand2) return time_step
def get_attention_duration(self): return erlang.rvs(Constants.phases, scale=float(Constants.time_receptionist) / Constants.phases, size=1)
from scipy.stats import erlang import numpy as np import matplotlib.pyplot as plt a = erlang.rvs(2, 2, size=100) print(float(np.mean(a))) print(np.std(a)) plt.hist(a, bins=10, density=True, color='green') plt.xlabel('$x$') plt.ylabel('$y$') plt.show()
def main(): parser = argparse.ArgumentParser() parser.add_argument('-s', '--stages', type=int, required=False, help='Etapas de la distribución') parser.add_argument('-l', '--lambdap', type=float, required=True, nargs='+', help='Parámetro lambda de cada distribución') parser.add_argument('-r', '--runs', type=int, required=True, help='Ejecuciones a realizar por cada simulación') parser.add_argument('-o', '--output', type=str, required=False, help='Archivo de salida para la grafica') parser.add_argument('-d', '--dist', type=str, required=True, choices=['erlang', 'expon', 'hyperexp'], help='Distribución a emplear para la simulación') parser.add_argument('--no-graph', required=False, help='Suprime la salida como gráfica', dest='graph', action='store_false') parser.add_argument('--graph', required=False, help='Habilita la salida como gráfica (usar con [-o])', dest='graph', action='store_true') parser.add_argument('-p', '--probability', required=False, type=float, help='Probabilidad para la distribución Hiperexp.') parser.set_defaults(graph=True) args = parser.parse_args() # msg = 'Distribución {3} con {0} etapas (lambda={1}) en {2} ejecuciones' # print msg.format(args.stages, args.lambdap, args.runs, args.dist) fig, ax = plt.subplots(1, 1) if args.dist in 'erlang': if args.stages <= 0: print 'Error: se necesita un número válido de etapas' sys.exit(1) lambdap = args.lambdap[0] mean, var, skew, kurt = erlang.stats(args.stages, scale=lambdap, moments='mvsk') x = np.linspace(erlang.ppf(0.00001, args.stages, scale=lambdap), erlang.ppf(0.99999, args.stages, scale=lambdap), num=1000) rv = erlang(args.stages, scale=lambdap) ax.plot(x, rv.pdf(x), 'r-', lw=5, alpha=0.6, label='Erlang PDF') # Generate random numbers with this distribution r = erlang.rvs(args.stages, scale=lambdap, size=args.runs) ax.hist(r, bins=20, normed=True, histtype='stepfilled', alpha=0.4, label='Experimental values') meanexp = np.mean(r) varexp = np.var(r) print 'Mediaexperimental: {0} MediaAnalitica: {1}'.format(meanexp, mean) print 'Sigma2_exp: {0} Sigma2_a: {1}'.format(varexp, var) print 'CoV_exp: {0} CoV_a: {1}'.format(np.sqrt(varexp)/meanexp, np.sqrt(var)/mean) elif args.dist in 'expon': lambdap = args.lambdap[0] mean, var, skew, kurt = expon.stats(scale=lambdap, moments='mvsk') x = np.linspace(expon.ppf(0.00001, scale=lambdap), expon.ppf(0.99999, scale=lambdap), num=1000) rv = expon(scale=lambdap) ax.plot(x, rv.pdf(x), 'r-', lw=5, alpha=0.6, label='Exponential PDF') # Generate random numbers with this distribution r = expon.rvs(scale=lambdap, size=args.runs) ax.hist(r, bins=20, normed=True, histtype='stepfilled', alpha=0.4, label='Experimental values') meanexp = np.mean(r) varexp = np.var(r) print 'Mediaexperimental: {0} MediaAnalitica: {1}'.format(meanexp, mean) print 'Sigma2_exp: {0} Sigma2_a: {1}'.format(varexp, var) print 'CoV_exp: {0} CoV_a: {1}'.format(np.sqrt(varexp)/meanexp, np.sqrt(var)/mean) elif args.dist in 'hyperexp': rv = hyperexp(args.probability, args.lambdap[0], args.lambdap[1]) x = np.linspace(0.00000001, 10.99999, num=1000) ax.plot(x, rv.pdf(x), 'r-', lw=5, alpha=0.6, label='HyperExp PDF') # ax.plot(x, rv.cdf(x), 'b-', lw=2, alpha=0.6, label='HyperExp CDF') r = rv.rvs(size=args.runs) ax.hist(r, normed=True, bins=100, range=(0, 11), histtype='stepfilled', alpha=0.4, label='Experimental values') meanexp = np.mean(r) varexp = np.var(r) mean = rv.mean() var = rv.standard_dev()**2 print 'Mediaexperimental: {0} MediaAnalitica: {1}'.format(meanexp, mean) print 'Sigma2_exp: {0} Sigma2_a: {1}'.format(varexp, var) print 'CoV_exp: {0} CoV_a: {1}'.format(np.sqrt(varexp)/meanexp, rv.CoV()) if args.graph: ax.legend(loc='best', frameon=False) plt.show()
def main(): parser = argparse.ArgumentParser() parser.add_argument("-s", "--stages", type=int, required=False, help="Etapas de la distribución") parser.add_argument( "-l", "--lambdap", type=float, required=True, nargs="+", help="Parámetro lambda de cada distribución" ) parser.add_argument("-r", "--runs", type=int, required=True, help="Ejecuciones a realizar por cada simulación") parser.add_argument("-o", "--output", type=str, required=False, help="Archivo de salida para la grafica") parser.add_argument( "-d", "--dist", type=str, required=True, choices=["erlang", "expon", "hyperexp"], help="Distribución a emplear para la simulación", ) parser.add_argument( "--no-graph", required=False, help="Suprime la salida como gráfica", dest="graph", action="store_false" ) parser.add_argument( "--graph", required=False, help="Habilita la salida como gráfica (usar con [-o])", dest="graph", action="store_true", ) parser.set_defaults(graph=True) args = parser.parse_args() msg = "Distribución {3} con {0} etapas (lambda={1}) en {2} ejecuciones" print msg.format(args.stages, args.lambdap, args.runs, args.dist) fig, ax = plt.subplots(1, 1) if args.dist in "erlang": if args.stages <= 0: print "Error: se necesita un número válido de etapas" sys.exit(1) lambdap = args.lambdap[0] mean, var, skew, kurt = erlang.stats(args.stages, scale=lambdap, moments="mvsk") print "E[X]={0}, var(X)={1}".format(mean, var) x = np.linspace( erlang.ppf(0.00001, args.stages, scale=lambdap), erlang.ppf(0.99999, args.stages, scale=lambdap), num=1000 ) rv = erlang(args.stages, scale=lambdap) ax.plot(x, rv.pdf(x), "r-", lw=5, alpha=0.6, label="Erlang PDF") # Generate random numbers with this distribution r = erlang.rvs(args.stages, scale=lambdap, size=args.runs) ax.hist(r, bins=20, normed=True, histtype="stepfilled", alpha=0.2) meanexp = np.mean(r) varexp = np.var(r) print "Mediaexperimental: {0} MediaAnalitica: {1}".format(meanexp, mean) print "Sigma2_exp: {0} Sigma2_a: {1}".format(varexp, var) print "CoV_exp: {0} CoV_a: {1}".format(np.sqrt(varexp) / meanexp, np.sqrt(var) / mean) elif args.dist in "expon": lambdap = args.lambdap[0] mean, var, skew, kurt = expon.stats(scale=lambdap, moments="mvsk") print "E[X]={0}, var(X)={1}".format(mean, var) x = np.linspace(expon.ppf(0.00001, scale=lambdap), expon.ppf(0.99999, scale=lambdap), num=1000) rv = expon(scale=lambdap) ax.plot(x, rv.pdf(x), "r-", lw=5, alpha=0.6, label="Exponential PDF") # Generate random numbers with this distribution r = expon.rvs(scale=lambdap, size=args.runs) ax.hist(r, bins=20, normed=True, histtype="stepfilled", alpha=0.2) meanexp = np.mean(r) varexp = np.var(r) print "Mediaexperimental: {0} MediaAnalitica: {1}".format(meanexp, mean) print "Sigma2_exp: {0} Sigma2_a: {1}".format(varexp, var) print "CoV_exp: {0} CoV_a: {1}".format(np.sqrt(varexp) / meanexp, np.sqrt(var) / mean) elif args.dist in "hyperexp": print "HyperExponential RV" rv = hyperexp(0.1, args.lambdap[0], args.lambdap[1]) x = np.linspace(0.00000001, 10.99999, num=1000) ax.plot(x, rv.pdf(x), "r-", lw=5, alpha=0.6, label="HyperExp PDF") # ax.plot(x, rv.cdf(x), 'b-', lw=2, alpha=0.6, label='HyperExp CDF') r = rv.rvs(size=args.runs) ax.hist(r, normed=True, bins=100, range=(0, 11), histtype="stepfilled", alpha=0.2) meanexp = np.mean(r) varexp = np.var(r) print "Mediaexperimental: {0} MediaAnalitica: {1}".format(meanexp, mean) print "Sigma2_exp: {0} Sigma2_a: {1}".format(varexp, var) print "CoV_exp: {0} CoV_a: {1}".format(np.sqrt(varexp) / meanexp, np.sqrt(var) / mean) if args.graph: plt.show()