Channels4World / docs /tutorial-numpy.md
INL-Yonsei's picture
1.0.0 release
50464c0
|
Raw History Blame Contribute Delete
9.28 kB
# Read one scene without the library
The same link as the [library tutorial](tutorial-library.md), **BS 0 → UE 14 of
`urban_scene_019234` at 3.5 GHz**, read with NumPy and the standard library from Tiny's loose
files: about 15 MB. The [notebook version](notebooks/02-read-one-scene-numpy.ipynb) runs top
to bottom. Archives from larger tiers hold the same files; see
[without the library](without-library.md) for TAR access.
Install with `pip install numpy huggingface_hub matplotlib`.
```python
from pathlib import Path
import json
import zipfile
import matplotlib.pyplot as plt
import numpy as np
from huggingface_hub import snapshot_download
from matplotlib.collections import PolyCollection
```
## 1. Choose the link
The same identifiers as the library tutorial. A UE ID is a row of `ue_positions`, and the BS
ID is both a row of `bs_positions` and the number in the record's file name.
```python
REPO, REVISION = "Intelligence-Networking-Lab/Channels4World", "v1.0.0"
SCENE_ID, GROUP = "urban_scene_019234", "test-urban-g00000" # GROUP: from the tiny_scenes catalog
CARRIER_HZ, BS_ID, UE_ID = 3_500_000_000, 0, 14
OTHER_HZ = 7_000_000_000
DATA = Path("c4w")
```
## 2. Download the scene's files
NumPy needs only the record files: positions, geometry, and BS 0's core and detail at both
carriers.
```python
scene_dir = DATA / "tiny" / "records" / f"scene={SCENE_ID}"
remote = f"tiny/records/scene={SCENE_ID}"
snapshot_download(REPO, repo_type="dataset", revision=REVISION, local_dir=DATA, allow_patterns=[
f"{remote}/positions.npz", f"{remote}/geometry.zip", f"{remote}/band_hz=*/component=*/bs{BS_ID:05d}.npz"])
def record_path(carrier_hz, component):
return scene_dir / f"band_hz={carrier_hz}" / f"component={component}" / f"bs{BS_ID:05d}.npz"
print(sorted(p.relative_to(scene_dir).as_posix() for p in scene_dir.rglob("*") if p.is_file()))
```
## 3. The hierarchy on disk
Each scene folder holds `positions.npz` and `geometry.zip`, shared by both carriers, and one
file per carrier, component and BS: `band_hz=<Hz>/component=<core|detail>/bs<NNNNN>.npz`.
Every NPZ carries its identity in a JSON `__meta__` entry:
```python
with np.load(record_path(CARRIER_HZ, "core"), allow_pickle=False) as npz:
meta = json.loads(npz["__meta__"].item())
print(json.dumps(meta["identity"], indent=1))
print(meta["dimensions"]) # retained links and paths in this record
```
## 4. Geometry and positions
Geometry, positions and interaction points share one frame: scene metres, z up.
```python
with np.load(scene_dir / "positions.npz", allow_pickle=False) as positions:
bs_positions, ue_positions = positions["bs_positions"], positions["ue_positions"]
bs_xyz, ue_xyz = bs_positions[BS_ID], ue_positions[UE_ID]
print(bs_positions.shape, ue_positions.shape)
print("BS", bs_xyz, "UE", ue_xyz, f"distance {np.linalg.norm(ue_xyz - bs_xyz):.1f} m")
def top_view(read, names):
"""Building triangles projected onto the ground (x, y), from OBJ meshes."""
triangles = []
for name in names:
verts, faces = [], []
for line in read(name).decode().splitlines():
if line.startswith("v "):
verts.append([float(v) for v in line.split()[1:4]])
elif line.startswith("f "):
idx = [int(t.split("/")[0]) for t in line.split()[1:]]
faces += [[idx[0], idx[k], idx[k + 1]] for k in range(1, len(idx) - 1)]
v = np.array(verts)
triangles += [v[[i - 1 for i in f], :2] for f in faces] # OBJ indices start at 1
return triangles
with zipfile.ZipFile(scene_dir / "geometry.zip") as geometry:
print("entry point:", json.loads(geometry.read("scene.json"))["entrypoint"])
meshes = [n for n in geometry.namelist() if n.endswith(".obj") and "ground" not in n]
triangles = top_view(geometry.read, meshes)
print(len(meshes), "building meshes")
```
```python
fig, ax = plt.subplots(figsize=(6, 6))
ax.add_collection(PolyCollection(triangles, facecolor="#c3cbc2", edgecolor="none"))
ax.scatter(ue_positions[:, 0], ue_positions[:, 1], s=0.2, color="#4d9688", label=f"{len(ue_positions):,} UEs")
ax.scatter(bs_positions[:, 0], bs_positions[:, 1], marker="^", s=30, color="k", label=f"{len(bs_positions)} BSs")
ax.plot(*zip(bs_xyz[:2], ue_xyz[:2]), color="#e2733d", lw=2, label=f"BS {BS_ID} → UE {UE_ID}")
ax.set(xlim=(-250, 250), ylim=(-250, 250), aspect="equal", xlabel="x (m)", ylabel="y (m)", title=SCENE_ID)
ax.legend(loc="upper right")
plt.show()
```
## 5. Find the link
`link_ue_index` lists the UEs this BS reaches, in ascending order; the link's row is where
`UE_ID` sits in that list. Link `row` owns paths `link_path_offsets[row]` to
`link_path_offsets[row + 1]`. A UE that is not listed has no retained link to this BS (not a
zero-valued channel).
```python
def load(carrier_hz, component):
with np.load(record_path(carrier_hz, component), allow_pickle=False) as npz:
return {name: npz[name] for name in npz.files if name != "__meta__"}
def link_of(core, detail, ue_id):
ue_ids = core["link_ue_index"]
row = int(np.searchsorted(ue_ids, ue_id))
if row == ue_ids.size or ue_ids[row] != ue_id:
return None # no retained link to this UE
p0, p1 = map(int, core["link_path_offsets"][row:row + 2])
link_core = {k: v[p0:p1] for k, v in core.items() if k not in ("link_ue_index", "link_path_offsets")}
i0, i1 = map(int, detail["path_interaction_offsets"][[p0, p1]])
link_detail = {k: detail[k][i0:i1] for k in ("interaction_rank", "interaction_type", "interaction_vertex")}
link_detail["path_interaction_offsets"] = detail["path_interaction_offsets"][p0:p1 + 1] - i0
return row, link_core, link_detail
core, detail = load(CARRIER_HZ, "core"), load(CARRIER_HZ, "detail")
row, link_core, link_detail = link_of(core, detail, UE_ID)
print(f"UE {UE_ID}: link row {row} of {core['link_ue_index'].size}, {link_core['tau'].size} paths")
```
## 6. What each path stores
The same arrays as in the library tutorial: the complex coefficient `a_real + 1j*a_imag`
(passband, without the carrier-delay phase, antennas included), the delay `tau` in seconds,
departure and arrival angles in radians and, in detail, each interaction's type and location
in order. Paths are stored strongest first, at most 16 per link above −150 dB.
```python
NAMES = {1: "specular reflection", 2: "diffuse reflection", 4: "refraction", 8: "diffraction"}
def describe(core, detail):
"""One line per retained path, strongest first."""
re, im = core["a_real"].astype(np.float64), core["a_imag"].astype(np.float64)
power_db = 10 * np.log10(re**2 + im**2)
off = detail["path_interaction_offsets"]
for p in range(len(core["tau"])):
kinds = [NAMES.get(int(t), str(t)) for t in detail["interaction_type"][off[p]:off[p + 1]]]
print(f"rank {int(core['path_rank'][p]):2d} {core['tau'][p] * 1e9:8.2f} ns {power_db[p]:7.2f} dB "
f"AoD az {np.degrees(core['phi_t'][p]):6.1f}° AoA az {np.degrees(core['phi_r'][p]):6.1f}° "
f"{' → '.join(kinds) or 'line of sight'}")
describe(link_core, link_detail)
```
## 7. A power–delay profile
Placing each path by delay and power gives the link's power–delay profile: a path-based view
of the stored channel, not a sampled impulse response.
```python
def stems(ax, tau, a_real, a_imag, label, marker, color):
power_db = 10 * np.log10(a_real.astype(np.float64)**2 + a_imag.astype(np.float64)**2)
ax.vlines(tau * 1e9, -150, power_db, color=color, lw=1.2)
ax.scatter(tau * 1e9, power_db, marker=marker, color=color, zorder=3, label=label)
fig, ax = plt.subplots(figsize=(7, 3))
stems(ax, link_core["tau"], link_core["a_real"], link_core["a_imag"], "3.5 GHz", "o", "#e2733d")
ax.set(xlabel="delay (ns)", ylabel="path power (dB)", ylim=(-150, None),
title=f"{SCENE_ID} · BS {BS_ID} → UE {UE_ID}")
ax.legend()
plt.show()
```
## 8. The same link at 7 GHz
```python
other = link_of(load(OTHER_HZ, "core"), load(OTHER_HZ, "detail"), UE_ID)
fig, ax = plt.subplots(figsize=(7, 3))
stems(ax, link_core["tau"], link_core["a_real"], link_core["a_imag"], "3.5 GHz", "o", "#e2733d")
if other is None:
print("UE", UE_ID, "has no retained link at 7 GHz")
else:
_, core7, _ = other
stems(ax, core7["tau"], core7["a_real"], core7["a_imag"], "7 GHz", "s", "#4d9688")
for c, label in ((link_core, "3.5 GHz"), (core7, "7 GHz")):
power = np.sum(c["a_real"].astype(np.float64) ** 2 + c["a_imag"].astype(np.float64) ** 2)
print(f"{label}: {c['tau'].size} paths, link power {10 * np.log10(power):.2f} dB")
ax.set(xlabel="delay (ns)", ylabel="path power (dB)", ylim=(-150, None))
ax.legend()
plt.show()
```
Ranks order the paths within one record, so the same rank at 3.5 and 7 GHz need not be
the same route. Compare delays, interaction sequences or interaction points instead.
## Next
- [Without the library](without-library.md): TAR archives, catalogs and byte-range reads.
- [Schema reference](schema-reference.md): every array, its dtype and its meaning.
*Notebook: [02-read-one-scene-numpy.ipynb](notebooks/02-read-one-scene-numpy.ipynb). The page and the notebook hold the same code.*
[Return to card](../README.md)