forked from Mona566/ACM_DLT-user-experience
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusernode.py
1533 lines (1391 loc) · 68.9 KB
/
usernode.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
from time import gmtime, strftime
from shutil import copyfile
import csv
np.random.seed(0)
# Simulation Parameters
MONTE_CARLOS = 10
SIM_TIME = 180
STEP = 0.01
# Network Parameters
GRAPH = 'regular' # regular, complete or cycle
NU = 50
NUM_NODES = 50
NUM_USERS = 2
NUM_NEIGHBOURS = 4
START_TIMES = 10*np.ones(NUM_NODES)
NODETX_SIZE= [int(10*(NUM_NODES+1)/((NodeID+1)**0.9)) for NodeID in range(NUM_NODES)]
RE_PEERING= False
C_MAX1 = 8
C_MAX2 = 10
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 = [2 for _ in range(NUM_NODES)]
#MODE = [1 for _ in range(NUM_NODES)]
#MODE = [3-(NodeID+1)%4 for NodeID in range(NUM_NODES)] # malicoius env
#MODE[2]=4
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 = 10
SCHEDULE_ON_SOLID = True
SOLID_REQUESTS = True
SCHEDULING = 'drr_lds'
NODE_SELECTION = ['URNS', 'RBNS', 'DBNS', 'DBNS+'] # URNS, RBNS, DBNS or DBNS+
USER_TRAFFIC = [0.9, 0.98, 1.2]
DELAY_SETPOINT = [5,10,15]
def main():
# time_string = strftime("%Y-%m-%d_%H%M%S", gmtime())
# for NodeSelection in NODE_SELECTION:
# for traffic in USER_TRAFFIC:
# for delay_setpoint in DELAY_SETPOINT:
# simulate(traffic, NodeSelection, delay_setpoint, time_string)
#dirstr = 'data/' + time_string
dirstr = 'data/2022-11-29_230628' # regular results
#dirstr = 'data/2022-11-30_173312'
#node_plots_delay_setpoint(dirstr)
print_qos(dirstr)
#node_plots_traffic(dirstr)
def print_qos(dirstr):
for j, NodeSelection in enumerate(NODE_SELECTION):
for i,traffic in enumerate(USER_TRAFFIC):
LTPDelays = np.loadtxt(dirstr+ '_' + NodeSelection + '_' + str(int(100*traffic)) + '/LTPDelay.csv', delimiter=',')
qos = len([i for i in LTPDelays if i>20])/len(LTPDelays)
expectedDelay = sum(LTPDelays)/len(LTPDelays)
print(NodeSelection + str(int(100*traffic)) + 'qos = ' +str(qos))
print(NodeSelection + str(int(100*traffic)) + 'expected delay = ' +str(expectedDelay) + '\n')
def node_plots_traffic(dirstr):
N=100
os.makedirs(dirstr, exist_ok=True)
titles = ['(a) ', '(b) ', '(c) ']
ylims = [[5,5,5], [5,5,35], [5,5,35], [5,5,35]]
for j, NodeSelection in enumerate(NODE_SELECTION):
fig, axes = plt.subplots(nrows=len(USER_TRAFFIC), figsize=(8,12))
for i,traffic in enumerate(USER_TRAFFIC):
if len(USER_TRAFFIC)>1:
ax = axes[i]
else:
ax = axes
ax.grid(linestyle='--')
ax.set_ylabel('LTP Delay (sec)')
ax.set_xlabel('Time (sec)')
#ax.set_ylim(0,ylims[j][i])
AvgActualTXdelay = np.loadtxt(dirstr+ '_' + NodeSelection + '_' + str(int(100*traffic)) + '/AvgActualTXdelay.csv', delimiter=',')# '_' + str(DELAY_SETPOINT[0]) + '/AvgActualTXdelay.csv', delimiter=',')
ax.set_title(titles[i]+ str(int(100*traffic)) + '% capacity')
for NodeID in range(NUM_NODES):
ax.plot(np.arange((N-1)*STEP, SIM_TIME, STEP), np.convolve(np.ones(N)/N, AvgActualTXdelay[:,NodeID], 'valid'), color='tab:red', linewidth=5*REP[NodeID]/REP[0])
fig.tight_layout()
plt.savefig(dirstr+'/'+NodeSelection+'.png', bbox_inches='tight')
plt.close()
def node_plots_delay_setpoint(dirstr):
N=100
os.makedirs(dirstr, exist_ok=True)
for NodeSelection in NODE_SELECTION:
fig, axes = plt.subplots(nrows=len(DELAY_SETPOINT), figsize=(8,12))
for i,delay_setpoint in enumerate(DELAY_SETPOINT):
if len(DELAY_SETPOINT)>1:
ax = axes[i]
else:
ax = axes
ax.grid(linestyle='--')
ax.set_xlabel('Time (sec)')
ax.set_ylabel('LTP Delay (sec)')
ax.set_ylim(0, 25)
AvgActualTXdelay = np.loadtxt(dirstr+ '_' + NodeSelection + '_' + str(int(100*USER_TRAFFIC[0])) + '_' + str(delay_setpoint) + '/AvgActualTXdelay.csv', delimiter=',')
NodeIncome = np.loadtxt(dirstr+'_' + NodeSelection + '_' + str(int(100*USER_TRAFFIC[0])) + '_' + str(delay_setpoint) +'/Income.csv', delimiter=',')
ax.set_title('Income = ' + str(sum(NodeIncome)))
for NodeID in range(NUM_NODES):
ax.plot(np.arange((N-1)*STEP, SIM_TIME, STEP), np.convolve(np.ones(N)/N, AvgActualTXdelay[:,NodeID], 'valid'), color='tab:red', linewidth=5*REP[NodeID]/REP[0])
fig.tight_layout()
plt.savefig(dirstr+'/'+NodeSelection+'.png', bbox_inches='tight')
plt.close()
def simulate(traffic, NodeSelection, delay_setpoint, time_string):
"""
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)]
TXPool= [np.zeros((TimeSteps, NUM_NODES)) for mc in range(MONTE_CARLOS)]
UserTX= [np.zeros((TimeSteps, NUM_USERS)) for mc in range(MONTE_CARLOS)]
EstTXPoolDelay = [np.zeros((TimeSteps, NUM_NODES)) for mc in range(MONTE_CARLOS)]
ActualTXdelay= [np.zeros((TimeSteps, NUM_NODES)) for mc in range(MONTE_CARLOS)]
FilteredRateRecord= [np.zeros((TimeSteps, NUM_NODES)) for mc in range(MONTE_CARLOS)]
TXdelayError= [np.zeros((TimeSteps, NUM_NODES)) for mc in range(MONTE_CARLOS)]
ScheduledTX= np.zeros((TimeSteps, NUM_NODES))
UserDelay = [np.zeros((TimeSteps, NUM_USERS)) for mc in range(MONTE_CARLOS)]
Costfee = [np.zeros((TimeSteps, NUM_NODES)) for mc in range(MONTE_CARLOS)]
Income = [np.zeros(NUM_NODES) for _ in range(MONTE_CARLOS)]
TP = []
WTP = []
UserIssuedTX= []
NodeschedulTX= []
latencies = [[] for NodeID in range(NUM_NODES)]
LTPDelays = []
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, traffic, NodeSelection, delay_setpoint) # 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 Users
'''
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
if Net.Nodes[2].Neighbours!=[]:
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
TXPool[mc][i, NodeID] = len(Net.Nodes[NodeID].LTP)
EstTXPoolDelay[mc][i, NodeID] = Net.Nodes[NodeID].Estdelay
ActualTXdelay[mc][i, NodeID]= Net.Nodes[NodeID].ActualTXdelay
FilteredRateRecord[mc][i, NodeID]= Net.Nodes[NodeID].FilteredRateRecord
TXdelayError[mc][i, NodeID]= Net.Nodes[NodeID].TXdelayError
Costfee[mc][i, NodeID]= Net.Nodes[NodeID].Fee
ScheduledTX[i, NodeID]+= Net.Nodes[NodeID].Inbox.ScheduledTX
for UserID in range(NUM_USERS):
UserTX[mc][i, UserID] = Net.IssuedTX[UserID]
UserDelay[mc][i, UserID]= Net.Users[UserID].User_lastdelay
print("Simulation: "+str(mc) +"\t 100% Complete")
OldestTxAge.append(np.mean(OldestTxAges, axis=1))
for NodeID in range(NUM_NODES):
Income[mc][NodeID] = Net.Nodes[NodeID].Income
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)
LTPDelays.extend(Net.LTPDelays)
latencies, latTimes = Net.tran_latency(latencies, latTimes)
window = 10
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)
UserIssuedTX.append(np.concatenate((np.zeros((int(window/STEP), NUM_USERS)),(UserTX[mc][int(window/STEP):,:]-UserTX[mc][:-int(window/STEP),:])))/window)
NodeschedulTX.append(np.concatenate((np.zeros((int(window/STEP), NUM_NODES)),(ScheduledTX[int(window/STEP):,:]-ScheduledTX[:-int(window/STEP),:])))/window)
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)
avgTXPool= sum(TXPool)/len(TXPool)
avguserTX= sum(UserIssuedTX)/len(UserIssuedTX)
avgNodeschedulTX= sum(NodeschedulTX)/len(NodeschedulTX)
avgEstTXPoolDelay= sum(EstTXPoolDelay)/len(EstTXPoolDelay)
AvgActualTXdelay= sum(ActualTXdelay)/len(ActualTXdelay)
AvgFilteredRateRecord= sum(FilteredRateRecord)/len(FilteredRateRecord)
AvgTXdelayError= sum(TXdelayError)/len(TXdelayError)
AvgUserDelay = sum(UserDelay)/len(UserDelay)
AvgCostfee = sum(Costfee)/len(Costfee)
avgIncome = sum(Income)/len(Income)
"""
Create a directory for these results and save them
"""
dirstr = 'data/'+ time_string + '_' + NodeSelection + '_' + str(int(100*traffic)) + '_' + str(delay_setpoint)
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 users = ' + str(NUM_USERS) +
'\nuser traffic = ' + str(traffic) +
'\nnumber of neighbours = ' + str(NUM_NEIGHBOURS) +
'\nrepdist = ' + str(REPDIST) +
'\nmodes = ' + str(MODE) +
'\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) +
'\nnode selection = ' + NodeSelection +
'\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+'/avgTXPool.csv', avgTXPool, delimiter=',')
np.savetxt(dirstr+'/avguserTX.csv', avguserTX, delimiter=',')
np.savetxt(dirstr+'/avgNodeschedulTX.csv', avgNodeschedulTX, delimiter=',')
np.savetxt(dirstr+'/avgEstTXPoolDelay.csv', avgEstTXPoolDelay, delimiter=',')
np.savetxt(dirstr+'/AvgActualTXdelay.csv', AvgActualTXdelay, delimiter=',')
np.savetxt(dirstr+'/AvgFilteredRateRecord.csv', AvgFilteredRateRecord, delimiter=',')
np.savetxt(dirstr+'/AvgTXdelayError.csv', AvgTXdelayError, delimiter=',')
np.savetxt(dirstr+'/AvgUserDelay.csv', AvgUserDelay, delimiter=',')
np.savetxt(dirstr+'/AvgCostfee.csv', AvgCostfee, delimiter=',')
np.savetxt(dirstr+'/LTPDelay.csv', LTPDelays, delimiter=',')
np.savetxt(dirstr+'/Income.csv', avgIncome, delimiter=',')
for NodeID in range(NUM_NODES):
np.savetxt(dirstr+'/latencies'+str(NodeID)+'.csv',
np.asarray(latencies[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_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=',')
avgMeanDelay = np.loadtxt(dirstr+'/avgMeanDelay.csv', delimiter=',')
avgOTA = np.loadtxt(dirstr+'/avgOldestTxAge.csv', delimiter=',')
avgDefs = np.loadtxt(dirstr+'/avgDefs.csv', delimiter=',')
avgTXPool = np.loadtxt(dirstr+'/avgTXPool.csv', delimiter=',')
avguserTX = np.loadtxt(dirstr+'/avguserTX.csv', delimiter=',')
avgNodeschedulTX = np.loadtxt(dirstr+'/avgNodeschedulTX.csv', delimiter=',')
avgEstTXPoolDelay = np.loadtxt(dirstr+'/avgEstTXPoolDelay.csv', delimiter=',')
AvgActualTXdelay = np.loadtxt(dirstr+'/AvgActualTXdelay.csv', delimiter=',')
AvgFilteredRateRecord= np.loadtxt(dirstr+'/AvgFilteredRateRecord.csv', delimiter=',')
AvgTXdelayError= np.loadtxt(dirstr+'/AvgTXdelayError.csv', delimiter=',')
AvgUserDelay = np.loadtxt(dirstr+'/AvgUserDelay.csv', delimiter=',')
AvgCostfee = np.loadtxt(dirstr+'/AvgCostfee.csv', delimiter=',')
LTPDelays = np.loadtxt(dirstr+'/LTPDelay.csv', delimiter=',')
latencies = []
alllatencies = []
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)
alllatencies.extend(lat[0])
'''
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=',')])
_, ax = plt.subplots(figsize=(8,4))
ax.grid(linestyle='--')
ax.set_xlabel('Delay (sec)')
plot_pdf(LTPDelays, ax)
plt.savefig(dirstr+'/LTPDelay.png', bbox_inches='tight')
_, ax = plt.subplots(figsize=(8,4))
ax.grid(linestyle='--')
ax.set_xlabel('Delay (sec)')
plot_pdf(alllatencies, ax)
plt.savefig(dirstr+'/DelayPDF.png', bbox_inches='tight')
"""
Plot results
"""
window = 10
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
for NodeID in range(NUM_NODES):
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')
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')
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 or MODE[NodeID]==4:
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(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')
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')
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')
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('avgTXPool')
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, avgTXPool[:,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, avgTXPool[:,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, avgTXPool[:,NodeID], 'valid'), color='tab:green', linewidth=5*REP[NodeID]/REP[0])
ax5.set_xlim(0, SIM_TIME)
plt.savefig(dirstr+'/avgTXPool.png', bbox_inches='tight')
fig5, ax5 = plt.subplots(figsize=(8,4))
ax5.grid(linestyle='--')
ax5.set_xlabel('Time (sec)')
ax5.set_ylabel('AvgCostfee')
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, AvgCostfee[:,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, AvgCostfee[:,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, AvgCostfee[:,NodeID], 'valid'), color='tab:green', linewidth=5*REP[NodeID]/REP[0])
ax5.set_xlim(0, SIM_TIME)
plt.savefig(dirstr+'/AvgCostfee.png', bbox_inches='tight')
fig10, ax10 = plt.subplots(figsize=(8,4))
ax10.grid(linestyle='--')
ax10.set_xlabel('Time (sec)')
l1= ax10.plot(np.arange(window, SIM_TIME, STEP), np.sum(avguserTX[int(window/STEP):,:], axis=1), color = 'black')
#ax10.set_ylim((0,1.1*NU))
l2= ax10.plot(np.arange(window, SIM_TIME, STEP), avgNodeschedulTX[int(window/STEP):,:], color='tab:gray')
ax10.tick_params(axis='y', labelcolor='black')
ax10.set_ylabel(' Rate', color='black')
fig10.tight_layout()
ModeLines = [Line2D([0],[0],color='black', lw=2), Line2D([0],[0],color='gray', lw=2, linestyle="--")]
ax10.set_ylim(0, 70)
ax10.legend(ModeLines, ['Sending', 'Scheduling'], loc='lower right')
plt.savefig(dirstr+'/User_demand1.png', bbox_inches='tight')
fig10, ax10 = plt.subplots(figsize=(8,4))
ax10.grid(linestyle='--')
ax10.set_xlabel('Time (sec)')
l1= ax10.plot(np.arange(window, SIM_TIME, STEP), np.sum(avguserTX[int(window/STEP):,:], axis=1), color = 'black')
#ax10.set_ylim((0,1.1*NU))
l2= ax10.plot(np.arange(window, SIM_TIME, STEP), [50 for i in range(int((SIM_TIME-window)/STEP))], color='tab:gray', linestyle="--")
ax10.tick_params(axis='y', labelcolor='black')
ax10.set_ylabel(' Rate (sec)', color='black')
fig10.tight_layout()
ModeLines = [Line2D([0],[0],color='black', lw=2), Line2D([0],[0],color='gray', lw=2, linestyle="--")]
ax10.set_ylim(0, 70)
ax10.legend(ModeLines, ['Sending', 'Scheduling'], loc='lower right')
plt.savefig(dirstr+'/User_demand2.png', bbox_inches='tight')
fig5, ax5 = plt.subplots(figsize=(8,4))
ax5.grid(linestyle='--')
ax5.set_xlabel('Time (sec)')
ax5.set_ylabel('EstTXPoolDelay')
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, avgEstTXPoolDelay[:,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, avgEstTXPoolDelay[:,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, avgEstTXPoolDelay[:,NodeID], 'valid'), color='tab:green', linewidth=5*REP[NodeID]/REP[0])
#ax5.set_ylim(0, 120)
plt.savefig(dirstr+'/EstTXPoolDelay.png', bbox_inches='tight')
fig5, ax5 = plt.subplots(figsize=(8,4))
ax5.grid(linestyle='--')
ax5.set_xlabel('Time (sec)')
ax5.set_ylabel('AvgUserDelay')
N=100
for UserID in range(NUM_USERS):
ax5.plot(np.arange((N-1)*STEP, SIM_TIME, STEP), np.convolve(np.ones(N)/N, AvgUserDelay[:,UserID], 'valid'))
#ax5.set_ylim(0, 120)
plt.savefig(dirstr+'/AvgUserDelay.png', bbox_inches='tight')
fig5, ax5 = plt.subplots(figsize=(8,4))
ax5.grid(linestyle='--')
ax5.set_xlabel('Time (sec)')
ax5.set_ylabel('AvgActualTXdelay')
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, AvgActualTXdelay[:,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, AvgActualTXdelay[:,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, AvgActualTXdelay[:,NodeID], 'valid'), color='tab:green', linewidth=5*REP[NodeID]/REP[0])
#ax5.set_ylim(0, 120)
plt.savefig(dirstr+'/AvgActualTXdelay.png', bbox_inches='tight')
fig5, ax5 = plt.subplots(figsize=(8,4))
ax5.grid(linestyle='--')
ax5.set_xlabel('Time (sec)')
ax5.set_ylabel('TXdelayError')
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, AvgTXdelayError[:,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, AvgTXdelayError[:,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, AvgTXdelayError[:,NodeID], 'valid'), color='tab:green', linewidth=5*REP[NodeID]/REP[0])
#ax5.set_ylim(0, 120)
plt.savefig(dirstr+'/TXdelayError.png', bbox_inches='tight')
fig5, ax5 = plt.subplots(figsize=(8,4))
ax5.grid(linestyle='--')
ax5.set_xlabel('Time (sec)')
ax5.set_ylabel('AvgFilteredRateRecord')
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, AvgFilteredRateRecord[:,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, AvgFilteredRateRecord[:,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, AvgFilteredRateRecord[:,NodeID], 'valid'), color='tab:green', linewidth=5*REP[NodeID]/REP[0])
#ax5.set_ylim(0, 120)
plt.savefig(dirstr+'/AvgFilteredRateRecord.png', bbox_inches='tight')
def plot_pdf(data, ax):
step = STEP
maxval = np.max(data)
bins = np.arange(0, round(maxval/step), 1)*step
pdf = np.zeros(len(bins))
i = 0
lats = sorted(data)
for lat in lats:
while i<len(bins)-1:
if lat>=bins[i]:
i += 1
else:
break
pdf[i] += 1
pdf = pdf/sum(pdf) # normalise
ax.plot(bins, pdf, color='tab:blue')
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
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 isinstance(data[NodeID][0], np.ndarray):
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)
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.3)
if MODE[NodeID]==2:
Lines[NodeID] = ax.plot(bins, cdf, color='tab:red', linewidth=4*REP[NodeID]/REP[0], marker=marker, markevery=0.3)
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.3)
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')
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 UserTransaction:
"""
Object to simulate a transaction generated by a user
"""
def __init__(self, User, Time, estimateddelay, Fee):
self.User= User
self.Time = Time
self.estimateddelay= estimateddelay
self.Fee = Fee
class User:
"""
Object to simulate a user
"""
def __init__(self, Network, UserID, NodeSelection, Mu=0):
self.UserID= UserID
self.Network = Network
self.User_lastdelay = 0
self.Estdelay=[[] for NodeID in range(NUM_NODES)]
self.Aam = 0.01
self.Bbm = (1- self.Aam)
self.Mu = Mu
self.NodeSelection = NodeSelection
def choose_node(self, Time):
"""
Users choose a node to process a transaction
"""
times = np.sort(np.random.uniform(Time, Time+STEP, np.random.poisson(STEP*self.Mu)))
for t in times:
Node_result = None
fee = 0
# Compute the estimated delay and filtered rate for each node
for NodeID in range(NUM_NODES):
LTPSize= len(self.Network.Nodes[NodeID].LTP)+1
FilRate = self.Network.Nodes[NodeID].get_filtered_rate(Time)
self.Estdelay[NodeID]= LTPSize/FilRate
if self.NodeSelection=='URNS':
Node_result = np.random.choice([NodeID for NodeID in range(NUM_NODES)])
elif self.NodeSelection=='RBNS':
probs = [REP[NodeID]/sum(REP) for NodeID in range(NUM_NODES)]
Node_result = np.random.choice([NodeID for NodeID in range(NUM_NODES)], p=probs)
elif self.NodeSelection=='DBNS':
repdelays = [REP[NodeID]/self.Estdelay[NodeID] for NodeID in range(NUM_NODES)]
probs = [repdelays[NodeID]/sum(repdelays) for NodeID in range(NUM_NODES)]
Node_result = np.random.choice([NodeID for NodeID in range(NUM_NODES)], p=probs)
elif self.NodeSelection=='DBNS+':
nodes = []
qos = []
fee = self.Network.Nodes[NodeID].Fee
for NodeID in range(NUM_NODES):
c = (self.Aam*self.Estdelay[NodeID] + self.Bbm*fee)
if c<np.random.uniform(C_MAX1, C_MAX2):
qos.append(REP[NodeID]/c)
nodes.append(NodeID)
if qos: # if any nodes have satisfactory qos
probs = [q/sum(qos) for q in qos]
Node_result = np.random.choice(nodes, p=probs)
if Node_result is not None:
self.Network.Nodes[Node_result].FilteredRateRecord= FilRate
self.Network.Nodes[Node_result].LTP.append(UserTransaction(self, t, self.Estdelay[Node_result], fee))
self.Network.IssuedTX[self.UserID]+= 1
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.LastBackOffRate = None
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.TranCounter = 0
self.FreeSize= NODETX_SIZE[self.NodeID]
self.LTP= []
self.ActualTXdelay= 0
self.Estdelay= 0
self.LambdaRecord= []
self.FilterRate= NU*REP[NodeID]/sum(REP)
self.FilterRateRecord= []
self.FilteredRateRecord = NU*REP[NodeID]/sum(REP)
self.FilterTXsize= 0
self.TXdelayError= 0
self.BlackTime=0
self.xmin= 0
self.IniFee = np.random.random()
self.Fee = 0
self.Kp = 0.8
self.Desiredelay = Network.delay_setpoint
self.Income = 0
def get_filtered_rate(self, Time):
window=3000
if self.LastBackOffRate is not None:
self.FilterRateRecord.append(self.LastBackOffRate)
if len(self.FilterRateRecord)>window:
return sum(self.FilterRateRecord[len(self.FilterRateRecord)-window:-1])/window
else:
return sum(self.FilterRateRecord)/len(self.FilterRateRecord)
else:
return self.Lambda
def issue_txs(self, Time):
"""
Create new TXs at rate lambda and do PoW
"""
# Assume all nodes are best effort
self.LambdaRecord.append(self.Lambda)
if self.BackOff:
self.LastIssueTime += TAU
while Time+STEP >= self.LastIssueTime + self.LastIssueWork/self.Lambda and len(self.LTP)!=0:
UserTX= self.LTP.pop(0)
self.LastIssueTime += self.LastIssueWork/self.Lambda
if self.LastIssueTime <= UserTX.Time:
self.LastIssueTime = UserTX.Time
Parents = self.select_tips()
Work = 1
self.LastIssueWork = Work