-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueNetworkSimulation.py
More file actions
586 lines (510 loc) · 27.9 KB
/
QueueNetworkSimulation.py
File metadata and controls
586 lines (510 loc) · 27.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
from QueueNetwork import QueueNetwork
from StatsCollector import *
import matplotlib.pyplot as plt
import datetime
from timeit import default_timer as timer
import math
import cProfile
def guessAvgWorkload(arrivalRate, oneQmu, systemMuEffective):
if arrivalRate >= systemMuEffective:
return 0.0
return arrivalRate * math.exp(arrivalRate) / (oneQmu*(systemMuEffective - arrivalRate))
########################################################################################################################
# STATS CLASS
########################################################################################################################
class AdjacentWindowsAndAverageWorkloadStats:
"""User-defined stats class."""
##
# Init MyStats with 2 statistics windows. The 2 windows are adjacent to each other. This is done in order to provide
# a way to compare 2 windows.
##
def __init__(self, windowSize, numOfRounds):
self.perLambdaStatsCollector = StatsCollector(windowSizes=[windowSize, windowSize])
self.wholeSimStatsCollector = Stats(windowSize=numOfRounds)
self.currentWindow = 0
def insertToWindow(self, value):
self.perLambdaStatsCollector.getStatNumber(self.currentWindow).insert(value)
def insertToAvgWorkloadWindow(self, value):
self.wholeSimStatsCollector.insert(value)
def resetWindows(self):
self.perLambdaStatsCollector.reset()
self.currentWindow = 0
def resetAll(self):
self.resetWindows()
self.wholeSimStatsCollector.reset()
def getCurrentWindowStats(self):
return self.perLambdaStatsCollector.getStatNumber(self.currentWindow)
def getPreviousWindowStats(self):
return self.perLambdaStatsCollector.getStatNumber(1 - self.currentWindow)
def getAvgWorkloadWindowStats(self):
return self.wholeSimStatsCollector
def switchWindows(self):
self.currentWindow = (self.currentWindow + 1) % 2
self.perLambdaStatsCollector.getStatNumber(self.currentWindow).reset()
########################################################################################################################
# STATS CLASS
########################################################################################################################
class RunningAverageWindowAndAverageWorkloadStats:
"""User-defined stats class."""
##
# Init MyStats with a running average statistics window.
##
def __init__(self, windowSize, numOfRounds):
self.perLambdaStatsCollector = Stats(windowSize=windowSize)
self.wholeSimStatsCollector = Stats(windowSize=numOfRounds)
def insertToWindow(self, value):
self.perLambdaStatsCollector.insert(value)
def insertToAvgWorkloadWindow(self, value):
self.wholeSimStatsCollector.insert(value)
def resetWindows(self):
self.perLambdaStatsCollector.reset()
def resetAll(self):
self.resetWindows()
self.wholeSimStatsCollector.reset()
def getWindowStats(self):
return self.perLambdaStatsCollector
def getAvgWorkloadWindowStats(self):
return self.wholeSimStatsCollector
def getLastWindowEntry(self):
return self.perLambdaStatsCollector.window[self.perLambdaStatsCollector.nextOpenSlot - 1]
########################################################################################################################
# SIMULATION BUILDING
########################################################################################################################
class QueueNetworkSimulation:
"""Class for simulating a queue network in discrete time with a given dispatch policy."""
##
# Initialize a queue network simulation given a size, services and initial workloads along with a dispatch policy
# and a converge condition.
# If only a size and policy were given, all queues will have service = 1, workload = 0.
# NOTICE: Edit this to set a different statistics class for init.
##
def __init__(self, size, dispatchPolicyStrategy, convergenceConditionStrategy, plotStrategy=None, services=[],
workloads=[], historyWindowSize=10000, numOfRounds=100,
verbose=False, T_min=0, T_max=10000000, guess=False):
_T_min = T_min
if T_min == 0:
_T_min = historyWindowSize
# Member fields init.
self.network = QueueNetwork(size, services=services, workloads=workloads)
self.dispatchPolicyStrategy = dispatchPolicyStrategy
self.convergenceConditionStrategy = convergenceConditionStrategy
self.plotStrategy = plotStrategy
self.statsCollector = RunningAverageWindowAndAverageWorkloadStats(windowSize=historyWindowSize,
numOfRounds=numOfRounds)
self.verbose = verbose
self.T_max = T_max
self.T_min = _T_min
self.numOfRounds = numOfRounds
self.guessAvgWorkload = guess
self.box = 0.0
##
# Resets the simulation.
##
def reset(self):
self.network.flush()
self.statsCollector.resetAll()
if self.verbose:
print "INFO: Simulation reset."
##
# Set the dispatch policy.
##
def setDispatchPolicy(self, dispatchPolicyStrategy):
self.dispatchPolicyStrategy = dispatchPolicyStrategy
if self.verbose:
print "INFO: Simulation dispatch policy set."
##
# Set the convergence check function.
##
def setConvergenceCondition(self, convergenceConditionStrategy):
self.convergenceConditionStrategy = convergenceConditionStrategy
if self.verbose:
print "INFO: Simulation convergence condition set."
##
# Set the plotting function.
##
def setPlot(self, plotStrategy):
self.plotStrategy = plotStrategy
if self.verbose:
print "INFO: Simulation plotting scheme set."
# calculate the next average workload in the avg workload vector
def calcAvgWorkLoad(self, T, AvgWorkLoad_prev, TotalWorkLoad):
T = float(T)
AvgWorkLoad_prev = float(AvgWorkLoad_prev)
TotalWorkLoad = float(TotalWorkLoad)
return (1.0 / T) * ((T - 1) * AvgWorkLoad_prev + TotalWorkLoad)
def getEffectiveServiceRate(self):
return self.dispatchPolicyStrategy.getEffectiveServiceRate(self.network)
def singleRun(self, arrivalRate, effectiveServiceRate, resultQueue=None, resultNum=None):
if self.verbose:
print "INFO: arrival rate = " + str(arrivalRate) + " [ " + str(100.0 * arrivalRate /
effectiveServiceRate) + "% ]"
print "INFO: Round Started at : " + str(datetime.datetime.now()) + "\n"
if arrivalRate <= 0:
if self.verbose:
print "INFO: arrival rate = " + str(arrivalRate) + " [ " + str(100.0 * arrivalRate /
effectiveServiceRate) + "% ]"
print "INFO: Round ended at : " + str(datetime.datetime.now())
print "INFO: Time slot : " + str(self.network.getTime()) + "\n"
if resultQueue is not None:
resultQueue.put([resultNum, 0.0])
return
else:
self.box = 0.0
return 0.0
start = timer()
# runningAvg = [0]
# Time-slot operating loop.
while self.network.getTime() < self.T_max:
t = self.network.getTime()
# Determine whether a new job arrived or not.
if np.random.binomial(1, arrivalRate) == 1:
queues, newWork = self.dispatchPolicyStrategy.getDispatch(self.network)
self.network.addWorkload(queues, newWork)
# End the time-slot.
self.network.endTimeSlot()
# Check for convergence.
if t >= self.T_min and (t + 1) % self.statsCollector.getWindowStats().getWindowSize() == 0:
# If converged, record stats and end round.
if self.convergenceConditionStrategy.hasConverged(self.network,
[self.statsCollector.getWindowStats().getWindow()],
self.T_min, self.T_max):
self.statsCollector.insertToWindow(
self.calcAvgWorkLoad(
t + 1,
self.statsCollector.getLastWindowEntry(),
self.network.getTotalWorkload()
)
)
if self.verbose:
print "INFO: arrival rate = " + str(arrivalRate) + " [ " + \
str(100.0 * arrivalRate / effectiveServiceRate) + "% ]"
print "INFO: Round ended at : " + str(datetime.datetime.now())
print "INFO: Time slot : " + str(self.network.getTime() + 1) + "\n"
if resultQueue is not None:
resultQueue.put([resultNum, np.mean(self.statsCollector.getWindowStats().getWindow())])
return
else:
self.box = np.mean(self.statsCollector.getWindowStats().getWindow())
return np.mean(self.statsCollector.getWindowStats().getWindow())
# Gather stats of this time-slot.
self.statsCollector.insertToWindow(
self.calcAvgWorkLoad(
t+1,
self.statsCollector.getLastWindowEntry(),
self.network.getTotalWorkload()
)
)
# runningAvg.append(self.calcAvgWorkLoad(t+1, runningAvg[t], self.network.getTotalWorkload()))
# Advance simulation time.
self.network.advanceTimeSlot()
if self.verbose:
print "INFO: arrival rate = " + str(arrivalRate) + " [ " + \
str(100.0 * arrivalRate / effectiveServiceRate) + "% ]"
print "INFO: Round ended at : " + str(datetime.datetime.now())
print "INFO: Time slot : " + str(self.network.getTime() + 1)
end = timer() # Time in seconds
# if (arrivalRate / effectiveServiceRate == 0.2) or (arrivalRate / effectiveServiceRate == 0.75) or \
# (arrivalRate / effectiveServiceRate == 0.9) or (arrivalRate / effectiveServiceRate == 0.95):
# plt.plot(runningAvg)
# plt.show()
if resultQueue is not None:
print "INFO: Time in seconds : " + str(float(end) - float(start))
resultQueue.put([resultNum, np.mean(self.statsCollector.getWindowStats().getWindow())])
print "XXX\n"
return
else:
return np.mean(self.statsCollector.getWindowStats().getWindow())
##
# Run the simulation.
# NOTICE: Edit this to make your simulation advance through time as you expect it to.
##
def run(self):
start_time = datetime.datetime.now()
initialWorkloadStr = str(self.network.getWorkloads())
if self.verbose:
print "INFO: Starting simulation:"
print "INFO: time : " + str(start_time)
print "INFO: number of servers : " + str(self.network.getSize())
print "INFO: starting in time slot : " + str(self.network.getTime())
print "INFO: policy : " + self.dispatchPolicyStrategy.getName()
print "INFO: servers service per time slot : " + str(self.network.getServices())
print "INFO: servers initial workload : " + str(self.network.getWorkloads()) + "\n"
effectiveServiceRate = self.dispatchPolicyStrategy.getEffectiveServiceRate(self.network)
arrivalRates = [0]*self.numOfRounds
if effectiveServiceRate != 0:
arrivalRates = np.arange(0, effectiveServiceRate, float(effectiveServiceRate) / float(self.numOfRounds))
# Round operating loop.
simTimeAnalysis = []
for arrivalRate in arrivalRates:
if self.verbose:
print "INFO: arrival rate = " + str(arrivalRate) + " [ " + str(100.0 * arrivalRate /
effectiveServiceRate) + "% ]"
print "INFO: Round Started at : " + str(datetime.datetime.now())
start = timer()
# Try and guess avg workload for faster convergence.
# TODO: test this feature and this guess function.
if self.guessAvgWorkload:
guess = int(guessAvgWorkload(arrivalRate, self.dispatchPolicyStrategy.getOneQueueMu(),
effectiveServiceRate))
initWorkloads = [int(guess / self.network.getSize()) for i in range(self.network.getSize())]
self.network.setWorkloads(initWorkloads)
if self.verbose:
print "INFO: Guessed avg workload = " + str(guess)
# runningAvg = [0]
# Time-slot operating loop.
while self.network.getTime() < self.T_max:
t = self.network.getTime()
# Determine whether a new job arrived or not.
if np.random.binomial(1, arrivalRate) == 1:
queues, newWork = self.dispatchPolicyStrategy.getDispatch(self.network)
self.network.addWorkload(queues, newWork)
# End the time-slot.
self.network.endTimeSlot()
# Check for convergence.
if arrivalRate == 0:
self.statsCollector.insertToAvgWorkloadWindow(0.0)
self.statsCollector.resetWindows()
break
# Is it time to check for convergence?
elif t >= self.T_min and (t + 1) % self.statsCollector.getWindowStats().getWindowSize() == 0:
# If converged, record stats and end round.
if self.convergenceConditionStrategy.hasConverged(self.network,
[self.statsCollector.getWindowStats().getWindow()],
self.T_min, self.T_max):
self.statsCollector.insertToAvgWorkloadWindow(
self.calcAvgWorkLoad(
t+1,
self.statsCollector.getLastWindowEntry(),
self.network.getTotalWorkload()
)
)
self.statsCollector.resetWindows()
break
# # If didn't converge, switch the windows.
# self.statsCollector.switchWindows()
# Gather stats of this time-slot.
self.statsCollector.insertToWindow(
self.calcAvgWorkLoad(
t+1,
self.statsCollector.getLastWindowEntry(),
self.network.getTotalWorkload()
)
)
# runningAvg.append(self.calcAvgWorkLoad(t+1, runningAvg[t], self.network.getTotalWorkload()))
# Advance simulation time.
self.network.advanceTimeSlot()
if self.verbose:
print "INFO: Round ended at : " + str(datetime.datetime.now())
print "INFO: Time slot : " + str(self.network.getTime() + 1) + "\n"
end = timer() # Time in seconds
simTimeAnalysis.append(float(end) - float(start))
# if (arrivalRate / effectiveServiceRate == 0.2) or (arrivalRate / effectiveServiceRate == 0.75) or \
# (arrivalRate / effectiveServiceRate == 0.9) or (arrivalRate / effectiveServiceRate == 0.95):
# plt.plot(runningAvg)
# plt.show()
self.network.reset()
end_time = datetime.datetime.now()
if self.verbose:
print "INFO: Simulation ended at:"
print "INFO: time : " + str(end_time)
# Save results to file.
if self.verbose:
print "INFO: Saving results to file [ " + datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + "_queue_net_sim.dump ]"
fd = open(datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + '_queue_net_sim.dump', 'w')
for val in arrivalRates:
fd.write(str(val) + ",")
fd.write("\n")
for val in self.statsCollector.getAvgWorkloadWindowStats().getWindow():
fd.write(str(val) + ",")
fd.write("\n")
fd.write("\n")
fd.write("INFO: time started : " + str(start_time) + "\n")
fd.write("INFO: time ended : " + str(end_time) + "\n")
fd.write("INFO: number of servers : " + str(self.network.getSize()) + "\n")
fd.write("INFO: dispatch policy : " + self.dispatchPolicyStrategy.getName() + "\n")
fd.write("INFO: redundancy : " + str(self.dispatchPolicyStrategy.getRedundancy()) + "\n")
fd.write("INFO: convergence condition : " + self.convergenceConditionStrategy.getName() + "\n")
fd.write("INFO: convergence precision : " + str(self.convergenceConditionStrategy.getPrecision()) + "\n")
fd.write("INFO: servers service per time slot : " + str(self.network.getServices()) + "\n")
fd.write("INFO: servers initial workload : " + initialWorkloadStr + "\n")
fd.close()
# FIXME: Move the plotting to a plot strategy.
if self.verbose and len(arrivalRates) != len(self.statsCollector.getAvgWorkloadWindowStats().getWindow()):
print "WARN: length of arrivalRates != length of stats collected"
plt.plot(arrivalRates, self.statsCollector.getAvgWorkloadWindowStats().getWindow()[:len(arrivalRates)])
plt.show()
plt.plot(simTimeAnalysis, 'rx')
plt.xlabel("arrival rate as % of service effective rate")
plt.ylabel("simulation time [sec]")
plt.show()
##
# Load a network image to the simulation.
##
def load(self, filename):
if self.verbose:
print "INFO: Loading network from file [ " + filename + " ]"
##
# Save simulation to a file.
##
def save(self, filename="queue_net_sim.dump"):
if self.verbose:
print "INFO: Saving simulation to file [ " + str(datetime.datetime.now()) + "_" + filename + " ]"
##
# Plot results based on given plotting scheme.
##
def plot(self, x=None, y=None, plotStrategy=None):
if x is None or y is None:
return
if self.verbose:
print "INFO: Plotting..."
if plotStrategy is not None:
plotStrategy.plot(x, y)
elif self.plotStrategy is not None:
self.plotStrategy.plot(x, y)
##
# Plot results from file based on given plotting scheme.
##
def plotFromFile(self, resultsFiles, plotStrategy=None):
xx = []
yy = []
for resultsFile in resultsFiles:
if self.verbose:
print "INFO: Getting data from [ " + resultsFile + " ]"
with open(resultsFile, "r") as fd:
xx.append([float(val) for val in fd.readline().split(',')[:-1]])
yy.append([float(val) for val in fd.readline().split(',')[:-1]])
if self.verbose:
print "INFO: Results metadata:"
print "################################################################"
print fd.read()
print "################################################################"
self.plot(xx, yy, plotStrategy=plotStrategy)
########################################################################################################################
# MAIN
########################################################################################################################
import DispatchPolicyStrategy
import ConvergenceConditionStrategy
# Operate your simulation here.
# Init simulation instance.
# n=1
# dispatch policy = one queue, fixed service rate
# alpha=10
# mu=0.5
# p=0.75
# convergence condition = window delta percent change.
# precision = 0.05 (5%)
# sweep over 100 arrival rates.
# statistics history window size = 50000
# d=[1, 2, 4]
# sim = QueueNetworkSimulation(4, DispatchPolicyStrategy.FixedSubsetsStrategy(d[0], 10, 1000, 0.75),
# ConvergenceConditionStrategy.DeltaConvergenceStrategy(epsilon=0.05),
# verbose=True, numOfRounds=100, historyWindowSize=50000)
# for redundancy in d:
# sim.setDispatchPolicy(DispatchPolicyStrategy.FixedSubsetsStrategy(redundancy, 10, 1000, 0.75))
# sim.run()
# sim = QueueNetworkSimulation(1, DispatchPolicyStrategy.OneQueueFixedServiceRateStrategy(alpha=10, mu=0.05, p=0.75),
# ConvergenceConditionStrategy.VarianceConvergenceStrategy(epsilon=0.01),
# verbose=True, numOfRounds=100, historyWindowSize=10000, T_min=100000)
# cProfile.run('sim.run()')
# sim = QueueNetworkSimulation(2, DispatchPolicyStrategy.OnlyFirstQueueGetsJobsStrategy(n=2, alpha=10, beta=1000, p=0.75),
# ConvergenceConditionStrategy.VarianceConvergenceStrategy(epsilon=0.01),
# verbose=True, numOfRounds=10, historyWindowSize=10000, T_min=100000)
# cProfile.run('sim.run()')
# sim = QueueNetworkSimulation(2, DispatchPolicyStrategy.JoinShortestWorkloadStrategy(alpha=10, beta=1000, p=0.75),
# ConvergenceConditionStrategy.VarianceConvergenceStrategy(epsilon=0.01),
# verbose=True, numOfRounds=50, historyWindowSize=10000, T_min=100000)
# cProfile.run('sim.run()')
# FIXME: REMEMBER - HISTORY WINDOW SIZE IS PREFERRED TO BE 10*(1-p)*T_min. THE REASON IS WE WANT A WINDOW TO PROPERLY REFLECT AN AVERAGE SERIES OF EVENTS IN THE SYSTEM.
# sim = QueueNetworkSimulation(2, DispatchPolicyStrategy.RouteToAllStrategy(alpha=10, beta=1000, p=0.8),
# ConvergenceConditionStrategy.VarianceConvergenceStrategy(epsilon=0.05),
# verbose=True, numOfRounds=20, historyWindowSize=20000, T_min=100000, T_max=20000000)
# cProfile.run('sim.run()')
# sim = QueueNetworkSimulation(2, DispatchPolicyStrategy.JoinShortestWorkloadStrategy(alpha=10, beta=1000, p=0.75),
# ConvergenceConditionStrategy.RunForXSlotsConvergenceStrategy(1000000),
# verbose=True, numOfRounds=20, historyWindowSize=100000, T_min=100000)
# cProfile.run('sim.run()')
# sim = QueueNetworkSimulation(2, DispatchPolicyStrategy.VolunteerOrTeamworkStrategy(alpha=10, beta=1000, p=0.8, q=0.5),
# ConvergenceConditionStrategy.VarianceConvergenceStrategy(epsilon=0.05),
# verbose=True, numOfRounds=20, historyWindowSize=20000, T_min=100000, T_max=20000000)
# cProfile.run('sim.run()')
# sim = QueueNetworkSimulation(2, DispatchPolicyStrategy.RandomQueueStrategy(alpha=10, beta=1000, p=0.8),
# ConvergenceConditionStrategy.VarianceConvergenceStrategy(epsilon=0.05),
# verbose=True, numOfRounds=20, historyWindowSize=20000, T_min=1000000, T_max=20000000)
# cProfile.run('sim.run()')
# sim = QueueNetworkSimulation(4, DispatchPolicyStrategy.RouteToAllStrategy(alpha=1, beta=1000, p=0.9),
# ConvergenceConditionStrategy.VarianceConvergenceStrategy(epsilon=0.001),
# verbose=True, numOfRounds=10, historyWindowSize=10000, T_min=1000000, T_max=150000000)
# cProfile.run('sim.run()')
# sim = QueueNetworkSimulation(3, DispatchPolicyStrategy.RandomDStrategy(alpha=10, beta=2000, p=0.8, d=2),
# ConvergenceConditionStrategy.VarianceConvergenceStrategy(epsilon=5e-05),
# verbose=True, numOfRounds=30, historyWindowSize=20000, T_min=500000, T_max=150000000)
# # cProfile.run('sim.run()')
class PLOTd1vsd2:
def __init__(self, properties=None):
self.properties = properties
def plot(self, xx, yy):
plt.xlabel(r'$\lambda$')
plt.ylabel(r'Average Workload')
plt.axvline(self.properties.getEffectiveMu(), linestyle="--")
plt.text(self.properties.getEffectiveMu() + (xx[0][1] - xx[0][0]) / 5.0, np.max(yy) / 2.0,
s=r'$d=1$',
fontsize="x-large",
verticalalignment='center',
rotation=90)
i = 1
for x, y in zip(xx, yy):
# gain = ((x[-1] - self.properties.getEffectiveMu()) / self.properties.getEffectiveMu()) * 100.0
# plt.annotate(r'Capacity region increased by approx. %d%%' % gain,
# xy=(x[-1], y[-1]),
# xytext=(x[-1] / 2.0, y[-1] / 1.5),
# fontsize="large")
plt.plot(x, y, label=r'$d=%d$' % i, linewidth=2)
i += 1
plt.legend(loc="best", fontsize="x-large")
plt.show()
class PLOTd1vsd2vsRIQ:
def __init__(self, properties=None):
self.properties = properties
def plot(self, xx, yy):
plt.xlabel(r'$\lambda$')
plt.ylabel(r'Average Workload')
plt.axvline(self.properties.getEffectiveMu(), linestyle="--")
plt.text(self.properties.getEffectiveMu() + (xx[0][1] - xx[0][0]) / 5.0, np.max(yy) / 2.0,
s=r'$d=1$',
fontsize="x-large",
verticalalignment='center',
rotation=90)
i = 1
for x, y in zip(xx, yy):
# gain = ((x[-1] - self.properties.getEffectiveMu()) / self.properties.getEffectiveMu()) * 100.0
# plt.annotate(r'Capacity region increased by approx. %d%%' % gain,
# xy=(x[-1], y[-1]),
# xytext=(x[-1] / 2.0, y[-1] / 1.5),
# fontsize="large")
if i != 2:
plt.plot(x, y, label=r'$d=%d$' % i, linewidth=2)
else:
plt.plot(x, y, label=r'$RIQ$', linewidth=2)
i += 1
plt.legend(loc="best", fontsize="x-large")
plt.show()
class SimplePlotParams:
def __init__(self, effectiveMu):
self.effectiveMu = effectiveMu
def getEffectiveMu(self):
return self.effectiveMu
# random-d policy, n=3, alpha=10, beta=2000, p=0.8. d=1 vs. d=2.
sim = QueueNetworkSimulation(3, DispatchPolicyStrategy.RandomDStrategy(alpha=10, beta=2000, p=0.8, d=2),
ConvergenceConditionStrategy.VarianceConvergenceStrategy(epsilon=5e-05),
verbose=True, numOfRounds=30, historyWindowSize=20000, T_min=500000, T_max=150000000)
plotter = PLOTd1vsd2(properties=SimplePlotParams(sim.getEffectiveServiceRate()))
sim.plotFromFile(["project_results/20190117-213847_queue_net_sim.dump",
"project_results/20190117-162848_queue_net_sim.dump"], plotStrategy=plotter)
# n=3, alpha=10, beta=2000, p=0.8. no RR vs. random-d=2 vs. RIQ.
sim = QueueNetworkSimulation(3, DispatchPolicyStrategy.RandomDStrategy(alpha=10, beta=2000, p=0.8, d=2),
ConvergenceConditionStrategy.VarianceConvergenceStrategy(epsilon=5e-05),
verbose=True, numOfRounds=30, historyWindowSize=20000, T_min=500000, T_max=150000000)
plotter = PLOTd1vsd2vsRIQ(properties=SimplePlotParams(sim.getEffectiveServiceRate()))
sim.plotFromFile(["20190121-231359_queue_net_sim.dump",
"20190122-024429_queue_net_sim.dump",
"20190121-175444_queue_net_sim.dump"], plotStrategy=plotter)