aircompkit 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of aircompkit might be problematic. Click here for more details.
- aircompkit/__init__.py +32 -0
- aircompkit/__main__.py +5 -0
- aircompkit/adversary/__init__.py +175 -0
- aircompkit/aircomp/__init__.py +41 -0
- aircompkit/aircomp/analytic.py +42 -0
- aircompkit/aircomp/power_control.py +183 -0
- aircompkit/aircomp/preprocess.py +48 -0
- aircompkit/bench.py +159 -0
- aircompkit/channel/__init__.py +209 -0
- aircompkit/cli.py +165 -0
- aircompkit/core/__init__.py +1 -0
- aircompkit/core/registry.py +123 -0
- aircompkit/core/result.py +45 -0
- aircompkit/core/rng.py +47 -0
- aircompkit/core/scenario.py +226 -0
- aircompkit/defense/__init__.py +156 -0
- aircompkit/defense/evaluate.py +48 -0
- aircompkit/devices/__init__.py +79 -0
- aircompkit/learning/__init__.py +32 -0
- aircompkit/learning/aggregate.py +49 -0
- aircompkit/learning/array.py +140 -0
- aircompkit/learning/bank.py +86 -0
- aircompkit/learning/data.py +128 -0
- aircompkit/learning/fl.py +249 -0
- aircompkit/learning/models.py +89 -0
- aircompkit/learning/partition.py +58 -0
- aircompkit/metrics/__init__.py +36 -0
- aircompkit/metrics/privacy.py +36 -0
- aircompkit/plot/__init__.py +5 -0
- aircompkit/receiver/__init__.py +244 -0
- aircompkit/reproduce/__init__.py +26 -0
- aircompkit/reproduce/yang2020.py +182 -0
- aircompkit/reproduce/zhu2020.py +205 -0
- aircompkit-1.0.0.dist-info/METADATA +167 -0
- aircompkit-1.0.0.dist-info/RECORD +39 -0
- aircompkit-1.0.0.dist-info/WHEEL +5 -0
- aircompkit-1.0.0.dist-info/entry_points.txt +2 -0
- aircompkit-1.0.0.dist-info/licenses/LICENSE +21 -0
- aircompkit-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
"""Channel models and impairments (FEATURES H1–H4, H6, H7).
|
|
2
|
+
|
|
3
|
+
Block-fading, complex-baseband uplink from ``K`` single-antenna devices to a server with
|
|
4
|
+
``n_rx`` antennas (a uniform linear array with half-wavelength spacing). ``sample`` returns
|
|
5
|
+
|
|
6
|
+
* ``h``: complex coefficients, shape ``[trials, K, n_rx]``;
|
|
7
|
+
* ``beta``: large-scale gains, shape ``[trials, K]`` (constant across trials unless
|
|
8
|
+
shadowing is enabled).
|
|
9
|
+
|
|
10
|
+
Every model is normalised so that ``E|h_{k,n}|^2 = beta_k`` on every antenna. Optional
|
|
11
|
+
exponential spatial correlation ``R_ij = corr^|i-j|`` applies to the scattered part.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
|
|
21
|
+
from aircompkit.core.registry import register
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class PathLoss:
|
|
26
|
+
"""Log-distance path loss with optional log-normal shadowing (FEATURES H3).
|
|
27
|
+
|
|
28
|
+
``beta(d) = 10^(ref_gain_db/10) * (max(d, ref_distance) / ref_distance)^(-exponent)``,
|
|
29
|
+
multiplied by ``10^(S/10)`` with ``S ~ N(0, shadowing_db^2)`` drawn per trial and device.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
exponent: float = 3.0
|
|
33
|
+
ref_distance: float = 1.0
|
|
34
|
+
ref_gain_db: float = 0.0
|
|
35
|
+
shadowing_db: float = 0.0
|
|
36
|
+
|
|
37
|
+
def __post_init__(self) -> None:
|
|
38
|
+
if self.ref_distance <= 0 or self.exponent < 0 or self.shadowing_db < 0:
|
|
39
|
+
raise ValueError("invalid path-loss parameters")
|
|
40
|
+
|
|
41
|
+
def gains(
|
|
42
|
+
self, distances: np.ndarray | None, rng: np.random.Generator, trials: int, K: int
|
|
43
|
+
) -> np.ndarray:
|
|
44
|
+
if distances is None:
|
|
45
|
+
base = np.full(K, 10 ** (self.ref_gain_db / 10))
|
|
46
|
+
else:
|
|
47
|
+
d = np.maximum(np.asarray(distances, float), self.ref_distance)
|
|
48
|
+
base = 10 ** (self.ref_gain_db / 10) * (d / self.ref_distance) ** (-self.exponent)
|
|
49
|
+
beta = np.broadcast_to(base, (trials, K)).copy()
|
|
50
|
+
if self.shadowing_db > 0:
|
|
51
|
+
beta *= 10 ** (rng.normal(0.0, self.shadowing_db, size=(trials, K)) / 10)
|
|
52
|
+
return beta
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _as_pathloss(pl: PathLoss | dict[str, Any] | None) -> PathLoss | None:
|
|
56
|
+
if pl is None or isinstance(pl, PathLoss):
|
|
57
|
+
return pl
|
|
58
|
+
return PathLoss(**pl)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _cn(rng: np.random.Generator, shape: tuple[int, ...]) -> np.ndarray:
|
|
62
|
+
"""Circularly-symmetric complex Gaussian, unit variance."""
|
|
63
|
+
z = rng.standard_normal(shape + (2,))
|
|
64
|
+
return (z[..., 0] + 1j * z[..., 1]) / np.sqrt(2.0)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def steering(n_rx: int, angles: np.ndarray) -> np.ndarray:
|
|
68
|
+
"""ULA steering vectors ``a_n(theta) = exp(j pi n sin theta)``; shape ``angles.shape + (n_rx,)``."""
|
|
69
|
+
n = np.arange(n_rx)
|
|
70
|
+
return np.exp(1j * np.pi * np.sin(angles)[..., None] * n)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def exp_corr_sqrt(n_rx: int, corr: float) -> np.ndarray:
|
|
74
|
+
"""Lower Cholesky factor ``L`` of the exponential correlation matrix ``R_ij = corr^|i-j|``."""
|
|
75
|
+
idx = np.arange(n_rx)
|
|
76
|
+
R = corr ** np.abs(idx[:, None] - idx[None, :])
|
|
77
|
+
return np.linalg.cholesky(R)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass
|
|
81
|
+
class _Channel:
|
|
82
|
+
pathloss: PathLoss | dict[str, Any] | None = None
|
|
83
|
+
n_rx: int = 1
|
|
84
|
+
corr: float = 0.0
|
|
85
|
+
|
|
86
|
+
def __post_init__(self) -> None:
|
|
87
|
+
self.pathloss = _as_pathloss(self.pathloss)
|
|
88
|
+
if self.n_rx < 1:
|
|
89
|
+
raise ValueError("n_rx must be >= 1")
|
|
90
|
+
if not 0 <= self.corr < 1:
|
|
91
|
+
raise ValueError("corr must be in [0, 1)")
|
|
92
|
+
|
|
93
|
+
def _beta(self, rng, trials, K, distances):
|
|
94
|
+
if self.pathloss is None:
|
|
95
|
+
return np.ones((trials, K))
|
|
96
|
+
assert isinstance(self.pathloss, PathLoss)
|
|
97
|
+
return self.pathloss.gains(distances, rng, trials, K)
|
|
98
|
+
|
|
99
|
+
def _scatter(self, rng, trials, K):
|
|
100
|
+
w = _cn(rng, (trials, K, self.n_rx))
|
|
101
|
+
if self.corr > 0 and self.n_rx > 1:
|
|
102
|
+
w = w @ exp_corr_sqrt(self.n_rx, self.corr).T
|
|
103
|
+
return w
|
|
104
|
+
|
|
105
|
+
def _los(self, rng, trials, K):
|
|
106
|
+
"""Unit-modulus LoS component: random phase, plus a random AoA when ``n_rx > 1``."""
|
|
107
|
+
phase = np.exp(1j * rng.uniform(0, 2 * np.pi, size=(trials, K)))[..., None]
|
|
108
|
+
if self.n_rx == 1:
|
|
109
|
+
return phase
|
|
110
|
+
theta = rng.uniform(-np.pi / 2, np.pi / 2, size=(trials, K))
|
|
111
|
+
return phase * steering(self.n_rx, theta)
|
|
112
|
+
|
|
113
|
+
def small_scale(self, rng: np.random.Generator, trials: int, K: int) -> np.ndarray:
|
|
114
|
+
raise NotImplementedError
|
|
115
|
+
|
|
116
|
+
def sample(
|
|
117
|
+
self, rng: np.random.Generator, trials: int, K: int, distances: np.ndarray | None = None
|
|
118
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
119
|
+
beta = self._beta(rng, trials, K, distances)
|
|
120
|
+
return np.sqrt(beta)[..., None] * self.small_scale(rng, trials, K), beta
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@register("channel", "awgn")
|
|
124
|
+
@dataclass
|
|
125
|
+
class AWGN(_Channel):
|
|
126
|
+
"""No fading. Single antenna: ``h_k = sqrt(beta_k)``. Multi-antenna: a pure LoS ray
|
|
127
|
+
``sqrt(beta_k) a(theta_k)`` with a random angle of arrival per trial and device."""
|
|
128
|
+
|
|
129
|
+
def small_scale(self, rng, trials, K):
|
|
130
|
+
if self.n_rx == 1:
|
|
131
|
+
return np.ones((trials, K, 1), dtype=complex)
|
|
132
|
+
theta = rng.uniform(-np.pi / 2, np.pi / 2, size=(trials, K))
|
|
133
|
+
return steering(self.n_rx, theta)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@register("channel", "rayleigh")
|
|
137
|
+
@dataclass
|
|
138
|
+
class Rayleigh(_Channel):
|
|
139
|
+
"""i.i.d. Rayleigh block fading: ``h_k ~ CN(0, beta_k R)``, independent across trials."""
|
|
140
|
+
|
|
141
|
+
def small_scale(self, rng, trials, K):
|
|
142
|
+
return self._scatter(rng, trials, K)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@register("channel", "rician")
|
|
146
|
+
@dataclass
|
|
147
|
+
class Rician(_Channel):
|
|
148
|
+
"""Rician fading with K-factor ``k_factor`` (linear, LoS-to-scatter power ratio).
|
|
149
|
+
|
|
150
|
+
``h_k = sqrt(beta_k) (sqrt(k/(k+1)) e^{j phi} a(theta) + sqrt(1/(k+1)) w)`` with
|
|
151
|
+
``w ~ CN(0, R)``. ``k_factor = 0`` gives Rayleigh.
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
k_factor: float = field(default=3.0)
|
|
155
|
+
|
|
156
|
+
def __post_init__(self) -> None:
|
|
157
|
+
super().__post_init__()
|
|
158
|
+
if self.k_factor < 0:
|
|
159
|
+
raise ValueError("k_factor must be >= 0")
|
|
160
|
+
|
|
161
|
+
def small_scale(self, rng, trials, K):
|
|
162
|
+
k = self.k_factor
|
|
163
|
+
los = self._los(rng, trials, K)
|
|
164
|
+
return np.sqrt(k / (k + 1)) * los + np.sqrt(1 / (k + 1)) * self._scatter(rng, trials, K)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@dataclass
|
|
168
|
+
class Impairments:
|
|
169
|
+
"""Imperfect CSI and residual phase errors (FEATURES H6, H7).
|
|
170
|
+
|
|
171
|
+
* ``csi_error``: relative estimation-error variance ``eps^2``. The server and devices
|
|
172
|
+
design beamformers and power control from ``h_est = h + e`` with
|
|
173
|
+
``e ~ CN(0, eps^2 beta_k I)``.
|
|
174
|
+
* ``phase_error_std``: residual synchronisation phase error (radians). At transmission,
|
|
175
|
+
device ``k`` sees ``h_k e^{j theta_k}`` with ``theta_k ~ N(0, std^2)`` per trial.
|
|
176
|
+
|
|
177
|
+
Both are drawn from their own random stream, so channel realisations stay paired with
|
|
178
|
+
an impairment-free run.
|
|
179
|
+
"""
|
|
180
|
+
|
|
181
|
+
csi_error: float = 0.0
|
|
182
|
+
phase_error_std: float = 0.0
|
|
183
|
+
|
|
184
|
+
def __post_init__(self) -> None:
|
|
185
|
+
if self.csi_error < 0 or self.phase_error_std < 0:
|
|
186
|
+
raise ValueError("impairment levels must be >= 0")
|
|
187
|
+
|
|
188
|
+
def apply(
|
|
189
|
+
self, rng: np.random.Generator, h: np.ndarray, beta: np.ndarray
|
|
190
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
191
|
+
"""Return ``(h_actual, h_est)``."""
|
|
192
|
+
T, K, N = h.shape
|
|
193
|
+
h_est = h
|
|
194
|
+
if self.csi_error > 0:
|
|
195
|
+
e = np.sqrt(self.csi_error * beta)[..., None] * _cn(rng, (T, K, N))
|
|
196
|
+
h_est = h + e
|
|
197
|
+
h_act = h
|
|
198
|
+
if self.phase_error_std > 0:
|
|
199
|
+
theta = rng.normal(0.0, self.phase_error_std, size=(T, K))
|
|
200
|
+
h_act = h * np.exp(1j * theta)[..., None]
|
|
201
|
+
return h_act, h_est
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def as_impairments(x: Impairments | dict[str, Any] | None) -> Impairments:
|
|
205
|
+
if x is None:
|
|
206
|
+
return Impairments()
|
|
207
|
+
if isinstance(x, Impairments):
|
|
208
|
+
return x
|
|
209
|
+
return Impairments(**x)
|
aircompkit/cli.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Command-line interface (FEATURES C7): ``list``, ``run``, ``train``, ``reproduce``, ``bench``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
|
|
9
|
+
from aircompkit import __version__
|
|
10
|
+
from aircompkit.core.registry import KINDS, available
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _cmd_list(args: argparse.Namespace) -> int:
|
|
14
|
+
kinds = [args.kind] if args.kind else list(KINDS)
|
|
15
|
+
for kind in kinds:
|
|
16
|
+
names = available(kind)
|
|
17
|
+
print(f"{kind}: {', '.join(names) if names else '(none yet)'}")
|
|
18
|
+
return 0
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _cmd_run(args: argparse.Namespace) -> int:
|
|
22
|
+
from aircompkit.core.scenario import Scenario, load_yaml
|
|
23
|
+
|
|
24
|
+
cfg = load_yaml(args.config)
|
|
25
|
+
run_opts = dict(cfg.get("run", {}) or {})
|
|
26
|
+
for key in ("trials", "dim", "batch"):
|
|
27
|
+
if getattr(args, key) is not None:
|
|
28
|
+
run_opts[key] = getattr(args, key)
|
|
29
|
+
res = Scenario.from_dict(cfg).run(**run_opts)
|
|
30
|
+
for name, (m, ci) in res.summary().items():
|
|
31
|
+
print(f"{name:>14}: {m:.6g} +/- {ci:.2g} (95% CI)")
|
|
32
|
+
if args.out:
|
|
33
|
+
npz, js = res.save(args.out)
|
|
34
|
+
print(f"saved {npz} and {js}")
|
|
35
|
+
return 0
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _cmd_train(args: argparse.Namespace) -> int:
|
|
39
|
+
from aircompkit.core.scenario import Scenario, load_yaml
|
|
40
|
+
from aircompkit.learning import FederatedConfig, train
|
|
41
|
+
|
|
42
|
+
cfg = load_yaml(args.config)
|
|
43
|
+
if "learning" not in cfg:
|
|
44
|
+
raise SystemExit(f"{args.config}: needs a 'learning:' section")
|
|
45
|
+
learning = dict(cfg["learning"])
|
|
46
|
+
if args.rounds is not None:
|
|
47
|
+
learning["rounds"] = args.rounds
|
|
48
|
+
res = train(Scenario.from_dict(cfg), FederatedConfig(**learning),
|
|
49
|
+
data_root=args.data_root, verbose=True)
|
|
50
|
+
print(f"final test accuracy {res['test_acc'][-1]:.4f}, "
|
|
51
|
+
f"mean aggregation NMSE {res['agg_nmse'].mean():.3g}")
|
|
52
|
+
if args.out:
|
|
53
|
+
npz, js = res.save(args.out)
|
|
54
|
+
print(f"saved {npz} and {js}")
|
|
55
|
+
return 0
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _cmd_reproduce(args: argparse.Namespace) -> int:
|
|
59
|
+
import inspect
|
|
60
|
+
from pathlib import Path
|
|
61
|
+
|
|
62
|
+
from aircompkit.core.registry import get
|
|
63
|
+
from aircompkit.reproduce import CHECKS, report
|
|
64
|
+
|
|
65
|
+
if args.all:
|
|
66
|
+
names = available("reproduction")
|
|
67
|
+
elif args.name:
|
|
68
|
+
names = [args.name]
|
|
69
|
+
else:
|
|
70
|
+
print("available reproductions: " + ", ".join(available("reproduction")))
|
|
71
|
+
return 0
|
|
72
|
+
failed, skipped = [], []
|
|
73
|
+
for name in names:
|
|
74
|
+
fn = get("reproduction", name)
|
|
75
|
+
out = None if args.out is None else (Path(args.out) / name if args.all else args.out)
|
|
76
|
+
kw = {"trials": args.trials, "quick": args.quick, "out": out}
|
|
77
|
+
if args.data_root is not None:
|
|
78
|
+
if "data_root" in inspect.signature(fn).parameters:
|
|
79
|
+
kw["data_root"] = args.data_root
|
|
80
|
+
elif not args.all:
|
|
81
|
+
raise SystemExit(f"{name} uses no dataset; drop --data-root")
|
|
82
|
+
if args.all:
|
|
83
|
+
print(f"\n=== {name} ===", flush=True)
|
|
84
|
+
try:
|
|
85
|
+
res = fn(**kw)
|
|
86
|
+
except FileNotFoundError as e:
|
|
87
|
+
if not args.all:
|
|
88
|
+
raise
|
|
89
|
+
skipped.append(name)
|
|
90
|
+
print(f"skipped {name}: {str(e).splitlines()[0]}")
|
|
91
|
+
continue
|
|
92
|
+
if args.check:
|
|
93
|
+
if name not in CHECKS:
|
|
94
|
+
raise SystemExit(f"no checks defined for {name}")
|
|
95
|
+
if not report(name, res):
|
|
96
|
+
failed.append(name)
|
|
97
|
+
if args.all:
|
|
98
|
+
print(f"\nreproductions: {len(names) - len(skipped)} run, {len(skipped)} skipped"
|
|
99
|
+
+ (f" ({', '.join(skipped)}: dataset not found)" if skipped else "")
|
|
100
|
+
+ (f", checks failed: {', '.join(failed)}" if failed else ""))
|
|
101
|
+
return 1 if failed else 0
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _cmd_bench(args: argparse.Namespace) -> int:
|
|
105
|
+
from aircompkit import bench
|
|
106
|
+
|
|
107
|
+
bench.run(groups=args.groups or tuple(bench.GROUPS), quick=args.quick, repeat=args.repeat,
|
|
108
|
+
out=args.out)
|
|
109
|
+
return 0
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
113
|
+
p = argparse.ArgumentParser(
|
|
114
|
+
prog="aircompkit",
|
|
115
|
+
description="Security-aware over-the-air computation simulator.",
|
|
116
|
+
)
|
|
117
|
+
p.add_argument("--version", action="version", version=f"aircompkit {__version__}")
|
|
118
|
+
sub = p.add_subparsers(dest="command")
|
|
119
|
+
pl = sub.add_parser("list", help="list registered components")
|
|
120
|
+
pl.add_argument("kind", nargs="?", choices=KINDS, help="only this component kind")
|
|
121
|
+
pl.set_defaults(func=_cmd_list)
|
|
122
|
+
pr = sub.add_parser("run", help="run a scenario from a YAML config")
|
|
123
|
+
pr.add_argument("config", help="YAML scenario file")
|
|
124
|
+
pr.add_argument("--trials", type=int, help="override run.trials")
|
|
125
|
+
pr.add_argument("--dim", type=int, help="override run.dim (0 = analytical MSE only)")
|
|
126
|
+
pr.add_argument("--batch", type=int, help="override run.batch")
|
|
127
|
+
pr.add_argument("--out", help="save results to OUT.npz / OUT.json")
|
|
128
|
+
pr.set_defaults(func=_cmd_run)
|
|
129
|
+
pt = sub.add_parser("train", help="run OTA-FL from a YAML config with a 'learning:' section")
|
|
130
|
+
pt.add_argument("config")
|
|
131
|
+
pt.add_argument("--rounds", type=int, help="override learning.rounds")
|
|
132
|
+
pt.add_argument("--data-root", help="folder with mnist.npz etc. (else $AIRCOMPKIT_DATA)")
|
|
133
|
+
pt.add_argument("--out", help="save results to OUT.npz / OUT.json")
|
|
134
|
+
pt.set_defaults(func=_cmd_train)
|
|
135
|
+
pp = sub.add_parser("reproduce", help="reproduce a published result (no name: list)")
|
|
136
|
+
pp.add_argument("name", nargs="?")
|
|
137
|
+
pp.add_argument("--all", action="store_true", help="run every reproduction (OUT/NAME/ each)")
|
|
138
|
+
pp.add_argument("--quick", action="store_true", help="few trials (smoke test)")
|
|
139
|
+
pp.add_argument("--trials", type=int)
|
|
140
|
+
pp.add_argument("--out", help="directory for JSON results and figure")
|
|
141
|
+
pp.add_argument("--data-root", help="folder with mnist.npz (else $AIRCOMPKIT_DATA)")
|
|
142
|
+
pp.add_argument("--check", action="store_true",
|
|
143
|
+
help="compare with the published values; exit 1 if a tolerance fails")
|
|
144
|
+
pp.set_defaults(func=_cmd_reproduce)
|
|
145
|
+
pb = sub.add_parser("bench", help="performance benchmarks")
|
|
146
|
+
pb.add_argument("groups", nargs="*", choices=["mse", "receiver", "fl"],
|
|
147
|
+
help="benchmark groups (default: all)")
|
|
148
|
+
pb.add_argument("--quick", action="store_true", help="small sizes (smoke test)")
|
|
149
|
+
pb.add_argument("--repeat", type=int, default=3, help="best of REPEAT runs")
|
|
150
|
+
pb.add_argument("--out", help="directory for bench.json and bench.md")
|
|
151
|
+
pb.set_defaults(func=_cmd_bench)
|
|
152
|
+
return p
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
156
|
+
parser = build_parser()
|
|
157
|
+
args = parser.parse_args(argv)
|
|
158
|
+
if not hasattr(args, "func"):
|
|
159
|
+
parser.print_help()
|
|
160
|
+
return 0
|
|
161
|
+
return int(args.func(args))
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
if __name__ == "__main__":
|
|
165
|
+
sys.exit(main())
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Core infrastructure: component registry, seed tree (later: Scenario, config, backend)."""
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Plug-in registry (FEATURES C2).
|
|
2
|
+
|
|
3
|
+
Every swappable component registers under a *kind* and a *name*::
|
|
4
|
+
|
|
5
|
+
@register("channel", "rayleigh")
|
|
6
|
+
class Rayleigh: ...
|
|
7
|
+
|
|
8
|
+
get("channel", "rayleigh") # -> Rayleigh
|
|
9
|
+
available("channel") # -> ["rayleigh", ...]
|
|
10
|
+
|
|
11
|
+
Configs refer to components by name, so users can add their own without touching the core.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import dataclasses
|
|
17
|
+
from collections.abc import Callable
|
|
18
|
+
from typing import Any, TypeVar
|
|
19
|
+
|
|
20
|
+
T = TypeVar("T")
|
|
21
|
+
|
|
22
|
+
KINDS: tuple[str, ...] = (
|
|
23
|
+
"devices",
|
|
24
|
+
"channel",
|
|
25
|
+
"power_control",
|
|
26
|
+
"aircomp",
|
|
27
|
+
"receiver",
|
|
28
|
+
"attack",
|
|
29
|
+
"defense",
|
|
30
|
+
"aggregator",
|
|
31
|
+
"dataset",
|
|
32
|
+
"partitioner",
|
|
33
|
+
"model",
|
|
34
|
+
"metric",
|
|
35
|
+
"reproduction",
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
_REGISTRY: dict[str, dict[str, Any]] = {k: {} for k in KINDS}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _check_kind(kind: str) -> None:
|
|
42
|
+
if kind not in _REGISTRY:
|
|
43
|
+
raise KeyError(f"unknown component kind {kind!r}; expected one of {', '.join(KINDS)}")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def register(kind: str, name: str, *, overwrite: bool = False) -> Callable[[T], T]:
|
|
47
|
+
"""Class/function decorator that registers a component under ``kind``/``name``."""
|
|
48
|
+
_check_kind(kind)
|
|
49
|
+
key = name.lower()
|
|
50
|
+
|
|
51
|
+
def deco(obj: T) -> T:
|
|
52
|
+
if key in _REGISTRY[kind] and not overwrite and _REGISTRY[kind][key] is not obj:
|
|
53
|
+
raise ValueError(f"{kind} {name!r} is already registered")
|
|
54
|
+
_REGISTRY[kind][key] = obj
|
|
55
|
+
return obj
|
|
56
|
+
|
|
57
|
+
return deco
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def get(kind: str, name: str) -> Any:
|
|
61
|
+
"""Return the component registered under ``kind``/``name`` (case-insensitive)."""
|
|
62
|
+
_check_kind(kind)
|
|
63
|
+
try:
|
|
64
|
+
return _REGISTRY[kind][name.lower()]
|
|
65
|
+
except KeyError:
|
|
66
|
+
opts = ", ".join(sorted(_REGISTRY[kind])) or "none registered"
|
|
67
|
+
raise KeyError(f"no {kind} named {name!r} (available: {opts})") from None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def available(kind: str | None = None) -> list[str] | dict[str, list[str]]:
|
|
71
|
+
"""Names registered for one kind, or a ``{kind: names}`` map for all kinds."""
|
|
72
|
+
if kind is None:
|
|
73
|
+
return {k: sorted(v) for k, v in _REGISTRY.items()}
|
|
74
|
+
_check_kind(kind)
|
|
75
|
+
return sorted(_REGISTRY[kind])
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def build(kind: str, spec: Any) -> Any:
|
|
79
|
+
"""Turn a config spec into a component instance.
|
|
80
|
+
|
|
81
|
+
``spec`` may be an instance already, a name (``"rayleigh"``) or a dict
|
|
82
|
+
``{"name": "rician", "k_factor": 5}``.
|
|
83
|
+
"""
|
|
84
|
+
if isinstance(spec, str):
|
|
85
|
+
return get(kind, spec)()
|
|
86
|
+
if isinstance(spec, dict):
|
|
87
|
+
params = dict(spec)
|
|
88
|
+
try:
|
|
89
|
+
name = params.pop("name")
|
|
90
|
+
except KeyError:
|
|
91
|
+
raise KeyError(f"{kind} spec needs a 'name' key: {spec!r}") from None
|
|
92
|
+
return get(kind, name)(**params)
|
|
93
|
+
return spec
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def spec_of(kind: str, obj: Any) -> dict[str, Any]:
|
|
97
|
+
"""Inverse of ``build`` for registered dataclass components."""
|
|
98
|
+
_check_kind(kind)
|
|
99
|
+
for name, cls in _REGISTRY[kind].items():
|
|
100
|
+
if type(obj) is cls:
|
|
101
|
+
break
|
|
102
|
+
else:
|
|
103
|
+
raise KeyError(f"{type(obj).__name__} is not a registered {kind}")
|
|
104
|
+
if not dataclasses.is_dataclass(obj) or isinstance(obj, type):
|
|
105
|
+
return {"name": name}
|
|
106
|
+
return {"name": name, **_plain(dataclasses.asdict(obj))}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _plain(x: Any) -> Any:
|
|
110
|
+
"""Convert numpy scalars/arrays inside a params dict to built-in types (for JSON/YAML)."""
|
|
111
|
+
if isinstance(x, dict):
|
|
112
|
+
return {k: _plain(v) for k, v in x.items()}
|
|
113
|
+
if isinstance(x, (list, tuple)):
|
|
114
|
+
return [_plain(v) for v in x]
|
|
115
|
+
if hasattr(x, "tolist"):
|
|
116
|
+
return x.tolist()
|
|
117
|
+
return x
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def unregister(kind: str, name: str) -> None:
|
|
121
|
+
"""Remove a component (mainly for tests)."""
|
|
122
|
+
_check_kind(kind)
|
|
123
|
+
_REGISTRY[kind].pop(name.lower(), None)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Results container (FEATURES C6): arrays plus the exact config and versions that made them."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class Result:
|
|
15
|
+
config: dict[str, Any]
|
|
16
|
+
arrays: dict[str, np.ndarray]
|
|
17
|
+
meta: dict[str, Any] = field(default_factory=dict)
|
|
18
|
+
|
|
19
|
+
def __getitem__(self, key: str) -> np.ndarray:
|
|
20
|
+
return self.arrays[key]
|
|
21
|
+
|
|
22
|
+
def summary(self, z: float = 1.96) -> dict[str, tuple[float, float]]:
|
|
23
|
+
"""``{name: (mean, CI half-width)}`` for every per-trial 1-D array."""
|
|
24
|
+
from aircompkit.metrics import mean_ci
|
|
25
|
+
|
|
26
|
+
return {k: mean_ci(v, z) for k, v in self.arrays.items() if v.ndim == 1}
|
|
27
|
+
|
|
28
|
+
def save(self, path: str | Path) -> tuple[Path, Path]:
|
|
29
|
+
"""Write ``<path>.npz`` (arrays) and ``<path>.json`` (config + meta)."""
|
|
30
|
+
p = Path(path)
|
|
31
|
+
stem = p.with_suffix("") if p.suffix in {".npz", ".json"} else p
|
|
32
|
+
stem.parent.mkdir(parents=True, exist_ok=True)
|
|
33
|
+
npz, js = stem.with_suffix(".npz"), stem.with_suffix(".json")
|
|
34
|
+
np.savez_compressed(npz, **self.arrays) # type: ignore[arg-type]
|
|
35
|
+
js.write_text(json.dumps({"config": self.config, "meta": self.meta}, indent=2))
|
|
36
|
+
return npz, js
|
|
37
|
+
|
|
38
|
+
@classmethod
|
|
39
|
+
def load(cls, path: str | Path) -> Result:
|
|
40
|
+
p = Path(path)
|
|
41
|
+
stem = p.with_suffix("") if p.suffix in {".npz", ".json"} else p
|
|
42
|
+
with np.load(stem.with_suffix(".npz")) as z:
|
|
43
|
+
arrays = {k: z[k] for k in z.files}
|
|
44
|
+
info = json.loads(stem.with_suffix(".json").read_text())
|
|
45
|
+
return cls(config=info["config"], arrays=arrays, meta=info.get("meta", {}))
|
aircompkit/core/rng.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Deterministic seed tree (FEATURES C3).
|
|
2
|
+
|
|
3
|
+
One master seed yields independent, *named* random streams. A stream depends only on the
|
|
4
|
+
master seed and its path of names, not on how many other streams were created or in which
|
|
5
|
+
order. So adding an attacker does not change the channel realisations, which makes
|
|
6
|
+
"with vs. without attack" comparisons paired.
|
|
7
|
+
|
|
8
|
+
tree = SeedTree(0)
|
|
9
|
+
h = tree.generator("channel").standard_normal(4)
|
|
10
|
+
tree.child("round").generator("noise")
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _name_key(name: str) -> int:
|
|
21
|
+
# Stable across processes and Python versions (unlike hash()).
|
|
22
|
+
return int.from_bytes(hashlib.sha256(name.encode("utf-8")).digest()[:4], "little")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SeedTree:
|
|
26
|
+
"""A node in a tree of named, reproducible random streams."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, seed: int, _path: tuple[str, ...] = ()) -> None:
|
|
29
|
+
if not isinstance(seed, (int, np.integer)) or seed < 0:
|
|
30
|
+
raise ValueError("seed must be a non-negative integer")
|
|
31
|
+
self.seed = int(seed)
|
|
32
|
+
self.path = _path
|
|
33
|
+
|
|
34
|
+
def child(self, name: str) -> SeedTree:
|
|
35
|
+
"""Sub-tree for a component, e.g. ``tree.child("adversary")``."""
|
|
36
|
+
return SeedTree(self.seed, self.path + (name,))
|
|
37
|
+
|
|
38
|
+
def seed_sequence(self, name: str | None = None) -> np.random.SeedSequence:
|
|
39
|
+
path = self.path + ((name,) if name is not None else ())
|
|
40
|
+
return np.random.SeedSequence(self.seed, spawn_key=tuple(_name_key(p) for p in path))
|
|
41
|
+
|
|
42
|
+
def generator(self, name: str | None = None) -> np.random.Generator:
|
|
43
|
+
"""A fresh ``np.random.Generator`` for the stream ``path/name``."""
|
|
44
|
+
return np.random.Generator(np.random.PCG64(self.seed_sequence(name)))
|
|
45
|
+
|
|
46
|
+
def __repr__(self) -> str:
|
|
47
|
+
return f"SeedTree(seed={self.seed}, path={'/'.join(self.path) or '/'})"
|