File size: 13,599 Bytes
50464c0 a319a4e 50464c0 | 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 | {
"cells": [
{
"cell_type": "markdown",
"id": "cell-00",
"metadata": {},
"source": [
"# From channel records to a DataLoader\n",
"\n",
"This guide turns Channels4World records into fixed-size arrays and a PyTorch `DataLoader`,\n",
"with train, validation and test sets split by scene. It ends at one batch whose contents\n",
"are explained, so you can adapt the inputs and targets to your model, or swap these\n",
"batches into an existing training loop.\n",
"\n",
"The example uses the 100 urban scenes of Tiny (90 train, 10 test), BS 0 at 3.5 GHz. Change the\n",
"selection to scale up; the steps stay the same. Install the library with `pip install channels4world`\n",
"(Python 3.11+), then `pip install torch huggingface_hub`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cell-01",
"metadata": {},
"outputs": [],
"source": [
"from pathlib import Path\n",
"import hashlib\n",
"import json\n",
"\n",
"import numpy as np\n",
"import torch\n",
"from huggingface_hub import snapshot_download\n",
"from torch.utils.data import DataLoader, Dataset\n",
"\n",
"import channels4world as c4w\n",
"from channels4world import transforms as T\n",
"\n",
"REPO, REVISION = \"Intelligence-Networking-Lab/Channels4World\", \"v1.0.0\"\n",
"DATA = Path(\"c4w\")"
]
},
{
"cell_type": "markdown",
"id": "cell-02",
"metadata": {},
"source": [
"## 1. Choose the records\n",
"\n",
"One **sample** here is one retained link: a (scene, carrier, BS, UE) channel. A record holds\n",
"every retained link of one BS at one carrier, so records are read whole and split into\n",
"links. First download Tiny's catalog and the metadata of the five groups that hold its urban\n",
"scenes (about 42 MB), so the library can plan exactly which record files the selection needs:\n",
"here about 0.4 GB."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cell-03",
"metadata": {},
"outputs": [],
"source": [
"snapshot_download(REPO, repo_type=\"dataset\", revision=REVISION, local_dir=DATA, allow_patterns=[\n",
" \"tiny/c4w-root.json\", \"tiny/c4w-root/*\", \"tiny/schema/*\",\n",
" \"tiny/groups/*-urban-g*/catalog/members.parquet\", \"tiny/groups/*-urban-g*/snapshot.json\"])\n",
"\n",
"ds = c4w.open(DATA / \"tiny\")\n",
"selection = ds.select(profile=\"urban\", frequencies_hz=[3_500_000_000], bs_ids=[0],\n",
" components=(\"core\", \"positions\"))\n",
"report = selection.missing()\n",
"print(report)\n",
"if report.files:\n",
" snapshot_download(REPO, repo_type=\"dataset\", revision=REVISION, local_dir=report.local_dir,\n",
" allow_patterns=report.repo_files)\n",
"assert selection.missing().complete"
]
},
{
"cell_type": "markdown",
"id": "cell-04",
"metadata": {},
"source": [
"## 2. Split by scene\n",
"\n",
"Keep the release's train and test split: test scenes are places no training scene shows.\n",
"Take validation scenes from the training split, by scene and never by link, so links of one\n",
"place never sit on both sides. Hashing the scene ID makes the choice reproducible, and\n",
"saving the lists records it."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cell-05",
"metadata": {},
"outputs": [],
"source": [
"def is_validation(scene_id, fraction=0.1):\n",
" return int(hashlib.sha256(scene_id.encode()).hexdigest(), 16) % 1000 < fraction * 1000\n",
"\n",
"splits = {\"train\": [], \"validation\": [], \"test\": []}\n",
"for scene in selection.scenes():\n",
" part = \"test\" if scene.split == \"test\" else (\"validation\" if is_validation(scene.id) else \"train\")\n",
" splits[part].append(scene.id)\n",
"print({k: len(v) for k, v in splits.items()})\n",
"Path(\"splits.json\").write_text(json.dumps(splits, indent=1))"
]
},
{
"cell_type": "markdown",
"id": "cell-06",
"metadata": {},
"source": [
"## 3. From a record to arrays\n",
"\n",
"Each record becomes arrays with one row per link. This is where your own preprocessing goes:\n",
"`inputs` here are the UE position relative to the BS and the BS height; `targets` are the\n",
"strongest 16 paths' delays (ns), powers (dB) and arrival angles, padded to fixed size with a\n",
"mask that marks stored paths. Replace either function to fit your task. `LINKS_PER_RECORD`\n",
"bounds memory by sampling links reproducibly."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cell-07",
"metadata": {},
"outputs": [],
"source": [
"LINKS_PER_RECORD = 512\n",
"PREPROCESSING = \"v1: dxyz+bs_z -> 16 x (delay ns, power dB, cos/sin AoA az, AoA zenith)\"\n",
"\n",
"def inputs(record, positions):\n",
" ue = positions.ue[record.ue_ids].astype(np.float32)\n",
" bs = positions.bs[record.bs_id].astype(np.float32)\n",
" return np.concatenate([ue - bs, np.full((len(ue), 1), bs[2], np.float32)], axis=1) # (links, 4)\n",
"\n",
"def targets(record):\n",
" core = record.core\n",
" power = 10 * np.log10(core[\"a_real\"].astype(np.float64) ** 2 + core[\"a_imag\"].astype(np.float64) ** 2)\n",
" per_path = np.stack([core[\"tau\"] * 1e9, power, np.cos(core[\"phi_r\"]), np.sin(core[\"phi_r\"]),\n",
" core[\"theta_r\"]], axis=1).astype(np.float32) # (paths, 5)\n",
" padded, mask = T.pad_paths(core, per_path) # (links, 16, 5), (links, 16)\n",
" return padded, mask\n",
"\n",
"def arrays(scene_ids):\n",
" rng = np.random.default_rng(0)\n",
" x, y, m, ids = [], [], [], []\n",
" for scene in selection.scenes():\n",
" if scene.id not in scene_ids:\n",
" continue\n",
" positions = scene.read_positions()\n",
" for record in scene.records():\n",
" keep = np.sort(rng.permutation(record.n_links)[:LINKS_PER_RECORD])\n",
" padded, mask = targets(record)\n",
" x.append(inputs(record, positions)[keep]); y.append(padded[keep]); m.append(mask[keep])\n",
" ids += [(scene.id, record.frequency_hz, record.bs_id, int(u)) for u in record.ue_ids[keep]]\n",
" return {\"x\": np.concatenate(x), \"y\": np.concatenate(y), \"mask\": np.concatenate(m),\n",
" \"ids\": np.array(ids, dtype=object)}"
]
},
{
"cell_type": "markdown",
"id": "cell-08",
"metadata": {},
"source": [
"## 4. Cache, then normalize with training statistics only\n",
"\n",
"Converting records takes a while, so save the arrays once. The cache key covers the release,\n",
"the selection, the scene lists of the split and the preprocessing version: change any of them\n",
"(including the validation fraction) and a new cache is built. Loading checks that every cached\n",
"row comes from a scene of its part.\n",
"Normalization is fitted on the training split and then applied unchanged to validation and\n",
"test, so no information leaks from held-out scenes. Target statistics use stored paths only,\n",
"and padded entries stay zero. Keep the statistics to turn predictions back into units."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cell-09",
"metadata": {},
"outputs": [],
"source": [
"recipe = c4w.recipe.dumps(selection.to_recipe(revision=REVISION))\n",
"split_lists = json.dumps(splits, sort_keys=True)\n",
"key = hashlib.sha256(\n",
" f\"{ds.release}|{recipe}|{split_lists}|{PREPROCESSING}|{LINKS_PER_RECORD}\".encode()).hexdigest()[:16]\n",
"cache = Path(\"cache\") / key\n",
"data = {}\n",
"for part, scene_ids in splits.items():\n",
" path = cache / f\"{part}.npz\"\n",
" if not path.exists():\n",
" cache.mkdir(parents=True, exist_ok=True)\n",
" a = arrays(set(scene_ids))\n",
" np.savez(path, x=a[\"x\"], y=a[\"y\"], mask=a[\"mask\"], ids=a[\"ids\"].astype(str))\n",
" with np.load(path) as z:\n",
" data[part] = {k: z[k] for k in z.files}\n",
" assert set(data[part][\"ids\"][:, 0]) <= set(scene_ids), f\"cached {part} rows from other scenes\"\n",
" print(part, data[part][\"x\"].shape, data[part][\"y\"].shape)\n",
"\n",
"train = data[\"train\"]\n",
"stored = train[\"y\"][train[\"mask\"]] # (stored paths, 5)\n",
"stats = {\"x_mean\": train[\"x\"].mean(axis=0), \"x_std\": train[\"x\"].std(axis=0) + 1e-6,\n",
" \"y_mean\": stored.mean(axis=0), \"y_std\": stored.std(axis=0) + 1e-6}\n",
"np.savez(cache / \"normalization.npz\", **stats)\n",
"for part in data.values():\n",
" part[\"x\"] = ((part[\"x\"] - stats[\"x_mean\"]) / stats[\"x_std\"]).astype(np.float32)\n",
" y = (part[\"y\"] - stats[\"y_mean\"]) / stats[\"y_std\"]\n",
" part[\"y\"] = np.where(part[\"mask\"][..., None], y, 0).astype(np.float32)"
]
},
{
"cell_type": "markdown",
"id": "cell-10",
"metadata": {},
"source": [
"## 5. A Dataset and a DataLoader\n",
"\n",
"Every sample has the same shape, so PyTorch's default collate function batches them. Shuffle\n",
"the training set; keep validation and test in order."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cell-11",
"metadata": {},
"outputs": [],
"source": [
"class LinkDataset(Dataset):\n",
" def __init__(self, part):\n",
" self.x = torch.from_numpy(part[\"x\"])\n",
" self.y = torch.from_numpy(part[\"y\"])\n",
" self.mask = torch.from_numpy(part[\"mask\"])\n",
"\n",
" def __len__(self):\n",
" return len(self.x)\n",
"\n",
" def __getitem__(self, i):\n",
" return {\"x\": self.x[i], \"y\": self.y[i], \"mask\": self.mask[i]}\n",
"\n",
"loaders = {part: DataLoader(LinkDataset(data[part]), batch_size=256, shuffle=(part == \"train\"))\n",
" for part in data}\n",
"batch = next(iter(loaders[\"train\"]))\n",
"for name, value in batch.items():\n",
" print(f\"{name:5s} {tuple(value.shape)} {value.dtype}\")"
]
},
{
"cell_type": "markdown",
"id": "cell-12",
"metadata": {},
"source": [
"## 6. What a batch holds\n",
"\n",
"- `x` (batch, 4): the UE position relative to the BS, in metres, and the BS height,\n",
" normalized with training statistics.\n",
"- `y` (batch, 16, 5): up to 16 paths per link, strongest first; per path the delay in ns, the\n",
" power in dB relative to unit power, the cosine and sine of the arrival azimuth and the\n",
" arrival zenith in radians, each normalized with the training split's stored paths.\n",
"- `mask` (batch, 16): true where a path is stored. Padded paths are zeros: use the mask in\n",
" every loss and metric so they never count as weak paths.\n",
"\n",
"The saved `ids` (scene, carrier, BS, UE) tie each row back to its record."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cell-13",
"metadata": {},
"outputs": [],
"source": [
"paths = data[\"train\"][\"mask\"].sum(axis=1)\n",
"print(\"stored paths per link: min\", paths.min(), \"mean\", round(float(paths.mean()), 1), \"max\", paths.max())\n",
"\n",
"def masked_mse(prediction, target, mask):\n",
" error = ((prediction - target) ** 2).mean(dim=-1) # (batch, 16)\n",
" return (error * mask).sum() / mask.sum().clamp(min=1)\n",
"\n",
"# Predicting the training mean (zero after normalization) gives a masked MSE near 1.\n",
"print(\"masked MSE of predicting the mean:\",\n",
" round(float(masked_mse(torch.zeros_like(batch[\"y\"]), batch[\"y\"], batch[\"mask\"])), 3))"
]
},
{
"cell_type": "markdown",
"id": "cell-14",
"metadata": {},
"source": [
"## Adapt it\n",
"\n",
"- **Other inputs:** add the carrier, the scene geometry (`scene.open_geometry()`), or the\n",
" channel at the other carrier for cross-band tasks; keep them per link.\n",
"- **Other targets:** use the complex coefficients, departure angles, the frequency response\n",
" (`T.frequency_response`) or the interaction detail (`components=(\"core\", \"detail\")`,\n",
" `T.pad_interactions`).\n",
"- **More data:** widen the selection (`tier=\"small\"` on the release catalog, other profiles or\n",
" BSs) and raise `LINKS_PER_RECORD`; the [library guide](https://huggingface.co/datasets/Intelligence-Networking-Lab/Channels4World/blob/main/docs/library-guide.md) plans TAR\n",
" downloads, and `c4w.to_cache` keeps records memory-mapped for repeated reads.\n",
"- **Shuffling at scale:** records are stored in groups of 25 scenes; shuffle groups or scenes\n",
" and read each one's records together, as above.\n",
"- **Records instead of links:** `channels4world.torch.RecordDataset(selection, transform=...)`\n",
" yields one record per item and reopens the dataset in each worker process."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|