├── .gitignore ├── .vscode └── settings.json ├── Drone.py ├── LICENSE ├── LTEBaseStation.py ├── NRBaseStation.py ├── README.md ├── Satellite.py ├── UserEquipment.py ├── environment.py ├── test.py └── util.py /.gitignore: -------------------------------------------------------------------------------- 1 | "# Created by https://www.gitignore.io/api/python,visualstudiocode 2 | # Edit at https://www.gitignore.io/?templates=python,visualstudiocode 3 | 4 | ### Python ### 5 | # Byte-compiled / optimized / DLL files 6 | __pycache__/ 7 | *.py[cod] 8 | *$py.class 9 | 10 | # C extensions 11 | *.so 12 | 13 | # Distribution / packaging 14 | .Python 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | pip-wheel-metadata/ 28 | share/python-wheels/ 29 | *.egg-info/ 30 | .installed.cfg 31 | *.egg 32 | MANIFEST 33 | 34 | # PyInstaller 35 | # Usually these files are written by a python script from a template 36 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 37 | *.manifest 38 | *.spec 39 | 40 | # Installer logs 41 | pip-log.txt 42 | pip-delete-this-directory.txt 43 | 44 | # Unit test / coverage reports 45 | htmlcov/ 46 | .tox/ 47 | .nox/ 48 | .coverage 49 | .coverage.* 50 | .cache 51 | nosetests.xml 52 | coverage.xml 53 | *.cover 54 | .hypothesis/ 55 | .pytest_cache/ 56 | 57 | # Translations 58 | *.mo 59 | *.pot 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # pyenv 71 | .python-version 72 | 73 | # pipenv 74 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 75 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 76 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 77 | # install all needed dependencies. 78 | #Pipfile.lock 79 | 80 | # celery beat schedule file 81 | celerybeat-schedule 82 | 83 | # SageMath parsed files 84 | *.sage.py 85 | 86 | # Spyder project settings 87 | .spyderproject 88 | .spyproject 89 | 90 | # Rope project settings 91 | .ropeproject 92 | 93 | # Mr Developer 94 | .mr.developer.cfg 95 | .project 96 | .pydevproject 97 | 98 | # mkdocs documentation 99 | /site 100 | 101 | # mypy 102 | .mypy_cache/ 103 | .dmypy.json 104 | dmypy.json 105 | 106 | # Pyre type checker 107 | .pyre/ 108 | 109 | ### VisualStudioCode ### 110 | .vscode/* 111 | !.vscode/settings.json 112 | !.vscode/tasks.json 113 | !.vscode/launch.json 114 | !.vscode/extensions.json 115 | 116 | ### VisualStudioCode Patch ### 117 | # Ignore all local history of files 118 | .history 119 | 120 | # End of https://www.gitignore.io/api/python,visualstudiocode 121 | 122 | models 123 | *.npy 124 | *.csv -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "C:\\Users\\Emanuele-PC\\AppData\\Local\\Programs\\Python\\Python36\\python.exe" 3 | } -------------------------------------------------------------------------------- /Drone.py: -------------------------------------------------------------------------------- 1 | import environment 2 | import math 3 | from scipy import constants 4 | import util 5 | 6 | class DroneRelay: 7 | bs_type = "drone_relay" 8 | 9 | def __init__(self, bs_id, linked_bs_id, amplification, antenna_gain, feeder_loss, carrier_frequency, position, env): 10 | if position[2] > 200 or position[2] < 30: 11 | raise Exception("COST-HATA model requires BS height in [30, 200]m") 12 | 13 | if (carrier_frequency < 150 or carrier_frequency > 2000): 14 | raise Exception("your results may be incorrect because your carrier frequency is outside the boundaries of COST-HATA path loss model") 15 | 16 | 17 | self.amplification = amplification 18 | self.antenna_gain = antenna_gain 19 | self.feeder_loss = feeder_loss 20 | self.bs_id = bs_id 21 | self.carrier_frequency = carrier_frequency 22 | self.fr = -1 23 | if (carrier_frequency <= 6000): #below 6GHz 24 | self.fr = 0 25 | elif (carrier_frequency >= 24250 and carrier_frequency <= 52600): #between 24.25GHz and 52.6GHz 26 | self.fr = 1 27 | self.position = (position[0],position[1]) 28 | self.current_position = self.position 29 | self.starting_position = position 30 | self.h_b = position[2] 31 | self.h_m = position[2] 32 | self.env = env 33 | 34 | self.linked_bs = linked_bs_id 35 | 36 | self.theta_k = 0 37 | 38 | def compute_rbur(self): 39 | return util.find_bs_by_id(self.linked_bs).compute_rbur() 40 | 41 | def compute_rsrp_drone(self, ue): 42 | #relay rsrp depends from the signal received by the BS and by the re-amp made by the drone 43 | print(util.compute_rsrp(self, util.find_bs_by_id(self.linked_bs), self.env)) 44 | return self.amplification + util.compute_rsrp(self, util.find_bs_by_id(self.linked_bs), self.env) + self.antenna_gain - self.feeder_loss - util.compute_path_loss_cost_hata(ue, self, self.env) 45 | 46 | def request_connection(self, ue_id, data_rate, available_bs): 47 | rsrp = available_bs.copy() 48 | if self.bs_id in rsrp: 49 | value = rsrp[self.bs_id] 50 | del rsrp[self.bs_id] 51 | if self.linked_bs in rsrp: 52 | del rsrp[self.linked_bs] 53 | rsrp[self.linked_bs] = value 54 | return util.find_bs_by_id(self.linked_bs).request_connection(ue_id, data_rate, rsrp) 55 | 56 | def request_disconnection(self, ue_id): 57 | util.find_bs_by_id(self.linked_bs).request_disconnection(ue_id) 58 | 59 | def update_connection(self, ue_id, data_rate, available_bs): 60 | rsrp = available_bs.copy() 61 | if self.bs_id in rsrp: 62 | value = rsrp[self.bs_id] 63 | del rsrp[self.bs_id] 64 | if self.linked_bs in rsrp: 65 | del rsrp[self.linked_bs] 66 | rsrp[self.linked_bs] = value 67 | return util.find_bs_by_id(self.linked_bs).update_connection(ue_id, data_rate, rsrp) 68 | 69 | def next_timestep(self): 70 | return 71 | 72 | def new_state(self): 73 | return util.find_bs_by_id(self.linked_bs).new_state() 74 | 75 | def get_state(self): 76 | return util.find_bs_by_id(self.linked_bs).get_state() 77 | 78 | def get_connection_info(self, ue_id): 79 | return util.find_bs_by_id(self.linked_bs).get_connection_info(ue_id) 80 | 81 | def get_connected_users(self): 82 | return util.find_bs_by_id(self.linked_bs).get_connected_users() 83 | 84 | def reset(self): 85 | self.position = (self.starting_position[0], self.starting_position[1]) 86 | self.current_position = self.position 87 | self.h_b = self.starting_position[2] 88 | self.h_m = self.starting_position[2] 89 | return util.find_bs_by_id(self.linked_bs).reset() 90 | 91 | def move(self, destination, speed): 92 | x_k = destination[0] - self.position[0] 93 | y_k = destination[1] - self.position[1] 94 | z_k = destination[2] - self.h_b 95 | theta_k = self.theta_k 96 | v_k = 1*(x_k*math.cos(theta_k) + y_k*math.sin(theta_k)) 97 | v_z_k = 1*z_k 98 | if v_k > speed and v_k > 0: 99 | v_k = speed 100 | elif v_k < -speed and v_k < 0: 101 | v_k = -speed 102 | if v_z_k > speed and v_z_k > 0: 103 | v_z_k = speed 104 | elif v_z_k < -speed and v_z_k < 0: 105 | v_z_k = -speed 106 | w_k = 1*(math.atan2(-y_k,-x_k) - theta_k + math.pi) 107 | 108 | 109 | new_x = self.position[0]+v_k*math.cos(theta_k + (w_k / 2)) 110 | new_y = self.position[1]+v_k*math.sin(theta_k + (w_k / 2)) 111 | new_z = self.h_b + v_z_k 112 | new_theta = self.theta_k + w_k 113 | self.position = (new_x, new_y) 114 | self.h_b = new_z 115 | self.h_m = new_z 116 | self.current_position = self.position 117 | self.theta_k = new_theta 118 | 119 | def compute_latency(self, ue_id): 120 | return util.find_bs_by_id(self.linked_bs).compute_latency(ue_id) 121 | 122 | def compute_r(self, ue_id, rsrp): 123 | return util.find_bs_by_id(self.linked_bs).compute_r(ue_id, rsrp) 124 | 125 | 126 | 127 | #Table 5.3.3-1: Minimum guardband [kHz] (FR1) and Table: 5.3.3-2: Minimum guardband [kHz] (FR2), 3GPPP 38.104 128 | #number of prb depending on the numerology (0,1,2,3), on the frequency range (FR1, FR2) and on the base station bandwidth 129 | NRbandwidth_prb_lookup = { 130 | 0:[{ 131 | 5:25, 132 | 10:52, 133 | 15:79, 134 | 20:106, 135 | 25:133, 136 | 30:160, 137 | 40:216, 138 | 50:270 139 | }, None], 140 | 1:[{ 141 | 5:11, 142 | 10:24, 143 | 15:38, 144 | 20:51, 145 | 25:65, 146 | 30:78, 147 | 40:106, 148 | 50:133, 149 | 60:162, 150 | 70:189, 151 | 80:217, 152 | 90:245, 153 | 100:273 154 | }, None], 155 | 2:[{ 156 | 10:11, 157 | 15:18, 158 | 20:24, 159 | 25:31, 160 | 30:38, 161 | 40:51, 162 | 50:65, 163 | 60:79, 164 | 70:93, 165 | 80:107, 166 | 90:121, 167 | 100:135 168 | }, 169 | { 170 | 50:66, 171 | 100:132, 172 | 200:264 173 | }], 174 | 3:[None, 175 | { 176 | 50:32, 177 | 100:66, 178 | 200:132, 179 | 400:264 180 | }] 181 | } 182 | 183 | 184 | 185 | class DroneBaseStation: 186 | bs_type = "drone_bs" 187 | 188 | def __init__(self, bs_id, total_prb, prb_bandwidth_size, number_subcarriers, numerology, antenna_power, antenna_gain, feeder_loss, carrier_frequency, total_bitrate, position, env): 189 | if position[2] > 200 or position[2] < 30: 190 | raise Exception("COST-HATA model requires BS height in [30, 200]m") 191 | 192 | if (carrier_frequency < 150 or carrier_frequency > 2000): 193 | raise Exception("your results may be incorrect because your carrier frequency is outside the boundaries of COST-HATA path loss model") 194 | 195 | self.prb_bandwidth_size = prb_bandwidth_size 196 | self.total_prb = total_prb 197 | self.total_bitrate = total_bitrate 198 | self.allocated_prb = 0 199 | self.allocated_bitrate = 0 200 | self.antenna_power = antenna_power 201 | self.antenna_gain = antenna_gain 202 | self.feeder_loss = feeder_loss 203 | self.bs_id = bs_id 204 | self.carrier_frequency = carrier_frequency 205 | self.fr = -1 206 | if (carrier_frequency <= 6000): #below 6GHz 207 | self.fr = 0 208 | elif (carrier_frequency >= 24250 and carrier_frequency <= 52600): #between 24.25GHz and 52.6GHz 209 | self.fr = 1 210 | self.position = (position[0],position[1]) 211 | self.starting_position = position 212 | self.h_b = position[2] 213 | self.number_subcarriers = number_subcarriers 214 | self.env = env 215 | self.numerology = numerology 216 | self.ue_pb_allocation = {} 217 | self.ue_bitrate_allocation = {} 218 | self.wardrop_alpha = 1 219 | self.T = 10 220 | self.resource_utilization_array = [0] * self.T 221 | self.resource_utilization_counter = 0 222 | 223 | self.theta_k = 0 224 | 225 | 226 | 227 | def compute_rbur(self): 228 | return sum(self.resource_utilization_array)/(self.T*self.total_prb) 229 | 230 | 231 | def compute_nprb_NR(self, data_rate, rsrp): 232 | #compute SINR 233 | interference = 0 234 | for elem in rsrp: 235 | if elem != self.bs_id and util.find_bs_by_id(elem).bs_type != "sat" and util.find_bs_by_id(elem).carrier_frequency == self.carrier_frequency: 236 | total, used = util.find_bs_by_id(elem).get_state() 237 | interference = interference + (10 ** (rsrp[elem]/10))*(used/total)*(self.allocated_prb/self.total_prb) 238 | 239 | #thermal noise is computed as k_b*T*delta_f, where k_b is the Boltzmann's constant, T is the temperature in kelvin and delta_f is the bandwidth 240 | #thermal_noise = constants.Boltzmann*293.15*list(NRbandwidth_prb_lookup[self.numerology][self.fr].keys())[list(NRbandwidth_prb_lookup[self.numerology][self.fr].values()).index(self.total_prb / (10 * 2**self.numerology))]*1000000*(self.compute_rbur()+0.001) 241 | thermal_noise = constants.Boltzmann*293.15*15*(2**self.numerology)*1000 # delta_F = 15*2^mu KHz each subcarrier since we are considering measurements at subcarrirer level (like RSRP) 242 | sinr = (10**(rsrp[self.bs_id]/10))/(thermal_noise + interference) 243 | 244 | r = self.prb_bandwidth_size*1000*math.log2(1+sinr) #bandwidth is in kHz 245 | #based on the numerology choosen and considered the frame duration of 10ms, we transmit 1ms for mu = 0, 0.5ms for mu = 1, 0.25ms for mu = 2, 0.125ms for mu = 3 for each PRB each 10ms 246 | #print(r) 247 | r = r / (10 * (2**self.numerology)) 248 | #print(r) 249 | N_prb = math.ceil(data_rate*1000000 / r) #data rate is in Mbps 250 | return N_prb, r 251 | 252 | #this method will be called by an UE that tries to connect to this BS. 253 | #the return value will be the actual bandwidth assigned to the user 254 | def request_connection(self, ue_id, data_rate, rsrp): 255 | 256 | N_prb, r = self.compute_nprb_NR(data_rate, rsrp) 257 | old_N_prb = N_prb 258 | 259 | #check if there is enough bitrate, if not then do not allocate the user 260 | if self.total_bitrate - self.allocated_bitrate <= r*N_prb/1000000: 261 | dr = self.total_bitrate - self.allocated_bitrate 262 | N_prb, r = self.compute_nprb_NR(dr, rsrp) 263 | 264 | #check if there are enough PRBs 265 | if self.total_prb - self.allocated_prb <= N_prb: 266 | N_prb = self.total_prb - self.allocated_prb 267 | 268 | if ue_id not in self.ue_pb_allocation: 269 | self.ue_pb_allocation[ue_id] = N_prb 270 | self.allocated_prb += N_prb 271 | else: 272 | self.allocated_prb -= self.ue_pb_allocation[ue_id] 273 | self.ue_pb_allocation[ue_id] = N_prb 274 | self.allocated_prb += N_prb 275 | 276 | if ue_id not in self.ue_bitrate_allocation: 277 | self.ue_bitrate_allocation[ue_id] = r * N_prb / 1000000 278 | self.allocated_bitrate += r * N_prb / 1000000 279 | else: 280 | self.allocated_bitrate -= self.ue_bitrate_allocation[ue_id] 281 | self.ue_bitrate_allocation[ue_id] = r * N_prb / 1000000 282 | self.allocated_bitrate += r * N_prb / 1000000 283 | 284 | print("Allocated %s/%s NR PRB" %(N_prb, old_N_prb)) 285 | return r*N_prb/1000000 #we want a data rate in Mbps, not in bps 286 | 287 | def request_disconnection(self, ue_id): 288 | N_prb = self.ue_pb_allocation[ue_id] 289 | self.allocated_prb -= N_prb 290 | del self.ue_pb_allocation[ue_id] 291 | 292 | 293 | def update_connection(self, ue_id, data_rate, rsrp): 294 | 295 | N_prb, r = self.compute_nprb_NR(data_rate, rsrp) 296 | diff = N_prb - self.ue_pb_allocation[ue_id] 297 | 298 | #check before if there is enough bitrate 299 | if self.total_bitrate - self.allocated_bitrate < diff * r / 100000: 300 | dr = self.total_bitrate - self.allocated_bitrate 301 | N_prb, r = self.compute_nprb_NR(self.ue_bitrate_allocation[ue_id]+dr, rsrp) 302 | diff = N_prb - self.ue_pb_allocation[ue_id] 303 | 304 | 305 | if self.total_prb - self.allocated_prb >= diff: 306 | #there is the place for more PRB allocation (or less if diff is negative) 307 | self.allocated_prb += diff 308 | self.ue_pb_allocation[ue_id] += diff 309 | 310 | self.allocated_bitrate += diff * r / 1000000 311 | self.ue_bitrate_allocation[ue_id] += diff * r / 1000000 312 | else: 313 | #there is no room for more PRB allocation 314 | diff = self.total_prb - self.allocated_prb 315 | self.allocated_prb += diff 316 | self.ue_pb_allocation[ue_id] += diff 317 | 318 | self.allocated_bitrate += diff * r / 1000000 319 | self.ue_bitrate_allocation[ue_id] += diff * r / 1000000 320 | 321 | N_prb = self.ue_pb_allocation[ue_id] 322 | return N_prb*r/1000000 #remember that we want the result in Mbps 323 | 324 | #things to do before moving to the next timestep 325 | def next_timestep(self): 326 | #print(self.allocated_prb) 327 | self.resource_utilization_array[self.resource_utilization_counter] = self.allocated_prb 328 | self.resource_utilization_counter += 1 329 | if self.resource_utilization_counter % self.T == 0: 330 | self.resource_utilization_counter = 0 331 | 332 | def new_state(self): 333 | return (sum(self.resource_utilization_array) - self.resource_utilization_array[self.resource_utilization_counter] + self.allocated_prb)/(self.total_prb*self.T) 334 | 335 | def get_state(self): 336 | return self.total_prb, self.allocated_prb 337 | 338 | def get_connection_info(self, ue_id): 339 | return self.ue_pb_allocation[ue_id], self.total_prb 340 | 341 | def get_connected_users(self): 342 | return list(self.ue_pb_allocation.keys()) 343 | 344 | def reset(self): 345 | self.resource_utilization_array = [0] * self.T 346 | self.resource_utilization_counter = 0 347 | self.position = (self.starting_position[0], self.starting_position[1]) 348 | self.h_b = self.starting_position[2] 349 | 350 | def move(self, destination, speed): 351 | x_k = destination[0] - self.position[0] 352 | y_k = destination[1] - self.position[1] 353 | z_k = destination[2] - self.h_b 354 | theta_k = self.theta_k 355 | v_k = 1*(x_k*math.cos(theta_k) + y_k*math.sin(theta_k)) 356 | v_z_k = 1*z_k 357 | if v_k > speed and v_k > 0: 358 | v_k = speed 359 | elif v_k < -speed and v_k < 0: 360 | v_k = -speed 361 | if v_z_k > speed and v_z_k > 0: 362 | v_z_k = speed 363 | elif v_z_k < -speed and v_z_k < 0: 364 | v_z_k = -speed 365 | w_k = 1*(math.atan2(-y_k,-x_k) - theta_k + math.pi) 366 | 367 | 368 | new_x = self.position[0]+v_k*math.cos(theta_k + (w_k / 2)) 369 | new_y = self.position[1]+v_k*math.sin(theta_k + (w_k / 2)) 370 | new_z = self.h_b + v_z_k 371 | new_theta = self.theta_k + w_k 372 | self.position = (new_x, new_y) 373 | self.h_b = new_z 374 | self.current_position = self.position 375 | self.theta_k = new_theta 376 | 377 | 378 | def compute_latency(self, ue_id): 379 | return self.wardrop_alpha * self.ue_pb_allocation[ue_id] 380 | 381 | def compute_r(self, ue_id, rsrp): 382 | N_prb, r = self.compute_nprb_NR(1, rsrp) 383 | return r 384 | 385 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /LTEBaseStation.py: -------------------------------------------------------------------------------- 1 | import math 2 | from scipy import constants 3 | import util 4 | 5 | LTEbandwidth_prb_lookup = { 6 | 1.4: 6, 7 | 3: 15, 8 | 5: 25, 9 | 10: 50, 10 | 15: 75, 11 | 20: 100 12 | } 13 | 14 | class LTEBaseStation: 15 | bs_type = "lte" 16 | 17 | def __init__(self, bs_id, total_prb, prb_bandwidth_size, number_subcarriers, antenna_power, antenna_gain, feeder_loss, carrier_frequency, total_bitrate, position, env): 18 | if position[2] > 200 or position[2] < 30: 19 | raise Exception("COST-HATA model requires BS height in [30, 200]m") 20 | 21 | if (carrier_frequency < 150 or carrier_frequency > 2000): 22 | raise Exception("your results may be incorrect because your carrier frequency is outside the boundaries of COST-HATA path loss model") 23 | 24 | self.prb_bandwidth_size = prb_bandwidth_size 25 | self.total_prb = total_prb 26 | self.total_bitrate = total_bitrate #Mbps 27 | self.allocated_prb = 0 28 | self.allocated_bitrate = 0 29 | self.antenna_power = antenna_power 30 | self.antenna_gain = antenna_gain 31 | self.feeder_loss = feeder_loss 32 | self.bs_id = bs_id 33 | self.carrier_frequency = carrier_frequency 34 | self.position = (position[0],position[1]) 35 | self.h_b = position[2] 36 | self.number_subcarriers = number_subcarriers 37 | self.env = env 38 | self.ue_pb_allocation = {} 39 | self.ue_bitrate_allocation = {} 40 | self.T = 10 41 | self.resource_utilization_array = [0] * self.T 42 | self.resource_utilization_counter = 0 43 | self.wardrop_alpha = 1 44 | 45 | def compute_rbur(self): 46 | return sum(self.resource_utilization_array)/(self.T*self.total_prb) 47 | 48 | 49 | def compute_nprb_LTE(self, data_rate, rsrp): 50 | 51 | #compute SINR 52 | interference = 0 53 | for elem in rsrp: 54 | if elem != self.bs_id and util.find_bs_by_id(elem).bs_type != "sat" and util.find_bs_by_id(elem).carrier_frequency == self.carrier_frequency: 55 | total, used = util.find_bs_by_id(elem).get_state() 56 | interference = interference + (10 ** (rsrp[elem]/10))*util.find_bs_by_id(elem)*(used/total)*(self.allocated_prb/self.total_prb) 57 | 58 | #thermal noise is computed as k_b*T*delta_f, where k_b is the Boltzmann's constant, T is the temperature in kelvin and delta_f is the bandwidth 59 | thermal_noise = constants.Boltzmann*293.15*15*1000 # delta_F = 12*15KHz each resource block since we are considering resource block related measurements (like RSRP) 60 | sinr = (10**(rsrp[self.bs_id]/10))/(thermal_noise + interference) 61 | 62 | r = self.prb_bandwidth_size*1000*math.log2(1+sinr) #bandwidth is in kHz 63 | #with a single PRB we transmit just 1ms each 10ms (that is the frame lenght), so the actual rate is divided by 10 64 | r = r / 10 65 | N_prb = math.ceil(data_rate*1000000 / r) #data rate is in Mbps 66 | return N_prb, r 67 | 68 | #this method will be called by an UE that tries to connect to this BS. 69 | #the return value will be the actual bandwidth assigned to the user 70 | def request_connection(self, ue_id, data_rate, rsrp): 71 | 72 | N_prb, r = self.compute_nprb_LTE(data_rate, rsrp) 73 | old_N_prb = N_prb 74 | 75 | #check if there is enough bitrate, if not then do not allocate the user 76 | if self.total_bitrate - self.allocated_bitrate < r*N_prb/1000000: 77 | dr = self.total_bitrate - self.allocated_bitrate 78 | N_prb, r = self.compute_nprb_LTE(dr, rsrp) 79 | 80 | #check if there are enough PRBs 81 | if self.total_prb - self.allocated_prb <= N_prb: 82 | N_prb = self.total_prb - self.allocated_prb 83 | 84 | if ue_id not in self.ue_pb_allocation: 85 | self.ue_pb_allocation[ue_id] = N_prb 86 | self.allocated_prb += N_prb 87 | else: 88 | self.allocated_prb -= self.ue_pb_allocation[ue_id] 89 | self.ue_pb_allocation[ue_id] = N_prb 90 | self.allocated_prb += N_prb 91 | 92 | if ue_id not in self.ue_bitrate_allocation: 93 | self.ue_bitrate_allocation[ue_id] = r * N_prb / 1000000 94 | self.allocated_bitrate += r * N_prb / 1000000 95 | else: 96 | self.allocated_bitrate -= self.ue_bitrate_allocation[ue_id] 97 | self.ue_bitrate_allocation[ue_id] = r * N_prb * 1000000 98 | self.allocated_bitrate += r * N_prb / 1000000 99 | 100 | #print("Allocated %s/%s LTE PRB" %(N_prb, old_N_prb)) 101 | return r*N_prb/1000000 #we want a data rate in Mbps, not in bps 102 | 103 | def request_disconnection(self, ue_id): 104 | N_prb = self.ue_pb_allocation[ue_id] 105 | self.allocated_prb -= N_prb 106 | del self.ue_pb_allocation[ue_id] 107 | 108 | 109 | def update_connection(self, ue_id, data_rate, rsrp): 110 | 111 | N_prb, r = self.compute_nprb_LTE(data_rate, rsrp) 112 | diff = N_prb - self.ue_pb_allocation[ue_id] 113 | 114 | #check before if there is enough bitrate 115 | if self.total_bitrate - self.allocated_bitrate < diff * r / 1000000: 116 | dr = self.total_bitrate - self.allocated_bitrate 117 | N_prb, r = self.compute_nprb_LTE(self.ue_bitrate_allocation[ue_id]+dr, rsrp) 118 | diff = N_prb - self.ue_pb_allocation[ue_id] 119 | 120 | if self.total_prb - self.allocated_prb >= diff: 121 | #there is the place for more PRB allocation (or less if diff is negative) 122 | self.allocated_prb += diff 123 | self.ue_pb_allocation[ue_id] += diff 124 | 125 | self.allocated_bitrate += diff * r / 1000000 126 | self.ue_bitrate_allocation[ue_id] += diff * r / 1000000 127 | else: 128 | #there is no room for more PRB allocation 129 | diff = self.total_prb - self.allocated_prb 130 | self.allocated_prb += diff 131 | self.ue_pb_allocation[ue_id] += diff 132 | 133 | self.allocated_bitrate += diff * r / 1000000 134 | self.ue_bitrate_allocation[ue_id] += diff * r / 1000000 135 | 136 | N_prb = self.ue_pb_allocation[ue_id] 137 | return N_prb*r/1000000 #remember that we want the result in Mbps 138 | 139 | #things to do before moving to the next timestep 140 | def next_timestep(self): 141 | self.resource_utilization_array[self.resource_utilization_counter] = self.allocated_prb 142 | self.resource_utilization_counter += 1 143 | if self.resource_utilization_counter % self.T == 0: 144 | self.resource_utilization_counter = 0 145 | 146 | def new_state(self): 147 | return (sum(self.resource_utilization_array) - self.resource_utilization_array[self.resource_utilization_counter] + self.allocated_prb)/(self.total_prb*self.T) 148 | 149 | def get_state(self): 150 | return self.total_prb, self.allocated_prb 151 | 152 | def get_connection_info(self, ue_id): 153 | return self.ue_pb_allocation[ue_id], self.total_prb 154 | 155 | def get_connected_users(self): 156 | return list(self.ue_pb_allocation.keys()) 157 | 158 | def reset(self): 159 | self.resource_utilization_array = [0] * self.T 160 | self.resource_utilization_counter = 0 161 | 162 | def compute_latency(self, ue_id): 163 | if ue_id in self.ue_pb_allocation: 164 | return self.wardrop_alpha * self.ue_pb_allocation[ue_id] 165 | return 0 166 | 167 | def compute_r(self, ue_id, rsrp): 168 | N_prb, r = self.compute_nprb_LTE(1, rsrp) 169 | return r 170 | 171 | 172 | 173 | -------------------------------------------------------------------------------- /NRBaseStation.py: -------------------------------------------------------------------------------- 1 | import environment 2 | import math 3 | from scipy import constants 4 | import util 5 | 6 | #Table 5.3.3-1: Minimum guardband [kHz] (FR1) and Table: 5.3.3-2: Minimum guardband [kHz] (FR2), 3GPPP 38.104 7 | #number of prb depending on the numerology (0,1,2,3), on the frequency range (FR1, FR2) and on the base station bandwidth 8 | NRbandwidth_prb_lookup = { 9 | 0:[{ 10 | 5:25, 11 | 10:52, 12 | 15:79, 13 | 20:106, 14 | 25:133, 15 | 30:160, 16 | 40:216, 17 | 50:270 18 | }, None], 19 | 1:[{ 20 | 5:11, 21 | 10:24, 22 | 15:38, 23 | 20:51, 24 | 25:65, 25 | 30:78, 26 | 40:106, 27 | 50:133, 28 | 60:162, 29 | 70:189, 30 | 80:217, 31 | 90:245, 32 | 100:273 33 | }, None], 34 | 2:[{ 35 | 10:11, 36 | 15:18, 37 | 20:24, 38 | 25:31, 39 | 30:38, 40 | 40:51, 41 | 50:65, 42 | 60:79, 43 | 70:93, 44 | 80:107, 45 | 90:121, 46 | 100:135 47 | }, 48 | { 49 | 50:66, 50 | 100:132, 51 | 200:264 52 | }], 53 | 3:[None, 54 | { 55 | 50:32, 56 | 100:66, 57 | 200:132, 58 | 400:264 59 | }] 60 | } 61 | 62 | 63 | 64 | class NRBaseStation: 65 | bs_type = "nr" 66 | 67 | def __init__(self, bs_id, total_prb, prb_bandwidth_size, number_subcarriers, numerology, antenna_power, antenna_gain, feeder_loss, carrier_frequency, total_bitrate, position, env): 68 | if position[2] > 200 or position[2] < 30: 69 | raise Exception("COST-HATA model requires BS height in [30, 200]m") 70 | 71 | if (carrier_frequency < 150 or carrier_frequency > 2000): 72 | raise Exception("your results may be incorrect because your carrier frequency is outside the boundaries of COST-HATA path loss model") 73 | 74 | self.prb_bandwidth_size = prb_bandwidth_size 75 | self.total_prb = total_prb 76 | self.total_bitrate = total_bitrate #Mbps 77 | self.allocated_prb = 0 78 | self.allocated_bitrate = 0 79 | self.antenna_power = antenna_power 80 | self.antenna_gain = antenna_gain 81 | self.feeder_loss = feeder_loss 82 | self.bs_id = bs_id 83 | self.carrier_frequency = carrier_frequency 84 | self.fr = -1 85 | if (carrier_frequency <= 6000): #below 6GHz 86 | self.fr = 0 87 | elif (carrier_frequency >= 24250 and carrier_frequency <= 52600): #between 24.25GHz and 52.6GHz 88 | self.fr = 1 89 | self.position = (position[0],position[1]) 90 | self.h_b = position[2] 91 | self.number_subcarriers = number_subcarriers 92 | self.env = env 93 | self.numerology = numerology 94 | self.ue_pb_allocation = {} 95 | self.ue_bitrate_allocation = {} 96 | self.T = 10 97 | self.resource_utilization_array = [0] * self.T 98 | self.resource_utilization_counter = 0 99 | 100 | if(self.antenna_power < 5): 101 | self.wardrop_alpha = 0.1 102 | else: 103 | self.wardrop_alpha = 0.2 104 | 105 | 106 | def compute_rbur(self): 107 | return sum(self.resource_utilization_array)/(self.T*self.total_prb) 108 | 109 | 110 | def compute_nprb_NR(self, data_rate, rsrp): 111 | #compute SINR 112 | interference = 0 113 | 114 | for elem in rsrp: 115 | if elem != self.bs_id and util.find_bs_by_id(elem).bs_type != "sat" and util.find_bs_by_id(elem).carrier_frequency == self.carrier_frequency: 116 | total, used = util.find_bs_by_id(elem).get_state() 117 | interference = interference + (10 ** (rsrp[elem]/10))*(used/total)*(self.allocated_prb/self.total_prb) 118 | 119 | #thermal noise is computed as k_b*T*delta_f, where k_b is the Boltzmann's constant, T is the temperature in kelvin and delta_f is the bandwidth 120 | #thermal_noise = constants.Boltzmann*293.15*list(NRbandwidth_prb_lookup[self.numerology][self.fr].keys())[list(NRbandwidth_prb_lookup[self.numerology][self.fr].values()).index(self.total_prb / (10 * 2**self.numerology))]*1000000*(self.compute_rbur()+0.001) 121 | thermal_noise = constants.Boltzmann*293.15*15*(2**self.numerology)*1000 # delta_F = 15*2^mu KHz each subcarrier since we are considering measurements at subcarrirer level (like RSRP) 122 | sinr = (10**(rsrp[self.bs_id]/10))/(thermal_noise + interference) 123 | 124 | r = self.prb_bandwidth_size*1000*math.log2(1+sinr) #bandwidth is in kHz 125 | #based on the numerology choosen and considered the frame duration of 10ms, we transmit 1ms for mu = 0, 0.5ms for mu = 1, 0.25ms for mu = 2, 0.125ms for mu = 3 for each PRB each 10ms 126 | #print(r) 127 | r = r / (10 * (2**self.numerology)) 128 | #print(r) 129 | N_prb = math.ceil(data_rate*1000000 / r) #data rate is in Mbps 130 | return N_prb, r 131 | 132 | def compute_sinr(self, rsrp): 133 | interference = 0 134 | 135 | for elem in rsrp: 136 | if elem != self.bs_id and util.find_bs_by_id(elem).bs_type != "sat" and util.find_bs_by_id(elem).carrier_frequency != self.carrier_frequency: 137 | interference = interference + (10 ** (rsrp[elem]/10))*util.find_bs_by_id(elem).compute_rbur() 138 | 139 | #thermal noise is computed as k_b*T*delta_f, where k_b is the Boltzmann's constant, T is the temperature in kelvin and delta_f is the bandwidth 140 | #thermal_noise = constants.Boltzmann*293.15*list(NRbandwidth_prb_lookup[self.numerology][self.fr].keys())[list(NRbandwidth_prb_lookup[self.numerology][self.fr].values()).index(self.total_prb / (10 * 2**self.numerology))]*1000000*(self.compute_rbur()+0.001) 141 | thermal_noise = constants.Boltzmann*293.15*15*(2**self.numerology)*1000 # delta_F = 15*2^mu KHz each subcarrier since we are considering measurements at subcarrirer level (like RSRP) 142 | sinr = (10**(rsrp[self.bs_id]/10))/(thermal_noise + interference) 143 | return sinr 144 | 145 | #this method will be called by an UE that tries to connect to this BS. 146 | #the return value will be the actual bandwidth assigned to the user 147 | def request_connection(self, ue_id, data_rate, rsrp): 148 | 149 | N_prb, r = self.compute_nprb_NR(data_rate, rsrp) 150 | old_N_prb = N_prb 151 | 152 | #check if there is enough bitrate, if not then do not allocate the user 153 | if self.total_bitrate - self.allocated_bitrate < r*N_prb/1000000: 154 | dr = self.total_bitrate - self.allocated_bitrate 155 | N_prb, r = self.compute_nprb_NR(dr, rsrp) 156 | 157 | #check if there are enough PRBs 158 | if self.total_prb - self.allocated_prb <= N_prb: 159 | N_prb = self.total_prb - self.allocated_prb 160 | 161 | if ue_id not in self.ue_pb_allocation: 162 | self.ue_pb_allocation[ue_id] = N_prb 163 | self.allocated_prb += N_prb 164 | else: 165 | self.allocated_prb -= self.ue_pb_allocation[ue_id] 166 | self.ue_pb_allocation[ue_id] = N_prb 167 | self.allocated_prb += N_prb 168 | 169 | if ue_id not in self.ue_bitrate_allocation: 170 | self.ue_bitrate_allocation[ue_id] = r * N_prb / 1000000 171 | self.allocated_bitrate += r * N_prb / 1000000 172 | else: 173 | self.allocated_bitrate -= self.ue_bitrate_allocation[ue_id] 174 | self.ue_bitrate_allocation[ue_id] = r * N_prb / 1000000 175 | self.allocated_bitrate += r * N_prb / 1000000 176 | 177 | #print("Allocated %s/%s NR PRB" %(N_prb, old_N_prb)) 178 | return r*N_prb/1000000 #we want a data rate in Mbps, not in bps 179 | 180 | def request_disconnection(self, ue_id): 181 | N_prb = self.ue_pb_allocation[ue_id] 182 | self.allocated_prb -= N_prb 183 | del self.ue_pb_allocation[ue_id] 184 | 185 | 186 | def update_connection(self, ue_id, data_rate, rsrp): 187 | 188 | N_prb, r = self.compute_nprb_NR(data_rate, rsrp) 189 | #if (ue_id == 3 and self.bs_id == 2): 190 | # print(N_prb, r) 191 | diff = N_prb - self.ue_pb_allocation[ue_id] 192 | #print("BS_ID", self.bs_id, "UE_ID: ", ue_id ," data_rate: ", data_rate," diff: ", diff, "ALREADY ALLOCATED: ", self.ue_pb_allocation[ue_id]) 193 | #print(N_prb*r/1000000) 194 | 195 | #check before if there is enough bitrate 196 | if diff >= 0 and self.total_bitrate > self.allocated_bitrate and self.total_bitrate - self.allocated_bitrate < diff * r / 1000000: 197 | #print("BS_ID", self.bs_id, "UE_ID: ", ue_id ,"NO MORE BITRATE", self.total_bitrate - self.allocated_bitrate, diff * r / 1000000) 198 | #return self.ue_pb_allocation[ue_id] * r / 1000000 199 | dr = self.total_bitrate - self.allocated_bitrate 200 | N_prb, r = self.compute_nprb_NR(self.ue_bitrate_allocation[ue_id]+dr, rsrp) 201 | diff = N_prb - self.ue_pb_allocation[ue_id] 202 | 203 | 204 | if self.total_prb - self.allocated_prb >= diff: 205 | #there is the place for more PRB allocation (or less if diff is negative) 206 | self.allocated_prb += diff 207 | self.ue_pb_allocation[ue_id] += diff 208 | 209 | self.allocated_bitrate += diff * r / 1000000 210 | self.ue_bitrate_allocation[ue_id] += diff * r / 1000000 211 | else: 212 | #there is no room for more PRB allocation 213 | diff = self.total_prb - self.allocated_prb 214 | self.allocated_prb += diff 215 | self.ue_pb_allocation[ue_id] += diff 216 | 217 | self.allocated_bitrate += diff * r / 1000000 218 | self.ue_bitrate_allocation[ue_id] += diff * r / 1000000 219 | 220 | N_prb = self.ue_pb_allocation[ue_id] 221 | return N_prb*r/1000000 #remember that we want the result in Mbps 222 | 223 | #things to do before moving to the next timestep 224 | def next_timestep(self): 225 | #print(self.allocated_prb) 226 | self.resource_utilization_array[self.resource_utilization_counter] = self.allocated_prb 227 | self.resource_utilization_counter += 1 228 | if self.resource_utilization_counter % self.T == 0: 229 | self.resource_utilization_counter = 0 230 | 231 | def new_state(self): 232 | return (sum(self.resource_utilization_array) - self.resource_utilization_array[self.resource_utilization_counter] + self.allocated_prb)/(self.total_prb*self.T) 233 | 234 | def get_state(self): 235 | return self.total_prb, self.allocated_prb 236 | 237 | def get_connection_info(self, ue_id): 238 | return self.ue_pb_allocation[ue_id], self.total_prb 239 | 240 | def get_connected_users(self): 241 | return list(self.ue_pb_allocation.keys()) 242 | 243 | def reset(self): 244 | self.resource_utilization_array = [0] * self.T 245 | self.resource_utilization_counter = 0 246 | 247 | def compute_latency(self, ue_id): 248 | if ue_id in self.ue_pb_allocation: 249 | return self.wardrop_alpha * self.ue_pb_allocation[ue_id] 250 | #return self.wardrop_alpha * self.allocated_prb 251 | return 0 252 | 253 | def compute_r(self, ue_id, rsrp): 254 | N_prb, r = self.compute_nprb_NR(1, rsrp) 255 | return r 256 | 257 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 4G/5G/Satellite Wireless Network Simulator 2 | 3 | **New version of the simulator available here: https://github.com/trunk96/wireless-network-simulator-v2** 4 | 5 | This tool is designed in the context of my PhD in Automatic Control in Sapienza University of Rome to simulate resource allocations in 4G, 5G and Satellite networks, without entering in the details of the various protocols and of the syncronization mechanisms. Moreover this simulator does not considers actual transmission of the data, but just allocation of uplink/downlink resources. 6 | 7 | This simulator is very modular and the internal logic of each component can be changed according to specific needs. 8 | 9 | According to the idea of Multi-RAT, in this simulator the User Equipment (UE) is not aware of the type of Access Point (AP) it is connecting to. This implies that the UE makes a request in terms of bitrate to one (or more) AP(s). 10 | Each AP, will then compute the actual network resources to be allocated (Resource Blocks for LTE and NR networks, Symbols for Satellite networks) considering the path loss between AP and UE and the inter-AP interference. 11 | 12 | This simulator can consider also the movement of UEs, as well as the movement of the APs (with the Drone BaseStation/Relay): 13 | - UEs have fixed speed and there are two possible movements implemented at this time: 14 | - random movement 15 | - line movement given a direction, with bumping on the borders of the map 16 | - Drones move with a maximum speed towards a certain point; the speed control is done using the unicycle model (without considering orientation) 17 | 18 | ## Basic steps 19 | 20 | The connection process is as follows: 21 | 22 | 1. UE measures the receiving power for each visible AP 23 | 2. According to the measured receiving power (as well as any other variable of interest the programmer can add), it chooses the AP(s) to connect to (in a User-Centric, RAN-Assisted or RAN-Controlled way, depending on the specific needs) 24 | 3. The UE sends a connection request to the selected AP(s), indicating its requested bitrate for that connection 25 | 4. The AP allocates the resources for the UE’s request based on the SINR in a best-effort manner, notifying the UE the actual bitrate derived from the allocated resources. 26 | 27 | In case of moving UEs or APs or in any other specific case, it is possible to update an established connection in order to consider the new path loss, the new SINR or any other change in the connection parameters. 28 | The logic behind the connection update can be personalized according to the specific needs (e.g. reallocation policies and resource contention) 29 | 30 | ## Resource allocation 31 | 32 | As said before the first thing the UE has to do is to measure the receiving power (i.e., the RSRP) of each visible base station. This value depends on four main parameters: the AP antenna power, on the feeder loss, on the antenna gain and on the path loss between the AP and the UE 33 | 34 | The path loss model used is the [COST HATA model](https://en.wikipedia.org/wiki/COST_Hata_model) is implemented inside `util.py`, but any other model can be implemented. 35 | 36 | Once a connection request/update is made by an UE, the AP computes the SINR (Signal-to-interference-plus-noise-ratio) in order to determine the bitrate each of its resource blocks can actually provide (using the [Shannon Formula](https://en.wikipedia.org/wiki/Shannon%E2%80%93Hartley_theorem)). Using this value it can compute the number of resource blocks to be allocated for the UE connection. 37 | 38 | The interference is computed according to the other APs visible by the UE, to their RSRP, to their utilization ratio and to the utilization ratio of the AP involved in the connection ([reference1](https://ieeexplore.ieee.org/document/6097237), [reference2](https://ieeexplore.ieee.org/document/8826267)) 39 | 40 | ## Usage guidelines 41 | 42 | An example of the usage of this simulator can be found in `test.py`. 43 | 44 | The first thing to do is to set-up the environment, indicating the width of the map and the system sampling time 45 | 46 | ```python 47 | env = environment.wireless_environment(x [, y], sampling_time]) 48 | ``` 49 | 50 | Now that the environment is created, it is possible to add UEs using the function 51 | 52 | ```python 53 | id = insert_ue(ue_class, starting_position = None, speed = 0, direction = 0) 54 | ``` 55 | 56 | where ue_class specifies the bitrate required by the user (see `ue_class` dictionary in `UserEquipment.py`). The starting poisition, if not specified, will be randomly sampled. The speed is in m/s and the direction is in degrees from the positive x axis of the cartesian plan. 57 | 58 | At the same way it is possible to add all the APs using the appropriate functions 59 | 60 | ```python 61 | bs_id = place_SAT_base_station(total_bitrate, position) 62 | 63 | bs_id = place_LTE_base_station(position, carrier_frequency, antenna_power, antenna_gain, feeder_loss, available_bandwidth, total_bitrate) 64 | 65 | bs_id = place_NR_base_station(position, carrier_frequency, numerology, antenna_power, antenna_gain, feeder_loss, available_bandwidth, total_bitrate) 66 | 67 | bs_id = place_DRONE_relay(starting_position, linked_bs_id, carrier_frequency, amplification_factor, antenna_gain, feeder_loss) 68 | 69 | bs_id = place_DRONE_base_station(position, carrier_frequency, numerology, antenna_power, antenna_gain, feeder_loss, available_bandwidth, total_bitrate) 70 | ``` 71 | 72 | If specific actions has to be done before the first simulation step, they can be added in the `initial_timestep()` function of `environment.py` or `UserEquipment.py` or in the appropriate AP class. 73 | This function should be explicitly called before starting the simulation (i.e., after all the UEs and APs are placed). 74 | 75 | ```python 76 | env.initial_timestep() 77 | ``` 78 | 79 | At the same way, if specific actions has to be done after each simulation step, they can be added in the `next_timestep()` function of `environment.py` or `UserEquipment.py` or in the appropriate AP class. 80 | Same as before, this function has to be explicitely called at the end of each timestep in order to let the system move to the next one. 81 | 82 | ```python 83 | env.next_timestep() 84 | ``` 85 | 86 | Each of the APs has already implemented some common functions, that can be used for specific needs: 87 | 88 | - `compute_rbur()` that returns the mean utilization ratio of the AP 89 | - `compute_sinr(rsrp)` that takes a dictionary with the RSRP values of each of the visible APs (it can be generated using the function `env.discover_bs(ue_id)`, that given an UE id finds all the visible APs together with their RSRP values) and returns the SINR value (as real number, not in dB) 90 | - `request_connection(ue_id, data_rate, rsrp)` that given the UE id, the desired data rate for this connection and the RSRP dictionary, allocates the resources for the connection and returns the actual data rate. 91 | - `request_disconnection(ue_id)` that given the UE id releases the resources for its connection 92 | - `update_connection(ue_id, data_rate, rsrp)`, that given the UE id, the desired data rate and the new RSRP dictionary updates the connection (allocating more/less resource blocks) and returns the new actual data rate 93 | - `get_state()` that returns the number of resource block of the AP and the occupied ones 94 | - `get_connection_info(ue_id)` that given the UE id returns the number of resource blocks occupied by the selected UE and the total number of resource blocks of the AP 95 | - `get_connected_users()` that returns the list of all the UEs connected to the AP 96 | - `reset()` that resets the state variable of the AP (here it is possible to add other actions for specific needs) 97 | 98 | 99 | 100 | 101 | 102 | -------------------------------------------------------------------------------- /Satellite.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import constants 3 | import math 4 | import util 5 | 6 | 7 | class Satellite: 8 | """ 9 | Reference: INMARSAT 4F2 ATTACHMENT 1 TECHNICAL DESCRIPTION, 10 | Table A.12-1 - Link Budget for Signaling Forward Link from Class-1 User Terminal (200 kHz bandwidth; Spot Beam) 11 | TDMA is taken from the example at section 6.6.2 on "Satellite Communication Systems - Systems, Techniques and Technologies, Gérard Maral, Michel Bousquet" 12 | The values are adapted in order to have at least 1bit per symbol with typical SNR values (reference papers: 13 | -High Throughput Satellite Systems: An Analytical Approach, H. FENECH, Fellow, IEEE, S. AMOS, A. TOMATIS, V. SOUMPHOLPHAKDY 14 | -High Throughput Satellites - Delivering future capacity needs, ADL) 15 | """ 16 | bs_type = "sat" 17 | #bs_id= None 18 | #position = None # tuple, (x,y) in meters 19 | #h = None # height [m] 20 | carrier_bnd = 220 # carrier bandwidth [MHz] 21 | carrier_frequency = 28.4 # frequency [GHz] 22 | sat_eirp = 62 #45.1 # satellite effective isotropic radiated power [dBW] 23 | path_loss = 188.4 # path loss [dB] 24 | atm_loss = 0.1 # mean atmospheric loss [dB] 25 | ut_G_T = -9.7 # user terminal G/T [dB/K] 26 | #boltzmann_const = 10*math.log10(constants.Boltzmann) # Boltzmann Constant [dBW/K/Hz] 27 | #dw_path_CN0 = 93.8 # Down-path C/N_0 (carrier power to noise power spectral density) [dBHz] 28 | #adj_channel_int = 0.2 # adjacent channel interference [dB] 29 | #env = None 30 | #rsrp = subcarrier_pow + antenna_gain - path_loss - atm_loss - adj_channel_int # Reference Signals Received Power (for LTE) 31 | #rsrp = None 32 | #rbur = None # resource block utilization ration 33 | 34 | 35 | 36 | # tb_length = tb_header + n * 64 [symbols] 37 | 38 | def __init__(self, bs_id, total_bitrate, position, env): 39 | self.bs_id = bs_id 40 | self.position = (position[0], position[1]) 41 | self.env = env 42 | #self.h = position[2] 43 | self.frame_length = 120832 # [120832 symbols] 44 | self.rb_length = 288 # reference burst length, fixed [symbols] 45 | self.tb_header = 280 # traffic burst header, fixed [symbols] 46 | self.guard_space = 64 # fixed [symbols] 47 | self.total_users = 0 48 | self.frame_duration = 2 # lenght of the frame in milliseconds 49 | self.total_symbols = (self.frame_length - 288*2 - 64*2)#39104 - 288*2 - 64*2 #(self.frame_length - 288*2 - 64*2) # in a frame there are 2 reference burst made of 288 symbols each, with a guard time of 64 symbols between them and between any other burst 50 | self.frame_utilization = 0 # allocated resources 51 | self.total_bitrate = total_bitrate 52 | self.allocated_bitrate = 0 53 | self.ue_allocation = {} 54 | self.ue_bitrate_allocation ={} 55 | 56 | self.wardrop_alpha = 0.5 57 | 58 | self.T = 10 59 | self.resource_utilization_array = [0] * self.T 60 | self.resource_utilization_counter = 0 61 | 62 | 63 | def compute_nsymb_SAT(self, data_rate, rsrp): 64 | 65 | #compute SINR 66 | interference = 0 67 | for elem in rsrp: 68 | if elem != self.bs_id and util.find_bs_by_id(elem).bs_type == "sat": 69 | interference = interference + (10 ** (rsrp[elem]/10))*util.find_bs_by_id(elem).compute_rbur()*(self.frame_utilization/self.total_symbols) 70 | thermal_noise = constants.Boltzmann*290*self.carrier_bnd*1000000 71 | sinr = (10**(rsrp[self.bs_id]/10))/(thermal_noise + interference) 72 | r = self.carrier_bnd * 1000000 * math.log2(1 + sinr) 73 | 74 | r = r / self.frame_length # this is the data rate in [b/s] that is possible to obtains for a single symbol assigned every time frame 75 | 76 | r_64 = r * 64 # we can transmit in blocks of 64 symbols 77 | 78 | n_symb = math.ceil(data_rate*1000000 / r_64) 79 | return n_symb, r 80 | 81 | def compute_sinr(self, rsrp): 82 | interference = 0 83 | 84 | for elem in rsrp: 85 | if elem != self.bs_id and util.find_bs_by_id(elem).bs_type == "sat": 86 | interference = interference + (10 ** (rsrp[elem]/10))*util.find_bs_by_id(elem).compute_rbur() 87 | 88 | thermal_noise = constants.Boltzmann*290*self.carrier_bnd*1000000 89 | sinr = (10**(rsrp[self.bs_id]/10))/(thermal_noise + interference) 90 | return sinr 91 | 92 | def request_connection(self, ue_id, data_rate, rsrp): 93 | # this method will be called by an UE that tries to connect to this satellite. 94 | # the return value will be the actual datarate assigned to the user 95 | 96 | #IMPORTANT: there must always be a guard space to be added to each allocation. This guard space is included 97 | # in the frame utilization but not in the ue_allocation dictionary 98 | 99 | N_symb, r = self.compute_nsymb_SAT(data_rate, rsrp) 100 | 101 | #check if there is enough bitrate 102 | if self.total_bitrate-self.allocated_bitrate <= (r*N_symb*64)/1000000: 103 | dr = self.total_bitrate - self.allocated_bitrate 104 | N_prb, r = self.compute_nsymb_SAT(dr, rsrp) 105 | 106 | #check if there are enough symbols 107 | if self.total_symbols - self.frame_utilization <= self.tb_header + N_symb*64 + self.guard_space: 108 | N_symb = math.floor((self.total_symbols - self.frame_utilization - self.guard_space - self.tb_header)/64) 109 | 110 | if N_symb <= 0: #we can allocate at least 1 block of 64 symbols 111 | self.ue_allocation[ue_id] = 0 112 | return 0 113 | 114 | if ue_id not in self.ue_allocation: 115 | self.ue_allocation[ue_id] = self.tb_header + N_symb*64 + self.guard_space 116 | self.frame_utilization += self.tb_header + N_symb*64 + self.guard_space 117 | else: 118 | self.frame_utilization -= self.ue_allocation[ue_id] 119 | self.ue_allocation[ue_id] = self.tb_header + N_symb*64 + self.guard_space 120 | self.frame_utilization += self.ue_allocation[ue_id] 121 | 122 | if ue_id not in self.ue_bitrate_allocation: 123 | self.ue_bitrate_allocation[ue_id] = (r*N_symb*64)/1000000 124 | self.allocated_bitrate += (r*N_symb*64)/1000000 125 | else: 126 | self.allocated_bitrate -= self.ue_bitrate_allocation[ue_id] 127 | self.ue_bitrate_allocation[ue_id] = (r*N_symb*64)/1000000 128 | self.allocated_bitrate += (r*N_symb*64)/1000000 129 | #print(r) 130 | #print(N_symb) 131 | return (r*N_symb*64)/1000000 #we want a data rate in Mbps, not in bps 132 | 133 | def request_disconnection(self, ue_id): 134 | self.frame_utilization -= self.ue_allocation[ue_id] 135 | del self.ue_allocation[ue_id] 136 | 137 | 138 | def update_connection(self, ue_id, data_rate, rsrp): 139 | # There are two cases: the first case is when an user has already some sybols allocated, the second case is when the user has no symbol allocated. 140 | # In the first case self.ue_allocation[ue_id] contains already the header and some symbols, so we have just to add the remaining symbols (if there is room) 141 | # In the second case self.ue_allocation[ue_id] is equal to 0, so we have to add the symbols, the header and the guard space. 142 | # If there is no room for actual data symbols allocation (in the latter case), we still must have self.ue_allocation[ue_id]=0, since it is useless to allocate just the header and the guard space. 143 | 144 | N_symb, r = self.compute_nsymb_SAT(data_rate, rsrp) 145 | 146 | #check again if there is enough bitrate 147 | if self.total_bitrate - (self.allocated_bitrate - self.ue_bitrate_allocation[ue_id]) <= (r*N_symb*64)/1000000: 148 | dr = self.total_bitrate - (self.allocated_bitrate - self.ue_bitrate_allocation[ue_id]) 149 | N_prb, r = self.compute_nsymb_SAT(dr, rsrp) 150 | 151 | 152 | if self.total_symbols - (self.frame_utilization - self.ue_allocation[ue_id]) >= N_symb*64 + self.tb_header + self.guard_space: 153 | # there is room for allocation 154 | self.frame_utilization -= self.ue_allocation[ue_id] 155 | self.ue_allocation[ue_id] = N_symb*64 + self.tb_header +self.guard_space 156 | self.frame_utilization += self.ue_allocation[ue_id] 157 | 158 | self.allocated_bitrate -= self.ue_bitrate_allocation[ue_id] 159 | self.ue_bitrate_allocation[ue_id] = (r*N_symb*64)/1000000 160 | self.allocated_bitrate += self.ue_bitrate_allocation[ue_id] 161 | 162 | else: 163 | # no room for the entire allocation, trying to allocate at least a part 164 | N_symb = math.floor((self.total_symbols - (self.frame_utilization - self.ue_allocation[ue_id]) - self.tb_header - self.guard_space)/64) 165 | if N_symb <= 0: 166 | self.frame_utilization -= self.ue_allocation[ue_id] 167 | self.ue_allocation[ue_id] = 0 168 | 169 | self.allocated_bitrate -= self.ue_bitrate_allocation[ue_id] 170 | self.ue_allocation[ue_id] = 0 171 | return 0 172 | 173 | self.frame_utilization -= self.ue_allocation[ue_id] 174 | self.ue_allocation[ue_id] = self.tb_header + N_symb*64 + self.guard_space 175 | self.frame_utilization += self.ue_allocation[ue_id] 176 | 177 | self.allocated_bitrate -= self.ue_bitrate_allocation[ue_id] 178 | self.ue_allocation[ue_id] = (r*N_symb*64)/1000000 179 | self.allocated_bitrate += self.ue_bitrate_allocation[ue_id] 180 | 181 | return (r*N_symb*64)/1000000 #in Mbps, not in bps 182 | 183 | ''' 184 | if self.ue_allocation[ue_id] != 0: 185 | diff = N_symb + self.tb_header - self.ue_allocation[ue_id] 186 | else: 187 | diff = N_symb + self.tb_header + self.guard_space 188 | 189 | if self.total_symbols - self.frame_utilization >= diff: 190 | #there is the place for more symbols allocation (or less if diff is negative) 191 | self.frame_utilization += diff 192 | if self.ue_allocation[ue_id] != 0: 193 | self.ue_allocation[ue_id] += diff 194 | else: 195 | self.ue_allocation[ue_id] += diff - self.guard_space 196 | else: 197 | #there is no room for more symbols allocation 198 | diff = self.total_symbols - self.frame_utilization 199 | if self.ue_allocation[ue_id] == 0 and diff < self.guard_space + self.tb_header + 64: 200 | diff = 0 201 | elif self.ue_allocation[ue_id] == 0: 202 | self.frame_utilization += diff 203 | self.ue_allocation[ue_id] = diff - self.guard_space 204 | else: 205 | self.frame_utilization += diff 206 | self.ue_allocation[ue_id] += diff 207 | 208 | if self.ue_allocation[ue_id] == 0: 209 | return 0 210 | N_symb = self.ue_allocation[ue_id] - self.tb_header 211 | return N_symb*r/1000000 #remember that we want the result in Mbps 212 | ''' 213 | 214 | 215 | def next_timestep(self): 216 | #print(self.frame_utilization) 217 | self.resource_utilization_array[self.resource_utilization_counter] = self.frame_utilization 218 | self.resource_utilization_counter += 1 219 | if self.resource_utilization_counter % self.T == 0: 220 | self.resource_utilization_counter = 0 221 | 222 | def compute_rbur(self): 223 | """ 224 | RBUR: resource block utilization ratio. 225 | PRB: physical resource block 226 | Returns 227 | ------- 228 | RBUR = #PRB allocated to che cell / #PRB belonging to the cell 229 | """ 230 | 231 | return sum(self.resource_utilization_array)/(self.T*self.total_symbols) 232 | 233 | def new_state(self): 234 | return (sum(self.resource_utilization_array) - self.resource_utilization_array[self.resource_utilization_counter] + self.frame_utilization)/(self.total_symbols*self.T) 235 | 236 | 237 | def get_state(self): 238 | return self.total_symbols, self.frame_utilization 239 | 240 | def get_connection_info(self, ue_id): 241 | return self.ue_allocation[ue_id]-self.tb_header-self.guard_space, self.total_symbols 242 | 243 | def get_connected_users(self): 244 | return list(self.ue_allocation.keys()) 245 | 246 | def reset(self): 247 | self.resource_utilization_array = [0] * self.T 248 | self.resource_utilization_counter = 0 249 | 250 | def compute_latency(self, ue_id): 251 | if ue_id in self.ue_allocation: 252 | return self.wardrop_alpha * self.ue_allocation[ue_id]/64 253 | #return self.wardrop_alpha * self.frame_utilization/64 254 | return 0 255 | 256 | def compute_r(self, ue_id, rsrp): 257 | N_symb, r = self.compute_nsymb_SAT(1, rsrp) 258 | #we are interested in the r of a block, not of a single symbol 259 | return r*64 260 | -------------------------------------------------------------------------------- /UserEquipment.py: -------------------------------------------------------------------------------- 1 | import random 2 | import util 3 | import math 4 | #import matlab.engine 5 | 6 | MAX_STEP = 2000 7 | 8 | # service classes for UEs, "class: Mbps" 9 | ue_class = { 10 | 0: 50, 11 | 1: 3 12 | } 13 | ue_class_lambda = { 14 | 0: 1/4000, 15 | 1: 1/15 16 | } 17 | 18 | class user_equipment: 19 | MATLAB = 0 20 | RANDOM = 0 21 | epsilon = -1 22 | 23 | def __init__ (self, requested_bitrate, service_class, ue_id, starting_position, env, speed, direction): 24 | self.ue_id = ue_id 25 | self.requested_bitrate = requested_bitrate 26 | self.current_position = (starting_position[0], starting_position[1]) 27 | self.starting_position = (starting_position[0], starting_position[1]) 28 | self.h_m = starting_position[2] 29 | self.env = env 30 | self.speed = speed #how much distance we made in one step 31 | self.direction = direction #in degrees from the x axis (0 horizontal movement, 90 vertical movement) 32 | self.old_position = (starting_position[0], starting_position[1]) 33 | self.old_sevice_class = service_class 34 | self.service_class = service_class 35 | self.lambda_exp = ue_class_lambda[self.service_class] 36 | self.current_bs = {} 37 | self.actual_data_rate = 0 38 | self.last_action_t = 0 39 | 40 | self.bs_bitrate_allocation = {} 41 | self.wardrop_sigma = 0 42 | 43 | 44 | def move(self): 45 | if self.speed == 0: 46 | return self.current_position 47 | elif self.RANDOM == 1: 48 | return self.random_move() 49 | else: 50 | return self.line_move() 51 | 52 | def random_move(self): 53 | val = random.randint(1, 4) 54 | size = random.randint(0, MAX_STEP) 55 | if val == 1: 56 | if (self.current_position[0] + size) > 0 and (self.current_position[0] + size) < self.env.x_limit: 57 | self.current_position = (self.current_position[0] + size, self.current_position[1]) 58 | elif val == 2: 59 | if (self.current_position[0] - size) > 0 and (self.current_position[0] - size) < self.env.x_limit: 60 | self.current_position = (self.current_position[0] - size, self.current_position[1]) 61 | elif val == 3: 62 | if (self.current_position[1] + size) > 0 and (self.current_position[1] + size) < self.env.y_limit: 63 | self.current_position = (self.current_position[0], self.current_position[1] + size) 64 | else: 65 | if (self.current_position[1] - size) > 0 and (self.current_position[1] - size) < self.env.y_limit: 66 | self.current_position = (self.current_position[0], self.current_position[1] - size) 67 | return self.current_position 68 | 69 | def line_move(self): 70 | new_x = self.current_position[0]+self.speed*math.cos(math.radians(self.direction)) 71 | new_y = self.current_position[1]+self.speed*math.sin(math.radians(self.direction)) 72 | 73 | #90-degrees bumping 74 | if new_x <= 0 and new_y <= 0: 75 | #bottom-left corner 76 | new_x = 0 77 | new_y = 0 78 | self.direction -= 180 79 | elif new_x <= 0 and new_y >= self.env.y_limit: 80 | #top-left corener 81 | new_x = 0 82 | new_y = self.env.y_limit 83 | self.direction += 180 84 | elif new_x >= self.env.x_limit and new_y >= self.env.y_limit: 85 | #top-right corner 86 | new_x = self.env.x_limit 87 | new_y = self.env.y_limit 88 | self.direction += 180 89 | elif new_x >= self.env.x_limit and new_y <= 0: 90 | #bottom-right corner 91 | new_x = self.env.x_limit 92 | new_y = 0 93 | self.direction -= 180 94 | elif new_x >= self.env.x_limit and self.direction != 90 and self.direction != 270: 95 | #bumping on the right margin 96 | new_x = self.env.x_limit 97 | if self.direction < 90 and self.direction > 0: 98 | self.direction += 90 99 | elif self.direction > 270 and self.direction < 360: 100 | self.direction -= 90 101 | elif new_x <= 0 and self.direction != 90 and self.direction != 270: 102 | #bumping on the left margin 103 | new_x = 0 104 | if self.direction > 180 and self.direction < 270: 105 | self.direction += 90 106 | elif self.direction > 90 and self.direction < 180: 107 | self.direction -= 90 108 | elif new_y <= 0 and self.direction != 0 and self.direction != 180: 109 | #bumping on the bottom margin 110 | new_y = 0 111 | self.direction = (360 - self.direction) % 360 112 | elif new_y >= self.env.y_limit and self.direction != 0 and self.direction != 180: 113 | #bumping on the top margin 114 | new_y = self.env.y_limit 115 | self.direction = (360 - self.direction) % 360 116 | 117 | self.direction = self.direction % 360 118 | self.current_position = (new_x, new_y) 119 | return self.current_position 120 | 121 | def do_action(self, t): 122 | ''' 123 | if self.current_bs == None: 124 | self.connect_to_bs() 125 | return 126 | 127 | # compute the time spent in the service class 128 | #delta_t = (t+1) - (self.last_action_t+1) 129 | delta_t = 0 130 | if self.last_action_t > 0 and t + 1 - self.last_action_t > 40: 131 | if self.actual_data_rate < self.requested_bitrate/2: 132 | self.disconnect_from_bs() 133 | return 134 | else: 135 | self.disconnect_from_bs() 136 | self.connect_to_bs() 137 | return 138 | elif self.last_action_t > 0: 139 | self.disconnect_from_bs() 140 | self.connect_to_bs() 141 | 142 | prob = 1 - (1 - math.exp(-self.lambda_exp * delta_t)) 143 | if random.random() > prob: 144 | 145 | # it's time to change service class 146 | print("CHANGED SERVICE CLASS: User ID %s has now changed to class %s" %(self.ue_id, self.service_class)) 147 | self.disconnect_from_bs() 148 | if self.service_class == 0: 149 | self.service_class = 1 150 | else: 151 | self.service_class = 0 152 | # apply new class parameters: requested bitrate, lambda, last action time 153 | self.requested_bitrate = ue_class[self.service_class] 154 | self.lambda_exp = ue_class_lambda[self.service_class] 155 | 156 | self.last_action_t = t + 1 157 | self.connect_to_bs() 158 | 159 | #just in scenario 1, otherwise comment 160 | else: 161 | self.disconnect_from_bs() 162 | self.connect_to_bs() 163 | #self.update_connection() 164 | ''' 165 | return 166 | 167 | #deprecated 168 | def connect_to_bs_random(self): 169 | available_bs = self.env.discover_bs(self.ue_id) 170 | bs = None 171 | data_rate = None 172 | if len(available_bs) == 0: 173 | print("[NO BASE STATION FOUND]: User ID %s has not found any base station" %(self.ue_id)) 174 | return 175 | elif len(available_bs) == 1: 176 | #this means there is only one available bs, so we have to connect to it 177 | #bs = list(available_bs.keys())[0] 178 | #self.actual_data_rate = util.find_bs_by_id(bs).request_connection(self.ue_id, self.requested_bitrate, available_bs) 179 | bs , data_rate = self.env.request_connection(self.ue_id, self.requested_bitrate, available_bs) 180 | self.current_bs[bs] = data_rate 181 | self.actual_data_rate += data_rate 182 | 183 | else: 184 | if self.MATLAB == 1: 185 | #import function from matlab, in order to select the best action 186 | 187 | #eng = matlab.engine.start_matlab() 188 | #ret = eng.nomefunzione(arg1, arg2,...,argn) 189 | return 190 | else: 191 | bs, rsrp = random.choice(list(available_bs.items())) 192 | data_rate = util.find_bs_by_id(bs).request_connection(self.ue_id, self.requested_bitrate, available_bs) 193 | #self.current_bs, self.actual_data_rate = self.env.request_connection(self.ue_id, self.requested_bitrate, available_bs) 194 | self.current_bs[bs] = data_rate 195 | self.actual_data_rate += data_rate 196 | print("[CONNECTION_ESTABLISHED]: User ID %s is now connected to base_station %s with a data rate of %s/%s Mbps" %(self.ue_id, self.current_bs[bs], data_rate, self.requested_bitrate)) 197 | 198 | #deprecated 199 | def connect_to_bs(self): 200 | available_bs = self.env.discover_bs(self.ue_id) 201 | bs = None 202 | data_rate = None 203 | if len(available_bs) == 0: 204 | print("[NO BASE STATION FOUND]: User ID %s has not found any base station" %(self.ue_id)) 205 | return 206 | elif len(available_bs) == 1: 207 | #this means there is only one available bs, so we have to connect to it 208 | #bs = list(available_bs.keys())[0] 209 | #self.actual_data_rate = util.find_bs_by_id(bs).request_connection(self.ue_id, self.requested_bitrate, available_bs) 210 | bs, data_rate = self.env.request_connection(self.ue_id, self.requested_bitrate, available_bs) 211 | self.current_bs[bs] = data_rate 212 | self.actual_data_rate += data_rate 213 | 214 | else: 215 | if self.MATLAB == 1: 216 | #import function from matlab, in order to select the best action 217 | 218 | #eng = matlab.engine.start_matlab() 219 | #ret = eng.nomefunzione(arg1, arg2,...,argn) 220 | return 221 | else: 222 | #bs = max(available_bs, key = available_bs.get) 223 | #self.actual_data_rate = util.find_bs_by_id(bs).request_connection(self.ue_id, self.requested_bitrate, available_bs) 224 | bs, data_rate = self.env.request_connection(self.ue_id, self.requested_bitrate, available_bs) 225 | self.current_bs[bs] = data_rate 226 | self.actual_data_rate += data_rate 227 | #self.current_bs = bs 228 | print("[CONNECTION_ESTABLISHED]: User ID %s is now connected to base_station %s with a data rate of %s/%s Mbps" %(self.ue_id, bs, data_rate, self.requested_bitrate)) 229 | 230 | def connect_to_bs_id(self, bs_id): 231 | available_bs = self.env.discover_bs(self.ue_id) 232 | bs = None 233 | data_rate = None 234 | if bs_id not in available_bs: 235 | #print("[NO BASE STATION FOUND]: User ID %s has not found the selected base station (BS %s)" %(self.ue_id, bs_id)) 236 | return 237 | else: 238 | if bs_id not in self.bs_bitrate_allocation: 239 | #print("[NO ALLOCATION FOR THIS BASE STATION FOUND]: User ID %s has not found any bitrate allocation for the selected base station (BS %s)" %(self.ue_id, bs_id)) 240 | return 241 | elif self.bs_bitrate_allocation[bs_id] == 0: 242 | self.current_bs[bs_id] = 0 243 | return 244 | data_rate = util.find_bs_by_id(bs_id).request_connection(self.ue_id, self.bs_bitrate_allocation[bs_id], available_bs) 245 | self.current_bs[bs_id] = data_rate 246 | self.actual_data_rate += data_rate 247 | #print("[CONNECTION_ESTABLISHED]: User ID %s is now connected to base_station %s with a data rate of %s/%s Mbps" %(self.ue_id, bs_id, data_rate, self.requested_bitrate)) 248 | 249 | def connect_to_all_bs(self): 250 | for bs in self.env.bs_list: 251 | self.connect_to_bs_id(bs.bs_id) 252 | 253 | def disconnect_from_bs(self, bs_id): 254 | if bs_id in self.current_bs: 255 | util.find_bs_by_id(bs_id).request_disconnection(self.ue_id) 256 | #print("[CONNECTION_TERMINATED]: User ID %s is now disconnected from base_station %s" %(self.ue_id, bs_id)) 257 | self.actual_data_rate -= self.current_bs[bs_id] 258 | del self.current_bs[bs_id] 259 | return 260 | 261 | def disconnect_from_all_bs(self): 262 | for bs in self.current_bs: 263 | util.find_bs_by_id(bs).request_disconnection(self.ue_id) 264 | #print("[CONNECTION_TERMINATED]: User ID %s is now disconnected from base_station %s" %(self.ue_id, bs)) 265 | self.actual_data_rate = 0 266 | self.current_bs.clear() 267 | 268 | 269 | def update_connection(self): 270 | if len(self.current_bs) == 0: 271 | self.connect_to_bs() 272 | print("UE_ID: ", self.ue_id, " NO CURRENT BS") 273 | return 274 | 275 | available_bs = self.env.discover_bs(self.ue_id) 276 | #print("UE_ID: ", self.ue_id, " AVAILABLE BS: ", available_bs) 277 | #print(available_bs) 278 | if len(available_bs) == 0: 279 | #print("[NO BASE STATION FOUND]: User ID %s has not found any base station during connection update" %(self.ue_id)) 280 | #print("UE_ID: ", self.ue_id, " NO BS AVAILABLE") 281 | return 282 | 283 | for elem in self.current_bs: 284 | if elem in available_bs: 285 | if self.current_bs[elem] == 0: 286 | #print("UE_ID: ", self.ue_id, " NO CONNECTION TO BS", elem) 287 | self.connect_to_bs_id(elem) 288 | continue 289 | data_rate = util.find_bs_by_id(elem).update_connection(self.ue_id, self.bs_bitrate_allocation[elem], available_bs) 290 | 291 | self.actual_data_rate -= self.current_bs[elem] 292 | self.current_bs[elem] = data_rate 293 | self.actual_data_rate += self.current_bs[elem] 294 | 295 | #TODO update the connections according to the newly computed requested bitrates coming from the next_timestep() function 296 | ''' 297 | if self.actual_data_rate < self.requested_bitrate: 298 | print("[POOR BASE STATION]: User ID %s has a poor connection to its base station (actual data rate is %s/%s Mbps)" %(self.ue_id, self.actual_data_rate, self.requested_bitrate)) 299 | self.disconnect_from_bs(elem) 300 | self.connect_to_bs() 301 | ''' 302 | ''' 303 | elif random.random() < self.epsilon: 304 | print("[RANDOM DISCONNECTION]: User ID %s was randomly disconnected from its base station (actual data rate is %s/%s Mbps)" %(self.ue_id, self.actual_data_rate, self.requested_bitrate)) 305 | self.disconnect_from_bs() 306 | self.connect_to_bs() 307 | ''' 308 | else: 309 | #in this case no current base station is anymore visible 310 | #print("[BASE STATION LOST]: User ID %s has not found its base station during connection update" %(self.ue_id)) 311 | self.disconnect_from_bs(elem) 312 | self.connect_to_bs() 313 | 314 | #print("[CONNECTION_UPDATE]: User ID %s has updated its connection to base_station %s with a data rate of %s/%s Mbps" %(self.ue_id, elem, self.current_bs[elem], self.bs_bitrate_allocation[elem])) 315 | 316 | def initial_timestep(self): 317 | rsrp = self.env.discover_bs(self.ue_id) 318 | '''bs = max(rsrp, key = rsrp.get) 319 | rsrp2 = {} 320 | for elem in rsrp: 321 | if elem != bs: 322 | rsrp2[elem] = rsrp[elem] 323 | bs2 = max(rsrp2, key = rsrp2.get) 324 | self.bs_bitrate_allocation[bs] = self.requested_bitrate/2 325 | self.bs_bitrate_allocation[bs2] = self.requested_bitrate/2 326 | ''' 327 | n = len(rsrp) 328 | n1 = random.choice(list(rsrp)) 329 | if self.ue_id == 1 or self.ue_id == 19: 330 | n1 = 0 331 | if 4 in rsrp and random.random() < 0.9: 332 | n1 = 4 333 | for elem in rsrp: 334 | if elem != n1: 335 | self.bs_bitrate_allocation[elem] = self.requested_bitrate/(n-1) 336 | if self.ue_id == 2: 337 | swap = self.bs_bitrate_allocation[0]*0.3 338 | self.bs_bitrate_allocation[0] = self.bs_bitrate_allocation[0]*0.7 339 | self.bs_bitrate_allocation[1] += swap 340 | for elem in rsrp: 341 | if elem not in self.bs_bitrate_allocation: 342 | #this means that it is the first time we encounter that base station 343 | self.bs_bitrate_allocation[elem] = 0 344 | 345 | #compute wardrop sigma 346 | self.wardrop_sigma = (self.env.wardrop_epsilon)/(2*self.env.sampling_time*self.env.wardrop_beta*self.requested_bitrate*(len(rsrp)-1)*len(self.env.ue_list)) 347 | 348 | return 349 | 350 | def next_timestep(self): 351 | self.old_position = self.current_position 352 | self.move() 353 | 354 | #compute the next state variable x^i_p[k+1], considering the visible base stations 355 | rsrp = self.env.discover_bs(self.ue_id) 356 | 357 | #remove the old BSs that are out of visibility 358 | for elem in self.bs_bitrate_allocation: 359 | if elem not in rsrp: 360 | del self.bs_bitrate_allocation[elem] 361 | 362 | #add the new BSs 363 | for elem in rsrp: 364 | if elem not in self.bs_bitrate_allocation: 365 | self.bs_bitrate_allocation[elem] = 0 366 | 367 | #core of the Wardrop algorithm 368 | for p in self.bs_bitrate_allocation: 369 | for q in self.bs_bitrate_allocation: 370 | if p != q: 371 | bs_p = util.find_bs_by_id(p) 372 | l_p = bs_p.compute_latency(self.ue_id) 373 | 374 | 375 | bs_q = util.find_bs_by_id(q) 376 | l_q = bs_q.compute_latency(self.ue_id) 377 | 378 | mu_pq = 1 379 | if (l_p - l_q) < self.env.wardrop_epsilon or bs_q.allocated_bitrate >= bs_q.total_bitrate - (self.env.wardrop_epsilon/(2*self.env.wardrop_beta)): 380 | mu_pq = 0 381 | 382 | mu_qp = 1 383 | if (l_q - l_p) < self.env.wardrop_epsilon or bs_p.allocated_bitrate >= bs_p.total_bitrate - (self.env.wardrop_epsilon/(2*self.env.wardrop_beta)): 384 | mu_qp = 0 385 | 386 | r_pq = self.bs_bitrate_allocation[p]*mu_pq*self.wardrop_sigma 387 | r_qp = self.bs_bitrate_allocation[q]*mu_qp*self.wardrop_sigma 388 | 389 | 390 | self.bs_bitrate_allocation[p] += self.env.sampling_time * (r_qp - r_pq) 391 | return 392 | 393 | 394 | def reset(self, t): 395 | self.disconnect_from_all_bs() 396 | self.actual_data_rate = 0 397 | self.current_position = self.starting_position 398 | #self.service_class = self.old_sevice_class 399 | #self.lambda_exp = ue_class_lambda[self.service_class] 400 | #self.requested_bitrate = ue_class[self.service_class] 401 | self.last_action_t = t 402 | 403 | 404 | 405 | 406 | -------------------------------------------------------------------------------- /environment.py: -------------------------------------------------------------------------------- 1 | import UserEquipment as ue 2 | import LTEBaseStation as LTEbs 3 | import NRBaseStation as NRbs 4 | import Satellite as SATbs 5 | import Drone as DRONEbs 6 | import util 7 | from concurrent.futures import ThreadPoolExecutor 8 | import math 9 | import random 10 | 11 | 12 | class wireless_environment: 13 | bs_list = [] 14 | ue_list = [] 15 | x_limit = None 16 | y_limit = None 17 | env_type = util.EnvType.URBAN 18 | 19 | def __init__(self, n, m = None, sampling_time = 1): 20 | if m is not None: 21 | self.y_limit = m 22 | else: 23 | self.y_limit = n 24 | self.x_limit = n 25 | self.cumulative_reward = 0 26 | self.sampling_time = sampling_time 27 | self.wardrop_epsilon = 0.5 #TODO 28 | self.wardrop_beta = 0 29 | 30 | def insert_ue(self, ue_class, starting_position = None, speed = 0, direction = 0): 31 | if starting_position is not None and (starting_position[2] > 10 or starting_position[2] < 1): 32 | raise Exception("COST-HATA model requires UE height in [1,10]m") 33 | elif ue_class not in ue.ue_class: 34 | raise Exception("Invalid service class for the UE, available service classes are: %s" %(ue.ue_class.keys())) 35 | ue_id = -1 36 | 37 | if None in self.ue_list: 38 | ue_id = self.ue_list.index(None) 39 | else: 40 | ue_id = len(self.ue_list) 41 | 42 | if starting_position is None: 43 | new_ue = ue.user_equipment(ue.ue_class[ue_class], ue_class, ue_id, (random.randint(0, self.x_limit),random.randint(0, self.y_limit),1), self, speed*self.sampling_time, direction) 44 | else: 45 | new_ue = ue.user_equipment(ue.ue_class[ue_class], ue_class, ue_id, starting_position, self, speed*self.sampling_time, direction) 46 | 47 | if (ue_id == len(self.ue_list)): 48 | self.ue_list.append(new_ue) 49 | else: 50 | self.ue_list[ue_id] = new_ue 51 | return new_ue.ue_id 52 | 53 | 54 | def remove_ue(self, ue_id): 55 | self.ue_list[ue_id] = None 56 | 57 | 58 | def place_SAT_base_station(self, total_bitrate, position): 59 | new_bs = SATbs.Satellite(len(self.bs_list), total_bitrate, position, self) 60 | 61 | self.bs_list.append(new_bs) 62 | return new_bs.bs_id 63 | 64 | def place_LTE_base_station(self, position, carrier_frequency, antenna_power, antenna_gain, feeder_loss, available_bandwidth, total_bitrate): 65 | 66 | if (available_bandwidth in LTEbs.LTEbandwidth_prb_lookup): 67 | # LTE standard defines 12 subcarriers of 15KHz each, so the pbr_bandwidth is 180KHz 68 | # LTEbandwidth_prb_lookup defines the number of blocks of 180KHz available in the specified bandwidth, 69 | # so we have to multiply by the number of time slots (sub-frames in LTE terminology) in a time frame 70 | new_bs = LTEbs.LTEBaseStation(len(self.bs_list), LTEbs.LTEbandwidth_prb_lookup[available_bandwidth] * 10, 180, 12, antenna_power, antenna_gain, feeder_loss, carrier_frequency, total_bitrate, position, self) 71 | else: 72 | raise Exception("if you indicate the available bandwidth, it must be 1.4, 3, 5, 10, 15 or 20 MHz") 73 | 74 | self.bs_list.append(new_bs) 75 | return new_bs.bs_id 76 | 77 | def place_NR_base_station(self, position, carrier_frequency, numerology, antenna_power, antenna_gain, feeder_loss, available_bandwidth, total_bitrate, drone = False): 78 | #check if the bandwith is in line with the specified numerology and specified carrier frequency 79 | fr = -1 80 | if (carrier_frequency <= 6000): #below 6GHz 81 | fr = 0 82 | elif (carrier_frequency >= 24250 and carrier_frequency <= 52600): #between 24.25GHz and 52.6GHz 83 | fr = 1 84 | else: 85 | raise Exception("NR frequency outside admissible ranges") 86 | 87 | if available_bandwidth in NRbs.NRbandwidth_prb_lookup[numerology][fr]: 88 | prb_size = 15*(2**numerology)*12 #15KHz*12subcarriers for numerology 0, 30KHz*12subcarriers for numerology 1, etc. 89 | # NRbandwidth_prb_lookup defines the number of blocks of 180KHz available in the specified bandwidth with a certain numerology, 90 | # so we have to multiply by the number of time slots (sub-frames in LTE terminology) in a time frame 91 | if drone == False: 92 | new_bs = NRbs.NRBaseStation(len(self.bs_list), NRbs.NRbandwidth_prb_lookup[numerology][fr][available_bandwidth] * (10 * 2**numerology), prb_size, 12, numerology, antenna_power, antenna_gain, feeder_loss, carrier_frequency, total_bitrate, position, self) 93 | else: 94 | new_bs = DRONEbs.DroneBaseStation(len(self.bs_list), DRONEbs.NRbandwidth_prb_lookup[numerology][fr][available_bandwidth] * (10 * 2**numerology), prb_size, 12, numerology, antenna_power, antenna_gain, feeder_loss, carrier_frequency, total_bitrate, position, self) 95 | else: 96 | raise Exception("The choosen bandwidth is not present in 5G NR standard with such numerology and frequency range") 97 | 98 | self.bs_list.append(new_bs) 99 | return new_bs.bs_id 100 | 101 | def place_DRONE_relay(self, starting_position, linked_bs_id, carrier_frequency, amplification_factor, antenna_gain, feeder_loss): 102 | new_bs = DRONEbs.DroneRelay(len(self.bs_list), linked_bs_id, amplification_factor, antenna_gain, feeder_loss, carrier_frequency, starting_position, self) 103 | self.bs_list.append(new_bs) 104 | return new_bs.bs_id 105 | 106 | def place_DRONE_base_station(self, position, carrier_frequency, numerology, antenna_power, antenna_gain, feeder_loss, available_bandwidth, total_bitrate): 107 | return self.place_NR_base_station(position, carrier_frequency, numerology, antenna_power, antenna_gain, feeder_loss, available_bandwidth, total_bitrate, drone = True) 108 | 109 | #this method shall be called by an UE 110 | #that wants to have a measure of the RSRP 111 | #associated to each BS 112 | def discover_bs(self, ue_id): 113 | thread_pool = [] 114 | #rsrp = [None]*len(self.bs_list) 115 | rsrp = dict() 116 | with ThreadPoolExecutor(max_workers=len(self.bs_list)) as executor: 117 | for i in range(0, len(self.bs_list)): 118 | thread = executor.submit(util.compute_rsrp, self.ue_list[ue_id], self.bs_list[i], self) 119 | thread_pool.append(thread) 120 | for i in range(0, len(self.bs_list)): 121 | res = thread_pool[i].result() 122 | #if res > -1000000: 123 | if (res > util.MIN_RSRP): 124 | rsrp[i] = res 125 | #print(rsrp) 126 | return rsrp 127 | 128 | def initial_timestep(self): 129 | #compute beta value: 130 | #beta, by definition, is max{1/r}, where r is the data rate of a single resource block (or symbol) seen by a certain UE 131 | self.wardrop_beta = 0 132 | for ue in self.ue_list: 133 | rsrp = self.discover_bs(ue.ue_id) 134 | for elem in rsrp: 135 | r = util.find_bs_by_id(elem).compute_r(ue.ue_id, rsrp) 136 | if util.find_bs_by_id(elem).wardrop_alpha/(r/1000000) > self.wardrop_beta: #we convert r in Mbps 137 | self.wardrop_beta = util.find_bs_by_id(elem).wardrop_alpha/(r/1000000) 138 | #now call each initial_timestep function in order to set the initial conditions for each commodity in terms of bitrate 139 | #to be requested to each BS 140 | for ue in self.ue_list: 141 | ue.initial_timestep() 142 | return 143 | 144 | def next_timestep(self): 145 | #with ThreadPoolExecutor(max_workers=len(self.ue_list)) as executor: 146 | if self.wardrop_epsilon > self.wardrop_beta*ue.ue_class[0]*len(self.ue_list): 147 | print("Warning: Epsilon is outside the admissible ranges (", self.wardrop_epsilon, "/", self.wardrop_beta*ue.ue_class[0]*len(self.ue_list), ")") 148 | for ues in self.ue_list: 149 | #thread = executor.submit() 150 | ues.next_timestep() 151 | for bss in self.bs_list: 152 | bss.next_timestep() 153 | 154 | 155 | def request_connection(self, ue_id, requested_bitrate, available_bs): 156 | 157 | bs = max(available_bs, key = available_bs.get) 158 | data_rate = util.find_bs_by_id(bs).request_connection(ue_id, requested_bitrate, available_bs) 159 | reward = self.compute_reward(None, bs, data_rate, requested_bitrate, available_bs, ue_id) 160 | self.cumulative_reward += reward 161 | return bs, data_rate 162 | 163 | def compute_reward(self, state, action, bitrate, desired_data_rate, rsrp, ue_id): 164 | if action in rsrp: 165 | allocated, total = util.find_bs_by_id(action).get_connection_info(ue_id) 166 | alpha = 0 167 | if util.find_ue_by_id(ue_id).service_class == 0: 168 | alpha = 3 169 | else: 170 | alpha = 1 171 | if bitrate > desired_data_rate: 172 | # in case the DQN made a correct allocation I do not want the user occupies too much resources, so if the allocated resources 173 | # for the users are too much I will discount the reward of a proportional value 174 | return alpha * desired_data_rate / (allocated/total) 175 | else: 176 | if allocated > 0: 177 | # in case of a bad allocation, I do not want again that the user occupies too much resources (better if it is allocated to 178 | # one of its neighbor base stations) 179 | return alpha * (desired_data_rate**2) * (bitrate - desired_data_rate) #* (allocated/total) * 100 180 | else: 181 | return alpha * (desired_data_rate**2) * (bitrate - desired_data_rate) 182 | else: 183 | # it should never go here (there are checks on actions in the argmax) 184 | return -10000 185 | 186 | def reset(self, cycle): 187 | for ue in self.ue_list: 188 | ue.reset(cycle) 189 | for bs in self.bs_list: 190 | bs.reset() 191 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | import environment 2 | import util 3 | import Satellite 4 | import numpy as np 5 | import matplotlib.pyplot as plt 6 | import random 7 | import time 8 | import os 9 | import pandas as pd 10 | 11 | PLOT = False 12 | N_UE = 20 13 | ITER = 40000 14 | 15 | SELECTED_UE = 3 16 | 17 | random.seed(2) 18 | 19 | 20 | env = environment.wireless_environment(4000, sampling_time=0.001) 21 | ue = [] 22 | bs = [] 23 | error = [] 24 | latency = {} 25 | prbs = {} 26 | bitrates = {} 27 | 28 | for i in range(0, N_UE): 29 | id = env.insert_ue(0, starting_position=(random.randint(0, env.x_limit-1), random.randint(0, env.y_limit-1), 1), speed = 0, direction = random.randint(0, 359)) 30 | #id = env.insert_ue(0, starting_position=(0, 0, 1), speed = 0, direction = random.randint(0, 359)) 31 | ue.append(id) 32 | 33 | sat_bs = env.place_SAT_base_station(10000, (1000, 2000)) 34 | bs.append(sat_bs) 35 | 36 | #nr_bs2 = env.place_NR_base_station((1500, 1500, 40), 800, 2, 20, 16, 3, 100, total_bitrate = 10000) 37 | 38 | parm = [ 39 | #BS1 40 | {"pos": (2000, 2000, 40), 41 | "freq": 800, 42 | "numerology": 1, 43 | "power": 20, 44 | "gain": 16, 45 | "loss": 3, 46 | "bandwidth": 20, 47 | "max_bitrate": 1000}, 48 | 49 | #BS2 50 | {"pos": (1000, 1000, 40), 51 | "freq": 1700, 52 | "numerology": 1, 53 | "power": 1, 54 | "gain": 5, 55 | "loss": 1, 56 | "bandwidth": 40, 57 | "max_bitrate": 1000}, 58 | 59 | #BS3 60 | {"pos": (2000, 500, 40), 61 | "freq": 1900, 62 | "numerology": 1, 63 | "power": 1, 64 | "gain": 5, 65 | "loss": 1, 66 | "bandwidth": 40, 67 | #15 68 | "max_bitrate": 1000}, 69 | 70 | #BS4 71 | {"pos": (3000, 1000, 40), 72 | "freq": 2000, 73 | "numerology": 1, 74 | "power": 1, 75 | "gain": 5, 76 | "loss": 1, 77 | "bandwidth": 25, 78 | "max_bitrate": 55}, 79 | 80 | #BS5 81 | {"pos": (3000, 3000, 40), 82 | "freq": 1700, 83 | "numerology": 1, 84 | "power": 1, 85 | "gain": 5, 86 | "loss": 1, 87 | "bandwidth": 40, 88 | "max_bitrate": 1000}, 89 | 90 | #BS6 91 | {"pos": (2000, 3500, 40), 92 | "freq": 1900, 93 | "numerology": 1, 94 | "power": 1, 95 | "gain": 5, 96 | "loss": 1, 97 | "bandwidth": 40, 98 | "max_bitrate": 1000}, 99 | 100 | #BS7 101 | {"pos": (1000, 3000, 40), 102 | "freq": 2000, 103 | "numerology": 1, 104 | "power": 1, 105 | "gain": 5, 106 | "loss": 1, 107 | "bandwidth": 25, 108 | "max_bitrate": 1000} 109 | ] 110 | 111 | for i in range(len(parm)): 112 | nr_bs2 = env.place_NR_base_station(parm[i]["pos"], parm[i]["freq"], parm[i]["numerology"], parm[i]["power"], parm[i]["gain"], parm[i]["loss"], parm[i]["bandwidth"], total_bitrate = parm[i]["max_bitrate"]) 113 | bs.append(nr_bs2) 114 | 115 | 116 | 117 | env.initial_timestep(); 118 | print(env.wardrop_beta) 119 | 120 | #util.plot(ue, bs, env) 121 | #plt.pause(10) 122 | 123 | for phone in ue: 124 | util.find_ue_by_id(phone).connect_to_all_bs() 125 | #phone2.connect_to_bs_id(1) 126 | #phone2.connect_to_bs_id(0) 127 | env.next_timestep() 128 | #print(phone.bs_bitrate_allocation) 129 | 130 | for i in range(0,ITER): 131 | if i % 100 == 0: 132 | print("-------------------", i, "-------------------") 133 | 134 | #print(util.find_bs_by_id(2).get_state()) 135 | #print(util.find_bs_by_id(2).allocated_bitrate) 136 | #print(util.find_bs_by_id(2).ue_bitrate_allocation) 137 | ''' 138 | print("BITRATE: ", util.find_ue_by_id(SELECTED_UE).bs_bitrate_allocation) 139 | print("ACTUAL BITRATE: ", util.find_ue_by_id(SELECTED_UE).current_bs) 140 | rsrp = env.discover_bs(SELECTED_UE) 141 | sinr = {} 142 | for bsc in rsrp: 143 | sinr[bsc] = util.find_bs_by_id(bsc).compute_sinr(rsrp) 144 | print("SINR: ", sinr) 145 | if(i!= 0): 146 | print("LATENCY: ", latency[SELECTED_UE][i-1]) 147 | prb_dict = {} 148 | for elem in util.find_ue_by_id(SELECTED_UE).bs_bitrate_allocation: 149 | if util.find_bs_by_id(elem).bs_type != "sat" and SELECTED_UE in util.find_bs_by_id(elem).ue_pb_allocation: 150 | prb_dict[elem] = util.find_bs_by_id(elem).ue_pb_allocation[SELECTED_UE] 151 | elif util.find_bs_by_id(elem).bs_type == "sat" and SELECTED_UE in util.find_bs_by_id(elem).ue_allocation: 152 | prb_dict[elem] = util.find_bs_by_id(elem).ue_allocation[SELECTED_UE]/64 153 | print("PRB: ",prb_dict) 154 | ''' 155 | if i != 0: 156 | for elem in ue: 157 | phonex = util.find_ue_by_id(elem) 158 | for bsx in phonex.current_bs: 159 | if phonex.current_bs[bsx] < phonex.bs_bitrate_allocation[bsx]: 160 | print("Warning: UE", elem, "has saturated BS ", bsx) 161 | #print(util.find_bs_by_id(2).ue_pb_allocation[SELECTED_UE]) 162 | 163 | for bsi in bs: 164 | if util.find_bs_by_id(bsi).bs_type != "sat": 165 | print("BS ", bsi, " PRB: ", util.find_bs_by_id(bsi).allocated_prb, "/", util.find_bs_by_id(bsi).total_prb, " Bitrate: ", util.find_bs_by_id(bsi).allocated_bitrate, "/", util.find_bs_by_id(bsi).total_bitrate) 166 | else: 167 | print("BS ", bsi, " PRB: ", util.find_bs_by_id(bsi).frame_utilization/64, "/", util.find_bs_by_id(bsi).total_symbols/64, " Bitrate: ", util.find_bs_by_id(bsi).allocated_bitrate, "/", util.find_bs_by_id(bsi).total_bitrate) 168 | 169 | max_e = 0 170 | for phone in ue: 171 | #print(phone) 172 | util.find_ue_by_id(phone).update_connection() 173 | #phone2.update_connection() 174 | l_max = 0 175 | l_min = float("inf") 176 | latency_phone={} 177 | for bsa in util.find_ue_by_id(phone).bs_bitrate_allocation: 178 | l = util.find_bs_by_id(bsa).compute_latency(phone) 179 | 180 | latency_phone[bsa]=l 181 | 182 | if util.find_ue_by_id(phone).bs_bitrate_allocation[bsa] > 0.0001 and l > l_max: 183 | l_max = l 184 | elif util.find_ue_by_id(phone).bs_bitrate_allocation[bsa] < util.find_bs_by_id(bsa).total_bitrate-(env.wardrop_epsilon/(2*env.wardrop_beta)) and l < l_min: 185 | l_min = l 186 | e = l_max - l_min 187 | if e > max_e: 188 | max_e = e 189 | if phone not in latency: 190 | latency[phone] = [] 191 | latency[phone].append(latency_phone) 192 | error.append(max_e) 193 | 194 | for bsi in bs: 195 | if bsi not in prbs: 196 | prbs[bsi] = [] 197 | if bsi not in bitrates: 198 | bitrates[bsi] = [] 199 | 200 | if util.find_bs_by_id(bsi).bs_type != "sat": 201 | prbs[bsi].append(util.find_bs_by_id(bsi).allocated_prb) 202 | bitrates[bsi].append(util.find_bs_by_id(bsi).allocated_bitrate) 203 | else: 204 | prbs[bsi].append(util.find_bs_by_id(bsi).frame_utilization/64) 205 | bitrates[bsi].append(util.find_bs_by_id(bsi).allocated_bitrate) 206 | 207 | 208 | env.next_timestep() 209 | #print(phone1.bs_bitrate_allocation) 210 | 211 | print("\n\n---------------------------------------------------\n\n") 212 | for phone in ue: 213 | print("UE %s: %s" %(phone, util.find_ue_by_id(phone).bs_bitrate_allocation)) 214 | print("\n\n---------------------------------------------------\n\n") 215 | #print(latency) 216 | print(util.find_ue_by_id(3).current_position) 217 | 218 | ue_latency = {} 219 | 220 | for phone in latency: 221 | df = pd.DataFrame.from_dict(latency[phone]) 222 | df.to_csv(".\\data\\latency_UE"+str(phone)+".csv", sep=";") 223 | 224 | df = pd.DataFrame(error) 225 | df.to_csv(".\\data\\error.csv", sep=";") 226 | 227 | for bsi in bs: 228 | df = pd.DataFrame.from_dict(prbs[bsi]) 229 | df.to_csv(".\\data\\resourceblocks_BS"+str(bsi)+".csv", sep=";") 230 | df = pd.DataFrame.from_dict(bitrates[bsi]) 231 | df.to_csv(".\\data\\bitrate_BS"+str(bsi)+".csv", sep=";") 232 | 233 | 234 | x = range(ITER) 235 | 236 | plt.xlabel("Simulation time (ms)") 237 | plt.ylabel("Error") 238 | plt.title("Error") 239 | plt.plot(x,error) 240 | plt.show() 241 | 242 | ''' 243 | for phone in ue: 244 | 245 | latency_dict = {} 246 | for elem in latency[phone]: 247 | for bsx in elem: 248 | if bsx not in latency_dict: 249 | latency_dict[bsx] = [] 250 | latency_dict[bsx].append(elem[bsx]) 251 | 252 | #print(l_2) 253 | 254 | x = range(ITER) 255 | 256 | plt.xlabel("Simulation time (ms)") 257 | plt.ylabel("Latency") 258 | plt.title("Latency for UE " + str(phone)) 259 | for i in latency_dict: 260 | plt.plot(x,latency_dict[i],label = 'id %s'%i) 261 | plt.legend() 262 | plt.show() 263 | #print(phone1.current_position) 264 | #print(phone2.bs_bitrate_allocation) 265 | #print(phone2.current_position) 266 | ''' -------------------------------------------------------------------------------- /util.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | import math 3 | import environment 4 | import matplotlib.pyplot as plt 5 | import matplotlib.cm as cm 6 | import numpy as np 7 | 8 | class EnvType (Enum): 9 | RURAL = 0 10 | SUBURBAN = 1 11 | URBAN = 2 12 | 13 | 14 | MIN_RSRP = -120 # -140 #dB 15 | 16 | def compute_rsrp(ue, bs, env): 17 | if bs.bs_type == "sat": 18 | return bs.sat_eirp - bs.path_loss - bs.atm_loss - bs.ut_G_T 19 | elif bs.bs_type == "drone_relay": 20 | return bs.compute_rsrp_drone(ue) 21 | else: 22 | #lte and nr case 23 | path_loss = compute_path_loss_cost_hata(ue, bs, env) 24 | subcarrier_power = 0 25 | if (bs.bs_type == "lte"): 26 | subcarrier_power = 10*math.log10(bs.antenna_power*1000 / ((bs.total_prb/10)*bs.number_subcarriers)) 27 | else: 28 | subcarrier_power = 10*math.log10(bs.antenna_power*1000 / ((bs.total_prb/(10*2**bs.numerology))*bs.number_subcarriers)) 29 | return subcarrier_power + bs.antenna_gain - bs.feeder_loss - path_loss 30 | 31 | def compute_path_loss_cost_hata(ue, bs, env, save = None): 32 | #compute distance first 33 | dist = math.sqrt((ue.current_position[0]-bs.position[0])**2 + (ue.current_position[1]-bs.position[1])**2 + (ue.h_m - bs.h_b)**2) 34 | if dist == 0: #just to avoid log(0) in path loss computing 35 | dist = 0.01 36 | #compute C_0, C_f, b(h_b), a(h_m) and C_m with the magic numbers defined by the model 37 | if bs.carrier_frequency <= 1500 and bs.carrier_frequency >= 150 : 38 | C_0 = 69.55 39 | C_f = 26.16 40 | b = 13.82*math.log10(bs.h_b) 41 | if env.env_type == EnvType.URBAN: 42 | C_m = 0 43 | elif env.env_type == EnvType.SUBURBAN: 44 | C_m = -2*((math.log10(bs.carrier_frequency/28))**2) - 5.4 45 | else: 46 | C_m = -4.78*((math.log10(bs.carrier_frequency))**2) + 18.33*math.log10(bs.carrier_frequency) - 40.94 47 | else: 48 | C_0 = 46.3 49 | C_f = 26.16 50 | b = 13.82*math.log10(bs.h_b) 51 | if env.env_type == EnvType.URBAN: 52 | C_m = 3 53 | elif env.env_type == EnvType.SUBURBAN: 54 | C_m = 0 55 | else: 56 | raise Exception("COST-HATA model is not defined for frequencies in 1500-2000MHz with RURAL environments") 57 | 58 | if env.env_type == EnvType.SUBURBAN or env.env_type == EnvType.RURAL: 59 | a = (1.1*math.log10(bs.carrier_frequency) - 0.7)*ue.h_m - 1.56*math.log10(bs.carrier_frequency) + 0.8 60 | else: 61 | if bs.carrier_frequency >= 150 and bs.carrier_frequency <= 300: 62 | a = 8.29*(math.log10(1.54*ue.h_m)**2) - 1.1 63 | else: 64 | a = 3.2*(math.log10(11.75*ue.h_m)**2) - 4.97 65 | 66 | path_loss = C_0 + C_f * math.log10(bs.carrier_frequency) - b - a + (44.9-6.55*math.log10(bs.h_b))*math.log10(dist/1000) + C_m 67 | if (save is not None): 68 | save = path_loss 69 | return path_loss 70 | 71 | def find_bs_by_id(bs_id): 72 | return environment.wireless_environment.bs_list[bs_id] 73 | 74 | def find_ue_by_id(ue_id): 75 | return environment.wireless_environment.ue_list[ue_id] 76 | 77 | 78 | run = 0 79 | 80 | 81 | def plot(ue, bs, env): 82 | global ax 83 | global fig 84 | global run 85 | if run == 0: 86 | plt.ion() 87 | fig, ax = plt.subplots() 88 | run = 1 89 | 90 | 91 | x_ue = [] 92 | y_ue = [] 93 | x_bs = [] 94 | y_bs = [] 95 | 96 | plt.cla() 97 | 98 | #ax.set_xlim(0, env.x_limit) 99 | #ax.set_ylim(0, env.y_limit) 100 | 101 | colors = cm.rainbow(np.linspace(0, 1, len(bs))) 102 | 103 | for j in bs: 104 | x_bs.append(find_bs_by_id(j).position[0]) 105 | y_bs.append(find_bs_by_id(j).position[1]) 106 | 107 | for i in range(0, len(ue)): 108 | x_ue.append(find_ue_by_id(ue[i]).current_position[0]) 109 | y_ue.append(find_ue_by_id(ue[i]).current_position[1]) 110 | 111 | for i in range(0, len(ue)): 112 | for j in range(0, len(bs)): 113 | if find_ue_by_id(ue[i]).current_bs == j: 114 | ax.scatter(x_ue[i], y_ue[i], color = colors[j]) 115 | break 116 | else: 117 | ax.scatter(x_ue[i], y_ue[i], color = "tab:grey") 118 | 119 | for i in range(0, len(ue)): 120 | ax.annotate(str(ue[i]), (x_ue[i], y_ue[i])) 121 | 122 | for j in range(0, len(bs)): 123 | if find_bs_by_id(j).bs_type == "drone_relay": 124 | ax.scatter(x_bs[j], y_bs[j], color = colors[j], label = "BS", marker = "^", s = 400, edgecolor = colors[find_bs_by_id(j).linked_bs], linewidth = 3) 125 | elif find_bs_by_id(j).bs_type == "drone_bs": 126 | ax.scatter(x_bs[j], y_bs[j], color = colors[j], label = "BS", marker = "^", s = 400) 127 | else: 128 | ax.scatter(x_bs[j], y_bs[j], color = colors[j], label = "BS", marker = "s", s = 400) 129 | 130 | for j in range(0, len(bs)): 131 | ax.annotate("BS"+str(j), (x_bs[j], y_bs[j])) 132 | 133 | ax.grid(True) 134 | ax.set_ylabel("[m]") 135 | ax.set_xlabel("[m]") 136 | fig.canvas.draw() 137 | --------------------------------------------------------------------------------