File size: 12,925 Bytes
441a971
 
 
 
 
 
 
 
 
b5a4102
 
441a971
 
 
 
 
 
 
 
14b7025
 
441a971
 
 
 
 
 
d896324
441a971
 
 
d896324
 
441a971
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# -*- coding: utf-8 -*-
"""Funcional WLAN_design_gradio.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1MIfY3UkK4eSXOiPx3gtMSPoZMtnyJxux
"""

# from google.colab import drive
# drive.mount('/content/drive')

# Commented out IPython magic to ensure Python compatibility.
# %%capture
# !pip install gradio

import gradio as gr
from PIL import Image
import os
from tensorflow import keras
from keras.models import load_model
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
from io import BytesIO

# Images path
path_main = 'Data/'
images_file = path_main + 'Scennarios init/Scennarios W'

# Load DL models
modelo_1ap = load_model(path_main + 'Models/modelo_1ap_app.keras')
modelo_2ap = load_model(path_main + 'Models/modelo_2ap_app.keras')

plt.rc('font', family='Times New Roman')
fontsize_t = 15

def coordinates_process(texto):
    coordinates = texto.split("), ")

    resultado = []
    for coord in coordinates:
        try:
            coord = coord.replace("(", "").replace(")", "")
            x, y = map(int, coord.split(","))
            # Validate range
            if 0 <= x <= 255 and 0 <= y <= 255:
                resultado.append((x, y))
            else:
                return False
        except ValueError:
            return False

    while len(resultado) < 3:
        resultado.append((0, 0))

    return resultado

# plan images path
def plan_images_list():
    return [file_ for file_ in os.listdir(images_file) if file_.endswith((".JPG", ".jpg", ".jpeg", ".png"))]

# Valdate inputs
def validate_input(value):
    if value == "" or value is None:
        return 0
    elif value >= 0 or value <= 2:
        return value

