wi-lab commited on
Commit
6ab9038
Β·
verified Β·
1 Parent(s): 9c44c57

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +732 -732
app.py CHANGED
@@ -1,733 +1,733 @@
1
- import gradio as gr
2
- import os
3
- from PIL import Image
4
- import numpy as np
5
- import pickle
6
- import io
7
- import sys
8
- import torch
9
- import subprocess
10
- import h5py
11
- from sklearn.metrics import confusion_matrix
12
- import matplotlib.pyplot as plt
13
- import pandas as pd
14
- from sklearn.metrics import f1_score
15
- import seaborn as sns
16
-
17
- #################### BEAM PREDICTION #########################}
18
- def beam_prediction_task(data_percentage, task_complexity, theme='Dark'):
19
- # Folder naming convention based on input_type, data_percentage, and task_complexity
20
- raw_folder = f"images/raw_{data_percentage/100:.1f}_{task_complexity}"
21
- embeddings_folder = f"images/embedding_{data_percentage/100:.1f}_{task_complexity}"
22
-
23
- # Process raw confusion matrix
24
- raw_cm = compute_average_confusion_matrix(raw_folder)
25
- if raw_cm is not None:
26
- raw_cm_path = os.path.join(raw_folder, "confusion_matrix_raw.png")
27
- plot_confusion_matrix_beamPred(raw_cm,
28
- classes=np.arange(raw_cm.shape[0]),
29
- title=f"Confusion Matrix (Raw Channels)\n{data_percentage}% data, {task_complexity} beams",
30
- save_path=raw_cm_path,
31
- theme=theme)
32
- raw_img = Image.open(raw_cm_path)
33
- else:
34
- raw_img = None
35
-
36
- # Process embeddings confusion matrix
37
- embeddings_cm = compute_average_confusion_matrix(embeddings_folder)
38
- if embeddings_cm is not None:
39
- embeddings_cm_path = os.path.join(embeddings_folder, "confusion_matrix_embeddings.png")
40
- plot_confusion_matrix_beamPred(embeddings_cm,
41
- classes=np.arange(embeddings_cm.shape[0]),
42
- title=f"Confusion Matrix (LWM Embeddings)\n{data_percentage}% data, {task_complexity} beams",
43
- save_path=embeddings_cm_path,
44
- theme=theme)
45
- embeddings_img = Image.open(embeddings_cm_path)
46
- else:
47
- embeddings_img = None
48
-
49
- return raw_img, embeddings_img
50
-
51
- # Function to compute the F1-score based on the confusion matrix
52
- def compute_f1_score(cm):
53
- # Compute precision and recall
54
- TP = np.diag(cm)
55
- FP = np.sum(cm, axis=0) - TP
56
- FN = np.sum(cm, axis=1) - TP
57
-
58
- precision = TP / (TP + FP)
59
- recall = TP / (TP + FN)
60
-
61
- # Handle division by zero in precision or recall
62
- precision = np.nan_to_num(precision)
63
- recall = np.nan_to_num(recall)
64
-
65
- # Compute F1 score
66
- f1 = 2 * (precision * recall) / (precision + recall)
67
- f1 = np.nan_to_num(f1) # Replace NaN with 0
68
- return np.mean(f1) # Return the mean F1-score across all classes
69
-
70
- def plot_confusion_matrix_beamPred(cm, classes, title, save_path, theme='Dark'):
71
- # Compute the average F1-score
72
- avg_f1 = compute_f1_score(cm)
73
-
74
- # Choose the color scheme based on the user's mode
75
- if theme == 'Dark':
76
- plt.style.use('dark_background') # Use dark mode styling
77
- #text_color = 'white'
78
- text_color = 'gray'
79
- #cmap = 'cividis' # Dark-mode-friendly colormap
80
- cmap = 'coolwarm'
81
- else:
82
- plt.style.use('default') # Use default (light) mode styling
83
- #text_color = 'black'
84
- text_color = 'gray'
85
- cmap = 'Blues' # Light-mode-friendly colormap
86
-
87
- plt.figure(figsize=(10, 10))
88
-
89
- # Plot the confusion matrix with a colormap compatible for the mode
90
- ax = sns.heatmap(cm, cmap=cmap, cbar=True)
91
-
92
- cbar = ax.collections[0].colorbar
93
- cbar.ax.yaxis.set_tick_params(color=text_color)
94
- cbar.ax.yaxis.set_tick_params(labelcolor=text_color)
95
-
96
- # Add F1-score to the title
97
- plt.title(f"{title}\nF1 Score: {avg_f1:.3f}", color=text_color, fontsize=23)
98
-
99
- tick_marks = np.arange(len(classes))
100
- plt.xticks(tick_marks, classes, color=text_color, fontsize=14) # Adjust text color based on the mode
101
- plt.yticks(tick_marks, classes, color=text_color, fontsize=14) # Adjust text color based on the mode
102
-
103
- plt.ylabel('True label', color=text_color, fontsize=20)
104
- plt.xlabel('Predicted label', color=text_color, fontsize=20)
105
- plt.tight_layout()
106
-
107
- plt.savefig(save_path, transparent=True) # Transparent to blend with the site background
108
- plt.close()
109
-
110
- # Return the saved image
111
- return Image.open(save_path)
112
-
113
- def compute_average_confusion_matrix(folder):
114
- confusion_matrices = []
115
- max_num_labels = 0
116
-
117
- # First pass to determine the maximum number of labels
118
- for file in os.listdir(folder):
119
- if file.endswith(".csv"):
120
- data = pd.read_csv(os.path.join(folder, file))
121
- num_labels = len(np.unique(data["Target"]))
122
- max_num_labels = max(max_num_labels, num_labels)
123
-
124
- # Second pass to calculate the confusion matrices and pad if necessary
125
- for file in os.listdir(folder):
126
- if file.endswith(".csv"):
127
- data = pd.read_csv(os.path.join(folder, file))
128
- y_true = data["Target"]
129
- y_pred = data["Top-1 Prediction"]
130
- num_labels = len(np.unique(y_true))
131
-
132
- # Compute confusion matrix
133
- cm = confusion_matrix(y_true, y_pred, labels=np.arange(max_num_labels))
134
-
135
- # If the confusion matrix is smaller, pad it to match the largest size
136
- if cm.shape[0] < max_num_labels:
137
- padded_cm = np.zeros((max_num_labels, max_num_labels))
138
- padded_cm[:cm.shape[0], :cm.shape[1]] = cm
139
- confusion_matrices.append(padded_cm)
140
- else:
141
- confusion_matrices.append(cm)
142
-
143
- if confusion_matrices:
144
- avg_cm = np.mean(confusion_matrices, axis=0)
145
- return avg_cm
146
- else:
147
- return None
148
-
149
- ########################## LOS/NLOS CLASSIFICATION #############################3
150
-
151
-
152
- # Paths to the predefined images folder
153
- LOS_PATH = "images_LoS"
154
-
155
- # Define the percentage values
156
- percentage_values_los = np.linspace(0.001, 1, 20) * 100 #np.linspace(0.05, 1, 20) * 100 # np.linspace(0.001, 1, 20) * 100 # 20 percentage values
157
-
158
- from sklearn.metrics import f1_score
159
- import seaborn as sns
160
-
161
- # Function to compute confusion matrix, F1-score and plot it with dark mode style
162
- def plot_confusion_matrix_from_csv(csv_file_path, title, save_path, light_mode=False):
163
- # Load CSV file
164
- data = pd.read_csv(csv_file_path)
165
-
166
- # Extract ground truth and predictions
167
- y_true = data['Target']
168
- y_pred = data['Top-1 Prediction']
169
-
170
- # Compute confusion matrix
171
- cm = confusion_matrix(y_true, y_pred)
172
-
173
- # Compute F1-score
174
- f1 = f1_score(y_true, y_pred, average='macro') # Macro-average F1-score
175
-
176
- # Set styling based on light or dark mode
177
- if light_mode:
178
- plt.style.use('default') # Light mode styling
179
- text_color = 'black'
180
- cmap = 'Blues' # Light-mode-friendly colormap
181
- else:
182
- plt.style.use('dark_background') # Dark mode styling
183
- text_color = 'gray'
184
- #cmap = 'magma' # Dark-mode-friendly colormap
185
- cmap = 'coolwarm'
186
-
187
- plt.figure(figsize=(5, 5))
188
-
189
- # Plot the confusion matrix with the chosen colormap
190
- sns.heatmap(cm, annot=True, fmt="d", cmap=cmap, cbar=False, annot_kws={"size": 12}, linewidths=0.5, linecolor='white')
191
-
192
- # Add F1-score to the title
193
- plt.title(f"{title}\nF1 Score: {f1:.3f}", color=text_color, fontsize=18)
194
-
195
- # Customize tick labels for light/dark mode
196
- plt.xticks([0.5, 1.5], labels=['NLoS', 'LoS'], color=text_color, fontsize=12)
197
- plt.yticks([0.5, 1.5], labels=['NLoS', 'LoS'], color=text_color, fontsize=12)
198
-
199
- plt.ylabel('True label', color=text_color, fontsize=14)
200
- plt.xlabel('Predicted label', color=text_color, fontsize=14)
201
- plt.tight_layout()
202
-
203
- # Save the plot as an image
204
- plt.savefig(save_path, transparent=True) # Use transparent to blend with the website
205
- plt.close()
206
-
207
- # Return the saved image
208
- return Image.open(save_path)
209
-
210
- # Function to load confusion matrix based on percentage and input_type
211
- def display_confusion_matrices_los(percentage):
212
- #percentage = percentage_values_los[percentage_idx]
213
-
214
- # Construct folder names
215
- raw_folder = os.path.join(LOS_PATH, f"raw_{percentage/100:.3f}_los_noTraining")
216
- embeddings_folder = os.path.join(LOS_PATH, f"embedding_{percentage/100:.3f}_los_noTraining")
217
-
218
- # Process raw confusion matrix
219
- raw_csv_file = os.path.join(raw_folder, f"test_predictions_raw_{percentage/100:.3f}_los.csv")
220
- raw_cm_img_path = os.path.join(raw_folder, "confusion_matrix_raw.png")
221
- raw_img = plot_confusion_matrix_from_csv(raw_csv_file,
222
- f"Confusion Matrix (Raw Channels)\n{percentage:.1f}% data",
223
- raw_cm_img_path)
224
-
225
- # Process embeddings confusion matrix
226
- embeddings_csv_file = os.path.join(embeddings_folder, f"test_predictions_embedding_{percentage/100:.3f}_los.csv")
227
- embeddings_cm_img_path = os.path.join(embeddings_folder, "confusion_matrix_embeddings.png")
228
- embeddings_img = plot_confusion_matrix_from_csv(embeddings_csv_file,
229
- f"Confusion Matrix (LWM Embeddings)\n{percentage:.1f}% data",
230
- embeddings_cm_img_path)
231
-
232
- return raw_img, embeddings_img
233
-
234
- # Main function to handle user choice
235
- def handle_user_choice(choice, percentage=None, uploaded_file=None, emb_type='CLS Embedding'):
236
- if choice == "Use Default Dataset":
237
- raw_img, embeddings_img = display_confusion_matrices_los(percentage)
238
- return raw_img, embeddings_img, "" # Return empty string for console output
239
- elif choice == "Upload Dataset":
240
- if uploaded_file is not None:
241
- raw_img, embeddings_img, console_output = process_hdf5_file(uploaded_file, percentage, emb_type)
242
- return raw_img, embeddings_img, console_output
243
- else:
244
- return "Please upload a dataset", "Please upload a dataset", "" # Return empty string for console output
245
- else:
246
- return "Invalid choice", "Invalid choice", "" # Return empty string for console output
247
-
248
- # Custom class to capture print output
249
- class PrintCapture(io.StringIO):
250
- def __init__(self):
251
- super().__init__()
252
- self.output = []
253
-
254
- def write(self, txt):
255
- self.output.append(txt)
256
- super().write(txt)
257
-
258
- def get_output(self):
259
- return ''.join(self.output)
260
-
261
- # Function to load and display predefined images based on user selection
262
- def display_predefined_images(percentage):
263
- #percentage = percentage_values_los[percentage_idx]
264
- raw_image_path = os.path.join(RAW_PATH, f"percentage_{percentage}_complexity_16.png")
265
- embeddings_image_path = os.path.join(EMBEDDINGS_PATH, f"percentage_{percentage}_complexity_16.png")
266
-
267
- # Check if the images exist
268
- if os.path.exists(raw_image_path):
269
- raw_image = Image.open(raw_image_path)
270
- else:
271
- raw_image = create_random_image() # Use a fallback random image
272
-
273
- if os.path.exists(embeddings_image_path):
274
- embeddings_image = Image.open(embeddings_image_path)
275
- else:
276
- embeddings_image = create_random_image() # Use a fallback random image
277
-
278
- return raw_image, embeddings_image
279
-
280
- def los_nlos_classification(file, percentage):
281
- if file is not None:
282
- raw_cm_image, emb_cm_image, console_output = process_hdf5_file(file, percentage)
283
- return raw_cm_image, emb_cm_image, console_output # Returning all three: two images and console output
284
- else:
285
- raw_image, embeddings_image = display_predefined_images(percentage)
286
- return raw_image, embeddings_image, "" # Return an empty string for console output when no file is uploaded
287
-
288
- # Function to create random images for LoS/NLoS classification results
289
- def create_random_image(size=(300, 300)):
290
- random_image = np.random.rand(*size, 3) * 255
291
- return Image.fromarray(random_image.astype('uint8'))
292
-
293
- import importlib.util
294
-
295
- # Function to dynamically load a Python module from a given file path
296
- def load_module_from_path(module_name, file_path):
297
- spec = importlib.util.spec_from_file_location(module_name, file_path)
298
- module = importlib.util.module_from_spec(spec)
299
- spec.loader.exec_module(module)
300
- return module
301
-
302
- # Function to split dataset into training and test sets based on user selection
303
- def split_dataset(channels, labels, percentage):
304
- #percentage = percentage_values_los[percentage_idx] / 100
305
- num_samples = channels.shape[0]
306
- train_size = int(num_samples * percentage/100)
307
- print(f'Number of Training Samples: {train_size}')
308
-
309
- indices = np.arange(num_samples)
310
- np.random.shuffle(indices)
311
-
312
- train_idx, test_idx = indices[:train_size], indices[train_size:]
313
-
314
- train_data, test_data = channels[train_idx], channels[test_idx]
315
- train_labels, test_labels = labels[train_idx], labels[test_idx]
316
-
317
- return train_data, test_data, train_labels, test_labels
318
-
319
- # Function to calculate Euclidean distance between a point and a centroid
320
- def euclidean_distance(x, centroid):
321
- return np.linalg.norm(x - centroid)
322
-
323
- import torch
324
-
325
- def classify_based_on_distance(train_data, train_labels, test_data):
326
- # Compute the centroids for the two classes
327
- centroid_0 = train_data[train_labels == 0].mean(dim=0) # Use torch.mean
328
- centroid_1 = train_data[train_labels == 1].mean(dim=0) # Use torch.mean
329
-
330
- predictions = []
331
- for test_point in test_data:
332
- # Compute Euclidean distance between the test point and each centroid
333
- dist_0 = euclidean_distance(test_point, centroid_0)
334
- dist_1 = euclidean_distance(test_point, centroid_1)
335
- predictions.append(0 if dist_0 < dist_1 else 1)
336
-
337
- return torch.tensor(predictions) # Return predictions as a PyTorch tensor
338
-
339
- def plot_confusion_matrix(y_true, y_pred, title, light_mode=False):
340
- cm = confusion_matrix(y_true, y_pred)
341
-
342
- # Calculate F1 Score
343
- f1 = f1_score(y_true, y_pred, average='weighted')
344
-
345
- #plt.style.use('dark_background')
346
-
347
- # Set styling based on light or dark mode
348
- if light_mode:
349
- plt.style.use('default') # Light mode styling
350
- text_color = 'black'
351
- cmap = 'Blues' # Light-mode-friendly colormap
352
- else:
353
- plt.style.use('dark_background') # Dark mode styling
354
- text_color = 'gray'
355
- #cmap = 'magma' # Dark-mode-friendly colormap
356
- cmap = 'coolwarm'
357
-
358
- plt.figure(figsize=(5, 5))
359
-
360
- # Plot the confusion matrix with a dark-mode compatible colormap
361
- sns.heatmap(cm, annot=True, fmt="d", cmap=cmap, cbar=False, annot_kws={"size": 12}, linewidths=0.5, linecolor='white')
362
-
363
- # Add F1-score to the title
364
- plt.title(f"{title}\nF1 Score: {f1:.3f}", color=text_color, fontsize=18)
365
-
366
- # Customize tick labels for dark mode
367
- plt.xticks([0.5, 1.5], labels=['NLoS', 'LoS'], color=text_color, fontsize=12)
368
- plt.yticks([0.5, 1.5], labels=['NLoS', 'LoS'], color=text_color, fontsize=12)
369
-
370
- plt.ylabel('True label', color=text_color, fontsize=14)
371
- plt.xlabel('Predicted label', color=text_color, fontsize=14)
372
- plt.tight_layout()
373
-
374
- # Save the plot as an image
375
- plt.savefig(f"{title}.png", transparent=True) # Use transparent to blend with the dark mode website
376
- plt.close()
377
-
378
- # Return the saved image
379
- return Image.open(f"{title}.png")
380
-
381
-
382
- def identical_train_test_split(output_emb, output_raw, labels, train_percentage):
383
-
384
- torch.manual_seed(42)
385
-
386
- N = output_emb.shape[0]
387
- indices = torch.randperm(N)
388
- test_split_index = int(N * 0.20)
389
- test_indices = indices[:test_split_index]
390
- remaining_indices = indices[test_split_index:]
391
- train_split_index = int(len(remaining_indices) * train_percentage / 100)
392
- print(f'Training Size: {train_split_index} out of remaining {len(remaining_indices)}')
393
- print(f'Test Size: {test_split_index}')
394
-
395
- train_indices = remaining_indices[:train_split_index]
396
-
397
- train_emb = output_emb[train_indices]
398
- test_emb = output_emb[test_indices]
399
-
400
- train_raw = output_raw[train_indices]
401
- test_raw = output_raw[test_indices]
402
-
403
- train_labels = labels[train_indices]
404
- test_labels = labels[test_indices]
405
-
406
- return train_emb, test_emb, train_raw, test_raw, train_labels, test_labels
407
-
408
- # Store the original working directory when the app starts
409
- original_dir = os.getcwd()
410
-
411
- def process_hdf5_file(uploaded_file, percentage, emb_type='CLS Embedding'):
412
- capture = PrintCapture()
413
- sys.stdout = capture # Redirect print statements to capture
414
-
415
- try:
416
- model_repo_url = "https://huggingface.co/wi-lab/lwm"
417
- model_repo_dir = "./LWM"
418
-
419
- # Step 1: Clone the repository if not already done
420
- if not os.path.exists(model_repo_dir):
421
- print(f"Cloning model repository from {model_repo_url}...")
422
- subprocess.run(["git", "clone", model_repo_url, model_repo_dir], check=True)
423
-
424
- # Step 2: Verify the repository was cloned and change the working directory
425
- repo_work_dir = os.path.join(original_dir, model_repo_dir)
426
- if os.path.exists(repo_work_dir):
427
- os.chdir(repo_work_dir) # Change the working directory only once
428
- print(f"Changed working directory to {os.getcwd()}")
429
- #print(f"Directory content: {os.listdir(os.getcwd())}") # Debugging: Check repo content
430
- else:
431
- print(f"Directory {repo_work_dir} does not exist.")
432
- return
433
-
434
- # Step 3: Dynamically load lwm_model.py, input_preprocess.py, and inference.py
435
- lwm_model_path = os.path.join(os.getcwd(), 'lwm_model.py')
436
- input_preprocess_path = os.path.join(os.getcwd(), 'input_preprocess.py')
437
- inference_path = os.path.join(os.getcwd(), 'inference.py')
438
-
439
- # Load lwm_model
440
- lwm_model = load_module_from_path("lwm_model", lwm_model_path)
441
-
442
- # Load input_preprocess
443
- input_preprocess = load_module_from_path("input_preprocess", input_preprocess_path)
444
-
445
- # Load inference
446
- inference = load_module_from_path("inference", inference_path)
447
-
448
- # Step 4: Load the model from lwm_model module
449
- device = 'cuda' if torch.cuda.is_available() else 'cpu'
450
- print(f"Loading the LWM model on {device}...")
451
- model = lwm_model.lwm.from_pretrained(device=device).float()
452
-
453
- # Step 5: Load the HDF5 file and extract the channels and labels
454
- with h5py.File(uploaded_file.name, 'r') as f:
455
- channels = np.array(f['channels']).astype(np.complex64)
456
- labels = np.array(f['labels']).astype(np.int32)
457
- print(f"Loaded dataset with {channels.shape[0]} samples.")
458
- channels = channels * (10**(-3-np.floor(np.log10(np.abs(np.mean(channels).real)))))
459
-
460
- # Step 7: Tokenize the data using the tokenizer from input_preprocess
461
- preprocessed_chs = input_preprocess.tokenizer(manual_data=channels)
462
-
463
- # Step 7: Perform inference using the functions from inference.py
464
- if emb_type == 'Channel Embedding':
465
- embedding_type = 'channel_emb'
466
- elif emb_type == 'CLS Embedding':
467
- embedding_type = 'cls_emb'
468
-
469
- output_emb = inference.lwm_inference(preprocessed_chs, embedding_type, model, device)
470
- output_raw = inference.create_raw_dataset(preprocessed_chs, device)
471
-
472
- print(f"Output Embeddings Shape: {output_emb.shape}")
473
- print(f"Output Raw Shape: {output_raw.shape}")
474
-
475
- print(f'percentage_value: {percentage}')
476
- train_data_emb, test_data_emb, train_data_raw, test_data_raw, train_labels, test_labels = identical_train_test_split(output_emb.view(len(output_emb),-1),
477
- output_raw.view(len(output_raw),-1),
478
- labels,
479
- percentage)
480
-
481
- # Step 8: Perform classification using the Euclidean distance for both raw and embeddings
482
- #print(f'train_data_emb: {train_data_emb.shape}')
483
- #print(f'train_labels: {train_labels.shape}')
484
- #print(f'test_data_emb: {test_data_emb.shape}')
485
- pred_raw = classify_based_on_distance(train_data_raw, train_labels, test_data_raw)
486
- pred_emb = classify_based_on_distance(train_data_emb, train_labels, test_data_emb)
487
-
488
- # Step 9: Generate confusion matrices for both raw and embeddings
489
- raw_cm_image = plot_confusion_matrix(test_labels, pred_raw, title="Confusion Matrix (Raw Channels)")
490
- emb_cm_image = plot_confusion_matrix(test_labels, pred_emb, title="Confusion Matrix (Embeddings)")
491
-
492
- return raw_cm_image, emb_cm_image, capture.get_output()
493
-
494
- except Exception as e:
495
- return str(e), str(e), capture.get_output()
496
-
497
- finally:
498
- # Always return to the original working directory after processing
499
- os.chdir(original_dir)
500
- sys.stdout = sys.__stdout__ # Reset print statements
501
-
502
- ######################## Define the Gradio interface ###############################
503
- js_code = """
504
- () => {
505
- const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
506
- return isDarkMode ? 'dark' : 'light';
507
- }
508
- """
509
-
510
- with gr.Blocks(css="""
511
- .slider-container {
512
- display: inline-block;
513
- margin-right: 50px;
514
- text-align: center;
515
- }
516
-
517
- .explanation-box {
518
- font-size: 16px;
519
- font-style: italic;
520
- color: #4a4a4a;
521
- padding: 15px;
522
- background-color: #f0f0f0;
523
- border-radius: 10px;
524
- margin-bottom: 20px;
525
- }
526
-
527
- .bold-highlight {
528
- font-weight: bold;
529
- color: #2c3e50;
530
- font-size: 18px;
531
- text-align: center;
532
- margin-bottom: 20px;
533
- }
534
-
535
- #console-output {
536
- background-color: #ffffff; /* Light background for light mode */
537
- color: #000000; /* Dark text color for contrast */
538
- padding: 10px;
539
- border-radius: 5px;
540
- }
541
-
542
- .plot-title {
543
- font-weight: bold;
544
- color: #2c3e50;
545
- }
546
- """) as demo:
547
-
548
- # Contact Section
549
- gr.Markdown("""
550
- <div style="text-align: center;">
551
- <a target="_blank" href="https://www.wi-lab.net">
552
- <img src="https://www.wi-lab.net/wp-content/uploads/2021/08/WI-name.png" alt="Wireless Model" style="height: 30px;">
553
- </a>
554
- <a target="_blank" href="mailto:lwmwireless@gmail.com" style="margin-left: 10px;">
555
- <img src="https://img.shields.io/badge/email-lwmwireless@gmail.com-blue.svg?logo=gmail" alt="Email">
556
- </a>
557
- </div>
558
- """)
559
-
560
- gr.Markdown("""
561
- <div class="bold-highlight">
562
- πŸš€ Explore the pre-trained <b>LWM Model<b> here:
563
- <a target="_blank" href="https://huggingface.co/wi-lab/lwm">https://huggingface.co/wi-lab/lwm</a>
564
- </div>
565
- """)
566
-
567
- # Tab for Beam Prediction Task
568
- with gr.Tab("Beam Prediction Task"):
569
- #gr.Markdown("### Beam Prediction Task")
570
-
571
- # Explanation section with creative spacing and minimal design
572
- gr.Markdown("""
573
- <div style="background-color: var(--primary-background); padding: 15px; border-radius: 10px; color: var(--text-primary);">
574
- <h3 style="color: var(--text-primary);">πŸ“‘ <b>Sub-6GHz to mmWave Beam Prediction Task</b></h3>
575
- <ul style="padding-left: 20px;">
576
- <li><b>🎯 Goal</b>: Predict the strongest <b>mmWave beam</b> from a predefined codebook using Sub-6 GHz channels.</li>
577
- <li><b>βš™οΈ Adjust Settings</b>: Use the sliders to control the training data percentage and task complexity (beam count) to explore model performance.</li>
578
- <li><b>🧠 Inferences</b>:
579
- <ul>
580
- <li>πŸ” First, the LWM model extracts features.</li>
581
- <li>πŸ€– Then, the downstream residual 1D-CNN model (500K parameters) makes beam predictions.</li>
582
- </ul>
583
- </li>
584
- <li><b>πŸ—ΊοΈ Dataset</b>: A combination of six scenarios from the DeepMIMO dataset (excluded from LWM pre-training) highlights the model's strong generalization abilities.</li>
585
- </ul>
586
- </div>
587
- """)
588
-
589
- with gr.Row():
590
- with gr.Column():
591
- data_percentage_slider = gr.Slider(label="Data Percentage for Training", minimum=10, maximum=100, step=10, value=10)
592
- task_complexity_dropdown = gr.Dropdown(label="Task Complexity (Number of Beams)", choices=[16, 32, 64, 128, 256], value=16)
593
- #theme_dropdown = gr.Dropdown(label="Select Theme", choices=['Light', 'Dark'], value='Light')
594
-
595
- with gr.Row():
596
- raw_img_bp = gr.Image(label="Raw Channels", type="pil", width=300, height=500)
597
- embeddings_img_bp = gr.Image(label="Embeddings", type="pil", width=300, height=500)
598
-
599
- theme_dropdown = 'Dark'
600
- # Update the confusion matrices whenever sliders change
601
- data_percentage_slider.change(fn=beam_prediction_task, inputs=[data_percentage_slider, task_complexity_dropdown], outputs=[raw_img_bp, embeddings_img_bp])
602
- task_complexity_dropdown.change(fn=beam_prediction_task, inputs=[data_percentage_slider, task_complexity_dropdown], outputs=[raw_img_bp, embeddings_img_bp])
603
- #theme_dropdown.change(fn=beam_prediction_task, inputs=[data_percentage_slider, task_complexity_dropdown, theme_dropdown], outputs=[raw_img_bp, embeddings_img_bp])
604
-
605
- # Add a conclusion section at the bottom
606
- gr.Markdown("""
607
- <div class="explanation-box">
608
- The LWM embeddings demonstrate remarkable generalization capabilities, enabling impressive performance even with minimal training samples. This highlights their ability to effectively handle diverse tasks with limited data.
609
- </div>
610
- """)
611
-
612
- # Separate Tab for LoS/NLoS Classification Task
613
- with gr.Tab("LoS/NLoS Classification Task"):
614
- #gr.Markdown("### LoS/NLoS Classification Task")
615
-
616
- # Explanation section with creative spacing
617
- gr.Markdown("""
618
- <div style="background-color: var(--primary-background); padding: 15px; border-radius: 10px; color: var(--text-primary);">
619
- <h3 style="color: var(--text-primary);">πŸ” <b>LoS/NLoS Classification Task</b></h3>
620
- <ul style="padding-left: 20px;">
621
- <li><b>🎯 Goal</b>: Classify whether a channel is <b>LoS</b> (Line-of-Sight) or <b>NLoS</b> (Non-Line-of-Sight) with very small LWM CLS embeddings.</li>
622
- <li><b>πŸ“‚ Dataset</b>: Use the default dataset (a combination of six scenarios from the DeepMIMO dataset) or upload your own dataset in <b>H5</b> format.</li>
623
- <li><b>πŸ’‘ Custom Dataset Requirements:</b>
624
- <ul>
625
- <li>πŸ“‘ <b>channels</b> array: Shape (N,32,32), rows: 32 antennas at BS, columns: 32 subcarriers</li>
626
- <li>🏷️ <b>labels</b> array: Binary LoS/NLoS values (1/0)</li>
627
- </ul>
628
- </li>
629
- <li><b>πŸ”— Tip 1</b>: Instructions for organizing your dataset are available at the bottom of the page.</li>
630
- <li><b>πŸ”— Tip 2</b>: As the computations and inference are performed on HuggingFace CPUs, please use small datasets for faster demo experience (say <400 samples). Clone the model from <a href="https://huggingface.co/wi-lab/lwm" target="_blank">here</a> and use any number of samples locally.</li>
631
- <li><b>πŸ”— Tip 3</b>: Your dataset will be normalized automatically based on outdoor environments. </li>
632
- <li><b>πŸ’Ό No Downstream Model</b>: Instead of a complex downstream model, we classify each sample based on its distance to the centroid of training samples from each class (LoS/NLoS).</il>
633
- </ul>
634
- </div>
635
- """)
636
- # Radio button for user choice: predefined data or upload dataset
637
- choice_radio = gr.Radio(choices=["Use Default Dataset", "Upload Dataset"],
638
- label="Choose how to proceed",
639
- value="Use Default Dataset")
640
-
641
- percentage_slider_los = gr.Slider(minimum=float(percentage_values_los[0]),
642
- maximum=float(percentage_values_los[-1]),
643
- step=float((percentage_values_los[-1] - percentage_values_los[0]) / (len(percentage_values_los) - 1)),
644
- value=float(percentage_values_los[0]),
645
- label="Percentage of Data for Training",
646
- interactive=True)
647
-
648
- # File uploader for dataset (only visible if user chooses to upload a dataset)
649
- file_input = gr.File(label="Upload HDF5 Dataset", file_types=[".h5"], visible=False)
650
-
651
- # Dropdown for embedding type, also only visible when "Upload Dataset" is selected
652
- emb_type = gr.Dropdown(choices=["Channel Embedding", "CLS Embedding"],
653
- value="CLS Embedding",
654
- label="Embedding Type",
655
- visible=False)
656
-
657
- # Confusion matrices display
658
- with gr.Row():
659
- raw_img_los = gr.Image(label="Raw Channels", type="pil", width=300, height=300)
660
- embeddings_img_los = gr.Image(label="Embeddings", type="pil", width=300, height=300)
661
- output_textbox = gr.Textbox(label="Console Output", lines=10, elem_id="console-output")
662
-
663
- # Update the visibility of file_input and emb_type based on user choice
664
- def toggle_file_input_and_emb_type(choice):
665
- visible = (choice == "Upload Dataset")
666
- return gr.update(visible=visible), gr.update(visible=visible)
667
-
668
- # Change visibility of file input and embedding type dropdown based on choice
669
- choice_radio.change(fn=toggle_file_input_and_emb_type,
670
- inputs=[choice_radio],
671
- outputs=[file_input, emb_type])
672
-
673
- # When percentage slider changes (for predefined data)
674
- percentage_slider_los.change(fn=handle_user_choice,
675
- inputs=[choice_radio, percentage_slider_los, file_input, emb_type],
676
- outputs=[raw_img_los, embeddings_img_los, output_textbox])
677
-
678
- # Layout for the UI - this part does NOT need .render(), Gradio will render these automatically
679
- with gr.Row():
680
- file_input # No need for .render()
681
- emb_type # No need for .render()
682
-
683
- # Add a conclusion section at the bottom
684
- gr.Markdown("""
685
- <div class="explanation-box">
686
- Despite their compact size (1/32 of the raw channels), LWM CLS embeddings capture rich, holistic information about the channels. This makes them exceptionally well-suited for tasks like LoS/NLoS classification, especially when working with very limited data.
687
- </div>
688
- """)
689
-
690
- gr.Markdown("""
691
- <div class="explanation-box">
692
- To create a custom dataset, you'll need to structure your data with 32x32 channel matrices, where the rows correspond to antennas at the base station and the columns represent subcarriers. Here’s how to organize and store the channels and labels in an H5 file format for the demo:
693
- </div>
694
-
695
- ```python
696
- # How to pack channels and labels in a h5 file format as a custom dataset for the demo:
697
- import h5py
698
- with h5py.File('dataset.h5', 'w') as hdf:
699
- hdf.create_dataset('channels', data=channels)
700
- hdf.create_dataset('labels', data=labels)
701
- print("Dataset saved!")
702
- """)
703
- gr.Markdown("""
704
- <div class="explanation-box">
705
- To use your preferred DeepMIMO scenarios for the custom dataset, please
706
- <a href="https://huggingface.co/wi-lab/lwm" target="_blank">clone the model and datasets</a>
707
- and follow the instructions below:
708
- </div>
709
-
710
-
711
- ```python
712
- from input_preprocess import DeepMIMO_data_gen deepmimo_data_cleaning label_gen # Import required modules from the model repository
713
- import numpy as np
714
- scenario_names = np.array([
715
- "city_18_denver", "city_15_indianapolis", "city_19_oklahoma",
716
- "city_12_fortworth", "city_11_santaclara", "city_7_sandiego"
717
- ])
718
- scenario_name = scenario_names[0] # Select the scenario by choosing its index.
719
- deepmimo_data = DeepMIMO_data_gen(scenario_name) # Generates ray-traced wireless channels for the selected scenario.
720
- cleaned_deepmimo_data = deepmimo_data_cleaning(deepmimo_data) # Filters out users with no direct path to the base station (i.e., users with zero-valued channels).
721
-
722
- channels = np.squeeze(np.array(cleaned_deepmimo_data), axis=1) # The "channels" array is now prepared for packing into the custom dataset in H5 format.
723
- labels = label_gen('LoS/NLoS Classification', deepmimo_data, scenario_name) # Generates labels for each user, classifying them as Line-of-Sight (LoS) or Non-Line-of-Sight (NLoS), and prepares the "labels" array for inclusion in the custom dataset H5 file.
724
- ```
725
- """)
726
- #with gr.Tab("LWM Model and Framework"):
727
- # gr.Image("images/lwm_model_v2.png")
728
- # gr.Markdown("This figure depicts the offline pre-training and online embedding generation process for LWM. The channel is divided into fixed-size patches, which are linearly embedded and combined with positional encodings before being passed through a Transformer encoder. During self-supervised pre-training, some embeddings are masked, and LWM leverages self-attention to extract deep features, allowing the decoder to reconstruct the masked values. For downstream tasks, the generated LWM embeddings enhance performance.")
729
-
730
- # Launch the app
731
- if __name__ == "__main__":
732
- demo.launch()
733
 
 
1
+ import gradio as gr
2
+ import os
3
+ from PIL import Image
4
+ import numpy as np
5
+ import pickle
6
+ import io
7
+ import sys
8
+ import torch
9
+ import subprocess
10
+ import h5py
11
+ from sklearn.metrics import confusion_matrix
12
+ import matplotlib.pyplot as plt
13
+ import pandas as pd
14
+ from sklearn.metrics import f1_score
15
+ import seaborn as sns
16
+
17
+ #################### BEAM PREDICTION #########################}
18
+ def beam_prediction_task(data_percentage, task_complexity, theme='Dark'):
19
+ # Folder naming convention based on input_type, data_percentage, and task_complexity
20
+ raw_folder = f"images/raw_{data_percentage/100:.1f}_{task_complexity}"
21
+ embeddings_folder = f"images/embedding_{data_percentage/100:.1f}_{task_complexity}"
22
+
23
+ # Process raw confusion matrix
24
+ raw_cm = compute_average_confusion_matrix(raw_folder)
25
+ if raw_cm is not None:
26
+ raw_cm_path = os.path.join(raw_folder, "confusion_matrix_raw.png")
27
+ plot_confusion_matrix_beamPred(raw_cm,
28
+ classes=np.arange(raw_cm.shape[0]),
29
+ title=f"Confusion Matrix (Raw Channels)\n{data_percentage}% data, {task_complexity} beams",
30
+ save_path=raw_cm_path,
31
+ theme=theme)
32
+ raw_img = Image.open(raw_cm_path)
33
+ else:
34
+ raw_img = None
35
+
36
+ # Process embeddings confusion matrix
37
+ embeddings_cm = compute_average_confusion_matrix(embeddings_folder)
38
+ if embeddings_cm is not None:
39
+ embeddings_cm_path = os.path.join(embeddings_folder, "confusion_matrix_embeddings.png")
40
+ plot_confusion_matrix_beamPred(embeddings_cm,
41
+ classes=np.arange(embeddings_cm.shape[0]),
42
+ title=f"Confusion Matrix (LWM Embeddings)\n{data_percentage}% data, {task_complexity} beams",
43
+ save_path=embeddings_cm_path,
44
+ theme=theme)
45
+ embeddings_img = Image.open(embeddings_cm_path)
46
+ else:
47
+ embeddings_img = None
48
+
49
+ return raw_img, embeddings_img
50
+
51
+ # Function to compute the F1-score based on the confusion matrix
52
+ def compute_f1_score(cm):
53
+ # Compute precision and recall
54
+ TP = np.diag(cm)
55
+ FP = np.sum(cm, axis=0) - TP
56
+ FN = np.sum(cm, axis=1) - TP
57
+
58
+ precision = TP / (TP + FP)
59
+ recall = TP / (TP + FN)
60
+
61
+ # Handle division by zero in precision or recall
62
+ precision = np.nan_to_num(precision)
63
+ recall = np.nan_to_num(recall)
64
+
65
+ # Compute F1 score
66
+ f1 = 2 * (precision * recall) / (precision + recall)
67
+ f1 = np.nan_to_num(f1) # Replace NaN with 0
68
+ return np.mean(f1) # Return the mean F1-score across all classes
69
+
70
+ def plot_confusion_matrix_beamPred(cm, classes, title, save_path, theme='Dark'):
71
+ # Compute the average F1-score
72
+ avg_f1 = compute_f1_score(cm)
73
+
74
+ # Choose the color scheme based on the user's mode
75
+ if theme == 'Dark':
76
+ plt.style.use('dark_background') # Use dark mode styling
77
+ #text_color = 'white'
78
+ text_color = 'gray'
79
+ #cmap = 'cividis' # Dark-mode-friendly colormap
80
+ cmap = 'coolwarm'
81
+ else:
82
+ plt.style.use('default') # Use default (light) mode styling
83
+ #text_color = 'black'
84
+ text_color = 'gray'
85
+ cmap = 'Blues' # Light-mode-friendly colormap
86
+
87
+ plt.figure(figsize=(10, 10))
88
+
89
+ # Plot the confusion matrix with a colormap compatible for the mode
90
+ ax = sns.heatmap(cm, cmap=cmap, cbar=True)
91
+
92
+ cbar = ax.collections[0].colorbar
93
+ cbar.ax.yaxis.set_tick_params(color=text_color)
94
+ cbar.ax.yaxis.set_tick_params(labelcolor=text_color)
95
+
96
+ # Add F1-score to the title
97
+ plt.title(f"{title}\nF1 Score: {avg_f1:.3f}", color=text_color, fontsize=23)
98
+
99
+ tick_marks = np.arange(len(classes))
100
+ plt.xticks(tick_marks, classes, color=text_color, fontsize=14) # Adjust text color based on the mode
101
+ plt.yticks(tick_marks, classes, color=text_color, fontsize=14) # Adjust text color based on the mode
102
+
103
+ plt.ylabel('True label', color=text_color, fontsize=20)
104
+ plt.xlabel('Predicted label', color=text_color, fontsize=20)
105
+ plt.tight_layout()
106
+
107
+ plt.savefig(save_path, transparent=True) # Transparent to blend with the site background
108
+ plt.close()
109
+
110
+ # Return the saved image
111
+ return Image.open(save_path)
112
+
113
+ def compute_average_confusion_matrix(folder):
114
+ confusion_matrices = []
115
+ max_num_labels = 0
116
+
117
+ # First pass to determine the maximum number of labels
118
+ for file in os.listdir(folder):
119
+ if file.endswith(".csv"):
120
+ data = pd.read_csv(os.path.join(folder, file))
121
+ num_labels = len(np.unique(data["Target"]))
122
+ max_num_labels = max(max_num_labels, num_labels)
123
+
124
+ # Second pass to calculate the confusion matrices and pad if necessary
125
+ for file in os.listdir(folder):
126
+ if file.endswith(".csv"):
127
+ data = pd.read_csv(os.path.join(folder, file))
128
+ y_true = data["Target"]
129
+ y_pred = data["Top-1 Prediction"]
130
+ num_labels = len(np.unique(y_true))
131
+
132
+ # Compute confusion matrix
133
+ cm = confusion_matrix(y_true, y_pred, labels=np.arange(max_num_labels))
134
+
135
+ # If the confusion matrix is smaller, pad it to match the largest size
136
+ if cm.shape[0] < max_num_labels:
137
+ padded_cm = np.zeros((max_num_labels, max_num_labels))
138
+ padded_cm[:cm.shape[0], :cm.shape[1]] = cm
139
+ confusion_matrices.append(padded_cm)
140
+ else:
141
+ confusion_matrices.append(cm)
142
+
143
+ if confusion_matrices:
144
+ avg_cm = np.mean(confusion_matrices, axis=0)
145
+ return avg_cm
146
+ else:
147
+ return None
148
+
149
+ ########################## LOS/NLOS CLASSIFICATION #############################3
150
+
151
+
152
+ # Paths to the predefined images folder
153
+ LOS_PATH = "images_LoS"
154
+
155
+ # Define the percentage values
156
+ percentage_values_los = np.linspace(0.001, 1, 20) * 100 #np.linspace(0.05, 1, 20) * 100 # np.linspace(0.001, 1, 20) * 100 # 20 percentage values
157
+
158
+ from sklearn.metrics import f1_score
159
+ import seaborn as sns
160
+
161
+ # Function to compute confusion matrix, F1-score and plot it with dark mode style
162
+ def plot_confusion_matrix_from_csv(csv_file_path, title, save_path, light_mode=False):
163
+ # Load CSV file
164
+ data = pd.read_csv(csv_file_path)
165
+
166
+ # Extract ground truth and predictions
167
+ y_true = data['Target']
168
+ y_pred = data['Top-1 Prediction']
169
+
170
+ # Compute confusion matrix
171
+ cm = confusion_matrix(y_true, y_pred)
172
+
173
+ # Compute F1-score
174
+ f1 = f1_score(y_true, y_pred, average='macro') # Macro-average F1-score
175
+
176
+ # Set styling based on light or dark mode
177
+ if light_mode:
178
+ plt.style.use('default') # Light mode styling
179
+ text_color = 'black'
180
+ cmap = 'Blues' # Light-mode-friendly colormap
181
+ else:
182
+ plt.style.use('dark_background') # Dark mode styling
183
+ text_color = 'gray'
184
+ #cmap = 'magma' # Dark-mode-friendly colormap
185
+ cmap = 'coolwarm'
186
+
187
+ plt.figure(figsize=(5, 5))
188
+
189
+ # Plot the confusion matrix with the chosen colormap
190
+ sns.heatmap(cm, annot=True, fmt="d", cmap=cmap, cbar=False, annot_kws={"size": 12}, linewidths=0.5, linecolor='white')
191
+
192
+ # Add F1-score to the title
193
+ plt.title(f"{title}\nF1 Score: {f1:.3f}", color=text_color, fontsize=18)
194
+
195
+ # Customize tick labels for light/dark mode
196
+ plt.xticks([0.5, 1.5], labels=['NLoS', 'LoS'], color=text_color, fontsize=12)
197
+ plt.yticks([0.5, 1.5], labels=['NLoS', 'LoS'], color=text_color, fontsize=12)
198
+
199
+ plt.ylabel('True label', color=text_color, fontsize=14)
200
+ plt.xlabel('Predicted label', color=text_color, fontsize=14)
201
+ plt.tight_layout()
202
+
203
+ # Save the plot as an image
204
+ plt.savefig(save_path, transparent=True) # Use transparent to blend with the website
205
+ plt.close()
206
+
207
+ # Return the saved image
208
+ return Image.open(save_path)
209
+
210
+ # Function to load confusion matrix based on percentage and input_type
211
+ def display_confusion_matrices_los(percentage):
212
+ #percentage = percentage_values_los[percentage_idx]
213
+
214
+ # Construct folder names
215
+ raw_folder = os.path.join(LOS_PATH, f"raw_{percentage/100:.3f}_los_noTraining")
216
+ embeddings_folder = os.path.join(LOS_PATH, f"embedding_{percentage/100:.3f}_los_noTraining")
217
+
218
+ # Process raw confusion matrix
219
+ raw_csv_file = os.path.join(raw_folder, f"test_predictions_raw_{percentage/100:.3f}_los.csv")
220
+ raw_cm_img_path = os.path.join(raw_folder, "confusion_matrix_raw.png")
221
+ raw_img = plot_confusion_matrix_from_csv(raw_csv_file,
222
+ f"Confusion Matrix (Raw Channels)\n{percentage:.1f}% data",
223
+ raw_cm_img_path)
224
+
225
+ # Process embeddings confusion matrix
226
+ embeddings_csv_file = os.path.join(embeddings_folder, f"test_predictions_embedding_{percentage/100:.3f}_los.csv")
227
+ embeddings_cm_img_path = os.path.join(embeddings_folder, "confusion_matrix_embeddings.png")
228
+ embeddings_img = plot_confusion_matrix_from_csv(embeddings_csv_file,
229
+ f"Confusion Matrix (LWM Embeddings)\n{percentage:.1f}% data",
230
+ embeddings_cm_img_path)
231
+
232
+ return raw_img, embeddings_img
233
+
234
+ # Main function to handle user choice
235
+ def handle_user_choice(choice, percentage=None, uploaded_file=None, emb_type='CLS Embedding'):
236
+ if choice == "Use Default Dataset":
237
+ raw_img, embeddings_img = display_confusion_matrices_los(percentage)
238
+ return raw_img, embeddings_img, "" # Return empty string for console output
239
+ elif choice == "Upload Dataset":
240
+ if uploaded_file is not None:
241
+ raw_img, embeddings_img, console_output = process_hdf5_file(uploaded_file, percentage, emb_type)
242
+ return raw_img, embeddings_img, console_output
243
+ else:
244
+ return "Please upload a dataset", "Please upload a dataset", "" # Return empty string for console output
245
+ else:
246
+ return "Invalid choice", "Invalid choice", "" # Return empty string for console output
247
+
248
+ # Custom class to capture print output
249
+ class PrintCapture(io.StringIO):
250
+ def __init__(self):
251
+ super().__init__()
252
+ self.output = []
253
+
254
+ def write(self, txt):
255
+ self.output.append(txt)
256
+ super().write(txt)
257
+
258
+ def get_output(self):
259
+ return ''.join(self.output)
260
+
261
+ # Function to load and display predefined images based on user selection
262
+ def display_predefined_images(percentage):
263
+ #percentage = percentage_values_los[percentage_idx]
264
+ raw_image_path = os.path.join(RAW_PATH, f"percentage_{percentage}_complexity_16.png")
265
+ embeddings_image_path = os.path.join(EMBEDDINGS_PATH, f"percentage_{percentage}_complexity_16.png")
266
+
267
+ # Check if the images exist
268
+ if os.path.exists(raw_image_path):
269
+ raw_image = Image.open(raw_image_path)
270
+ else:
271
+ raw_image = create_random_image() # Use a fallback random image
272
+
273
+ if os.path.exists(embeddings_image_path):
274
+ embeddings_image = Image.open(embeddings_image_path)
275
+ else:
276
+ embeddings_image = create_random_image() # Use a fallback random image
277
+
278
+ return raw_image, embeddings_image
279
+
280
+ def los_nlos_classification(file, percentage):
281
+ if file is not None:
282
+ raw_cm_image, emb_cm_image, console_output = process_hdf5_file(file, percentage)
283
+ return raw_cm_image, emb_cm_image, console_output # Returning all three: two images and console output
284
+ else:
285
+ raw_image, embeddings_image = display_predefined_images(percentage)
286
+ return raw_image, embeddings_image, "" # Return an empty string for console output when no file is uploaded
287
+
288
+ # Function to create random images for LoS/NLoS classification results
289
+ def create_random_image(size=(300, 300)):
290
+ random_image = np.random.rand(*size, 3) * 255
291
+ return Image.fromarray(random_image.astype('uint8'))
292
+
293
+ import importlib.util
294
+
295
+ # Function to dynamically load a Python module from a given file path
296
+ def load_module_from_path(module_name, file_path):
297
+ spec = importlib.util.spec_from_file_location(module_name, file_path)
298
+ module = importlib.util.module_from_spec(spec)
299
+ spec.loader.exec_module(module)
300
+ return module
301
+
302
+ # Function to split dataset into training and test sets based on user selection
303
+ def split_dataset(channels, labels, percentage):
304
+ #percentage = percentage_values_los[percentage_idx] / 100
305
+ num_samples = channels.shape[0]
306
+ train_size = int(num_samples * percentage/100)
307
+ print(f'Number of Training Samples: {train_size}')
308
+
309
+ indices = np.arange(num_samples)
310
+ np.random.shuffle(indices)
311
+
312
+ train_idx, test_idx = indices[:train_size], indices[train_size:]
313
+
314
+ train_data, test_data = channels[train_idx], channels[test_idx]
315
+ train_labels, test_labels = labels[train_idx], labels[test_idx]
316
+
317
+ return train_data, test_data, train_labels, test_labels
318
+
319
+ # Function to calculate Euclidean distance between a point and a centroid
320
+ def euclidean_distance(x, centroid):
321
+ return np.linalg.norm(x - centroid)
322
+
323
+ import torch
324
+
325
+ def classify_based_on_distance(train_data, train_labels, test_data):
326
+ # Compute the centroids for the two classes
327
+ centroid_0 = train_data[train_labels == 0].mean(dim=0) # Use torch.mean
328
+ centroid_1 = train_data[train_labels == 1].mean(dim=0) # Use torch.mean
329
+
330
+ predictions = []
331
+ for test_point in test_data:
332
+ # Compute Euclidean distance between the test point and each centroid
333
+ dist_0 = euclidean_distance(test_point, centroid_0)
334
+ dist_1 = euclidean_distance(test_point, centroid_1)
335
+ predictions.append(0 if dist_0 < dist_1 else 1)
336
+
337
+ return torch.tensor(predictions) # Return predictions as a PyTorch tensor
338
+
339
+ def plot_confusion_matrix(y_true, y_pred, title, light_mode=False):
340
+ cm = confusion_matrix(y_true, y_pred)
341
+
342
+ # Calculate F1 Score
343
+ f1 = f1_score(y_true, y_pred, average='weighted')
344
+
345
+ #plt.style.use('dark_background')
346
+
347
+ # Set styling based on light or dark mode
348
+ if light_mode:
349
+ plt.style.use('default') # Light mode styling
350
+ text_color = 'black'
351
+ cmap = 'Blues' # Light-mode-friendly colormap
352
+ else:
353
+ plt.style.use('dark_background') # Dark mode styling
354
+ text_color = 'gray'
355
+ #cmap = 'magma' # Dark-mode-friendly colormap
356
+ cmap = 'coolwarm'
357
+
358
+ plt.figure(figsize=(5, 5))
359
+
360
+ # Plot the confusion matrix with a dark-mode compatible colormap
361
+ sns.heatmap(cm, annot=True, fmt="d", cmap=cmap, cbar=False, annot_kws={"size": 12}, linewidths=0.5, linecolor='white')
362
+
363
+ # Add F1-score to the title
364
+ plt.title(f"{title}\nF1 Score: {f1:.3f}", color=text_color, fontsize=18)
365
+
366
+ # Customize tick labels for dark mode
367
+ plt.xticks([0.5, 1.5], labels=['NLoS', 'LoS'], color=text_color, fontsize=12)
368
+ plt.yticks([0.5, 1.5], labels=['NLoS', 'LoS'], color=text_color, fontsize=12)
369
+
370
+ plt.ylabel('True label', color=text_color, fontsize=14)
371
+ plt.xlabel('Predicted label', color=text_color, fontsize=14)
372
+ plt.tight_layout()
373
+
374
+ # Save the plot as an image
375
+ plt.savefig(f"{title}.png", transparent=True) # Use transparent to blend with the dark mode website
376
+ plt.close()
377
+
378
+ # Return the saved image
379
+ return Image.open(f"{title}.png")
380
+
381
+
382
+ def identical_train_test_split(output_emb, output_raw, labels, train_percentage):
383
+
384
+ torch.manual_seed(42)
385
+
386
+ N = output_emb.shape[0]
387
+ indices = torch.randperm(N)
388
+ test_split_index = int(N * 0.20)
389
+ test_indices = indices[:test_split_index]
390
+ remaining_indices = indices[test_split_index:]
391
+ train_split_index = int(len(remaining_indices) * train_percentage / 100)
392
+ print(f'Training Size: {train_split_index} out of remaining {len(remaining_indices)}')
393
+ print(f'Test Size: {test_split_index}')
394
+
395
+ train_indices = remaining_indices[:train_split_index]
396
+
397
+ train_emb = output_emb[train_indices]
398
+ test_emb = output_emb[test_indices]
399
+
400
+ train_raw = output_raw[train_indices]
401
+ test_raw = output_raw[test_indices]
402
+
403
+ train_labels = labels[train_indices]
404
+ test_labels = labels[test_indices]
405
+
406
+ return train_emb, test_emb, train_raw, test_raw, train_labels, test_labels
407
+
408
+ # Store the original working directory when the app starts
409
+ original_dir = os.getcwd()
410
+
411
+ def process_hdf5_file(uploaded_file, percentage, emb_type='CLS Embedding'):
412
+ capture = PrintCapture()
413
+ sys.stdout = capture # Redirect print statements to capture
414
+
415
+ try:
416
+ model_repo_url = "https://huggingface.co/wi-lab/lwm"
417
+ model_repo_dir = "./LWM"
418
+
419
+ # Step 1: Clone the repository if not already done
420
+ if not os.path.exists(model_repo_dir):
421
+ print(f"Cloning model repository from {model_repo_url}...")
422
+ subprocess.run(["git", "clone", model_repo_url, model_repo_dir], check=True)
423
+
424
+ # Step 2: Verify the repository was cloned and change the working directory
425
+ repo_work_dir = os.path.join(original_dir, model_repo_dir)
426
+ if os.path.exists(repo_work_dir):
427
+ os.chdir(repo_work_dir) # Change the working directory only once
428
+ print(f"Changed working directory to {os.getcwd()}")
429
+ #print(f"Directory content: {os.listdir(os.getcwd())}") # Debugging: Check repo content
430
+ else:
431
+ print(f"Directory {repo_work_dir} does not exist.")
432
+ return
433
+
434
+ # Step 3: Dynamically load lwm_model.py, input_preprocess.py, and inference.py
435
+ lwm_model_path = os.path.join(os.getcwd(), 'lwm_model.py')
436
+ input_preprocess_path = os.path.join(os.getcwd(), 'input_preprocess.py')
437
+ inference_path = os.path.join(os.getcwd(), 'inference.py')
438
+
439
+ # Load lwm_model
440
+ lwm_model = load_module_from_path("lwm_model", lwm_model_path)
441
+
442
+ # Load input_preprocess
443
+ input_preprocess = load_module_from_path("input_preprocess", input_preprocess_path)
444
+
445
+ # Load inference
446
+ inference = load_module_from_path("inference", inference_path)
447
+
448
+ # Step 4: Load the model from lwm_model module
449
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
450
+ print(f"Loading the LWM model on {device}...")
451
+ model = lwm_model.lwm.from_pretrained(device=device).float()
452
+
453
+ # Step 5: Load the HDF5 file and extract the channels and labels
454
+ with h5py.File(uploaded_file.name, 'r') as f:
455
+ channels = np.array(f['channels']).astype(np.complex64)
456
+ labels = np.array(f['labels']).astype(np.int32)
457
+ print(f"Loaded dataset with {channels.shape[0]} samples.")
458
+ channels = channels * (10**(-3-np.floor(np.log10(np.abs(np.mean(channels).real)))))
459
+
460
+ # Step 7: Tokenize the data using the tokenizer from input_preprocess
461
+ preprocessed_chs = input_preprocess.tokenizer(manual_data=channels)
462
+
463
+ # Step 7: Perform inference using the functions from inference.py
464
+ if emb_type == 'Channel Embedding':
465
+ embedding_type = 'channel_emb'
466
+ elif emb_type == 'CLS Embedding':
467
+ embedding_type = 'cls_emb'
468
+
469
+ output_emb = inference.lwm_inference(preprocessed_chs, embedding_type, model, device)
470
+ output_raw = inference.create_raw_dataset(preprocessed_chs, device)
471
+
472
+ print(f"Output Embeddings Shape: {output_emb.shape}")
473
+ print(f"Output Raw Shape: {output_raw.shape}")
474
+
475
+ print(f'percentage_value: {percentage}')
476
+ train_data_emb, test_data_emb, train_data_raw, test_data_raw, train_labels, test_labels = identical_train_test_split(output_emb.view(len(output_emb),-1),
477
+ output_raw.view(len(output_raw),-1),
478
+ labels,
479
+ percentage)
480
+
481
+ # Step 8: Perform classification using the Euclidean distance for both raw and embeddings
482
+ #print(f'train_data_emb: {train_data_emb.shape}')
483
+ #print(f'train_labels: {train_labels.shape}')
484
+ #print(f'test_data_emb: {test_data_emb.shape}')
485
+ pred_raw = classify_based_on_distance(train_data_raw, train_labels, test_data_raw)
486
+ pred_emb = classify_based_on_distance(train_data_emb, train_labels, test_data_emb)
487
+
488
+ # Step 9: Generate confusion matrices for both raw and embeddings
489
+ raw_cm_image = plot_confusion_matrix(test_labels, pred_raw, title="Confusion Matrix (Raw Channels)")
490
+ emb_cm_image = plot_confusion_matrix(test_labels, pred_emb, title="Confusion Matrix (Embeddings)")
491
+
492
+ return raw_cm_image, emb_cm_image, capture.get_output()
493
+
494
+ except Exception as e:
495
+ return str(e), str(e), capture.get_output()
496
+
497
+ finally:
498
+ # Always return to the original working directory after processing
499
+ os.chdir(original_dir)
500
+ sys.stdout = sys.__stdout__ # Reset print statements
501
+
502
+ ######################## Define the Gradio interface ###############################
503
+ js_code = """
504
+ () => {
505
+ const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
506
+ return isDarkMode ? 'dark' : 'light';
507
+ }
508
+ """
509
+
510
+ with gr.Blocks(css="""
511
+ .slider-container {
512
+ display: inline-block;
513
+ margin-right: 50px;
514
+ text-align: center;
515
+ }
516
+
517
+ .explanation-box {
518
+ font-size: 16px;
519
+ font-style: italic;
520
+ color: #4a4a4a;
521
+ padding: 15px;
522
+ background-color: #f0f0f0;
523
+ border-radius: 10px;
524
+ margin-bottom: 20px;
525
+ }
526
+
527
+ .bold-highlight {
528
+ font-weight: bold;
529
+ color: #2c3e50;
530
+ font-size: 18px;
531
+ text-align: center;
532
+ margin-bottom: 20px;
533
+ }
534
+
535
+ #console-output {
536
+ background-color: #ffffff; /* Light background for light mode */
537
+ color: #000000; /* Dark text color for contrast */
538
+ padding: 10px;
539
+ border-radius: 5px;
540
+ }
541
+
542
+ .plot-title {
543
+ font-weight: bold;
544
+ color: #2c3e50;
545
+ }
546
+ """) as demo:
547
+
548
+ # Contact Section
549
+ gr.Markdown("""
550
+ <div style="text-align: center;">
551
+ <a target="_blank" href="https://www.wi-lab.net">
552
+ <img src="https://www.wi-lab.net/wp-content/uploads/2021/08/WI-name.png" alt="Wireless Model" style="height: 30px;">
553
+ </a>
554
+ <a target="_blank" href="mailto:lwmwireless@gmail.com" style="margin-left: 10px;">
555
+ <img src="https://img.shields.io/badge/email-lwmwireless@gmail.com-blue.svg?logo=gmail" alt="Email">
556
+ </a>
557
+ </div>
558
+ """)
559
+
560
+ gr.Markdown("""
561
+ <div class="bold-highlight">
562
+ πŸš€ Explore the pre-trained <b>LWM Model<b> here:
563
+ <a target="_blank" href="https://huggingface.co/wi-lab/lwm">https://huggingface.co/wi-lab/lwm</a>
564
+ </div>
565
+ """)
566
+
567
+ # Tab for Beam Prediction Task
568
+ with gr.Tab("Beam Prediction Task"):
569
+ #gr.Markdown("### Beam Prediction Task")
570
+
571
+ # Explanation section with creative spacing and minimal design
572
+ gr.Markdown("""
573
+ <div style="background-color: var(--primary-background); padding: 15px; border-radius: 10px; color: var(--text-primary);">
574
+ <h3 style="color: var(--text-primary);">πŸ“‘ <b>Sub-6GHz to mmWave Beam Prediction Task</b></h3>
575
+ <ul style="padding-left: 20px;">
576
+ <li><b>🎯 Goal</b>: Predict the strongest <b>mmWave beam</b> from a predefined codebook using Sub-6 GHz channels.</li>
577
+ <li><b>βš™οΈ Adjust Settings</b>: Use the sliders to control the training data percentage and task complexity (beam count) to explore model performance.</li>
578
+ <li><b>🧠 Inferences</b>:
579
+ <ul>
580
+ <li>πŸ” First, the LWM model extracts features.</li>
581
+ <li>πŸ€– Then, the downstream residual 1D-CNN model (500K parameters) makes beam predictions.</li>
582
+ </ul>
583
+ </li>
584
+ <li><b>πŸ—ΊοΈ Dataset</b>: A combination of six scenarios from the DeepMIMO dataset (excluded from LWM pre-training) highlights the model's strong generalization abilities.</li>
585
+ </ul>
586
+ </div>
587
+ """)
588
+
589
+ with gr.Row():
590
+ with gr.Column():
591
+ data_percentage_slider = gr.Slider(label="Data Percentage for Training", minimum=10, maximum=100, step=10, value=10)
592
+ task_complexity_dropdown = gr.Dropdown(label="Task Complexity (Number of Beams)", choices=[16, 32, 64, 128, 256], value=16)
593
+ #theme_dropdown = gr.Dropdown(label="Select Theme", choices=['Light', 'Dark'], value='Light')
594
+
595
+ with gr.Row():
596
+ raw_img_bp = gr.Image(label="Raw Channels", type="pil", width=300, height=500)
597
+ embeddings_img_bp = gr.Image(label="Embeddings", type="pil", width=300, height=500)
598
+
599
+ theme_dropdown = 'Dark'
600
+ # Update the confusion matrices whenever sliders change
601
+ data_percentage_slider.change(fn=beam_prediction_task, inputs=[data_percentage_slider, task_complexity_dropdown], outputs=[raw_img_bp, embeddings_img_bp])
602
+ task_complexity_dropdown.change(fn=beam_prediction_task, inputs=[data_percentage_slider, task_complexity_dropdown], outputs=[raw_img_bp, embeddings_img_bp])
603
+ #theme_dropdown.change(fn=beam_prediction_task, inputs=[data_percentage_slider, task_complexity_dropdown, theme_dropdown], outputs=[raw_img_bp, embeddings_img_bp])
604
+
605
+ # Add a conclusion section at the bottom
606
+ gr.Markdown("""
607
+ <div class="explanation-box">
608
+ The LWM embeddings demonstrate remarkable generalization capabilities, enabling impressive performance even with minimal training samples. This highlights their ability to effectively handle diverse tasks with limited data.
609
+ </div>
610
+ """)
611
+
612
+ # Separate Tab for LoS/NLoS Classification Task
613
+ with gr.Tab("LoS/NLoS Classification Task"):
614
+ #gr.Markdown("### LoS/NLoS Classification Task")
615
+
616
+ # Explanation section with creative spacing
617
+ gr.Markdown("""
618
+ <div style="background-color: var(--primary-background); padding: 15px; border-radius: 10px; color: var(--text-primary);">
619
+ <h3 style="color: var(--text-primary);">πŸ” <b>LoS/NLoS Classification Task</b></h3>
620
+ <ul style="padding-left: 20px;">
621
+ <li><b>🎯 Goal</b>: Classify whether a channel is <b>LoS</b> (Line-of-Sight) or <b>NLoS</b> (Non-Line-of-Sight) with very small LWM CLS embeddings.</li>
622
+ <li><b>πŸ“‚ Dataset</b>: Use the default dataset (a combination of six scenarios from the DeepMIMO dataset) or upload your own dataset in <b>H5</b> format.</li>
623
+ <li><b>πŸ’‘ Custom Dataset Requirements:</b>
624
+ <ul>
625
+ <li>πŸ“‘ <b>channels</b> array: Shape (N,32,32), rows: 32 antennas at BS, columns: 32 subcarriers</li>
626
+ <li>🏷️ <b>labels</b> array: Binary LoS/NLoS values (1/0)</li>
627
+ </ul>
628
+ </li>
629
+ <li><b>πŸ”— Tip 1</b>: Instructions for organizing your dataset are available at the bottom of the page.</li>
630
+ <li><b>πŸ”— Tip 2</b>: As the computations and inference are performed on HuggingFace CPUs, please use small datasets for faster demo experience (say <400 samples). Clone the model from <a href="https://huggingface.co/wi-lab/lwm" target="_blank">here</a> and use any number of samples locally.</li>
631
+ <li><b>πŸ”— Tip 3</b>: Your dataset will be normalized automatically based on outdoor environments. </li>
632
+ <li><b>πŸ’Ό No Downstream Model</b>: Instead of a complex downstream model, we classify each sample based on its distance to the centroid of training samples from each class (LoS/NLoS).</il>
633
+ </ul>
634
+ </div>
635
+ """)
636
+ # Radio button for user choice: predefined data or upload dataset
637
+ choice_radio = gr.Radio(choices=["Use Default Dataset", "Upload Dataset"],
638
+ label="Choose how to proceed",
639
+ value="Use Default Dataset")
640
+
641
+ percentage_slider_los = gr.Slider(minimum=float(percentage_values_los[0]),
642
+ maximum=float(percentage_values_los[-1]),
643
+ step=float((percentage_values_los[-1] - percentage_values_los[0]) / (len(percentage_values_los) - 1)),
644
+ value=float(percentage_values_los[0]),
645
+ label="Percentage of Data for Training",
646
+ interactive=True)
647
+
648
+ # File uploader for dataset (only visible if user chooses to upload a dataset)
649
+ file_input = gr.File(label="Upload HDF5 Dataset", file_types=[".h5"], visible=False)
650
+
651
+ # Dropdown for embedding type, also only visible when "Upload Dataset" is selected
652
+ emb_type = gr.Dropdown(choices=["Channel Embedding", "CLS Embedding"],
653
+ value="CLS Embedding",
654
+ label="Embedding Type",
655
+ visible=False)
656
+
657
+ # Confusion matrices display
658
+ with gr.Row():
659
+ raw_img_los = gr.Image(label="Raw Channels", type="pil", width=300, height=300)
660
+ embeddings_img_los = gr.Image(label="Embeddings", type="pil", width=300, height=300)
661
+ output_textbox = gr.Textbox(label="Console Output", lines=10, elem_id="console-output")
662
+
663
+ # Update the visibility of file_input and emb_type based on user choice
664
+ def toggle_file_input_and_emb_type(choice):
665
+ visible = (choice == "Upload Dataset")
666
+ return gr.update(visible=visible), gr.update(visible=visible)
667
+
668
+ # Change visibility of file input and embedding type dropdown based on choice
669
+ choice_radio.change(fn=toggle_file_input_and_emb_type,
670
+ inputs=[choice_radio],
671
+ outputs=[file_input, emb_type])
672
+
673
+ # When percentage slider changes (for predefined data)
674
+ percentage_slider_los.change(fn=handle_user_choice,
675
+ inputs=[choice_radio, percentage_slider_los, file_input, emb_type],
676
+ outputs=[raw_img_los, embeddings_img_los, output_textbox])
677
+
678
+ # Layout for the UI - this part does NOT need .render(), Gradio will render these automatically
679
+ with gr.Row():
680
+ file_input # No need for .render()
681
+ emb_type # No need for .render()
682
+
683
+ # Add a conclusion section at the bottom
684
+ gr.Markdown("""
685
+ <div class="explanation-box">
686
+ Despite their compact size (1/32 of the raw channels), LWM CLS embeddings capture rich, holistic information about the channels. This makes them exceptionally well-suited for tasks like LoS/NLoS classification, especially when working with very limited data.
687
+ </div>
688
+ """)
689
+
690
+ gr.Markdown("""
691
+ <div class="explanation-box">
692
+ To create a custom dataset, you'll need to structure your data with 32x32 channel matrices, where the rows correspond to antennas at the base station and the columns represent subcarriers. Here’s how to organize and store the channels and labels in an H5 file format for the demo:
693
+ </div>
694
+
695
+ ```python
696
+ # How to pack channels and labels in a h5 file format as a custom dataset for the demo:
697
+ import h5py
698
+ with h5py.File('dataset.h5', 'w') as hdf:
699
+ hdf.create_dataset('channels', data=channels)
700
+ hdf.create_dataset('labels', data=labels)
701
+ print("Dataset saved!")
702
+ """)
703
+ gr.Markdown("""
704
+ <div class="explanation-box">
705
+ To use your preferred DeepMIMO scenarios for the custom dataset, please
706
+ <a href="https://huggingface.co/wi-lab/lwm" target="_blank">clone the model and datasets</a>
707
+ and follow the instructions below:
708
+ </div>
709
+
710
+
711
+ ```python
712
+ from input_preprocess import DeepMIMO_data_gen deepmimo_data_cleaning label_gen # Import required modules from the model repository
713
+ import numpy as np
714
+ scenario_names = np.array([
715
+ "city_18_denver", "city_15_indianapolis", "city_19_oklahoma",
716
+ "city_12_fortworth", "city_11_santaclara", "city_7_sandiego"
717
+ ])
718
+ scenario_name = scenario_names[0] # Select the scenario by choosing its index.
719
+ deepmimo_data = DeepMIMO_data_gen(scenario_name) # Generates ray-traced wireless channels for the selected scenario.
720
+ cleaned_deepmimo_data = deepmimo_data_cleaning(deepmimo_data) # Filters out users with no direct path to the base station (i.e., users with zero-valued channels).
721
+
722
+ channels = np.squeeze(np.array(cleaned_deepmimo_data), axis=1) # The "channels" array is now prepared for packing into the custom dataset in H5 format.
723
+ labels = label_gen('LoS/NLoS Classification', deepmimo_data, scenario_name) # Generates labels for each user, classifying them as Line-of-Sight (LoS) or Non-Line-of-Sight (NLoS), and prepares the "labels" array for inclusion in the custom dataset H5 file.
724
+ ```
725
+ """)
726
+ #with gr.Tab("LWM Model and Framework"):
727
+ # gr.Image("images/lwm_model_v2.png")
728
+ # gr.Markdown("This figure depicts the offline pre-training and online embedding generation process for LWM. The channel is divided into fixed-size patches, which are linearly embedded and combined with positional encodings before being passed through a Transformer encoder. During self-supervised pre-training, some embeddings are masked, and LWM leverages self-attention to extract deep features, allowing the decoder to reconstruct the masked values. For downstream tasks, the generated LWM embeddings enhance performance.")
729
+
730
+ # Launch the app
731
+ if __name__ == "__main__":
732
+ demo.launch(server_name="0.0.0.0", server_port=7860)
733