Compare commits

..

18 Commits
v0.1.0 ... main

Author SHA1 Message Date
0ca66e886a fixed syntax
All checks were successful
Modulation Recognition Demo / ria-demo (push) Successful in 5m4s
2025-08-22 13:30:54 -04:00
9f8a583857 reduced number of epochs
All checks were successful
Modulation Recognition Demo / ria-demo (push) Successful in 3m24s
2025-08-22 13:16:32 -04:00
6b4e39e5be reverted back to fallback
Some checks failed
Modulation Recognition Demo / ria-demo (push) Has been cancelled
2025-08-22 13:11:08 -04:00
145f80849f deleted the check
Some checks failed
Modulation Recognition Demo / ria-demo (push) Failing after 33s
2025-08-22 11:06:29 -04:00
45a5f81c8c added init.py
All checks were successful
Modulation Recognition Demo / ria-demo (push) Successful in 14m27s
2025-08-22 10:00:04 -04:00
50e8912f73 debug
Some checks failed
Modulation Recognition Demo / ria-demo (push) Failing after 39s
2025-08-22 09:57:01 -04:00
af2d3fae90 reverted back to ahving a fall back
Some checks failed
Modulation Recognition Demo / ria-demo (push) Failing after 30s
2025-08-22 09:54:22 -04:00
71a1559dca adjusted workflow
Some checks failed
Modulation Recognition Demo / ria-demo (push) Failing after 40s
2025-08-22 09:51:51 -04:00
3a6e2ceac2 fixed syntax
Some checks failed
Modulation Recognition Demo / ria-demo (push) Failing after 32s
2025-08-22 09:46:43 -04:00
27f6ba306f adjusted parameters
Some checks failed
Modulation Recognition Demo / ria-demo (push) Failing after 46s
2025-08-22 09:42:16 -04:00
7c7a882f1f Merge pull request 'liyu-dev' (#3) from liyu-dev into main
Some checks failed
Modulation Recognition Demo / ria-demo (push) Has been cancelled
Reviewed-on: https://git.riahub.ai/qoherent/modrec-workflow/pulls/3
2025-08-21 11:05:55 -04:00
bf43d31225 adjusted default params
Some checks failed
Modulation Recognition Demo / ria-demo (pull_request) Has been cancelled
2025-08-21 10:56:56 -04:00
04e5f4db8a clean up code, adjusted default parameters 2025-08-21 10:56:23 -04:00
a298384f7e switched back to older support
All checks were successful
Modulation Recognition Demo / ria-demo (pull_request) Successful in 2m42s
2025-08-21 10:49:04 -04:00
18fac1de15 fixed workflow
Some checks failed
Modulation Recognition Demo / ria-demo (pull_request) Failing after 30s
2025-08-21 10:47:25 -04:00
fe952b8eb6 Linting, removed hard-coded values, sped up upload times for files
Some checks failed
Modulation Recognition Demo / ria-demo (pull_request) Failing after 1m25s
2025-08-21 10:44:32 -04:00
1c7ddef5cb formatting 2025-08-21 10:33:50 -04:00
6d531ae5f3 added in confusion matrix for the output
All checks were successful
Modulation Recognition Demo / ria-demo (push) Successful in 2m46s
2025-07-09 15:39:20 -04:00
11 changed files with 81 additions and 67 deletions

View File

@ -2,11 +2,9 @@ name: Modulation Recognition Demo
on:
push:
branches:
[main]
branches: [main]
pull_request:
branches:
[main]
branches: [main]
jobs:
ria-demo:
@ -46,17 +44,19 @@ jobs:
fi
pip install -r requirements.txt
- name: 1. Generate Recordings
run: |
mkdir -p data/recordings
PYTHONPATH=. python scripts/dataset_manager/data_gen.py --output-dir data/recordings
- name: 📦 Compress Recordings
run: tar -czf recordings.tar.gz -C data/recordings .
- name: ⬆️ Upload recordings
uses: actions/upload-artifact@v3
with:
name: recordings
path: data/recordings/**
path: recordings.tar.gz
- name: 2. Build HDF5 Dataset
run: |
@ -113,7 +113,7 @@ jobs:
uses: actions/upload-artifact@v3
with:
name: profile-data
path: '**/onnxruntime_profile_*.json'
path: "**/onnxruntime_profile_*.json"
- name: 7. Convert ONNX graph to an ORT file
run: |

View File

@ -24,7 +24,7 @@ dataset:
snr_step: 3
# Number of iterations (signal recordings) per modulation and SNR combination
num_iterations: 3
num_iterations: 10
# Modulation scheme settings; keys must match the `modulation_types` list above
# Each entry includes:

0
helpers/__init__.py Normal file
View File

View File

@ -41,7 +41,11 @@ class AppConfig:
class AppSettings:
"""Application settings, to be initialized from app.yaml configuration file."""
"""
Application settings,
to be initialized from
app.yaml configuration file.
"""
def __init__(self, config_file: str):
# Load the YAML configuration file

View File

@ -2,9 +2,9 @@ import os
import numpy as np
import torch
from scripts.model_builder.mobilenetv3 import RFClassifier, mobilenetv3
from helpers.app_settings import get_app_settings
from scripts.model_builder.mobilenetv3 import RFClassifier, mobilenetv3
def convert_to_onnx(ckpt_path: str, fp16: bool = False) -> None:
@ -21,7 +21,7 @@ def convert_to_onnx(ckpt_path: str, fp16: bool = False) -> None:
in_channels = 2
batch_size = 1
slice_length = int(1024 / dataset_cfg.num_slices)
slice_length = int(dataset_cfg.recording_length / dataset_cfg.num_slices)
num_classes = len(dataset_cfg.modulation_types)
model = RFClassifier(
@ -42,7 +42,7 @@ def convert_to_onnx(ckpt_path: str, fp16: bool = False) -> None:
model.eval()
# Generate random sample data
base, ext = os.path.splitext(os.path.basename(ckpt_path))
base, _ = os.path.splitext(os.path.basename(ckpt_path))
if fp16:
output_path = os.path.join("onnx_files", f"{base}.onnx")
sample_input = torch.from_numpy(

View File

@ -29,7 +29,7 @@ def generate_modulated_signals(output_dir: str) -> None:
for modulation in settings.modulation_types:
for snr in np.arange(settings.snr_start, settings.snr_stop, settings.snr_step):
for i in range(3):
for _ in range(settings.num_iterations):
recording_length = settings.recording_length
beta = (
settings.beta

View File

@ -49,8 +49,6 @@ def write_hdf5_file(records: List, output_path: str, dataset_name: str = "data")
int(md["sps"]),
)
first_rec, _ = records[0] # records[0] is a tuple of (data, md)
with h5py.File(output_path, "w") as hf:
data_arr = np.stack([rec[0] for rec in records])
dset = hf.create_dataset(dataset_name, data=data_arr, compression="gzip")

View File

@ -90,7 +90,7 @@ def split_recording(
snippet_list = []
for data, md in recording_list:
C, N = data.shape
_, N = data.shape
L = N // num_snippets
for i in range(num_snippets):
start = i * L

View File

@ -1,5 +1,4 @@
import lightning as L
import numpy as np
import timm
import torch
from torch import nn

View File

@ -2,26 +2,26 @@ import os
import numpy as np
import torch
from sklearn.metrics import classification_report
os.environ["NNPACK"] = "0"
from matplotlib import pyplot as plt
from mobilenetv3 import RFClassifier, mobilenetv3
from modulation_dataset import ModulationH5Dataset
from sklearn.metrics import classification_report
from helpers.app_settings import get_app_settings
os.environ["NNPACK"] = "0"
def load_validation_data():
val_dataset = ModulationH5Dataset(
"data/dataset/val.h5", label_name="modulation", data_key="validation_data"
)
X = np.stack([x.numpy() for x, _ in val_dataset]) # shape: (N, C, L)
x = np.stack([x.numpy() for x, _ in val_dataset]) # shape: (N, C, L)
y = np.array([y.item() for _, y in val_dataset]) # shape: (N,)
class_names = list(val_dataset.label_encoder.classes_)
return X, y, class_names
return x, y, class_names
def build_model_from_ckpt(
@ -75,7 +75,7 @@ def evaluate_checkpoint(ckpt_path: str):
classification_report(y_true, y_pred, target_names=class_names, zero_division=0)
)
plot_confusion_matrix_with_counts(
print_confusion_matrix(
y_true=np.array(y_true),
y_pred=np.array(y_pred),
classes=class_names,
@ -84,7 +84,7 @@ def evaluate_checkpoint(ckpt_path: str):
)
def plot_confusion_matrix_with_counts(
def print_confusion_matrix(
y_true: np.ndarray,
y_pred: np.ndarray,
classes: list[str],
@ -94,6 +94,7 @@ def plot_confusion_matrix_with_counts(
"""
Plot a confusion matrix showing both raw counts and (optionally) normalized values.
Args:
y_true: true labels (integers 0..C-1)
y_pred: predicted labels (same shape as y_true)
@ -102,8 +103,8 @@ def plot_confusion_matrix_with_counts(
title: title for the plot
"""
# 1) build raw CM
C = len(classes)
cm = np.zeros((C, C), dtype=int)
c = len(classes)
cm = np.zeros((c, c), dtype=int)
for t, p in zip(y_true, y_pred):
cm[t, p] += 1
@ -112,33 +113,48 @@ def plot_confusion_matrix_with_counts(
with np.errstate(divide="ignore", invalid="ignore"):
cm_norm = cm.astype(float) / cm.sum(axis=1)[:, None]
cm_norm = np.nan_to_num(cm_norm)
print_confusion_matrix_helper(cm_norm, classes)
else:
cm_norm = cm
print_confusion_matrix_helper(cm, classes)
# 3) plot
fig, ax = plt.subplots(figsize=(8, 8))
im = ax.imshow(cm_norm, interpolation="nearest")
ax.set_title(title)
ax.set_xlabel("Predicted label")
ax.set_ylabel("True label")
ax.set_xticks(np.arange(C))
ax.set_yticks(np.arange(C))
ax.set_xticklabels(classes, rotation=45, ha="right")
ax.set_yticklabels(classes)
# 4) annotate
for i in range(C):
for j in range(C):
count = cm[i, j]
val = cm_norm[i, j]
txt = f"{count}\n{val:.2f}"
ax.text(j, i, txt, ha="center", va="center")
import numpy as np
fig.colorbar(im, ax=ax, label="Normalized value" if normalize else "Count")
plt.tight_layout()
plt.show()
def print_confusion_matrix_helper(matrix, classes=None, normalize=False, digits=2):
"""
Pretty prints a confusion matrix with x/y labels.
Parameters:
- matrix: square 2D numpy array
- labels: list of class labels (default: range(num_classes))
- normalize: whether to normalize rows to sum to 1
- digits: number of decimal places to show for normalized values
"""
matrix = np.array(matrix)
num_classes = matrix.shape[0]
labels = classes or list(range(num_classes))
# Header
print(" " * 9 + "Ground Truth →")
header = "Pred ↓ | " + " ".join([f"{str(label):>6}" for label in labels])
print(header)
print("-" * len(header))
# Rows
for i in range(num_classes):
row_vals = matrix[i]
if normalize:
row_sum = row_vals.sum()
row_vals = row_vals / row_sum if row_sum != 0 else row_vals
row_str = " ".join([f"{val:>6.{digits}f}" for val in row_vals])
else:
row_str = " ".join([f"{int(val):>6}" for val in row_vals])
print(f"{str(labels[i]):>7} | {row_str}")
if __name__ == "__main__":
settings = get_app_settings()
evaluate_checkpoint(os.path.join("checkpoint_files", "inference_recognition_model.ckpt"))
evaluate_checkpoint(
os.path.join("checkpoint_files", "inference_recognition_model.ckpt")
)

View File

@ -1,23 +1,22 @@
import os
import sys
os.environ["NNPACK"] = "0"
import lightning as L
import mobilenetv3
import torch
import torch.nn.functional as F
import torchmetrics
from lightning.pytorch.callbacks import ModelCheckpoint
from lightning.pytorch.callbacks import ModelCheckpoint, TQDMProgressBar
from modulation_dataset import ModulationH5Dataset
from helpers.app_settings import get_app_settings
os.environ["NNPACK"] = "0"
script_dir = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.abspath(os.path.join(script_dir, ".."))
project_root = os.path.abspath(os.path.join(os.getcwd(), ".."))
if project_root not in sys.path:
sys.path.insert(0, project_root)
from lightning.pytorch.callbacks import TQDMProgressBar
class CustomProgressBar(TQDMProgressBar):
@ -59,8 +58,6 @@ def train_model():
print("X shape:", x.shape)
print("Y values:", y[:10])
break
unique_labels = list(set([row[label].decode("utf-8") for row in ds_train.metadata]))
num_classes = len(ds_train.label_encoder.classes_)
hparams = {