# MAIN FUNCTION ****************************************************************
def main_function(plan_name, apch1, apch6, apch11, coord1, coord6, coord11):
    image_plan_path = os.path.join(images_file, plan_name)
    imagen1 = Image.open(image_plan_path)

    # No negative number as input
    if not (0 <= apch1 <= 2):
        return False
    if not (0 <= apch6 <= 2):
        return False
    if not (0 <= apch11 <= 2):
        return False

    # Some variables init
    deep_count = 0
    deep_coverage = []
    channels = [1, 6, 11]
    num_APs = np.zeros(len(channels), dtype=int)
    num_APs[0] = apch1
    num_APs[1] = apch6
    num_APs[2] = apch11
    dimension = 256
    aps_chs = np.zeros((dimension, dimension, len(channels)))

    # Load plan
    numero = plan_name[:1]
    plan_in = np.array(Image.open(f"{path_main}Scennarios init/Scennarios B/{numero}.png")) / 255

    coords = [coord1, coord6, coord11]
    for att, channel in enumerate(channels):
      if num_APs[att] > 0:
          coordinates = coordinates_process(coords[att])
          for x, y in coordinates:
            if x != 0 and y != 0:
              aps_chs[int(y), int(x), att] = 1

    # Coverage process
    deep_coverage = []
    ap_images = []
    layer_indices = []
    imagencober = {}
    for k in range(len(channels)):
        capa = aps_chs[:, :, k]
        filas, columnas = np.where(capa == 1)

        if len(filas) == 2:
            # For 2 AP
            deep_count += 1
            layer_1 = np.zeros_like(capa)
            layer_2 = np.zeros_like(capa)
            layer_1[filas[0], columnas[0]] = 1
            layer_2[filas[1], columnas[1]] = 1

            datos_entrada = np.stack([plan_in, layer_1, layer_2], axis=-1)
            prediction = modelo_2ap.predict(datos_entrada[np.newaxis, ...])[0]

        elif len(filas) == 1:
            # For 1 AP
            deep_count += 1
            layer_1 = np.zeros_like(capa)
            layer_1[filas[0], columnas[0]] = 1

            datos_entrada = np.stack([plan_in, layer_1], axis=-1)
            prediction = modelo_1ap.predict(datos_entrada[np.newaxis, ...])[0]

        else:
            # Whitout AP
            prediction = np.zeros((dimension,dimension,1))

        # print(prediction.shape)
        deep_coverage.append(prediction)
        prediction_rgb = np.squeeze((Normalize()(prediction)))
        ap_images.append(prediction_rgb)  # Guardar la imagen de cobertura del AP

        if np.all(prediction == 0):
            plt.imshow(prediction_rgb)
            plt.title('No coverage', fontsize=fontsize_t + 2, family='Times New Roman')
            plt.axis("off")
        else:
            plt.imshow(prediction_rgb, cmap='jet')
            cbar = plt.colorbar(ticks=np.linspace(0, 1, num=6),)
            cbar.set_label('SINR [dB]', fontsize=fontsize_t, fontname='Times New Roman')
            cbar.set_ticklabels(['-3.01', '20.29', '43.60', '66.90', '90.20', '113.51'])
            cbar.ax.tick_params(labelsize=fontsize_t, labelfontfamily = 'Times New Roman')
            plt.axis("off")

        # Save the plot to a buffer
        buf = BytesIO()
        plt.savefig(buf, format='png')
        buf.seek(0)
        plt.close()

        # Convert buffer to an image
        imagencober[k] = Image.open(buf)

        # Cell map estimation
        layer_indices.append(np.argmax(prediction, axis=0))

    # Final coverage
    if deep_coverage:
        deep_coverage = np.array(deep_coverage)
        nor_matrix = np.max(deep_coverage, axis=0)
        celdas = np.argmax(deep_coverage, axis=0)

        resultado_rgb = np.squeeze((Normalize()(nor_matrix)))

        plt.imshow(resultado_rgb, cmap='jet')
        cbar = plt.colorbar(ticks=np.linspace(0, 1, num=6))
        cbar.set_label('SINR [dB]', fontsize=fontsize_t, fontname='Times New Roman')
        cbar.set_ticklabels(['-3.01', '20.29', '43.60', '66.90', '90.20', '113.51'])
        cbar.ax.tick_params(labelsize=fontsize_t, labelfontfamily = 'Times New Roman')
        plt.axis("off")

        # Save the plot to a buffer
        buf = BytesIO()
        plt.savefig(buf, format='png')
        buf.seek(0)
        plt.close()

        # Convert buffer to an image
        imagen3 = Image.open(buf)

        if num_APs[0] > 0 and num_APs[1] > 0 and num_APs[2] > 0:
            cmap = plt.cm.colors.ListedColormap(['blue', 'red', 'green'])
            plt.imshow(celdas, cmap=cmap)
            cbar = plt.colorbar()
            cbar.set_ticks([0, 1, 2])
            cbar.set_ticklabels(['1', '6', '11'])
            cbar.set_label('Cell ID', fontsize=fontsize_t, fontname='Times New Roman')
            cbar.ax.tick_params(labelsize=fontsize_t, labelfontfamily = 'Times New Roman')
            plt.axis("off")

            # Save the plot to a buffer
            buf = BytesIO()
            plt.savefig(buf, format='png')
            buf.seek(0)
            plt.close()

            # Convert buffer to an image
            imagen4 = Image.open(buf)

        elif num_APs[0] > 0 and num_APs[1] > 0:
            cmap = plt.cm.colors.ListedColormap(['blue', 'red'])
            plt.imshow(celdas, cmap=cmap)
            cbar = plt.colorbar()
            cbar.set_ticks([0, 1])
            cbar.set_ticklabels(['1', '6'])
            cbar.set_label('Cell ID', fontsize=fontsize_t, fontname='Times New Roman')
            cbar.ax.tick_params(labelsize=fontsize_t, labelfontfamily = 'Times New Roman')
            plt.axis("off")

            # Save the plot to a buffer
            buf = BytesIO()
            plt.savefig(buf, format='png')
            buf.seek(0)
            plt.close()

            # Convert buffer to an image
            imagen4 = Image.open(buf)

        elif num_APs[0] > 0 and num_APs[2] > 0:
            cmap = plt.cm.colors.ListedColormap(['blue', 'red'])
            plt.imshow(celdas, cmap=cmap)
            cbar = plt.colorbar()
            cbar.set_ticks([0, 1])
            cbar.set_ticklabels(['1', '11'])
            cbar.set_label('Cell ID', fontsize=fontsize_t, fontname='Times New Roman')
            cbar.ax.tick_params(labelsize=fontsize_t, labelfontfamily = 'Times New Roman')
            plt.axis("off")

            # Save the plot to a buffer
            buf = BytesIO()
            plt.savefig(buf, format='png')
            buf.seek(0)
            plt.close()

            # Convert buffer to an image
            imagen4 = Image.open(buf)

        elif num_APs[1] > 0 and num_APs[2] > 0:
            cmap = plt.cm.colors.ListedColormap(['blue', 'red'])
            plt.imshow(celdas, cmap=cmap)
            cbar = plt.colorbar()
            cbar.set_ticks([0, 1])
            cbar.set_ticklabels(['6', '11'])
            cbar.set_label('Cell ID', fontsize=fontsize_t, fontname='Times New Roman')
            cbar.ax.tick_params(labelsize=fontsize_t, labelfontfamily = 'Times New Roman')
            plt.axis("off")

            # Save the plot to a buffer
            buf = BytesIO()
            plt.savefig(buf, format='png')
            buf.seek(0)
            plt.close()

            # Convert buffer to an image
            imagen4 = Image.open(buf)

        else:
            cmap = plt.cm.colors.ListedColormap(['blue'])
            plt.imshow(celdas, cmap=cmap)
            cbar = plt.colorbar()
            cbar.set_ticks([0])
            cbar.set_ticklabels(['1'])
            cbar.set_label('Cell ID', fontsize=fontsize_t, fontname='Times New Roman')
            cbar.ax.tick_params(labelsize=fontsize_t, labelfontfamily = 'Times New Roman')
            plt.axis("off")

            # Save the plot to a buffer
            buf = BytesIO()
            plt.savefig(buf, format='png')
            buf.seek(0)
            plt.close()

            # Convert buffer to an image
            imagen4 = Image.open(buf)

    return [imagencober[0], imagencober[1], imagencober[2], imagen3, imagen4]

