File size: 5,265 Bytes
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
"""Read Channels4World channel archives with only NumPy and the standard library.

Usage:  python read_archives.py RELEASE_DIR [--band 3.5ghz] [--scenes ID ...] [--limit N]

RELEASE_DIR is the folder you downloaded the release into (it contains payload/).
The script finds every archive under RELEASE_DIR/payload, pairs each channel archive
with its group's positions archive, joins UE IDs to UE positions, and prints the first
retained link of each record it shows. It works with any folder layout, because archive
file names are unique.
"""

import argparse
import io
import tarfile
from collections import defaultdict
from pathlib import Path

import numpy as np


def find_archives(release_dir):
    """Map archive file name -> path for every .tar under RELEASE_DIR/payload."""
    payload = Path(release_dir) / "payload"
    if not payload.is_dir():
        raise SystemExit(f"{payload} not found: pass the folder you downloaded the release into")
    found = defaultdict(list)
    for path in payload.rglob("*.tar"):
        found[path.name].append(path)
    duplicates = {name: paths for name, paths in found.items() if len(paths) > 1}
    if duplicates:
        lines = [f"  {name}: {', '.join(str(p) for p in paths)}" for name, paths in sorted(duplicates.items())]
        raise SystemExit("The same archive appears more than once (mixed downloads or layouts?):\n"
                         + "\n".join(lines))
    return {name: paths[0] for name, paths in found.items()}


def scene_of(member_path):
    """'records/scene=<id>/...' -> '<id>'"""
    return member_path.split("/")[1].removeprefix("scene=")


def npz_members(tar_path, scenes=None):
    """Yield (member_path, arrays) for NPZ members, optionally only for the given scenes."""
    with tarfile.open(tar_path) as tar:
        for member in tar:
            if not (member.isfile() and member.name.endswith(".npz")):
                continue
            if scenes is not None and scene_of(member.name) not in scenes:
                continue                      # skip without reading the member's bytes
            with np.load(io.BytesIO(tar.extractfile(member).read())) as npz:
                yield member.name, {k: npz[k] for k in npz.files if k != "__meta__"}


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("release_dir")
    ap.add_argument("--band", default="3.5ghz", help="3.5ghz or 7ghz (default: 3.5ghz)")
    ap.add_argument("--scenes", nargs="*", help="only these scene IDs (their archives must be downloaded)")
    ap.add_argument("--limit", type=int, default=5,
                    help="stop after printing this many records (default: 5; 0 reads every record)")
    args = ap.parse_args()
    scenes = set(args.scenes) if args.scenes else None

    archives = find_archives(args.release_dir)
    suffix = f"-{args.band}-core.tar"
    core_archives = sorted(name for name in archives if name.endswith(suffix))
    groups = [name.removesuffix(suffix) for name in core_archives]
    missing = [f"{g}-positions.tar" for g in groups if f"{g}-positions.tar" not in archives]
    if missing:
        print(f"Skipping {len(missing)} group(s) whose positions archive is not downloaded:")
        print("\n".join(f"  {name}" for name in missing))
    if not core_archives:
        raise SystemExit(f"No *{suffix} archives under {args.release_dir}/payload")

    printed = seen = 0
    for group in groups:
        if f"{group}-positions.tar" in missing:
            continue
        if args.limit and printed >= args.limit:
            break                                          # stop reading once enough is printed
        positions = {scene_of(m): a for m, a in npz_members(archives[f"{group}-positions.tar"], scenes)}
        records = npz_members(archives[f"{group}{suffix}"], scenes)
        for member, core in records:
            seen += 1
            scene = scene_of(member)
            bs_id = int(member.rsplit("/bs", 1)[1].removesuffix(".npz"))
            pos = positions[scene]
            ue_ids = core["link_ue_index"]                 # retained UE IDs (rows of ue_positions)
            offsets = core["link_path_offsets"]            # link i owns paths offsets[i]:offsets[i+1]
            if ue_ids.size == 0:
                continue
            i = 0                                          # first retained link
            start, stop = offsets[i], offsets[i + 1]
            gain = core["a_real"][start:stop] + 1j * core["a_imag"][start:stop]
            distance = np.linalg.norm(pos["ue_positions"][ue_ids[i]] - pos["bs_positions"][bs_id])
            print(f"{scene} BS {bs_id}: {ue_ids.size} links, {offsets[-1]} paths; "
                  f"UE {ue_ids[i]} at {distance:.1f} m has {stop - start} paths, "
                  f"first delay {core['tau'][start]:.3e} s, |gain| {abs(gain[0]):.3e}")
            printed += 1
            if args.limit and printed >= args.limit:
                records.close()                            # closes the archive
                break
    note = f" (stopped at --limit {args.limit})" if args.limit and printed >= args.limit else ""
    print(f"Read {seen} channel records{note}.")


if __name__ == "__main__":
    main()