File size: 9,014 Bytes
690fde9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Dataset generation for both pipeline consumers (blueprint steps 2 and 3).

* ``sample_components`` / ``synthesize_h1``: raw random components
  (messages X, collaboration noise A, channels, receiver noise) and the
  linear synthesis Y_E = G (F_q(W X + A)) + N.  Policy optimization (PSGD /
  GA-PSGD) calls these with fresh RNGs per minibatch and with frozen
  common-random-number sets for held-out evaluation.

* ``eve_dataset``: balanced, shuffled H0/H1 received blocks under a frozen
  policy W for training/evaluating the transformer Eve.  H0 blocks contain
  receiver noise only; H1 blocks contain pilots, prefixes, data, and
  collaboration noise (blueprint Section 4).

Seeding: every shard derives its own ``np.random.SeedSequence`` from
(master_seed, format_id, snr_mdB, split_id, role), so train/val/test and all
shards are mutually independent and each shard is reproducible in isolation.
"""

from __future__ import annotations

import numpy as np

from .affine import AffineOperators, scramble_phases
from .channel import (
    block_channels,
    block_doppler_coef,
    block_taps,
    cn,
    exp_pdp,
    jakes_doppler,
    receive,
    receive_doubly_dispersive,
    receive_multipath,
    sigma2_from_snr,
)
from .config import SystemConfig
from .constellations import draw_symbols
from .formats.base import Waveform

SPLIT_IDS = {"train": 0, "val": 1, "test": 2}

# role tags inside a shard's seed tree
_ROLE_H1, _ROLE_H0, _ROLE_SHUFFLE, _ROLE_COMPONENTS, _ROLE_SCRAMBLE = 0, 1, 2, 3, 4


def shard_seed(master_seed: int, format_id: int, snr_db: float, split: str, role: int) -> np.random.SeedSequence:
    snr_key = int(round(snr_db * 1000)) % (2**32)
    return np.random.SeedSequence([master_seed, format_id, snr_key, SPLIT_IDS[split], role])


# --------------------------------------------------------------------------
# Raw components (policy-design stage)
# --------------------------------------------------------------------------

def sample_components(cfg: SystemConfig, rng: np.random.Generator, n_blocks: int,
                     bob_gains=None, eve_gains=None) -> dict:
    """Draw all H1 randomness except the policy: X, A, G_eve, H_bob, noises.

    bob_gains / eve_gains: optional (M,) per-user large-scale power gains (the
    selected users' path-loss/shadowing to Bob / Eve).  Small-scale fading stays
    CN(0,1); the gains scale each user's channel column by sqrt(gain).  Used by
    subset selection, where users are heterogeneous.
    """
    # draw in the original order (X, A, G_eve, H_bob, N_eve, N_bob) so gains=None
    # reproduces pre-existing data bit-exactly; apply gains only afterward.
    x = draw_symbols(rng, cfg.constellation, (n_blocks, cfg.kd, cfg.n_data))
    a = np.sqrt(cfg.sigma_a2) * cn(rng, (n_blocks, cfg.n_tx, cfg.n_data))
    if cfg.nu_max > 0:  # doubly-dispersive: (b, R, M, L, D) Doppler coefficients
        pdp = exp_pdp(cfg.n_taps, cfg.pdp_decay)
        _, q = jakes_doppler(cfg.n_doppler, cfg.nu_max)
        g_eve = block_doppler_coef(rng, n_blocks, cfg.n_rx_eve, cfg.n_tx, pdp, q)
        h_bob = block_doppler_coef(rng, n_blocks, cfg.n_rx_bob, cfg.n_tx, pdp, q)
    elif cfg.n_taps > 1:  # frequency-selective: channels are (b, R, M, L) taps
        pdp = exp_pdp(cfg.n_taps, cfg.pdp_decay)
        g_eve = block_taps(rng, n_blocks, cfg.n_rx_eve, cfg.n_tx, pdp)
        h_bob = block_taps(rng, n_blocks, cfg.n_rx_bob, cfg.n_tx, pdp)
    else:  # flat single-tap (bit-exact legacy)
        g_eve = block_channels(rng, n_blocks, cfg.n_rx_eve, cfg.n_tx)
        h_bob = block_channels(rng, n_blocks, cfg.n_rx_bob, cfg.n_tx)
    n_eve = cn(rng, (n_blocks, cfg.n_rx_eve, cfg.n_samples))  # unit variance; scale by sigma
    n_bob = cn(rng, (n_blocks, cfg.n_rx_bob, cfg.n_samples))
    # per-user gains scale each Tx column (axis 2); trailing tap/Doppler axes broadcast
    xdim = g_eve.ndim - 3  # 0 (flat), 1 (multipath), or 2 (doubly-dispersive)
    if eve_gains is not None:
        eg = np.sqrt(np.asarray(eve_gains)).reshape((1, 1, cfg.n_tx) + (1,) * xdim)
        g_eve = g_eve * eg
    if bob_gains is not None:
        bg = np.sqrt(np.asarray(bob_gains)).reshape((1, 1, cfg.n_tx) + (1,) * xdim)
        h_bob = h_bob * bg
    return {"X": x, "A": a, "G_eve": g_eve, "H_bob": h_bob, "N_eve": n_eve, "N_bob": n_bob}


def collaborate(w: np.ndarray, x: np.ndarray, a: np.ndarray) -> np.ndarray:
    """S = W X + A for batched blocks: (m,kd) @ (b,kd,n) + (b,m,n)."""
    return np.einsum("mk,bkn->bmn", w, x) + a


def _through_channel(h: np.ndarray, u: np.ndarray, noise: np.ndarray, cfg=None) -> np.ndarray:
    """Flat (3-D h), multipath (4-D taps), or doubly-dispersive (5-D Doppler coef)."""
    if h.ndim == 5:
        nu, _ = jakes_doppler(cfg.n_doppler, cfg.nu_max)
        return receive_doubly_dispersive(h, nu, u, noise)
    return receive_multipath(h, u, noise) if h.ndim == 4 else receive(h, u, noise)


def synthesize_h1(fmt: Waveform, w: np.ndarray, comp: dict, sigma2_eve: float) -> np.ndarray:
    """Eve's H1 received blocks from components: G (F_q(W X + A)) + sigma N."""
    u = fmt.modulate(collaborate(w, comp["X"], comp["A"]))
    return _through_channel(comp["G_eve"], u, np.sqrt(sigma2_eve) * comp["N_eve"], fmt.cfg)


def synthesize_h1_ctrl(ops, w, comp, sigma2_eve, beta, scramble) -> np.ndarray:
    """H1 blocks with pilot power/scramble control (ops: AffineOperators)."""
    u = ops.modulate_ctrl(collaborate(w, comp["X"], comp["A"]), beta, scramble)
    return _through_channel(comp["G_eve"], u, np.sqrt(sigma2_eve) * comp["N_eve"], ops.cfg)


def synthesize_bob(fmt: Waveform, w: np.ndarray, comp: dict, sigma2_bob: float) -> np.ndarray:
    u = fmt.modulate(collaborate(w, comp["X"], comp["A"]))
    return _through_channel(comp["H_bob"], u, np.sqrt(sigma2_bob) * comp["N_bob"], fmt.cfg)


# --------------------------------------------------------------------------
# Frozen-policy H0/H1 dataset (Eve-training stage)
# --------------------------------------------------------------------------

def eve_dataset(
    cfg: SystemConfig,
    fmt: Waveform,
    w: np.ndarray,
    n_samples: int,
    snr_db: float,
    master_seed: int,
    format_id: int,
    split: str,
    batch: int = 256,
    pilot_beta=None,
    pilot_scramble: bool = False,
    eve_gains=None,
) -> dict:
    """Balanced, shuffled H0/H1 received blocks for Eve (complex64).

    pilot_beta (None -> 1.0) scales pilot power; pilot_scramble applies a per-block
    Tx/Bob-shared pilot scramble (not exposed to Eve).  Both only affect H1.
    eve_gains: optional (M,) per-user Eve-channel gains (subset selection).
    """
    sigma2 = sigma2_from_snr(cfg, snr_db)
    n1 = n_samples // 2
    n0 = n_samples - n1
    ctrl = pilot_beta is not None or pilot_scramble
    ops = AffineOperators(fmt) if ctrl else None
    beta = 1.0 if pilot_beta is None else float(pilot_beta)

    rng1 = np.random.default_rng(shard_seed(master_seed, format_id, snr_db, split, _ROLE_H1))
    rng0 = np.random.default_rng(shard_seed(master_seed, format_id, snr_db, split, _ROLE_H0))
    rngs = np.random.default_rng(shard_seed(master_seed, format_id, snr_db, split, _ROLE_SHUFFLE))
    rngscr = np.random.default_rng(shard_seed(master_seed, format_id, snr_db, split, _ROLE_SCRAMBLE))

    y1 = np.empty((n1, cfg.n_rx_eve, cfg.n_samples), dtype=np.complex64)
    for lo in range(0, n1, batch):
        hi = min(lo + batch, n1)
        comp = sample_components(cfg, rng1, hi - lo, eve_gains=eve_gains)
        if ctrl:
            scr = scramble_phases(rngscr, hi - lo, ops.n_pilot_re) if pilot_scramble else None
            y1[lo:hi] = synthesize_h1_ctrl(ops, w, comp, sigma2, beta, scr).astype(np.complex64)
        else:
            y1[lo:hi] = synthesize_h1(fmt, w, comp, sigma2).astype(np.complex64)

    y0 = (np.sqrt(sigma2) * cn(rng0, (n0, cfg.n_rx_eve, cfg.n_samples))).astype(np.complex64)

    y = np.concatenate([y0, y1], axis=0)
    labels = np.concatenate([np.zeros(n0, np.uint8), np.ones(n1, np.uint8)])
    perm = rngs.permutation(n_samples)
    return {
        "Y": y[perm],
        "labels": labels[perm],
        "snr_db": np.float32(snr_db),
        "sigma2": np.float32(sigma2),
        "W": w.astype(np.complex64),
        "format": fmt.name,
        "split": split,
        "pilot_beta": np.float32(beta),
        "pilot_scramble": bool(pilot_scramble),
        "config_json": cfg.to_json(),
    }


def component_set(cfg: SystemConfig, master_seed: int, split: str, n_blocks: int) -> dict:
    """Frozen common-random-number component set for held-out policy evaluation."""
    rng = np.random.default_rng(shard_seed(master_seed, 0, 0.0, split, _ROLE_COMPONENTS))
    comp = sample_components(cfg, rng, n_blocks)
    comp = {k: v.astype(np.complex64) for k, v in comp.items()}
    comp["split"] = split
    comp["config_json"] = cfg.to_json()
    return comp


def save_shard(path, arrays: dict) -> None:
    import os

    os.makedirs(os.path.dirname(str(path)), exist_ok=True)
    np.savez_compressed(path, **arrays)