forked from cyberphysic4l/DLTCongestionControl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Classes.py
1315 lines (1225 loc) · 57 KB
/
Classes.py
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 27 22:28:39 2019
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import networkx as nx
from random import sample
import os
import winsound
from time import gmtime, strftime
from shutil import copyfile
import csv
np.random.seed(0)
# Simulation Parameters
MONTE_CARLOS = 1
SIM_TIME = 180
STEP = 0.01
# Network Parameters
GRAPH = 'cycle' # regular, complete or cycle
NU = 50
NUM_NODES = 50
NUM_NEIGHBOURS = 4
CHAN_DELAY_MEAN = 0.05
START_TIMES = 10*np.ones(NUM_NODES)
REPDIST = 'zipf'
if REPDIST=='zipf':
# IOTA data rep distribution - Zipf s=0.9
REP = [(NUM_NODES+1)/((NodeID+1)**0.9) for NodeID in range(NUM_NODES)]
elif REPDIST=='uniform':
# Permissioned System rep system?
REP = np.ones(NUM_NODES, dtype=int)
# Modes: 0 = inactive, 1 = content, 2 = best-effort, 3 = malicious
MODE = [2-NodeID%3 for NodeID in range(NUM_NODES)] # honest env
#MODE = [3-(NodeID+1)%4 for NodeID in range(NUM_NODES)] # malicoius env
#MODE[2]=4
#AVG_WORK = [2*rep/max(REP) for rep in REP
#AVG_WORK = np.ones(NUM_NODES)
#IOT = np.concatenate((np.zeros(int(NUM_NODES/2)), np.ones(int(NUM_NODES/2))))
#IOT = [NodeID%2 for NodeID in range(NUM_NODES)]
IOT = np.zeros(NUM_NODES)
IOTLOW = 0.5
IOTHIGH = 1
MAX_WORK = 10
MODE_COLOUR_MAP = ['grey', 'tab:blue', 'tab:red', 'tab:green', 'tab:green']
# Congestion Control Parameters
ALPHA = 0.075
BETA = 0.5
TAU = 2
MIN_TH = 1
MAX_TH = MIN_TH
QUANTUM = [MAX_WORK*rep/sum(REP) for rep in REP]
W_Q = 0.1
P_B = 0.5
DROP_TH = 5
SCHEDULE_ON_SOLID = True
SOLID_REQUESTS = True
BLACKLIST = True
SCHEDULING = 'drr_lds'
def main():
plt.close('all')
dirstr = simulate()
#dirstr = 'data/2020-08-19_142643'
plot_results(dirstr)
#plot_results('data/2020-07-23_213333') # honest environment
#plot_results('data/2020-07-26_122609') # malicious environment
#plot_results('data/2020-07-25_154015') # IoT
#plot_scheduler_comp('Data/2020-07-23_233549', 'Data/2020-07-23_213333')
#plot_ratesetter_comp('data/2020-07-24_132945', 'data/2020-07-23_213333', 'data/2020-07-24_153139') # changing beta
#plot_ratesetter_comp('data/2020-07-23_212831', 'data/2020-07-23_213333', 'data/2020-07-24_124532') # changing W
#plot_ratesetter_comp('data/2020-07-23_213056', 'data/2020-07-23_213333', 'data/2020-07-24_154211') # changing alpha
winsound.Beep(2500, 1000) # beep to say sim is finished
def simulate():
"""
Setup simulation inputs and instantiate output arrays
"""
# seed rng
np.random.seed(0)
TimeSteps = int(SIM_TIME/STEP)
'''
Create empty arrays to store results
'''
Lmds = [np.zeros((TimeSteps, NUM_NODES)) for mc in range(MONTE_CARLOS)]
OldestTxAges = np.zeros((TimeSteps, NUM_NODES))
OldestTxAge = []
InboxLens = [np.zeros((TimeSteps, NUM_NODES)) for mc in range(MONTE_CARLOS)]
InboxLensMA = [np.zeros((TimeSteps, NUM_NODES)) for mc in range(MONTE_CARLOS)]
SolidRequests = [np.zeros((TimeSteps, NUM_NODES)) for mc in range(MONTE_CARLOS)]
Deficits = [np.zeros((TimeSteps, NUM_NODES)) for mc in range(MONTE_CARLOS)]
Throughput = [np.zeros((TimeSteps, NUM_NODES)) for mc in range(MONTE_CARLOS)]
WorkThroughput = [np.zeros((TimeSteps, NUM_NODES)) for mc in range(MONTE_CARLOS)]
Undissem = [np.zeros((TimeSteps, NUM_NODES)) for mc in range(MONTE_CARLOS)]
MeanDelay = [np.zeros(SIM_TIME) for mc in range(MONTE_CARLOS)]
MeanVisDelay = [np.zeros(SIM_TIME) for mc in range(MONTE_CARLOS)]
TP = []
WTP = []
latencies = [[] for NodeID in range(NUM_NODES)]
inboxLatencies = [[] for NodeID in range(NUM_NODES)]
latTimes = [[] for NodeID in range(NUM_NODES)]
ServTimes = [[] for NodeID in range(NUM_NODES)]
ArrTimes = [[] for NodeID in range(NUM_NODES)]
interArrTimes = [[] for NodeID in range(NUM_NODES)]
DroppedTrans = [[] for NodeID in range(NUM_NODES)]
DropTimes = [[] for NodeID in range(NUM_NODES)]
"""
Monte Carlo Sims
"""
for mc in range(MONTE_CARLOS):
"""
Generate network topology:
Comment out one of the below lines for either random k-regular graph or a
graph from an adjlist txt file i.e. from the autopeering simulator
"""
if GRAPH=='regular':
G = nx.random_regular_graph(NUM_NEIGHBOURS, NUM_NODES) # random regular graph
elif GRAPH=='complete':
G = nx.complete_graph(NUM_NODES) # complete graph
elif GRAPH=='cycle':
G = nx.cycle_graph(NUM_NODES) # cycle graph
#G = nx.read_adjlist('input_adjlist.txt', delimiter=' ')
# Get adjacency matrix and weight by delay at each channel
ChannelDelays = 0.05*np.ones((NUM_NODES, NUM_NODES))+0.1*np.random.rand(NUM_NODES, NUM_NODES) # not used anymore
AdjMatrix = np.multiply(1*np.asarray(nx.to_numpy_matrix(G)), ChannelDelays)
Net = Network(AdjMatrix) # instantiate the network
for i in range(TimeSteps):
if 100*i/TimeSteps%10==0:
print("Simulation: "+str(mc) +"\t " + str(int(100*i/TimeSteps))+"% Complete")
# discrete time step size specified by global variable STEP
T = STEP*i
"""
The next line is the function which ultimately calls all others
and runs the simulation for a time step
"""
Net.simulate(T)
'''
save summary results in output arrays
'''
for NodeID in range(NUM_NODES):
Lmds[mc][i, NodeID] = Net.Nodes[NodeID].Lambda
if Net.Nodes[NodeID].Inbox.AllPackets and MODE[NodeID]<3: #don't include malicious nodes
HonestPackets = [p for p in Net.Nodes[NodeID].Inbox.AllPackets if MODE[p.Data.NodeID]<3]
if HonestPackets:
OldestPacket = min(HonestPackets, key=lambda x: x.Data.IssueTime)
OldestTxAges[i,NodeID] = T - OldestPacket.Data.IssueTime
InboxLens[mc][i, NodeID] = len(Net.Nodes[2].Neighbours[0].Inbox.Packets[NodeID])/REP[NodeID]
InboxLensMA[mc][i,NodeID] = len(Net.Nodes[2].Neighbours[0].Neighbours[-1].Inbox.Packets[NodeID])/REP[NodeID]
SolidRequests[mc][i,NodeID] = len(Net.Nodes[NodeID].Inbox.RequestedTrans)
Deficits[mc][i, NodeID] = Net.Nodes[6].Inbox.Deficit[NodeID]
Throughput[mc][i, NodeID] = Net.Throughput[NodeID]
WorkThroughput[mc][i,NodeID] = Net.WorkThroughput[NodeID]
Undissem[mc][i,NodeID] = Net.Nodes[NodeID].Undissem
print("Simulation: "+str(mc) +"\t 100% Complete")
OldestTxAge.append(np.mean(OldestTxAges, axis=1))
for NodeID in range(NUM_NODES):
for i in range(SIM_TIME):
delays = [Net.TranDelays[j] for j in range(len(Net.TranDelays)) if int(Net.DissemTimes[j])==i]
if delays:
MeanDelay[mc][i] = sum(delays)/len(delays)
visDelays = [Net.VisTranDelays[j] for j in range(len(Net.VisTranDelays)) if int(Net.DissemTimes[j])==i]
if visDelays:
MeanVisDelay[mc][i] = sum(visDelays)/len(visDelays)
ServTimes[NodeID] = sorted(Net.Nodes[NodeID].ServiceTimes)
ArrTimes[NodeID] = sorted(Net.Nodes[NodeID].ArrivalTimes)
ArrWorks = [x for _,x in sorted(zip(Net.Nodes[NodeID].ArrivalTimes,Net.Nodes[NodeID].ArrivalWorks))]
interArrTimes[NodeID].extend(np.diff(ArrTimes[NodeID])/ArrWorks[1:])
inboxLatencies[NodeID].extend(Net.Nodes[NodeID].InboxLatencies)
DroppedTrans[NodeID].extend(Net.Nodes[NodeID].Inbox.DroppedTrans)
DropTimes[NodeID].extend(Net.Nodes[NodeID].Inbox.DropTimes)
Blacklist = [Net.Nodes[NodeID].Blacklist for NodeID in range(NUM_NODES)]
latencies, latTimes = Net.tran_latency(latencies, latTimes)
window = 50
TP.append(np.concatenate((np.zeros((int(window/STEP), NUM_NODES)),(Throughput[mc][int(window/STEP):,:]-Throughput[mc][:-int(window/STEP),:])))/window)
WTP.append(np.concatenate((np.zeros((int(window/STEP), NUM_NODES)),(WorkThroughput[mc][int(window/STEP):,:]-WorkThroughput[mc][:-int(window/STEP),:])))/window)
#TP.append(np.convolve(np.zeros((Throughput[mc][500:,:]-Throughput[mc][:-500,:])))/5)
Neighbours = [[Neighb.NodeID for Neighb in Node.Neighbours] for Node in Net.Nodes]
del Net
"""
Get results
"""
avgLmds = sum(Lmds)/len(Lmds)
avgTP = sum(TP)/len(TP)
avgWTP = sum(WTP)/len(WTP)
avgInboxLen = sum(InboxLens)/len(InboxLens)
avgInboxLenMA = sum(InboxLensMA)/len(InboxLensMA)
avgSolReq = sum(SolidRequests)/len(SolidRequests)
avgDefs = sum(Deficits)/len(Deficits)
avgUndissem = sum(Undissem)/len(Undissem)
avgMeanDelay = sum(MeanDelay)/len(MeanDelay)
avgMeanVisDelay = sum(MeanVisDelay)/len(MeanVisDelay)
avgOTA = sum(OldestTxAge)/len(OldestTxAge)
"""
Create a directory for these results and save them
"""
dirstr = 'data/'+ strftime("%Y-%m-%d_%H%M%S", gmtime())
os.makedirs(dirstr, exist_ok=True)
pos=nx.spring_layout(G)
nx.draw_networkx_nodes(G,pos,
nodelist=range(NUM_NODES),
node_color=[MODE_COLOUR_MAP[MODE[NodeID]] for NodeID in range(NUM_NODES)],
node_size=200,
alpha=0.8)
nx.draw_networkx_edges(G,pos,width=1.0,alpha=0.5)
mng = plt.get_current_fig_manager()
mng.window.showMaximized()
plt.axis('off')
plt.savefig(dirstr+'/Graph.png', bbox_inches='tight')
np.savetxt(dirstr+'/aaconfig.txt', ['MCs = ' + str(MONTE_CARLOS) +
'\nsimtime = ' + str(SIM_TIME) +
'\nstep = ' + str(STEP) +
'\n\n# Network Parameters' +
'\nnu = ' + str(NU) +
'\ngraph type = ' + GRAPH +
'\nnumber of nodes = ' + str(NUM_NODES) +
'\nnumber of neighbours = ' + str(NUM_NEIGHBOURS) +
'\nrepdist = ' + str(REPDIST) +
'\nmodes = ' + str(MODE) +
'\niot = ' + str(IOT) +
'\niotlow = ' + str(IOTLOW) +
'\niothigh = ' + str(IOTHIGH) +
'\ndcmax = ' + str(MAX_WORK) +
'\n\n# Congestion Control Parameters' +
'\nalpha = ' + str(ALPHA) +
'\nbeta = ' + str(BETA) +
'\ntau = ' + str(TAU) +
'\nminth = ' + str(MIN_TH) +
'\nmaxth = ' + str(MAX_TH) +
'\nquantum = ' + str(QUANTUM) +
'\nw_q = ' + str(W_Q) +
'\np_b = ' + str(P_B) +
'\nSchedule on solid = ' + str(SCHEDULE_ON_SOLID) +
'\nsolidification requests = ' + str(SOLID_REQUESTS) +
'\nblacklist = ' + str(BLACKLIST) +
'\nsched=' + SCHEDULING], delimiter = " ", fmt='%s')
np.savetxt(dirstr+'/avgLmds.csv', avgLmds, delimiter=',')
np.savetxt(dirstr+'/avgTP.csv', avgTP, delimiter=',')
np.savetxt(dirstr+'/avgWTP.csv', avgWTP, delimiter=',')
np.savetxt(dirstr+'/avgInboxLen.csv', avgInboxLen, delimiter=',')
np.savetxt(dirstr+'/avgInboxLenMA.csv', avgInboxLenMA, delimiter=',')
np.savetxt(dirstr+'/avgSolReq.csv', avgSolReq, delimiter=',')
np.savetxt(dirstr+'/avgDefs.csv', avgDefs, delimiter=',')
np.savetxt(dirstr+'/avgUndissem.csv', avgUndissem, delimiter=',')
np.savetxt(dirstr+'/avgMeanDelay.csv', avgMeanDelay, delimiter=',')
np.savetxt(dirstr+'/avgMeanVisDelay.csv', avgMeanVisDelay, delimiter=',')
np.savetxt(dirstr+'/avgOldestTxAge.csv', avgOTA, delimiter=',')
#np.savetxt(dirstr+'/adjlist.csv', np.asarray(Neighbours), delimiter=',')
f = open(dirstr+'/blacklist.csv','w')
with f:
writer = csv.writer(f)
for row in Blacklist:
if row:
writer.writerow(row)
else:
writer.writerow('None')
for NodeID in range(NUM_NODES):
np.savetxt(dirstr+'/latencies'+str(NodeID)+'.csv',
np.asarray(latencies[NodeID]), delimiter=',')
'''
np.savetxt(dirstr+'/inboxLatencies'+str(NodeID)+'.csv',
np.asarray(inboxLatencies[NodeID]), delimiter=',')
np.savetxt(dirstr+'/ServTimes'+str(NodeID)+'.csv',
np.asarray(ServTimes[NodeID]), delimiter=',')
np.savetxt(dirstr+'/ArrTimes'+str(NodeID)+'.csv',
np.asarray(ArrTimes[NodeID]), delimiter=',')
'''
if DroppedTrans[NodeID]:
Drops = np.zeros((len(DroppedTrans[NodeID]), 3))
for i in range(len(DroppedTrans[NodeID])):
Drops[i, 0] = DroppedTrans[NodeID][i].NodeID
Drops[i, 1] = DroppedTrans[NodeID][i].Index
Drops[i, 2] = DropTimes[NodeID][i]
np.savetxt(dirstr+'/Drops'+str(NodeID)+'.csv', Drops, delimiter=',')
return dirstr
def plot_ratesetter_comp(dir1, dir2, dir3):
fig, ax = plt.subplots(figsize=(8,4))
ax.grid(linestyle='--')
ax.set_xlabel('Time (sec)')
axt = ax.twinx()
ax.tick_params(axis='y', labelcolor='black')
axt.tick_params(axis='y', labelcolor='tab:gray')
ax.set_ylabel('Dissemination rate (Work/sec)', color='black')
axt.set_ylabel('Mean Latency (sec)', color='tab:gray')
avgTP1 = np.loadtxt(dir1+'/avgTP.csv', delimiter=',')
avgMeanDelay1 = np.loadtxt(dir1+'/avgMeanDelay.csv', delimiter=',')
avgTP2 = np.loadtxt(dir2+'/avgTP.csv', delimiter=',')
avgMeanDelay2 = np.loadtxt(dir2+'/avgMeanDelay.csv', delimiter=',')
avgTP3 = np.loadtxt(dir3+'/avgTP.csv', delimiter=',')
avgMeanDelay3 = np.loadtxt(dir3+'/avgMeanDelay.csv', delimiter=',')
markerevery = 200
ax.plot(np.arange(10, SIM_TIME, STEP), np.sum(avgTP1[1000:,:], axis=1), color = 'black', marker = 'o', markevery=markerevery)
axt.plot(np.arange(0, SIM_TIME, 1), avgMeanDelay1, color='tab:gray', marker = 'o', markevery=int(markerevery*STEP))
ax.plot(np.arange(10, SIM_TIME, STEP), np.sum(avgTP2[1000:,:], axis=1), color = 'black', marker = 'x', markevery=markerevery)
axt.plot(np.arange(0, SIM_TIME, 1), avgMeanDelay2, color='tab:gray', marker = 'x', markevery=int(markerevery*STEP))
ax.plot(np.arange(10, SIM_TIME, STEP), np.sum(avgTP3[1000:,:], axis=1), color = 'black', marker = '^', markevery=markerevery)
axt.plot(np.arange(0, SIM_TIME, 1), avgMeanDelay3, color='tab:gray', marker = '^', markevery=int(markerevery*STEP))
ModeLines = [Line2D([0],[0],color='black', linestyle=None, marker='o'), Line2D([0],[0],color='black', linestyle=None, marker='x'), Line2D([0],[0],color='black', linestyle=None, marker='^')]
#ax.legend(ModeLines, [r'$A=0.05$', r'$A=0.075$', r'$A=0.1$'], loc='lower right')
#ax.set_title(r'$\beta=0.7, \quad W=2$')
ax.legend(ModeLines, [r'$\beta=0.5$', r'$\beta=0.7$', r'$\beta=0.9$'], loc='lower right')
ax.set_title(r'$A=0.075, \quad W=2$')
#ax.legend(ModeLines, [r'$W=1$', r'$W=2$', r'$W=3$'], loc='lower right')
#ax.set_title(r'$A=0.075, \quad \beta=0.7$')
dirstr = 'data/'+ strftime("%Y-%m-%d_%H%M%S", gmtime())
os.makedirs(dirstr, exist_ok=True)
copyfile(dir1+'/aaconfig.txt', dirstr+'/config1.txt')
copyfile(dir2+'/aaconfig.txt', dirstr+'/config2.txt')
copyfile(dir3+'/aaconfig.txt', dirstr+'/config3.txt')
fig.tight_layout()
plt.savefig(dirstr+'/Throughput.png', bbox_inches='tight')
def plot_scheduler_comp(dir1, dir2):
latencies1 = []
for NodeID in range(NUM_NODES):
if os.stat(dir1+'/latencies'+str(NodeID)+'.csv').st_size != 0:
lat = [np.loadtxt(dir1+'/latencies'+str(NodeID)+'.csv', delimiter=',')]
else:
lat = [0]
latencies1.append(lat)
latencies2 = []
for NodeID in range(NUM_NODES):
if os.stat(dir2+'/latencies'+str(NodeID)+'.csv').st_size != 0:
lat = [np.loadtxt(dir2+'/latencies'+str(NodeID)+'.csv', delimiter=',')]
else:
lat = [0]
latencies2.append(lat)
fig, ax = plt.subplots(2,1, sharex=True, figsize=(8,4))
ax[0].grid(linestyle='--')
ax[1].grid(linestyle='--')
ax[1].set_xlabel('Latency (sec)')
ax[0].set_title('DRR')
ax[1].set_title('DRR-')
xlim = plot_cdf(latencies1, ax[0])
plot_cdf(latencies2, ax[1], xlim)
dirstr = 'data/'+ strftime("%Y-%m-%d_%H%M%S", gmtime())
os.makedirs(dirstr, exist_ok=True)
copyfile(dir1+'/aaconfig.txt', dirstr+'/config1.txt')
copyfile(dir2+'/aaconfig.txt', dirstr+'/config2.txt')
plt.savefig(dirstr+'/LatencyComp.png', bbox_inches='tight')
def plot_results(dirstr):
"""
Initialise plots
"""
plt.close('all')
"""
Load results from the data directory
"""
avgLmds = np.loadtxt(dirstr+'/avgLmds.csv', delimiter=',')
#avgTP = np.loadtxt(dirstr+'/avgTP.csv', delimiter=',')
avgTP = np.loadtxt(dirstr+'/avgWTP.csv', delimiter=',')
avgInboxLen = np.loadtxt(dirstr+'/avgInboxLen.csv', delimiter=',')
avgInboxLenMA = np.loadtxt(dirstr+'/avgInboxLenMA.csv', delimiter=',')
avgSolReq = np.loadtxt(dirstr+'/avgSolReq.csv', delimiter=',')
avgUndissem = np.loadtxt(dirstr+'/avgUndissem.csv', delimiter=',')
avgMeanDelay = np.loadtxt(dirstr+'/avgMeanDelay.csv', delimiter=',')
avgOTA = np.loadtxt(dirstr+'/avgOldestTxAge.csv', delimiter=',')
avgDefs = np.loadtxt(dirstr+'/avgDefs.csv', delimiter=',')
latencies = []
ServTimes = []
ArrTimes = []
for NodeID in range(NUM_NODES):
if os.stat(dirstr+'/latencies'+str(NodeID)+'.csv').st_size != 0:
lat = [np.loadtxt(dirstr+'/latencies'+str(NodeID)+'.csv', delimiter=',')]
else:
lat = [0]
latencies.append(lat)
'''
if os.stat(dirstr+'/InboxLatencies'+str(NodeID)+'.csv').st_size != 0:
inbLat = [np.loadtxt(dirstr+'/inboxLatencies'+str(NodeID)+'.csv', delimiter=',')]
else:
inbLat = [0]
inboxLatencies.append(inbLat)
'''
#ServTimes.append([np.loadtxt(dirstr+'/ServTimes'+str(NodeID)+'.csv', delimiter=',')])
#ArrTimes.append([np.loadtxt(dirstr+'/ArrTimes'+str(NodeID)+'.csv', delimiter=',')])
"""
Plot results
"""
window = 50
fig1, ax1 = plt.subplots(2,1, sharex=True, figsize=(8,8))
ax1[0].title.set_text('Dissemination Rate')
ax1[1].title.set_text('Scaled Dissemination Rate')
ax1[0].grid(linestyle='--')
ax1[1].grid(linestyle='--')
ax1[1].set_xlabel('Time (sec)')
#ax1[0].set_ylabel(r'${\lambda_i} / {\~{\lambda}_i}$')
ax1[0].set_ylabel(r'$DR_i$')
ax1[1].set_ylabel(r'$DR_i / {\~{\lambda}_i}$')
mal = False
iot = False
for NodeID in range(NUM_NODES):
if IOT[NodeID]:
iot = True
marker = 'x'
else:
marker = None
if MODE[NodeID]==1:
ax1[0].plot(np.arange(window, SIM_TIME, STEP), avgTP[int(window/STEP):,NodeID], linewidth=5*REP[NodeID]/REP[0], color='tab:blue', marker=marker, markevery=0.1)
ax1[1].plot(np.arange(window, SIM_TIME, STEP), avgTP[int(window/STEP):,NodeID]*sum(REP)/(NU*REP[NodeID]), linewidth=5*REP[NodeID]/REP[0], color='tab:blue', marker=marker, markevery=0.1)
if MODE[NodeID]==2:
ax1[0].plot(np.arange(window, SIM_TIME, STEP), avgTP[int(window/STEP):,NodeID], linewidth=5*REP[NodeID]/REP[0], color='tab:red', marker=marker, markevery=0.1)
ax1[1].plot(np.arange(window, SIM_TIME, STEP), avgTP[int(window/STEP):,NodeID]*sum(REP)/(NU*REP[NodeID]), linewidth=5*REP[NodeID]/REP[0], color='tab:red', marker=marker, markevery=0.1)
if MODE[NodeID]>2:
ax1[0].plot(np.arange(window, SIM_TIME, STEP), avgTP[int(window/STEP):,NodeID], linewidth=5*REP[NodeID]/REP[0], color='tab:green', marker=marker, markevery=0.1)
ax1[1].plot(np.arange(window, SIM_TIME, STEP), avgTP[int(window/STEP):,NodeID]*sum(REP)/(NU*REP[NodeID]), linewidth=5*REP[NodeID]/REP[0], color='tab:green', marker=marker, markevery=0.1)
mal = True
if mal:
ModeLines = [Line2D([0],[0],color='tab:blue', lw=4), Line2D([0],[0],color='tab:red', lw=4), Line2D([0],[0],color='tab:green', lw=4)]
fig1.legend(ModeLines, ['Content','Best-effort', 'Malicious'], loc='right')
elif iot:
ModeLines = [Line2D([0],[0],color='tab:blue'), Line2D([0],[0],color='tab:red'), Line2D([0],[0],color='tab:blue', marker='x'), Line2D([0],[0],color='tab:red', marker='x')]
fig1.legend(ModeLines, ['Content value node','Best-effort value node', 'Content IoT node', 'Best-effort IoT node'], loc='right')
else:
ModeLines = [Line2D([0],[0],color='tab:blue', lw=4), Line2D([0],[0],color='tab:red', lw=4)]
fig1.legend(ModeLines, ['Content','Best-effort'], loc='right')
plt.savefig(dirstr+'/Rates.png', bbox_inches='tight')
fig2, ax2 = plt.subplots(figsize=(8,4))
ax2.grid(linestyle='--')
ax2.set_xlabel('Time (sec)')
ax2.plot(np.arange(window, SIM_TIME, STEP), np.sum(avgTP[int(window/STEP):,:], axis=1), color = 'black')
ax2.set_ylim((0,1.1*NU))
ax22 = ax2.twinx()
ax22.plot(np.arange(0, SIM_TIME, 1), avgMeanDelay, color='tab:gray')
ax2.tick_params(axis='y', labelcolor='black')
ax22.tick_params(axis='y', labelcolor='tab:gray')
ax2.set_ylabel('Dissemination rate (Work/sec)', color='black')
ax22.set_ylabel('Mean Latency (sec)', color='tab:gray')
fig2.tight_layout()
plt.savefig(dirstr+'/Throughput.png', bbox_inches='tight')
fig3, ax3 = plt.subplots(figsize=(8,4))
ax3.grid(linestyle='--')
ax3.set_xlabel('Latency (sec)')
plot_cdf(latencies, ax3)
plt.savefig(dirstr+'/Latency.png', bbox_inches='tight')
'''
fig3a, ax3a = plt.subplots(figsize=(8,4))
ax3a.grid(linestyle='--')
ax3a.set_xlabel('Inbox Latency (sec)')
plot_cdf(inboxLatencies, ax3a)
plt.savefig(dirstr+'/InboxLatency.png', bbox_inches='tight')
'''
'''
fig4, ax4 = plt.subplots(figsize=(8,4))
ax4.grid(linestyle='--')
ax4.set_xlabel('Time (sec)')
ax4.set_ylabel(r'$\lambda_i$')
ax4.plot(np.arange(0, SIM_TIME, STEP), np.sum(avgLmds, axis=1), color='tab:blue')
for NodeID in range(NUM_NODES):
if MODE[NodeID]==1:
ax4.plot(np.arange(0, SIM_TIME, STEP), avgLmds[:,NodeID], linewidth=5*REP[NodeID]/REP[0], color='tab:blue')
if MODE[NodeID]==2:
ax4.plot(np.arange(0, SIM_TIME, STEP), avgLmds[:,NodeID], linewidth=5*REP[NodeID]/REP[0], color='tab:red')
if MODE[NodeID]==3:
ax4.plot(np.arange(0, SIM_TIME, STEP), avgLmds[:,NodeID], linewidth=5*REP[NodeID]/REP[0], color='tab:green')
plt.savefig(dirstr+'/IssueRates.png', bbox_inches='tight')
'''
fig5, ax5 = plt.subplots(figsize=(8,4))
ax5.grid(linestyle='--')
ax5.set_xlabel('Time (sec)')
ax5.set_ylabel('Reputation-scaled inbox length (neighbour)')
N=100
for NodeID in range(NUM_NODES):
if MODE[NodeID]==1:
ax5.plot(np.arange((N-1)*STEP, SIM_TIME, STEP), np.convolve(np.ones(N)/N, avgInboxLen[:,NodeID], 'valid'), color='tab:blue', linewidth=5*REP[NodeID]/REP[0])
if MODE[NodeID]==2:
ax5.plot(np.arange((N-1)*STEP, SIM_TIME, STEP), np.convolve(np.ones(N)/N, avgInboxLen[:,NodeID], 'valid'), color='tab:red', linewidth=5*REP[NodeID]/REP[0])
if MODE[NodeID]>2:
ax5.plot(np.arange((N-1)*STEP, SIM_TIME, STEP), np.convolve(np.ones(N)/N, avgInboxLen[:,NodeID], 'valid'), color='tab:green', linewidth=5*REP[NodeID]/REP[0])
ax5.set_xlim(0, SIM_TIME)
plt.savefig(dirstr+'/AvgInboxLen.png', bbox_inches='tight')
fig5, ax5 = plt.subplots(figsize=(8,4))
ax5.grid(linestyle='--')
ax5.set_xlabel('Time (sec)')
ax5.set_ylabel('Reputation-scaled inbox length (neighbour of neighbour)')
N=100
for NodeID in range(NUM_NODES):
if MODE[NodeID]==1:
ax5.plot(np.arange((N-1)*STEP, SIM_TIME, STEP), np.convolve(np.ones(N)/N, avgInboxLenMA[:,NodeID], 'valid'), color='tab:blue', linewidth=5*REP[NodeID]/REP[0])
if MODE[NodeID]==2:
ax5.plot(np.arange((N-1)*STEP, SIM_TIME, STEP), np.convolve(np.ones(N)/N, avgInboxLenMA[:,NodeID], 'valid'), color='tab:red', linewidth=5*REP[NodeID]/REP[0])
if MODE[NodeID]>2:
ax5.plot(np.arange((N-1)*STEP, SIM_TIME, STEP), np.convolve(np.ones(N)/N, avgInboxLenMA[:,NodeID], 'valid'), color='tab:green', linewidth=5*REP[NodeID]/REP[0])
ax5.set_xlim(0, SIM_TIME)
plt.savefig(dirstr+'/AvgInboxLenMA.png', bbox_inches='tight')
"""
fig5, ax5 = plt.subplots(figsize=(8,4))
ax5.grid(linestyle='--')
ax5.set_xlabel('Time (sec)')
ax5.set_ylabel('Deficits at Node 6')
N=100
for NodeID in range(NUM_NODES):
if MODE[NodeID]==1:
ax5.plot(np.arange((N-1)*STEP, SIM_TIME, STEP), np.convolve(np.ones(N)/N, avgSolReq[:,NodeID], 'valid'), color='tab:blue', linewidth=5*REP[NodeID]/REP[0])
if MODE[NodeID]==2:
ax5.plot(np.arange((N-1)*STEP, SIM_TIME, STEP), np.convolve(np.ones(N)/N, avgSolReq[:,NodeID], 'valid'), color='tab:red', linewidth=5*REP[NodeID]/REP[0])
if MODE[NodeID]>2:
ax5.plot(np.arange((N-1)*STEP, SIM_TIME, STEP), np.convolve(np.ones(N)/N, avgSolReq[:,NodeID], 'valid'), color='tab:green', linewidth=5*REP[NodeID]/REP[0])
ax5.set_xlim(0, SIM_TIME)
plt.savefig(dirstr+'/AvgSolReq.png', bbox_inches='tight')
"""
fig5, ax5 = plt.subplots(figsize=(8,4))
ax5.grid(linestyle='--')
ax5.set_xlabel('Time (sec)')
ax5.set_ylabel('Deficits at Node 6')
N=100
for NodeID in range(NUM_NODES):
if MODE[NodeID]==1:
ax5.plot(np.arange(0, SIM_TIME, STEP), avgDefs[:,NodeID], color='tab:blue', linewidth=5*REP[NodeID]/REP[0])
if MODE[NodeID]==2:
ax5.plot(np.arange(0, SIM_TIME, STEP), avgDefs[:,NodeID], color='tab:red', linewidth=5*REP[NodeID]/REP[0])
if MODE[NodeID]>2:
ax5.plot(np.arange(0, SIM_TIME, STEP), avgDefs[:,NodeID], color='tab:green', linewidth=5*REP[NodeID]/REP[0])
ax5.set_xlim(0, SIM_TIME)
plt.savefig(dirstr+'/avgDefs.png', bbox_inches='tight')
'''
fig5a, ax5a = plt.subplots(figsize=(8,4))
ax5a.grid(linestyle='--')
ax5a.set_xlabel('Time (sec)')
ax5a.set_ylabel('Inbox Len and Arrivals')
NodeID = 2
step = 1
bins = np.arange(0, SIM_TIME, step)
i = 0
j = 0
nArr = np.zeros(len(bins))
inboxLen = np.zeros(len(bins))
for b, t in enumerate(bins):
if b>0:
inboxLen[b] = inboxLen[b-1]
while ArrTimes[NodeID][0][i] < t+step:
nArr[b] += 1
inboxLen[b] +=1
i += 1
if i>=len(ArrTimes[NodeID][0]):
break
while ServTimes[NodeID][0][j] < t+step:
inboxLen[b] -= 1
j += 1
if j>=len(ServTimes[NodeID][0]):
break
ax5a.plot(bins, nArr/(step*NU), color = 'black')
ax5b = ax5a.twinx()
ax5b.plot(bins, inboxLen, color='blue')
plt.savefig(dirstr+'/InboxLenMA.png', bbox_inches='tight')
'''
fig6, ax6 = plt.subplots(figsize=(8,4))
ax6.grid(linestyle='--')
ax6.set_xlabel('Node ID')
ax6.title.set_text('Reputation Distribution')
ax6.set_ylabel('Reputation')
for NodeID in range(NUM_NODES):
if MODE[NodeID]==0:
ax6.bar(NodeID, REP[NodeID], color='gray')
if MODE[NodeID]==1:
ax6.bar(NodeID, REP[NodeID], color='tab:blue')
if MODE[NodeID]==2:
ax6.bar(NodeID, REP[NodeID], color='tab:red')
if MODE[NodeID]>2:
ax6.bar(NodeID, REP[NodeID], color='tab:green')
ModeLines = [Line2D([0],[0],color='tab:red', lw=4), Line2D([0],[0],color='tab:blue', lw=4), Line2D([0],[0],color='gray', lw=4), Line2D([0],[0],color='tab:green', lw=4)]
ax6.legend(ModeLines, ['Best-effort', 'Content', 'Inactive', 'Malicious'], loc='upper right')
plt.savefig(dirstr+'/RepDist.png', bbox_inches='tight')
'''
fig7, ax7 = plt.subplots(figsize=(8,4))
plot_cdf(ISTimes, ax7)
ax7.grid(linestyle='--')
ax7.set_xlabel('Inter-service time (sec)')
plt.savefig(dirstr+'/InterServiceTimes.png', bbox_inches='tight')
'''
'''
fig8, ax8 = plt.subplots(figsize=(8,4))
#plot_cdf_exp(IATimes, ax8)
ax8.grid(linestyle='--')
ax8.set_xlabel('Inter-arrival time (sec)')
plt.savefig(dirstr+'/InterArrivalTimes.png', bbox_inches='tight')
'''
fig9, ax9 = plt.subplots(figsize=(8,4))
ax9.grid(linestyle='--')
ax9.plot(np.arange(0, SIM_TIME, STEP), avgOTA, color='black')
ax9.set_ylabel('Max time in transit (sec)')
ax9.set_xlabel('Time (sec)')
plt.savefig(dirstr+'/MaxAge.png', bbox_inches='tight')
def plot_cdf(data, ax, xlim=0):
step = STEP/10
maxval = 0
for NodeID in range(NUM_NODES):
val = np.max(data[NodeID][0])
if val>maxval:
maxval = val
maxval = max(maxval, xlim)
Lines = [[] for NodeID in range(NUM_NODES)]
mal = False
iot = False
for NodeID in range(NUM_NODES):
if MODE[NodeID]>0:
bins = np.arange(0, round(maxval*1/step), 1)*step
pdf = np.zeros(len(bins))
i = 0
if data[NodeID][0].size>1:
lats = sorted(data[NodeID][0])
for lat in lats:
while i<len(bins):
if lat>bins[i]:
i += 1
else:
break
pdf[i-1] += 1
pdf = pdf/sum(pdf) # normalise
cdf = np.cumsum(pdf)
if IOT[NodeID]:
iot = True
marker = 'x'
else:
marker = None
if MODE[NodeID]==1:
Lines[NodeID] = ax.plot(bins, cdf, color='tab:blue', linewidth=4*REP[NodeID]/REP[0], marker=marker, markevery=0.1)
if MODE[NodeID]==2:
Lines[NodeID] = ax.plot(bins, cdf, color='tab:red', linewidth=4*REP[NodeID]/REP[0], marker=marker, markevery=0.1)
if MODE[NodeID]>2:
mal = True
Lines[NodeID] = ax.plot(bins, cdf, color='tab:green', linewidth=4*REP[NodeID]/REP[0], marker=marker, markevery=0.1)
if mal:
ModeLines = [Line2D([0],[0],color='tab:red', lw=4), Line2D([0],[0],color='tab:blue', lw=4), Line2D([0],[0],color='tab:green', lw=4)]
ax.legend(ModeLines, ['Best-effort', 'Content','Malicious'], loc='lower right')
elif iot:
ModeLines = [Line2D([0],[0],color='tab:blue'), Line2D([0],[0],color='tab:red'), Line2D([0],[0],color='tab:blue', marker='x'), Line2D([0],[0],color='tab:red', marker='x')]
ax.legend(ModeLines, ['Content value node','Best-effort value node', 'Content IoT node', 'Best-effort IoT node'], loc='lower right')
else:
ModeLines = [Line2D([0],[0],color='tab:blue', lw=4), Line2D([0],[0],color='tab:red', lw=4)]
ax.legend(ModeLines, ['Content','Best-effort'], loc='lower right')
return maxval
def plot_cdf_exp(data, ax):
step = STEP/10
maxval = 0
for NodeID in range(NUM_NODES):
if len(data[NodeID][0])>0:
val = np.max(data[NodeID][0])
else:
val = 0
if val>maxval:
maxval = val
for NodeID in range(len(data)):
if MODE[NodeID]>0:
bins = np.arange(0, round(maxval*1/step), 1)*step
pdf = np.zeros(len(bins))
i = 0
lats = sorted(data[NodeID][0])
for lat in lats:
while i<len(bins):
if lat>bins[i]:
i += 1
else:
break
pdf[i-1] += 1
pdf = pdf/sum(pdf) # normalise
cdf = np.cumsum(pdf)
ax.plot(bins, cdf, color='tab:red')
lmd = np.mean(data[1][0])
ax.axvline(lmd, linestyle='--', color='tab:red')
ax.set_title('rho = ' + str(1/(lmd*NU)))
ax.plot(bins, np.ones(len(bins))-np.exp(-(1/lmd)*bins), color='black')
#ax.plot(bins, np.ones(len(bins))-np.exp(-0.95*NU*bins), linestyle='--', color='tab:red')
ModeLines = [Line2D([0],[0],color='tab:red', lw=2), Line2D([0],[0],linestyle='--',color='black', lw=2)]
ax.legend(ModeLines, ['Measured',r'$1-e^{-\lambda t}$'], loc='lower right')
class Transaction:
"""
Object to simulate a transaction and its edges in the DAG
"""
def __init__(self, IssueTime, Parents, Node, Work=0, Index=None, VisibleTime=None):
self.IssueTime = IssueTime
self.VisibleTime = VisibleTime
self.Children = []
self.Parents = Parents
for p in Parents:
p.Children.append(self)
self.Index = Index
self.InformedNodes = 0
self.GlobalSolidTime = []
self.Work = Work
if Node:
self.NodeID = Node.NodeID # signature of issuing node
else: # genesis
self.NodeID = []
class SolRequest:
'''
Object to request solidification of a transaction
'''
def __init__(self, Tran):
self.Tran = Tran
class Node:
"""
Object to simulate an IOTA full node
"""
def __init__(self, Network, NodeID, Genesis, PoWDelay = 1):
self.TipsSet = []
self.Ledger = [Genesis]
self.Neighbours = []
self.Network = Network
self.Inbox = Inbox(self)
self.NodeID = NodeID
self.Alpha = ALPHA*REP[NodeID]/sum(REP)
self.Lambda = NU*REP[NodeID]/sum(REP)
self.BackOff = []
self.LastBackOff = []
self.LastScheduleTime = 0
self.LastScheduleWork = 0
self.LastIssueTime = 0
self.LastIssueWork = 0
self.IssuedTrans = []
self.Undissem = 0
self.UndissemWork = 0
self.ServiceTimes = []
self.ArrivalTimes = []
self.ArrivalWorks = []
self.InboxLatencies = []
self.ValidTips = [True for NodeID in range(NUM_NODES)]
self.TranCounter = 0
self.Blacklist = []
def issue_txs(self, Time):
"""
Create new TXs at rate lambda and do PoW
"""
if MODE[self.NodeID]>0:
if MODE[self.NodeID]==2:
if self.BackOff:
self.LastIssueTime += TAU#BETA*REP[self.NodeID]/self.Lambda
while Time+STEP >= self.LastIssueTime + self.LastIssueWork/self.Lambda:
self.LastIssueTime += self.LastIssueWork/self.Lambda
Parents = self.select_tips()
#Work = np.random.uniform(AVG_WORK[self.NodeID]-0.5, AVG_WORK[self.NodeID]+0.5)
if IOT[self.NodeID]:
Work = np.random.uniform(IOTLOW,IOTHIGH)
else:
Work = 1
self.LastIssueWork = Work
self.TranCounter += 1
self.IssuedTrans.append(Transaction(self.LastIssueTime, Parents, self, Work, Index=self.TranCounter))
elif MODE[self.NodeID]==1:
if IOT[self.NodeID]:
Work = np.random.uniform(IOTLOW,IOTHIGH)
else:
Work = 1
times = np.sort(np.random.uniform(Time, Time+STEP, np.random.poisson(STEP*self.Lambda/Work)))
for t in times:
Parents = self.select_tips()
#Work = np.random.uniform(AVG_WORK[self.NodeID]-0.5, AVG_WORK[self.NodeID]+0.5)
self.TranCounter += 1
self.IssuedTrans.append(Transaction(t, Parents, self, Work, Index=self.TranCounter))
else:
Work = 1
times = np.sort(np.random.uniform(Time, Time+STEP, np.random.poisson(STEP*self.Lambda/Work)))
for t in times:
Parents = self.select_tips()
#Work = np.random.uniform(AVG_WORK[self.NodeID]-0.5, AVG_WORK[self.NodeID]+0.5)
self.TranCounter += 1
self.IssuedTrans.append(Transaction(t, Parents, self, Work, Index=self.TranCounter))
# check PoW completion
while self.IssuedTrans:
Tran = self.IssuedTrans.pop(0)
p = Packet(self, self, Tran, Tran.IssueTime, Tran.IssueTime)
if MODE[self.NodeID]>2: # malicious don't consider own txs for scheduling
self.add_to_ledger(self, Tran, Tran.IssueTime)
else:
self.add_to_inbox(p, Tran.IssueTime)
def select_tips(self):
"""
Implements uniform random tip selection
"""
ValidTips = [tip for tip in self.TipsSet if self.ValidTips[tip.NodeID]]
if len(ValidTips)>1:
Selection = sample(ValidTips, 2)
elif len(self.Ledger)<2:
Selection = [self.Ledger[0]]
else:
Selection = self.Ledger[-2:-1]
return Selection
def schedule_txs(self, Time):
"""
schedule txs from inbox at a fixed deterministic rate NU
"""
# sort inboxes by arrival time
self.Inbox.AllPackets.sort(key=lambda p: p.EndTime)
self.Inbox.SolidPackets.sort(key=lambda p: p.EndTime)
for NodeID in range(NUM_NODES):
self.Inbox.Packets[NodeID].sort(key=lambda p: p.Data.IssueTime)
# process according to global rate Nu
while self.Inbox.SolidPackets or self.Inbox.Scheduled:
if self.Inbox.Scheduled:
nextSchedTime = self.LastScheduleTime+(self.LastScheduleWork/NU)
else:
nextSchedTime = max(self.LastScheduleTime+(self.LastScheduleWork/NU), self.Inbox.SolidPackets[0].EndTime)
if nextSchedTime<Time+STEP:
if SCHEDULING=='drr':
Packet = self.Inbox.drr_schedule(nextSchedTime)
elif SCHEDULING=='drr_lds':
Packet = self.Inbox.drr_lds_schedule(nextSchedTime)
elif SCHEDULING=='drrpp':
Packet = self.Inbox.drrpp_schedule(nextSchedTime)
elif SCHEDULING=='fifo':
Packet = self.Inbox.fifo_schedule(nextSchedTime)
if Packet is not None:
if Packet.Data not in self.Ledger:
self.add_to_ledger(Packet.TxNode, Packet.Data, nextSchedTime)
# update AIMD
#if Packet.Data.NodeID==self.NodeID:
self.Network.Nodes[Packet.Data.NodeID].InboxLatencies.append(nextSchedTime-Packet.EndTime)
self.Inbox.Avg = (1-W_Q)*self.Inbox.Avg + W_Q*sum([p.Data.Work for p in self.Inbox.Packets[self.NodeID]])
self.set_rate(nextSchedTime)
self.LastScheduleTime = nextSchedTime
self.LastScheduleWork = Packet.Data.Work
self.ServiceTimes.append(nextSchedTime)
else:
break
else:
break
def add_to_ledger(self, TxNode, Tran, Time):
"""
Adds the transaction to the local copy of the ledger and broadcast it
"""
self.Ledger.append(Tran)
if Tran.NodeID==self.NodeID:
self.Undissem += 1
self.UndissemWork += Tran.Work
Tran.VisibleTime = Time
# mark this TX as received by this node
Tran.InformedNodes += 1
if Tran.InformedNodes==NUM_NODES:
self.Network.Throughput[Tran.NodeID] += 1
self.Network.WorkThroughput[Tran.NodeID] += Tran.Work
self.Network.TranDelays.append(Time-Tran.IssueTime)
self.Network.VisTranDelays.append(Time-Tran.VisibleTime)
self.Network.DissemTimes.append(Time)
Tran.GlobalSolidTime = Time
self.Network.Nodes[Tran.NodeID].Undissem -= 1
self.Network.Nodes[Tran.NodeID].UndissemWork -= Tran.Work
if Tran.Children:
if not [c for c in Tran.Children if c in self.Ledger]:
self.TipsSet.append(Tran)
for c in Tran.Children:
if c in self.Inbox.Trans:
if self.is_solid(c):
packet = [p for p in self.Inbox.AllPackets if p.Data==c]
self.Inbox.SolidPackets.append(packet[0])
else:
self.TipsSet.append(Tran)
for Parent in Tran.Parents:
if Parent in self.TipsSet:
self.TipsSet.remove(Parent)
else:
continue
self.forward(TxNode, Tran, Time)# broadcast the packet
def forward(self, TxNode, Tran, Time):
'''
Forward this transaction to all but the node it was received from
'''
if MODE[self.NodeID]==4:
neighb = np.random.randint(len(self.Neighbours))
self.Network.send_data(self, self.Neighbours[neighb], Tran, Time)
else:
self.Network.broadcast_data(self, TxNode, Tran, Time)
def check_congestion(self, Time):
"""
Check for rate setting
"""
if self.Inbox.Avg>MIN_TH*REP[self.NodeID]:
if self.Inbox.Avg>MAX_TH*REP[self.NodeID]:
self.BackOff = True
elif np.random.rand()<P_B*(self.Inbox.Avg-MIN_TH*REP[self.NodeID])/((MAX_TH-MIN_TH)*REP[self.NodeID]):
self.BackOff = True
def set_rate(self, Time):
"""
Additively increase or multiplicatively decrease lambda
"""
if MODE[self.NodeID]>0:
if MODE[self.NodeID]==2 and Time>=START_TIMES[self.NodeID]: # AIMD starts after settling time
# if wait time has not passed---reset.
if self.LastBackOff:
if Time < self.LastBackOff + TAU:#BETA*REP[self.NodeID]/self.Lambda:
self.BackOff = False
return
# multiplicative decrease or else additive increase
if self.BackOff:
self.Lambda = self.Lambda*BETA
self.BackOff = False
self.LastBackOff = Time
else:
self.Lambda += self.Alpha
elif MODE[self.NodeID]>2 and Time>=START_TIMES[self.NodeID]: # malicious starts after start time
self.Lambda = NUM_NEIGHBOURS*NU*REP[self.NodeID]/sum(REP)
else: # any active node, malicious or honest
self.Lambda = NU*REP[self.NodeID]/sum(REP)
else:
self.Lambda = 0
def add_to_inbox(self, Packet, Time):
"""
Add to inbox if not already received and/or processed
"""
Tran = Packet.Data
if Tran not in self.Inbox.Trans:
if Tran not in self.Ledger:
NodeID = Tran.NodeID
ScaledWork = self.Inbox.Work[NodeID]/REP[NodeID]
if Tran not in self.Inbox.RequestedTrans:
if NodeID not in self.Blacklist:
if NodeID==self.NodeID:
self.Inbox.add_packet(Packet)
self.check_congestion(Time)
else:
if ScaledWork>DROP_TH and BLACKLIST:
self.Blacklist.append(NodeID)
self.Inbox.drop_packet(Packet)
else:
self.ValidTips[NodeID] = True
self.Inbox.add_packet(Packet)
else:
self.Inbox.drop_packet(Packet)
else:
self.Inbox.add_packet(Packet)
self.ArrivalWorks.append(Tran.Work)
self.ArrivalTimes.append(Time)
def is_solid(self, Tran):
isSolid = True
for p in Tran.Parents:
if p not in self.Ledger:
isSolid = False
return isSolid
class Inbox:
"""
Object for holding packets in different channels corresponding to different nodes
"""
def __init__(self, Node):
self.Node = Node
self.AllPackets = [] # Inbox_m
self.SolidPackets = []
self.Packets = [[] for NodeID in range(NUM_NODES)] # Inbox_m(i)
self.Work = np.zeros(NUM_NODES)
self.Trans = []
self.RRNodeID = np.random.randint(NUM_NODES) # start at a random node