-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathga-heuristic.py
1872 lines (1650 loc) · 105 KB
/
ga-heuristic.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
import random
import numpy
import feasibility
import heuristic
import throughput
import time
import math
import json
import matplotlib.pyplot as plt
import os
from settings import Settings
import argparse
import logging
import sys
import exhaustive
import dijkstra
import copy
from deap import base
from deap import creator
from deap import tools
class GAWrapper:
def __init__(self, settings_file=None):
self.settings = Settings(settings_file)
logging.debug("Setting seed to {0}".format(self.settings["seed"]))
random.seed(self.settings["seed"])
# tsch variables
self.slot_length = self.settings["simulator"]["slotDuration"]
self.nr_slots = self.settings["simulator"]["slotframeLength"]
self.nr_frequencies = self.settings["simulator"]["numChans"]
# topology variables
self.nodes = [] # all nodes
self.nodes_0 = [] # nodes without root
self.d_parent = {} # maps a node to its parent
self.distance_to_root = {}
self.d_parent_closest_to_root = {} # the dictionary that maps a node to its possible parent that is most close to the root
self.d_parent_closer_to_root = {} # the dictionary that maps a node to its possible parent that is most close to the root
self.d_interferers = {} # maps a node to its interferers
# read from modulations file
self.d_MCS_to_slots = {} # maps MCS to number of slots in one bonded slot
self.d_MCS_to_max_bonded_slots = {} # maps MCS to max. nr of bonded slots in slot frame
self.d_MCS_to_index = {} # maps MCS to an index (I think a list is not as clear)
self.d_index_to_MCS = {} # maps the index to the MCS
self.d_MCS_to_rate = {} # maps MCS to an index (I think a list is not as clear)
# read from topology file
self.d_pdr = {} # maps node to MCS to parent to PDR, read literally from topology file
# parsed based on GA experiment type
self.d_node_to_allowed_parents = {} # maps a node to its allowed parents in the individual
self.d_node_to_allowed_MCSs_per_parent = {} # maps a node to its allowed MCSs per parent in the individual
self.not_equal_count = 1
if self.settings["modulations"]["modulations_file"]:
self.__init_modulations(self.settings["modulations"]["modulations_file"])
else:
raise Exception('No modulations file given.')
if self.settings["topology"]["topology_file"]:
self.__init_topology(self.settings["topology"]["topology_file"])
else:
raise Exception('No topology file given.')
# initialize the feasibility model
self.feasibility_model = feasibility.Feasibility(nr_slots=self.nr_slots, nr_frequencies=self.nr_frequencies, slots_per_MCS=self.d_MCS_to_slots, settings_file=settings_file)
# initialize the heuristic feasibility model
self.heuristic_model = heuristic.Heuristic(nr_slots=self.nr_slots, nr_frequencies=self.nr_frequencies, slots_per_MCS=self.d_MCS_to_slots, settings_file=settings_file)
# initialize the throughput model
self.throughput_model = throughput.Throughput(r_max=self.settings["tsch"]["r_max"], max_queue_length=self.settings["tsch"]["queue_size"], generated_packets_at_node=self.settings["tsch"]["generated_packets"], nr_slots=self.nr_slots, settings_file=settings_file)
# read all the necessary p_files from pdr_min until pdr 1.0 into memory
for i in range(int(self.settings["ga"]["min_pdr"]*1000), int(self.settings["ga"]["max_pdr"]*1000) + 1):
self.throughput_model.set_p(dir_name=self.settings["ga"]["p_files_dir"], pdr=i/1000.0)
self.print_progress_bar(iteration=i - int(self.settings["ga"]["min_pdr"]*1000), total=int(self.settings["ga"]["max_pdr"]*1000) + 1 - int(self.settings["ga"]["min_pdr"]*1000), prefix='Progress', suffix='of PDR files (PDR {0} - {1}) in memory'.format(self.settings["ga"]["min_pdr"], self.settings["ga"]["max_pdr"]), length=50)
# stats
self.valid_tree_time = 0.0
self.valid_tree_exec = 0.0
self.feasibility_time = 0.0
self.feasibility_exec = 0
self.feasibility_feasible = 0
self.heuristic_time = 0.0
self.heuristic_exec = 0
self.heuristic_feasible = 0
self.heuristic_false_positives = 0
self.heuristic_false_negatives = 0
self.heuristic_true_positives = 0
self.heuristic_true_negatives = 0
self.throughput_time = 0.0
self.throughput_exec = 0
self.mutation_exec = 0
self.mutation_exec_total = 0
self.mutation_time = 0.0
self.crossover_exec = 0
self.crossover_exec_total = 0
self.crossover_time = 0.0
self.total_time = 0.0
# GA deap instances
# log book to keep records of stats
self.logbook = tools.Logbook()
# hall of fame to keep best individuals
self.hof = tools.HallOfFame(self.settings["ga"]["hall_of_fame_size"])
self.best_individual = None
self.best_individual_performance = []
self.unique_individuals = {}
self.unique_individuals_performance = []
self.valid_individuals = set()
self.valid_individuals_performance = []
self.total_individuals = 0
self.infeasible_inds_performance = []
# saves those values here so you do not have to recalculate them always
self.parent_selection_tournament_size = self.settings["ga"]["parent_selection"]["tournament"]["size"]
self.survivor_selection_tournament_size = self.settings["ga"]["survivor_selection"]["tournament"]["size"]
if not (self.settings["ga"]["survivor_selection"]["elitism"]["percentage"] * self.settings["ga"]["pop_size"]).is_integer():
raise BaseException("Should be integer for elitism survivor selection!")
self.survivor_selection_elitism_pop_slice = int(self.settings["ga"]["survivor_selection"]["elitism"]["percentage"] * self.settings["ga"]["pop_size"])
self.survivor_selection_elitism_offspring_slice = int((1.0 - self.settings["ga"]["survivor_selection"]["elitism"]["percentage"]) * self.settings["ga"]["pop_size"])
def __init_topology(self, json_topology_file):
with open(json_topology_file) as json_file:
data = json.load(json_file)
# read out topology
for node, info in data["simulationTopology"].items():
node = int(node) # convert it to an int
self.nodes.append(node)
if node != self.settings["topology"]["root"]:
self.nodes_0.append(node)
# save the parents
self.d_parent[node] = int(info["parent"])
self.d_interferers[node] = info["interferers"]
# save the reliabilities
self.d_pdr[node] = {}
# I am manually reading it out because I want to convert all the nodes to actual integers
for mcs, reliabilities in data["simulationTopology"][str(node)]["reliability"].items():
if mcs not in self.d_pdr[node]:
self.d_pdr[node][mcs] = {}
for p, pdr in reliabilities.items():
self.d_pdr[node][mcs][int(p)] = pdr
self.distance_to_root[node] = info["distance_to_root"]
def __init_modulations(self, json_modulations_file):
with open(json_modulations_file) as json_file:
data = json.load(json_file)
self.d_MCS_to_rate = copy.deepcopy(data['modulations']['modulationRates'])
if self.settings["simulator"]["modulationConfig"] in data["configurations"]:
for ix, m in enumerate(data['configurations'][self.settings["simulator"]["modulationConfig"]]['allowedModulations']):
self.d_MCS_to_index[m] = ix
self.d_index_to_MCS[ix] = m
self.d_MCS_to_slots = copy.deepcopy(data['configurations'][self.settings["simulator"]["modulationConfig"]]['modulationSlots'])
else:
raise BaseException("Modulation config {0} not in in modulations file.".format(self.settings["simulator"]["modulationConfig"]))
self.d_MCS_to_max_bonded_slots = {}
for mcs, slots in self.d_MCS_to_slots.items():
self.d_MCS_to_max_bonded_slots[mcs] = math.floor(self.nr_slots / slots)
# print(self.d_MCS_to_index)
# print(self.d_index_to_MCS)
# print(self.d_MCS_to_slots)
# print(self.d_MCS_to_max_bonded_slots)
# exit()
#### Topology related methods ####
def calculate_descendants(self, node=0, children=[], l_descendants=[]):
if node not in l_descendants:
# self.descendants[node] = 0
l_descendants[node] = []
if node in children:
# self.descendants[node] += len(self.children[node])
l_descendants[node] += children[node]
for c in children[node]:
self.calculate_descendants(node=c, children=children, l_descendants=l_descendants)
# self.descendants[node] += self.descendants[c]
l_descendants[node] += l_descendants[c]
def get_parents(self, ind):
parents = {}
tmp_node = 1
while tmp_node <= len(self.nodes_0): # calculate all the children
node_ix = ((tmp_node - 1) * self.settings["ga"]["genes_per_node_with_topology"])
parents[tmp_node] = ind[node_ix + 2]
tmp_node += 1
return parents
def reach_root(self, node, par_parents, parents):
if node not in par_parents:
return False
elif par_parents[node] in parents:
return False
elif par_parents[node] == self.settings["topology"]["root"]:
return True
parents.append(par_parents[node])
return self.reach_root(par_parents[node], par_parents, parents)
def valid_individual_topology(self, ind):
parents = self.get_parents(ind)
for n in self.nodes:
if n != 0 and not self.reach_root(n, parents, []):
return False
return True
def fast_feasibility_check(self, individual, dict_children):
# 1) check if all the children of the root are not sending too much
nr_slots_children_root = 0
for c_root in dict_children[self.settings["topology"]["root"]]:
ix_c_root = (c_root - 1) * self.settings["ga"]["genes_per_node_with_topology"]
nr_slots_child_root = individual[ix_c_root + 1] * self.d_MCS_to_slots[self.d_index_to_MCS[individual[ix_c_root]]] # + 1 to get the slot count
nr_slots_children_root += nr_slots_child_root
if nr_slots_children_root > self.nr_slots:
return False
# 2) check if the total number of slots exceeds the total number of slots in the slotframe
n = 1
while n <= len(self.nodes_0): # calculate all the children, <= because you start at 1
ix_n = (n - 1) * self.settings["ga"]["genes_per_node_with_topology"]
# multiply the number of slots with the number of slots of the MCS used
nr_slots_node = individual[ix_n + 1] * self.d_MCS_to_slots[self.d_index_to_MCS[individual[ix_n]]]
# logging.debug("Node {0} has a total of {1} slots itself.".format(n, nr_slots_node))
if nr_slots_node > self.nr_slots:
return False
nr_slots_children = 0
if n in dict_children:
for c in dict_children[n]:
ix_c = (c - 1) * self.settings["ga"]["genes_per_node_with_topology"]
nr_slots_child = individual[ix_c + 1] * self.d_MCS_to_slots[self.d_index_to_MCS[individual[ix_c]]] # + 1 to get the slot count
nr_slots_children += nr_slots_child
# logging.debug("Adding {0} slots for child {1} of node {2}, bringing the total to {3}.".format(nr_slots_child, c, n, nr_slots_children))
if nr_slots_node + nr_slots_children > self.nr_slots:
return False
n += 1
return True
def ixs_fast_feasibility_check(self, individual, dict_children):
ixs = []
# 1) check if all the children of the root are not sending too much
nr_slots_children_root = 0
for c_root in dict_children[self.settings["topology"]["root"]]:
ix_c_root = (c_root - 1) * self.settings["ga"]["genes_per_node_with_topology"]
nr_slots_child_root = individual[ix_c_root + 1] * self.d_MCS_to_slots[self.d_index_to_MCS[individual[ix_c_root]]] # + 1 to get the slot count
nr_slots_children_root += nr_slots_child_root
ixs.append(ix_c_root + 1) # add the index
if nr_slots_children_root > self.nr_slots:
return ixs
ixs = []
# 2) check if the total number of slots exceeds the total number of slots in the slotframe
n = 1
while n <= len(self.nodes_0): # calculate all the children, <= because you start at 1
ix_n = (n - 1) * self.settings["ga"]["genes_per_node_with_topology"]
# multiply the number of slots with the number of slots of the MCS used
nr_slots_node = individual[ix_n + 1] * self.d_MCS_to_slots[self.d_index_to_MCS[individual[ix_n]]]
# logging.debug("Node {0} has a total of {1} slots itself.".format(n, nr_slots_node))
if nr_slots_node > self.nr_slots:
return [ix_n + 1]
nr_slots_children = 0
if n in dict_children:
for c in dict_children[n]:
ix_c = (c - 1) * self.settings["ga"]["genes_per_node_with_topology"]
nr_slots_child = individual[ix_c + 1] * self.d_MCS_to_slots[self.d_index_to_MCS[individual[ix_c]]] # + 1 to get the slot count
nr_slots_children += nr_slots_child
ixs.append(ix_c + 1)
# logging.debug("Adding {0} slots for child {1} of node {2}, bringing the total to {3}.".format(nr_slots_child, c, n, nr_slots_children))
if nr_slots_node + nr_slots_children > self.nr_slots:
ixs.append(ix_n + 1)
return list(set(ixs))
n += 1
ixs = [] # reset
return []
# def check_valid_nr_slots(self, individual, dict_children):
# tmp_node = 1
# total_slots = 0
# involved_indices = []
# while tmp_node <= len(self.nodes_0): # calculate all the children, <= because you start at 1
# tmp_involved_indices = []
# ix_tmp_node = (tmp_node - 1) * self.settings["ga"]["genes_per_node_with_topology"]
# parent_node = individual[ix_tmp_node + 2] # + 2 for the parent node of the tmp node
# total_slots = individual[ix_tmp_node + 1] # + 1 to get the slot count
# if individual[ix_tmp_node + 1] > 0: # only append nodes with more than 0 slots
# tmp_involved_indices.append(ix_tmp_node + 1)
# if tmp_node in dict_children: # only if the node has children
# for c in dict_children[tmp_node]:
# ix_c = (c - 1) * self.settings["ga"]["genes_per_node_with_topology"]
# total_slots += individual[ix_c + 1] # + 1 to get the slot count
# if individual[ix_c + 1] > 0: # only append nodes with more than 0 slots
# tmp_involved_indices.append(ix_c + 1)
# if parent_node in self.d_interferers: # only if the node has interferers
# for ifer in self.d_interferers[parent_node]:
# if ifer != self.settings["topology"]["root"]: # otherwise you will be adding a negative ix_ifer
# ix_ifer = (ifer - 1) * self.settings["ga"]["genes_per_node_with_topology"]
# total_slots += individual[ix_ifer + 1] # + 1 to get the slot count
# if individual[ix_ifer + 1] > 0: # only append nodes with more than 0 slots
# tmp_involved_indices.append(ix_ifer + 1)
# if total_slots > self.nr_slots: # if you exceed the slot frame length, all the nodes (with more than 0 slots) are considered involved and should be returned
# involved_indices += tmp_involved_indices
# tmp_node += 1
# return list(set(involved_indices)) # filter all duplicates
def make_ind_feasible(self, individual):
# recalculate the children dictionary, after the possible parent change
dict_children = {}
tmp_node = 1
while tmp_node <= len(self.nodes_0): # calculate all the children
ix_tmp_node = (tmp_node - 1) * self.settings["ga"]["genes_per_node_with_topology"]
ix_tmp_node_parent = ix_tmp_node + 2
if individual[ix_tmp_node_parent] not in dict_children: # if the parent is not in the children
dict_children[individual[ix_tmp_node_parent]] = [] # add the parent
dict_children[individual[ix_tmp_node_parent]].append(tmp_node) # add current node as a child
tmp_node += 1
# keep adjusting one node its slot count until you have a valid one
ixs_slot_count = self.ixs_fast_feasibility_check(individual=individual, dict_children=dict_children)
# valid_nr_slots function returns all the slot count indices in the individual that contribute for a node n (and its children and interferers)
# to having too many slots (i.e., more slots > slotframe length)
while len(ixs_slot_count) > 0:
choice = random.choice(ixs_slot_count)
while individual[choice] < 1: # do not let it go negative, so 0 is the minimum
choice = random.choice(ixs_slot_count)
individual[choice] -= 1
ixs_slot_count = self.ixs_fast_feasibility_check(individual=individual, dict_children=dict_children)
return individual
#### GA related methods ####
def selElitistAndRestOffspring(self, original_pop, k_elitist, offspring, k_offspring):
return tools.selBest(original_pop, k_elitist) + tools.selBest(offspring, k_offspring)
def mutate_with_topology_new(self, individual):
"""Mutate an individual by replacing attributes, with probability *indpb*,
by a integer uniformly drawn between *low* and *up* inclusively.
:param individual: :term:`Sequence <sequence>` individual to be mutated.
# :param low: The lower bound or a :term:`python:sequence` of
# of lower bounds of the range from wich to draw the new
# integer.
# :param up: The upper bound or a :term:`python:sequence` of
# of upper bounds of the range from wich to draw the new
# integer.
# :param indpb: Independent probability for each attribute to be mutated.
:returns: A tuple of one individual.
"""
start_time = time.time()
# PHASE 1, mutate a branch of the topology
altered_nodes = []
tmp_nodes_0 = self.nodes_0.copy()
# print(self.nodes_0)
# print(tmp_nodes_0)
random.shuffle(tmp_nodes_0)
# print(tmp_nodes_0)
tmp_n = random.choice(tmp_nodes_0)
tmp_nodes_0.remove(tmp_n)
while len(tmp_nodes_0) > 0:
if random.random() < self.settings["ga"]["mutation_idp_prob"] and len(self.d_node_to_allowed_parents[tmp_n]) > 1:
# position of the node in the chromosome
ix_n = (tmp_n - 1) * self.settings["ga"]["genes_per_node_with_topology"]
# 2) get list for node n of nodes it can connect to
current_parent = individual[ix_n + 2]
assert current_parent in self.d_node_to_allowed_parents[tmp_n]
children = {}
parents = {}
descendants = {}
tmp_node = 1
while tmp_node <= len(self.nodes_0): # calculate all the children
ix_tmp_node = (tmp_node - 1) * self.settings["ga"]["genes_per_node_with_topology"]
ix_tmp_node_parent = ix_tmp_node + 2
if individual[ix_tmp_node_parent] not in children: # if the parent is not in the children
children[individual[ix_tmp_node_parent]] = [] # add the parent
children[individual[ix_tmp_node_parent]].append(tmp_node) # add current node as a child
parents[tmp_node] = individual[ix_tmp_node_parent]
tmp_node += 1
# calculate the descendants of node n
self.calculate_descendants(node=tmp_n, children=children, l_descendants=descendants)
allowed_parent_list = self.d_node_to_allowed_parents[tmp_n].copy()
allowed_parent_list.remove(current_parent)
allowed_parent_list = [p for p in allowed_parent_list if p not in descendants[tmp_n]] # remove all the descendants because this would create loops
new_parent = current_parent
if len(allowed_parent_list) > 0: # only when there are parents left, pick a new one
new_parent = random.choice(allowed_parent_list) # set the new parent
if new_parent != current_parent: # now we know for sure this node its parent is altered
altered_nodes.append(tmp_n)
individual[ix_n + 2] = new_parent
parents[tmp_n] = new_parent
if not self.reach_root(tmp_n, parents, []):
raise BaseException('After mutation, I can not reach the root anymore from this node {0}'.format(tmp_n))
# continue with the next n
tmp_n = random.choice(tmp_nodes_0)
tmp_nodes_0.remove(tmp_n)
# PHASE 2, mutate the MCSs and the slots
# also for sure mutate the MCS and the slots of the node n that were adjusted because maybe they are wrong now
tuple_per_node = list(zip(individual, individual[1:], individual[2:]))[::3]
for ix, (mcs, slots, parent) in enumerate(tuple_per_node):
mutated_MCS = False
if len(self.d_MCS_to_index) > 1 and (ix + 1 in altered_nodes or random.random() < self.settings["ga"]["mutation_idp_prob"]): # ix + 1 is the actual node, if it equals n, you should also mutate its MCS
individual[(ix * self.settings["ga"]["genes_per_node_with_topology"]) + 0] = random.choice(self.d_node_to_allowed_MCSs_per_parent[ix + 1][parent]) # mutate MCS
mutated_MCS = True
# print('Mutate MCS')
if mutated_MCS or random.random() < self.settings["ga"]["mutation_idp_prob"]:
tmp_ix_mcs = individual[(ix * self.settings["ga"]["genes_per_node_with_topology"]) + 0]
# prev_nr_slots = individual[(ix * self.settings["ga"]["genes_per_node_with_topology"]) + 1]
individual[(ix * self.settings["ga"]["genes_per_node_with_topology"]) + 1] = random.randint(0, self.d_MCS_to_max_bonded_slots[self.d_index_to_MCS[tmp_ix_mcs]]) # mutate slots
# individual[(ix * self.settings["ga"]["genes_per_node_with_topology"]) + 1] = self.d_MCS_to_max_bonded_slots[self.d_index_to_MCS[tmp_ix_mcs]] # mutate slots
# print('Went from {0} slots to {1} slots for MCS {2}'.format(prev_nr_slots, individual[(ix * self.settings["ga"]["genes_per_node_with_topology"]) + 1], self.d_index_to_MCS[tmp_ix_mcs]))
# exit()
if self.settings["ga"]["type"] == "make-feasible" or \
self.settings["ga"]["type"] == "make-feasible-new" or \
self.settings["ga"]["type"] == "emperical-strategy" or \
self.settings["ga"]["type"] == "es-closertoroot" or \
self.settings["ga"]["type"] == "es-highreliability":
# make the individual feasible by checking if none of the nodes exceeds the slotframe length (with children and interferers)
individual = self.make_ind_feasible(individual)
self.mutation_time += time.time() - start_time
self.mutation_exec += 1
return individual
def mutate_with_topology(self, individual):
"""Mutate an individual by replacing attributes, with probability *indpb*,
by a integer uniformly drawn between *low* and *up* inclusively.
:param individual: :term:`Sequence <sequence>` individual to be mutated.
# :param low: The lower bound or a :term:`python:sequence` of
# of lower bounds of the range from wich to draw the new
# integer.
# :param up: The upper bound or a :term:`python:sequence` of
# of upper bounds of the range from wich to draw the new
# integer.
# :param indpb: Independent probability for each attribute to be mutated.
:returns: A tuple of one individual.
"""
start_time = time.time()
# PHASE 1, mutate a branch of the topology
# 1) pick a random node in the topology
n = random.randint(1, len(self.nodes_0))
# position of the node in the chromosome
ix_n = (n - 1) * self.settings["ga"]["genes_per_node_with_topology"]
# 2) get list for node n of nodes it can connect to
current_parent = individual[ix_n + 2]
assert current_parent in self.d_node_to_allowed_parents[n]
# 3) if there are more possible parents than just the current parent, choose another one
if len(self.d_node_to_allowed_parents[n]) > 1: # it should contain more possible parents than just the current parent to continue
children = {}
parents = {}
descendants = {}
tmp_node = 1
while tmp_node <= len(self.nodes_0): # calculate all the children
ix_tmp_node = (tmp_node - 1) * self.settings["ga"]["genes_per_node_with_topology"]
ix_tmp_node_parent = ix_tmp_node + 2
if individual[ix_tmp_node_parent] not in children: # if the parent is not in the children
children[individual[ix_tmp_node_parent]] = [] # add the parent
children[individual[ix_tmp_node_parent]].append(tmp_node) # add current node as a child
parents[tmp_node] = individual[ix_tmp_node_parent]
tmp_node += 1
# calculate the descendants of node n
self.calculate_descendants(node=n, children=children, l_descendants=descendants)
allowed_parent_list = self.d_node_to_allowed_parents[n].copy()
allowed_parent_list.remove(current_parent)
allowed_parent_list = [p for p in allowed_parent_list if p not in descendants[n]] # remove all the descendants because this would create loops
new_parent = current_parent
if len(allowed_parent_list) > 0: # only when there are parents left, pick a new one
new_parent = random.choice(allowed_parent_list) # set the new parent
individual[ix_n + 2] = new_parent
parents[n] = new_parent
if not self.reach_root(n, parents, []):
raise BaseException('After mutation, I can not reach the root anymore from this node {0}'.format(n))
else:
pass # leave the individual untouched
# print("After possibly altering the parent: {0}".format(individual))
# PHASE 2, mutate the MCSs and the slots
# also for sure mutate the MCS and the slots of the node n that were adjusted because maybe they are wrong now
tuple_per_node = list(zip(individual, individual[1:], individual[2:]))[::3]
for ix, (mcs, slots, parent) in enumerate(tuple_per_node):
mutated_MCS = False
if ix + 1 == n or random.random() < self.settings["ga"]["mutation_idp_prob"]: # ix + 1 is the actual node, if it equals n, you should also mutate its MCS
individual[(ix * self.settings["ga"]["genes_per_node_with_topology"]) + 0] = random.choice(self.d_node_to_allowed_MCSs_per_parent[ix + 1][parent]) # mutate MCS
mutated_MCS = True
if mutated_MCS or random.random() < self.settings["ga"]["mutation_idp_prob"]:
tmp_ix_mcs = individual[(ix * self.settings["ga"]["genes_per_node_with_topology"]) + 0]
individual[(ix * self.settings["ga"]["genes_per_node_with_topology"]) + 1] = random.randint(0, self.d_MCS_to_max_bonded_slots[self.d_index_to_MCS[tmp_ix_mcs]]) # mutate slots
# individual[(ix * self.settings["ga"]["genes_per_node_with_topology"]) + 1] = self.d_MCS_to_max_bonded_slots[self.d_index_to_MCS[tmp_ix_mcs]] # mutate slots
if self.settings["ga"]["type"] == "make-feasible" or \
self.settings["ga"]["type"] == "make-feasible-new" or \
self.settings["ga"]["type"] == "emperical-strategy" or \
self.settings["ga"]["type"] == "es-closertoroot" or \
self.settings["ga"]["type"] == "es-highreliability":
# make the individual feasible by checking if none of the nodes exceeds the slotframe length (with children and interferers)
individual = self.make_ind_feasible(individual)
self.mutation_time += time.time() - start_time
self.mutation_exec += 1
return individual
def mutate_without_topology(self, individual):
"""Mutate an individual by replacing attributes, with probability *indpb*,
by a integer uniformly drawn between *low* and *up* inclusively.
This mutation only mutates MCSs and slots numbers. It does not alter topology.
"""
start_time = time.time()
# PHASE 1, only mutate the MCSs and the slots
# also for sure mutate the MCS and the slots of the node n that were adjusted because maybe they are wrong now
tuple_per_node = list(zip(individual, individual[1:], individual[2:]))[::3]
for ix, (mcs, slots, parent) in enumerate(tuple_per_node):
mutated_MCS = False
if random.random() < self.settings["ga"]["mutation_idp_prob"]: # ix + 1 is the actual node, if it equals n, you should also mutate its MCS
individual[(ix * self.settings["ga"]["genes_per_node_with_topology"]) + 0] = \
random.choice(self.d_node_to_allowed_MCSs_per_parent[ix + 1][parent]) # mutate MCS
mutated_MCS = True
if mutated_MCS or random.random() < self.settings["ga"]["mutation_idp_prob"]:
tmp_ix_mcs = individual[(ix * self.settings["ga"]["genes_per_node_with_topology"]) + 0]
individual[(ix * self.settings["ga"]["genes_per_node_with_topology"]) + 1] = \
random.randint(0, self.d_MCS_to_max_bonded_slots[self.d_index_to_MCS[tmp_ix_mcs]]) # mutate slots
if self.settings["ga"]["type"] == "make-feasible" or \
self.settings["ga"]["type"] == "make-feasible-new" or \
self.settings["ga"]["type"] == "emperical-strategy" or \
self.settings["ga"]["type"] == "es-closertoroot" or \
self.settings["ga"]["type"] == "es-highreliability":
# make the individual feasible by checking if none of the nodes exceeds the slotframe length (with children and interferers)
individual = self.make_ind_feasible(individual)
self.mutation_time += time.time() - start_time
self.mutation_exec += 1
return individual
def crossover_twopoint_with_topology(self, ind1, ind2):
start_time = time.time()
factor = self.settings["ga"]["genes_per_node_with_topology"]
cxpoint1 = random.randint(0, len(self.nodes_0))
cxpoint2 = random.randint(0, len(self.nodes_0) - 1)
# if cxpoint2 >= cxpoint1:
if cxpoint2 == cxpoint1:
cxpoint2 += 1
# else: # Swap the two cx points
elif cxpoint2 < cxpoint1: # Swap the two cx points
cxpoint1, cxpoint2 = cxpoint2, cxpoint1
cxpoint1 *= factor
cxpoint2 *= factor
ind1_final = None
ind1_found = False
ind2_final = None
ind2_found = False
cxpoint1_ix = cxpoint1
while cxpoint1_ix < cxpoint2:
ind1_tmp = ind1.copy() # copy for temporary testing
ind2_tmp = ind2.copy() # copy for temporary testing
# do the cross-over
ind1_tmp[cxpoint1_ix:cxpoint2] = ind2_tmp[cxpoint1_ix:cxpoint2]
if self.valid_individual_topology(ind1_tmp):
# save the new ind1
ind1_final = ind1_tmp.copy()
ind1_found = True
break
else:
cxpoint1_ix += self.settings["ga"]["genes_per_node_with_topology"]
cxpoint1_ix = cxpoint1
while cxpoint1_ix < cxpoint2:
ind1_tmp = ind1.copy() # copy for temporary testing
ind2_tmp = ind2.copy() # copy for temporary testing
# do the cross-over
ind2_tmp[cxpoint1_ix:cxpoint2] = ind1_tmp[cxpoint1_ix:cxpoint2]
if self.valid_individual_topology(ind2_tmp):
# save the new ind2
ind2_final = ind2_tmp.copy()
ind2_found = True
break
else:
cxpoint1_ix += self.settings["ga"]["genes_per_node_with_topology"]
if ind1_found:
ind1[:] = ind1_final # replace inplace (in the actual reference to ind1)
if ind2_found:
ind2[:] = ind2_final # replace inplace (in the actual reference to ind1)
if self.settings["ga"]["type"] == "make-feasible" or \
self.settings["ga"]["type"] == "make-feasible-new" or \
self.settings["ga"]["type"] == "emperical-strategy" or \
self.settings["ga"]["type"] == "es-closertoroot" or \
self.settings["ga"]["type"] == "es-highreliability":
for ind in [ind1, ind2]:
# make the individual feasible by checking if none of the nodes exceeds the slotframe length (with children and interferers)
ind = self.make_ind_feasible(ind)
self.crossover_time += time.time() - start_time
self.crossover_exec += 1
return ind1, ind2
def crossover_twopoint_without_topology(self, ind1, ind2):
'''
This crossover does not crossover the topology, only the MCS and slots.
The ASSUMPTION here is that the allocated MCS and slots are always correct, also after crossover, because the
the topology is not changed.
All of this results in this just being a regular two-point crossover.
'''
start_time = time.time()
factor = self.settings["ga"]["genes_per_node_with_topology"]
cxpoint1 = random.randint(0, len(self.nodes_0))
cxpoint2 = random.randint(0, len(self.nodes_0) - 1)
# if cxpoint2 >= cxpoint1:
if cxpoint2 == cxpoint1:
cxpoint2 += 1
# else: # Swap the two cx points
elif cxpoint2 < cxpoint1: # Swap the two cx points
cxpoint1, cxpoint2 = cxpoint2, cxpoint1
cxpoint1 *= factor
cxpoint2 *= factor
ind1[cxpoint1:cxpoint2], ind2[cxpoint1:cxpoint2] \
= ind2[cxpoint1:cxpoint2], ind1[cxpoint1:cxpoint2]
for ind in [ind1, ind2]:
dict_children = {}
tmp_node = 1
while tmp_node <= len(self.nodes_0): # calculate all the children
ix_tmp_node = (tmp_node - 1) * self.settings["ga"]["genes_per_node_with_topology"]
ix_tmp_node_parent = ix_tmp_node + 2
if ind[ix_tmp_node_parent] not in dict_children: # if the parent is not in the children
dict_children[ind[ix_tmp_node_parent]] = [] # add the parent
dict_children[ind[ix_tmp_node_parent]].append(tmp_node) # add current node as a child
tmp_node += 1
# keep adjusting one node its slot count until you have a valid one
ixs_slot_count = self.check_valid_nr_slots(individual=ind, dict_children=dict_children)
# valid_nr_slots function returns all the slot count indices in the individual that contribute for a node n (and its children and interferers)
# to having too many slots (i.e., more slots > slotframe length)
while len(ixs_slot_count) > 0:
ind[random.choice(ixs_slot_count)] -= 1
ixs_slot_count = self.check_valid_nr_slots(individual=ind, dict_children=dict_children)
self.crossover_time += time.time() - start_time
self.crossover_exec += 1
return ind1, ind2
def initialize_default(self):
ind = []
for i in range(len(self.nodes_0)):
node = i + 1
parent = self.d_parent[i + 1] # parent that was in the topology file
tmp_mcs = random.choice(self.d_node_to_allowed_MCSs_per_parent[node][parent])
ind.append(tmp_mcs) # append a MCS
ind.append(random.randint(0, self.d_MCS_to_max_bonded_slots[self.d_index_to_MCS[tmp_mcs]])) # append a number of slots
ind.append(parent) # take the parent that was in the topology file
# to make it randomized
for i in range(100):
ind = self.mutate_with_topology(ind)
if not self.valid_individual_topology(ind):
raise BaseException("Default initialization returned an invalid topology...")
# for i in range(len(self.nodes_0)):
# num_slots_ix = i * self.settings["ga"]["genes_per_node_with_topology"] + 1
# ind[num_slots_ix] = 1
return ind
def initialize_default_new(self):
ind = []
for i in range(len(self.nodes_0)):
node = i + 1
parent = self.d_parent[i + 1] # parent that was in the topology file
tmp_mcs = random.choice(self.d_node_to_allowed_MCSs_per_parent[node][parent])
ind.append(tmp_mcs) # append a MCS
ind.append(random.randint(0, self.d_MCS_to_max_bonded_slots[self.d_index_to_MCS[tmp_mcs]])) # append a number of slots
ind.append(parent) # take the parent that was in the topology file
# to make it randomized
for i in range(100):
ind = self.mutate_with_topology_new(ind)
if not self.valid_individual_topology(ind):
raise BaseException("Default initialization returned an invalid topology...")
# for i in range(len(self.nodes_0)):
# num_slots_ix = i * self.settings["ga"]["genes_per_node_with_topology"] + 1
# ind[num_slots_ix] = 1
return ind
def initialize_emperical(self):
ind = []
for i in range(len(self.nodes_0)):
node = i + 1
parent = self.d_parent[i + 1] # parent that was in the topology file
tmp_mcs = random.choice(self.d_node_to_allowed_MCSs_per_parent[node][parent])
ind.append(tmp_mcs) # append a MCS
ind.append(random.randint(0, self.d_MCS_to_max_bonded_slots[self.d_index_to_MCS[tmp_mcs]])) # append a number of slots
ind.append(parent) # take the parent that was in the topology file
# to make it randomized
for i in range(100):
# print("Before mutation {1}: {0}".format(ind, i))
ind = self.mutate_with_topology(ind)
# print("after: {0}".format(ind))
# print("After mutation {1}: {0}".format(ind, i))
# exit()
if not self.valid_individual_topology(ind):
raise BaseException("Default initialization returned an invalid topology...")
# for i in range(len(self.nodes_0)):
# num_slots_ix = i * self.settings["ga"]["genes_per_node_with_topology"] + 1
# ind[num_slots_ix] = 1
return ind
def initialize_dijkstra(self):
ind = []
dijkstra_model = dijkstra.Dijkstra()
dijkstra_model.calculate(settings_file=self.settings.settings_file, topology_file=self.settings["topology"]["topology_file"])
for i in range(len(self.nodes_0)):
node = i + 1
parent = int(dijkstra_model.dijkstra_table[i + 1]['prev']) # parent based on minimal hopcount by Dijkstra
tmp_mcs = random.choice(self.d_node_to_allowed_MCSs_per_parent[node][parent])
ind.append(tmp_mcs) # append a MCS
ind.append(random.randint(0, self.d_MCS_to_max_bonded_slots[self.d_index_to_MCS[tmp_mcs]])) # append a number of slots
ind.append(parent) # take the parent that was in the topology file
# to make it randomized
for i in range(30):
ind = self.mutate_without_topology(ind)
if not self.valid_individual_topology(ind):
raise BaseException("Dijkstra initialization returned an invalid topology...")
return ind
def initialize_closest_to_root(self):
ind = []
for i in range(len(self.nodes_0)):
node = i + 1
parent = self.d_parent_closest_to_root[i + 1] # parent that was in the topology file
tmp_mcs = random.choice(self.d_node_to_allowed_MCSs_per_parent[node][parent])
ind.append(tmp_mcs) # append a MCS
ind.append(random.randint(0, self.d_MCS_to_max_bonded_slots[self.d_index_to_MCS[tmp_mcs]])) # append a number of slots
ind.append(parent) # take the parent that was in the topology file
# to make it randomized
for i in range(30):
ind = self.mutate_without_topology(ind)
if not self.valid_individual_topology(ind):
raise BaseException("Closest to the root returned an invalid topology...")
return ind
def evaluate_individual(self, individual):
# print('Evaluating an individual...')
# packs the individual in a format readable for the feasibility and throughput model, also does a validity test
# also returns a dict with child -> parents relationship to be to check the validity of the tree
if str(individual) in self.unique_individuals:
return (self.unique_individuals[str(individual)][0], self.unique_individuals[str(individual)][1])
links, parents = self.pack_individual(individual)
# links2, parents = self.pack_individual(individual)
if len(links) == 0:
raise Exception("Individual {0} was mal-formed.".format(individual))
valid_tree = True
start_time = time.time()
for n in self.nodes:
if n != 0 and not self.reach_root(n, parents, []):
valid_tree = False
break
self.valid_tree_time += (time.time() - start_time)
self.valid_tree_exec += 1
if not valid_tree:
if str(individual) not in self.unique_individuals:
self.unique_individuals[str(individual)] = (self.settings["ga"]["invalid_tree_throughput_val"], self.settings["ga"]["infeasible_airtime_val"])
return (self.settings["ga"]["invalid_tree_throughput_val"], self.settings["ga"]["infeasible_airtime_val"])
dict_children = {}
# check if the links in the individual were valid
for child, parent, reliability, slots, mcs, interferers in links:
if parent not in dict_children:
dict_children[parent] = []
dict_children[parent].append(child)
if child != self.settings["topology"]["root"]:
if slots > self.d_MCS_to_max_bonded_slots[mcs]:
if str(individual) not in self.unique_individuals:
self.unique_individuals[str(individual)] = (self.settings["ga"]["invalid_slots_throughput_val"],
self.settings["ga"]["infeasible_airtime_val"])
return (self.settings["ga"]["invalid_slots_throughput_val"], self.settings["ga"]["infeasible_airtime_val"])
feasible_heuristic = False
start_time = time.time()
self.heuristic_model.set(links)
if self.settings['heuristic']['manner'] == 'combo':
all_manners = ['breadth-top',
'largest-bonded-length',
'most-contention',
'dfs',
'smallest-bonded-length',
'breadth-bottom',
'least-contention',
'breadth-bottom-mix'
]
for manner in all_manners:
# reset it
self.heuristic_model.set(links)
# set to other manner
self.heuristic_model.sort_N_0(manner)
feasible_heuristic = self.heuristic_model.check()
if feasible_heuristic:
break
else:
# keep the sorting based on length
self.heuristic_model.sort_N_0(self.settings['heuristic']['manner'])
feasible_heuristic = self.heuristic_model.check()
self.heuristic_time += (time.time() - start_time)
self.heuristic_exec += 1
if feasible_heuristic:
self.heuristic_feasible += 1
feasible_ilp = False
start_time = time.time()
# enter the individual into the feasibility model and check for feasibility
# self.feasibility_model.set(links2)
# feasible_ilp = self.feasibility_model.check()
self.feasibility_time += (time.time() - start_time)
self.feasibility_exec += 1
if feasible_ilp:
self.feasibility_feasible += 1
# if feasible_heuristic and not feasible_ilp:
# self.heuristic_false_positives += 1
# # print(self.d_index_to_MCS)
# # print(self.d_MCS_to_slots)
# # print(self.d_MCS_to_max_bonded_slots)
# # print(self.d_interferers)
# # print("Links: {0}".format(links))
# # print('Heuristic ({0}) and ILP ({1}) say different feasibilities for individual = {2}'.format(feasible_heuristic, feasible_ilp, individual))
# #
# # # self.feasibility_model.set(links2, visualize_solution=True)
# # # feasible_ilp = self.feasibility_model.check(visualize_solution=True)
# #
# # feasibility_model_tmp = feasibility.Feasibility(nr_slots=self.nr_slots, nr_frequencies=self.nr_frequencies, slots_per_MCS=self.d_MCS_to_slots, settings_file=settings_file)
# # feasibility_model_tmp.set(links2, visualize_solution=True)
# # feasible_ilp = feasibility_model_tmp.check(visualize_solution=True)
# #
# # self.heuristic_model.set(links, visualize_solution=True)
# # self.heuristic_model.check(visualize_solution=True)
# raise BaseException('Heuristic ({0}) and ILP ({1}) say different feasibilities for individual = {2}'.format(feasible_heuristic, feasible_ilp, individual))
# elif not feasible_heuristic and feasible_ilp:
# self.heuristic_false_negatives += 1
# # if self.settings['heuristic']['manner'] == 'combo':
# # print(self.d_index_to_MCS)
# # print(self.d_MCS_to_slots)
# # print(self.d_MCS_to_max_bonded_slots)
# # print(self.d_interferers)
# # print("Links: {0}".format(links))
# # self.feasibility_model.set(links2, visualize_solution=True)
# # feasible_ilp = self.feasibility_model.check(visualize_solution=True)
# # self.heuristic_model.set(links, visualize_solution=True)
# # self.heuristic_model.sort_N_0("most-contention")
# # self.heuristic_model.check(visualize_solution=True)
# # print(self.heuristic_model.sorted_N_0)
# # raise BaseException('Heuristic ({0}) and ILP ({1}) say different feasibilities for individual = {2}'.format(
# # feasible_heuristic, feasible_ilp, individual))
# elif not feasible_heuristic and not feasible_ilp:
# self.heuristic_true_negatives += 1
# elif feasible_heuristic and feasible_ilp:
# self.heuristic_true_positives += 1
# else:
# raise BaseException('Heuristic ({0}) and ILP ({1}) say different feasibilities for individual = {2}'.format(feasible_heuristic, feasible_ilp, individual))
if not feasible_heuristic:
if str(individual) not in self.unique_individuals:
self.unique_individuals[str(individual)] = (self.settings["ga"]["infeasible_ind_throughput_val"], self.settings["ga"]["infeasible_airtime_val"])
return (self.settings["ga"]["infeasible_ind_throughput_val"], self.settings["ga"]["infeasible_airtime_val"])
else:
# calculate total expected throughput
start_time = time.time()
self.throughput_model.set(links)
tput = self.throughput_model.calculate()
total_airtime = self.throughput_model.calculate_airtime()
# if individual == [0, 2, 0, 2, 2, 0, 2, 1, 1, 2, 1, 2]:
# total_airtime = self.throughput_model.calculate_airtime(verbose=True)
# exit()
self.throughput_time += (time.time() - start_time)
self.throughput_exec += 1
# print('tput')
# print(self.throughput_time)
if tput > len(self.nodes_0):
self.unique_individuals[str(individual)] = (self.settings["ga"]["infeasible_ind_throughput_val"], self.settings["ga"]["infeasible_airtime_val"])
return (self.settings["ga"]["infeasible_ind_throughput_val"], self.settings["ga"]["infeasible_airtime_val"])
# calculate the airtime for all the slots
# total_airtime = 0.0
# total_airtime_normal = 0.0
# if self.settings["ga"]["airtime_objective"] == "tx_and_rx":
# # add tx and rx airtimes
# for child, parent, reliability, slots, mcs, interferers in links:
# if child != self.settings["topology"]["root"]:
# total_airtime += 2 * (slots * self.settings["radio"]["airtimes"][mcs])
# elif self.settings["ga"]["airtime_objective"] == "average_airtime":
# print(self.throughput_model.p)
# expected_packets_per_node = {}
# for n in self.throughput_model.p:
# pkts = 0.0
# for packets, prob_packets in enumerate(self.throughput_model.p[n]):
# pkts += (packets * prob_packets)
# expected_packets_per_node[n] = pkts
# print('Expected arriving packets at parent of node {0}: {1}'.format(n, expected_packets_per_node[n]))
# print(tput)
#
# # add tx and rx airtimes
# for child, parent, reliability, slots, mcs, interferers in links:
# print('Node {0}, parent {1}'.format(child, parent))
# if child != self.settings["topology"]["root"]:
# total_airtime_normal += (slots * self.settings["radio"]["airtimes"][mcs])
# total_airtime += (expected_packets_per_node[child] * self.settings["radio"]["airtimes"][mcs])
#
# print("normal total airtime: {0} ms".format(total_airtime_normal))
# print("new total airtime: {0} ms".format(total_airtime))
#
# exit()
# else:
# # only add tx airtimes
# for child, parent, reliability, slots, mcs, interferers in links:
# if child != self.settings["topology"]["root"]:
# total_airtime += slots * self.settings["radio"]["airtimes"][mcs]
# print(individual)
# print(links)
# print(tput)
# self.heuristic_model.set(links, visualize_solution=True)
# self.heuristic_model.check(visualize_solution=True)
# exit()
if str(individual) not in self.valid_individuals:
self.valid_individuals.add(str(individual))
if str(individual) not in self.unique_individuals:
self.unique_individuals[str(individual)] = (tput, total_airtime)
# return both the throughput and airtime
return tput, total_airtime
def pack_individual(self, individual):
'''
Transform the given individual to a list of (child, parent, reliability, slots, mcs) combination
Also builds a dictionary of child to parent to check the validity of tree later.
:param individual: The GA individual solution
:return: a list of (child, parent, reliability, slots, mcs) combination
'''
links = []
parents = {}
tuple_per_node = list(zip(individual, individual[1:], individual[2:]))[::3]