Andres Johan Florez Gonzalez commited on
Commit
441a971
·
verified ·
1 Parent(s): 9a08625

Upload functional_wlan_design_gradio.py

Browse files
Files changed (1) hide show
  1. functional_wlan_design_gradio.py +372 -0
functional_wlan_design_gradio.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Funcional WLAN_design_gradio.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1MIfY3UkK4eSXOiPx3gtMSPoZMtnyJxux
8
+ """
9
+
10
+ from google.colab import drive
11
+ drive.mount('/content/drive')
12
+
13
+ # Commented out IPython magic to ensure Python compatibility.
14
+ # %%capture
15
+ # !pip install gradio
16
+
17
+ import gradio as gr
18
+ from PIL import Image
19
+ import os
20
+ from tensorflow.keras.models import load_model
21
+ import numpy as np
22
+ import matplotlib.pyplot as plt
23
+ from matplotlib.colors import Normalize
24
+ from io import BytesIO
25
+
26
+ # Images path
27
+ path_main = '/content/drive/Othercomputers/False-2-Tesis-Maestria /Phase-3-thesis/'
28
+ images_file = path_main + 'Scennarios init/Scennarios W'
29
+
30
+ # Load DL models
31
+ modelo_1ap = load_model(path_main + 'Models/SINR-2APs/modelo_1ap_app.keras')
32
+ modelo_2ap = load_model(path_main + 'Models/SINR-2APs/modelo_2ap_app.keras')
33
+
34
+ plt.rc('font', family='Times New Roman')
35
+ fontsize_t = 15
36
+
37
+ def coordinates_process(texto):
38
+ coordinates = texto.split("), ")
39
+
40
+ resultado = []
41
+ for coord in coordinates:
42
+ try:
43
+ coord = coord.replace("(", "").replace(")", "")
44
+ x, y = map(int, coord.split(","))
45
+ # Validate range
46
+ if 0 <= x <= 255 and 0 <= y <= 255:
47
+ resultado.append((x, y))
48
+ else:
49
+ return False
50
+ except ValueError:
51
+ return False
52
+
53
+ while len(resultado) < 3:
54
+ resultado.append((0, 0))
55
+
56
+ return resultado
57
+
58
+ # plan images path
59
+ def plan_images_list():
60
+ return [file_ for file_ in os.listdir(images_file) if file_.endswith((".JPG", ".jpg", ".jpeg", ".png"))]
61
+
62
+ # Valdate inputs
63
+ def validate_input(value):
64
+ if value == "" or value is None:
65
+ return 0
66
+ elif value >= 0 or value <= 2:
67
+ return value
68
+
69
+ # MAIN FUNCTION ****************************************************************
70
+ def main_function(plan_name, apch1, apch6, apch11, coord1, coord6, coord11):
71
+ image_plan_path = os.path.join(images_file, plan_name)
72
+ imagen1 = Image.open(image_plan_path)
73
+
74
+ # No negative number as input
75
+ if not (0 <= apch1 <= 2):
76
+ return False
77
+ if not (0 <= apch6 <= 2):
78
+ return False
79
+ if not (0 <= apch11 <= 2):
80
+ return False
81
+
82
+ # Some variables init
83
+ deep_count = 0
84
+ deep_coverage = []
85
+ channels = [1, 6, 11]
86
+ num_APs = np.zeros(len(channels), dtype=int)
87
+ num_APs[0] = apch1
88
+ num_APs[1] = apch6
89
+ num_APs[2] = apch11
90
+ dimension = 256
91
+ aps_chs = np.zeros((dimension, dimension, len(channels)))
92
+
93
+ # Load plan
94
+ numero = plan_name[:1]
95
+ plan_in = np.array(Image.open(f"{path_main}Scennarios init/Scennarios B/{numero}.png")) / 255
96
+
97
+ coords = [coord1, coord6, coord11]
98
+ for att, channel in enumerate(channels):
99
+ if num_APs[att] > 0:
100
+ coordinates = coordinates_process(coords[att])
101
+ for x, y in coordinates:
102
+ if x != 0 and y != 0:
103
+ aps_chs[int(y), int(x), att] = 1
104
+
105
+ # Coverage process
106
+ deep_coverage = []
107
+ ap_images = []
108
+ layer_indices = []
109
+ imagencober = {}
110
+ for k in range(len(channels)):
111
+ capa = aps_chs[:, :, k]
112
+ filas, columnas = np.where(capa == 1)
113
+
114
+ if len(filas) == 2:
115
+ # For 2 AP
116
+ deep_count += 1
117
+ layer_1 = np.zeros_like(capa)
118
+ layer_2 = np.zeros_like(capa)
119
+ layer_1[filas[0], columnas[0]] = 1
120
+ layer_2[filas[1], columnas[1]] = 1
121
+
122
+ datos_entrada = np.stack([plan_in, layer_1, layer_2], axis=-1)
123
+ prediction = modelo_2ap.predict(datos_entrada[np.newaxis, ...])[0]
124
+
125
+ elif len(filas) == 1:
126
+ # For 1 AP
127
+ deep_count += 1
128
+ layer_1 = np.zeros_like(capa)
129
+ layer_1[filas[0], columnas[0]] = 1
130
+
131
+ datos_entrada = np.stack([plan_in, layer_1], axis=-1)
132
+ prediction = modelo_1ap.predict(datos_entrada[np.newaxis, ...])[0]
133
+
134
+ else:
135
+ # Whitout AP
136
+ prediction = np.zeros((dimension,dimension,1))
137
+
138
+ # print(prediction.shape)
139
+ deep_coverage.append(prediction)
140
+ prediction_rgb = np.squeeze((Normalize()(prediction)))
141
+ ap_images.append(prediction_rgb) # Guardar la imagen de cobertura del AP
142
+
143
+ if np.all(prediction == 0):
144
+ plt.imshow(prediction_rgb)
145
+ plt.title('No coverage', fontsize=fontsize_t + 2, family='Times New Roman')
146
+ plt.axis("off")
147
+ else:
148
+ plt.imshow(prediction_rgb, cmap='jet')
149
+ cbar = plt.colorbar(ticks=np.linspace(0, 1, num=6),)
150
+ cbar.set_label('SINR [dB]', fontsize=fontsize_t, fontname='Times New Roman')
151
+ cbar.set_ticklabels(['-3.01', '20.29', '43.60', '66.90', '90.20', '113.51'])
152
+ cbar.ax.tick_params(labelsize=fontsize_t, labelfontfamily = 'Times New Roman')
153
+ plt.axis("off")
154
+
155
+ # Save the plot to a buffer
156
+ buf = BytesIO()
157
+ plt.savefig(buf, format='png')
158
+ buf.seek(0)
159
+ plt.close()
160
+
161
+ # Convert buffer to an image
162
+ imagencober[k] = Image.open(buf)
163
+
164
+ # Cell map estimation
165
+ layer_indices.append(np.argmax(prediction, axis=0))
166
+
167
+ # Final coverage
168
+ if deep_coverage:
169
+ deep_coverage = np.array(deep_coverage)
170
+ nor_matrix = np.max(deep_coverage, axis=0)
171
+ celdas = np.argmax(deep_coverage, axis=0)
172
+
173
+ resultado_rgb = np.squeeze((Normalize()(nor_matrix)))
174
+
175
+ plt.imshow(resultado_rgb, cmap='jet')
176
+ cbar = plt.colorbar(ticks=np.linspace(0, 1, num=6))
177
+ cbar.set_label('SINR [dB]', fontsize=fontsize_t, fontname='Times New Roman')
178
+ cbar.set_ticklabels(['-3.01', '20.29', '43.60', '66.90', '90.20', '113.51'])
179
+ cbar.ax.tick_params(labelsize=fontsize_t, labelfontfamily = 'Times New Roman')
180
+ plt.axis("off")
181
+
182
+ # Save the plot to a buffer
183
+ buf = BytesIO()
184
+ plt.savefig(buf, format='png')
185
+ buf.seek(0)
186
+ plt.close()
187
+
188
+ # Convert buffer to an image
189
+ imagen3 = Image.open(buf)
190
+
191
+ if num_APs[0] > 0 and num_APs[1] > 0 and num_APs[2] > 0:
192
+ cmap = plt.cm.colors.ListedColormap(['blue', 'red', 'green'])
193
+ plt.imshow(celdas, cmap=cmap)
194
+ cbar = plt.colorbar()
195
+ cbar.set_ticks([0, 1, 2])
196
+ cbar.set_ticklabels(['1', '6', '11'])
197
+ cbar.set_label('Cell ID', fontsize=fontsize_t, fontname='Times New Roman')
198
+ cbar.ax.tick_params(labelsize=fontsize_t, labelfontfamily = 'Times New Roman')
199
+ plt.axis("off")
200
+
201
+ # Save the plot to a buffer
202
+ buf = BytesIO()
203
+ plt.savefig(buf, format='png')
204
+ buf.seek(0)
205
+ plt.close()
206
+
207
+ # Convert buffer to an image
208
+ imagen4 = Image.open(buf)
209
+
210
+ elif num_APs[0] > 0 and num_APs[1] > 0:
211
+ cmap = plt.cm.colors.ListedColormap(['blue', 'red'])
212
+ plt.imshow(celdas, cmap=cmap)
213
+ cbar = plt.colorbar()
214
+ cbar.set_ticks([0, 1])
215
+ cbar.set_ticklabels(['1', '6'])
216
+ cbar.set_label('Cell ID', fontsize=fontsize_t, fontname='Times New Roman')
217
+ cbar.ax.tick_params(labelsize=fontsize_t, labelfontfamily = 'Times New Roman')
218
+ plt.axis("off")
219
+
220
+ # Save the plot to a buffer
221
+ buf = BytesIO()
222
+ plt.savefig(buf, format='png')
223
+ buf.seek(0)
224
+ plt.close()
225
+
226
+ # Convert buffer to an image
227
+ imagen4 = Image.open(buf)
228
+
229
+ elif num_APs[0] > 0 and num_APs[2] > 0:
230
+ cmap = plt.cm.colors.ListedColormap(['blue', 'red'])
231
+ plt.imshow(celdas, cmap=cmap)
232
+ cbar = plt.colorbar()
233
+ cbar.set_ticks([0, 1])
234
+ cbar.set_ticklabels(['1', '11'])
235
+ cbar.set_label('Cell ID', fontsize=fontsize_t, fontname='Times New Roman')
236
+ cbar.ax.tick_params(labelsize=fontsize_t, labelfontfamily = 'Times New Roman')
237
+ plt.axis("off")
238
+
239
+ # Save the plot to a buffer
240
+ buf = BytesIO()
241
+ plt.savefig(buf, format='png')
242
+ buf.seek(0)
243
+ plt.close()
244
+
245
+ # Convert buffer to an image
246
+ imagen4 = Image.open(buf)
247
+
248
+ elif num_APs[1] > 0 and num_APs[2] > 0:
249
+ cmap = plt.cm.colors.ListedColormap(['blue', 'red'])
250
+ plt.imshow(celdas, cmap=cmap)
251
+ cbar = plt.colorbar()
252
+ cbar.set_ticks([0, 1])
253
+ cbar.set_ticklabels(['6', '11'])
254
+ cbar.set_label('Cell ID', fontsize=fontsize_t, fontname='Times New Roman')
255
+ cbar.ax.tick_params(labelsize=fontsize_t, labelfontfamily = 'Times New Roman')
256
+ plt.axis("off")
257
+
258
+ # Save the plot to a buffer
259
+ buf = BytesIO()
260
+ plt.savefig(buf, format='png')
261
+ buf.seek(0)
262
+ plt.close()
263
+
264
+ # Convert buffer to an image
265
+ imagen4 = Image.open(buf)
266
+
267
+ else:
268
+ cmap = plt.cm.colors.ListedColormap(['blue'])
269
+ plt.imshow(celdas, cmap=cmap)
270
+ cbar = plt.colorbar()
271
+ cbar.set_ticks([0])
272
+ cbar.set_ticklabels(['1'])
273
+ cbar.set_label('Cell ID', fontsize=fontsize_t, fontname='Times New Roman')
274
+ cbar.ax.tick_params(labelsize=fontsize_t, labelfontfamily = 'Times New Roman')
275
+ plt.axis("off")
276
+
277
+ # Save the plot to a buffer
278
+ buf = BytesIO()
279
+ plt.savefig(buf, format='png')
280
+ buf.seek(0)
281
+ plt.close()
282
+
283
+ # Convert buffer to an image
284
+ imagen4 = Image.open(buf)
285
+
286
+ return [imagencober[0], imagencober[1], imagencober[2], imagen3, imagen4]
287
+
288
+ # plan visualization
289
+ def load_plan_vi(mapa_seleccionado):
290
+
291
+ image_plan_path1 = os.path.join(images_file, mapa_seleccionado)
292
+ plan_image = Image.open(image_plan_path1)
293
+
294
+ plan_n = np.array(plan_image.convert('RGB'))
295
+ plt.figure(figsize=(3, 3))
296
+ plt.imshow(plan_n)
297
+ plt.xticks(np.arange(0, 256, 50))
298
+ plt.yticks(np.arange(0, 256, 50))
299
+
300
+ # Save the plot to a buffer
301
+ buf = BytesIO()
302
+ plt.savefig(buf, format='png')
303
+ buf.seek(0)
304
+ plt.close()
305
+
306
+ # Convert buffer to an image
307
+ plan_im = Image.open(buf)
308
+
309
+ return plan_im
310
+
311
+ with gr.Blocks() as demo:
312
+
313
+ gr.Markdown("""
314
+ ## Fast Radio Propagation Prediction in WLANs Using Deep Learning
315
+ This app use deep learning models to radio map estimation (RME). RME entails estimating the received RF power based on spatial information maps.
316
+
317
+ Instructions for use:
318
+
319
+ - A predefined list of indoor floor plans is available for use.
320
+ - A maximum of (255,255) pixels is allowed for image size.
321
+ - Negative numbers are not allowed.
322
+ - The established format for the coordinates of each access point (AP) must be maintained.
323
+ - A maximum of 2 APs are allowed per channel.
324
+ """)
325
+
326
+ with gr.Row():
327
+ # Input left panel
328
+ with gr.Column(scale=1): # Scale to resize
329
+ map_dropdown = gr.Dropdown(choices=plan_images_list(), label="Select indoor plan")
330
+ ch1_input = gr.Number(label="APs CH 1")
331
+ ch6_input = gr.Number(label="APs CH 6")
332
+ ch11_input = gr.Number(label="APs CH 11")
333
+ coords_ch1_input = gr.Textbox(label="Coordinate CH 1", placeholder="Format: (x1, y1), (x2, y2)")
334
+ coords_ch6_input = gr.Textbox(label="Coordinate CH 6", placeholder="Format: (x1, y1), (x2, y2)")
335
+ coords_ch11_input = gr.Textbox(label="Coordinate CH 11", placeholder="Format: (x1, y1), (x2, y2)")
336
+ button1 = gr.Button("Load plan")
337
+ button2 = gr.Button("Predict coverage")
338
+
339
+ # Rigth panel
340
+ a_images = 320 # Size putput images
341
+
342
+ with gr.Column(scale=3):
343
+ first_image_output = gr.Image(label="plan image", height=a_images, width=a_images)
344
+ # with gr.Row():
345
+ with gr.Row():
346
+ image_ch1 = gr.Image(label="CH 1 coverage", height=a_images, width=a_images)
347
+ image_ch6 = gr.Image(label="CH 6 coverage", height=a_images, width=a_images)
348
+ image_ch11 = gr.Image(label="CH 11 coverage", height=a_images, width=a_images)
349
+
350
+ with gr.Row():
351
+ image_cover_final = gr.Image(label="Final coverage", height=a_images, width=a_images)
352
+ image_cells = gr.Image(label="Cells coverage", height=a_images, width=a_images)
353
+
354
+
355
+ # Buttons
356
+ button1.click(load_plan_vi, inputs=[map_dropdown], outputs=first_image_output)
357
+ button2.click(
358
+ lambda map_dropdown, ch1, ch6, ch11, coords1, coords6, coords11: main_function(
359
+ map_dropdown,
360
+ validate_input(ch1),
361
+ validate_input(ch6),
362
+ validate_input(ch11),
363
+ coords1,
364
+ coords6,
365
+ coords11,
366
+ ),
367
+ inputs=[map_dropdown, ch1_input, ch6_input, ch11_input, coords_ch1_input, coords_ch6_input, coords_ch11_input],
368
+ outputs=[image_ch1, image_ch6, image_ch11, image_cover_final, image_cells]
369
+ )
370
+
371
+
372
+ demo.launch()