# plan visualization
def load_plan_vi(mapa_seleccionado):

    image_plan_path1 = os.path.join(images_file, mapa_seleccionado)
    plan_image = Image.open(image_plan_path1)

    plan_n = np.array(plan_image.convert('RGB'))
    plt.figure(figsize=(3, 3))
    plt.imshow(plan_n)
    plt.xticks(np.arange(0, 256, 50))
    plt.yticks(np.arange(0, 256, 50))

    # Save the plot to a buffer
    buf = BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    plt.close()

    # Convert buffer to an image
    plan_im = Image.open(buf)

    return plan_im

with gr.Blocks() as demo:

    gr.Markdown("""
    ## Fast Radio Propagation Prediction in WLANs Using Deep Learning
    This app use deep learning models to radio map estimation (RME). RME entails estimating the received RF power based on spatial information maps.

    Instructions for use:

    - A predefined list of indoor floor plans is available for use.
    - A maximum of (255,255) pixels is allowed for image size.
    - Negative numbers are not allowed.
    - The established format for the coordinates of each access point (AP) must be maintained.
    - A maximum of 2 APs are allowed per channel.
    """)

    with gr.Row():
        # Input left panel
        with gr.Column(scale=1):  # Scale to resize
            map_dropdown = gr.Dropdown(choices=plan_images_list(), label="Select indoor plan")
            ch1_input = gr.Number(label="APs CH 1")
            ch6_input = gr.Number(label="APs CH 6")
            ch11_input = gr.Number(label="APs CH 11")
            coords_ch1_input = gr.Textbox(label="Coordinate CH 1", placeholder="Format: (x1, y1), (x2, y2)")
            coords_ch6_input = gr.Textbox(label="Coordinate CH 6", placeholder="Format: (x1, y1), (x2, y2)")
            coords_ch11_input = gr.Textbox(label="Coordinate CH 11", placeholder="Format: (x1, y1), (x2, y2)")
            button1 = gr.Button("Load plan")
            button2 = gr.Button("Predict coverage")

        # Rigth panel
        a_images = 320 # Size putput images

        with gr.Column(scale=3):
            first_image_output = gr.Image(label="plan image", height=a_images, width=a_images)
            # with gr.Row():
            with gr.Row():
                image_ch1 = gr.Image(label="CH 1 coverage", height=a_images, width=a_images)
                image_ch6 = gr.Image(label="CH 6 coverage", height=a_images, width=a_images)
                image_ch11 = gr.Image(label="CH 11 coverage", height=a_images, width=a_images)

            with gr.Row():
                image_cover_final = gr.Image(label="Final coverage", height=a_images, width=a_images)
                image_cells = gr.Image(label="Cells coverage", height=a_images, width=a_images)


    # Buttons
    button1.click(load_plan_vi, inputs=[map_dropdown], outputs=first_image_output)
    button2.click(
    lambda map_dropdown, ch1, ch6, ch11, coords1, coords6, coords11: main_function(
        map_dropdown,
        validate_input(ch1),
        validate_input(ch6),
        validate_input(ch11),
        coords1,
        coords6,
        coords11,
    ),
    inputs=[map_dropdown, ch1_input, ch6_input, ch11_input, coords_ch1_input, coords_ch6_input, coords_ch11_input],
    outputs=[image_ch1, image_ch6, image_ch11, image_cover_final, image_cells]
)


demo.launch()