Structured key family as the main configuration

Unconstrained key training converged to disjoint sparse supports: 99
percent of each users key energy sat on three or four of the sixteen
entries, with pairwise disjoint supports and one numerically dead
codebook column. That is an orthogonal slot allocation, so the
superposition collapsed into OMA and the key space was far smaller than
the dense direction the brute-force study assumes.

The main configuration is now the structured Walsh-Hadamard family,
which is dense, exactly orthogonal, unit modulus, and already the best
family in the key-family table. base_keys generalizes to any key length
by truncating the next power-of-two Sylvester order, and the key-length
sweep keeps only lengths where the truncated rows stay exactly
orthogonal, verified numerically.

Also fixes the M-PAM energy normalization in oma_ser_keylen, which used
sqrt(6g/(M^2-1)) where unit average symbol energy gives A^2=3/(M^2-1);
the closed form was 3 dB optimistic and now reproduces a direct Monte
Carlo to 1e-5.

Results move accordingly: the proposal now stays below OMA at every SNR
and reaches 1.52x at key length 64, while the jamming margin falls to
5.5-6.3 dB and the brute-force curve to 0.59 at a million guesses.
This commit is contained in:
KiHoLee
2026-08-17 20:02:27 +09:00
parent b120364e38
commit 3d5a7fc6f3
27 changed files with 561 additions and 418 deletions
+73 -26
View File
@@ -1,14 +1,17 @@
# -*- coding: utf-8 -*-
"""Final consistency check: every headline number vs its raw CSV."""
"""Final consistency check: every headline number vs its raw CSV.
A quoted value that goes stale during a revision is the failure mode this
guards against, so each assertion recomputes from data/ rather than from
another quoted value. The manuscript-side assertions are skipped when
main.tex is absent, which is the case in the reproducibility package.
"""
import csv
import math
import re
from pathlib import Path
base = Path(__file__).resolve().parents[1]
# The manuscript is not part of the reproducibility package, so the
# tex-side assertions are skipped when it is absent and the data-side
# assertions still run.
_tex_path = base / "main.tex"
HAVE_TEX = _tex_path.exists()
tex = _tex_path.read_text(encoding="utf-8") if HAVE_TEX else ""
@@ -38,56 +41,100 @@ def chk(label, cond, detail, needs_tex=False):
print("headline numbers vs raw data")
# 1.27x key-length ratio
# --- Fig. 2: the proposal is below OMA -------------------------------
sn = rows("sec_snr.csv")
lg = [float(x["legit"]) for x in sn]
om = [float(x["oma"]) for x in sn]
rel = [(a - b) / b * 100 for a, b in zip(lg, om)]
chk("legit below OMA at every SNR", max(rel) < 0, "max relative %+.2f%%" % max(rel))
chk("gain 1.3 to 7.9 percent",
round(-max(rel), 1) == 1.3 and round(-min(rel), 1) == 7.9,
"%.2f to %.2f percent" % (-max(rel), -min(rel)))
chk("1.3 and 7.9 in tex", "$1.3$ to\n$7.9$~percent" in tex or "$1.3$ to $7.9$~percent" in tex,
"searched tex", needs_tex=True)
ew = [float(x["eve_wrong"]) for x in sn]
ch = float(sn[0]["chance"])
chk("outsider at chance to 2e-5", max(abs(x - ch) for x in ew) < 2e-5,
"max deviation %.2e" % max(abs(x - ch) for x in ew))
# --- Fig. 3: key-length ratio ----------------------------------------
k = rows("sec_keylen.csv")
r64 = [x for x in k if int(x["L"]) == 64][0]
ratio = float(r64["oma"]) / float(r64["legit_ser"])
chk("key-length ratio 1.27", round(ratio, 2) == 1.27, "%.4f" % ratio)
chk("1.27 in tex", tex.count("1.27") >= 2, "%d occurrences" % tex.count("1.27"), needs_tex=True)
chk("key-length ratio 1.52", round(ratio, 2) == 1.52, "%.4f" % ratio)
chk("1.52 in tex", tex.count("1.52") >= 2, "%d occurrences" % tex.count("1.52"),
needs_tex=True)
chk("keys exactly orthogonal in the sweep",
max(float(x["mask_xcorr"]) for x in k) < 1e-6,
"max xcorr %.2e" % max(float(x["mask_xcorr"]) for x in k))
# blind-jammer gap
# --- Fig. 4: jamming --------------------------------------------------
g = col("sec_jam_gap.csv", "gap_db")
chk("gap 7.4-8.1 dB", round(min(g), 1) == 7.4 and round(max(g), 1) == 8.1,
chk("gap 5.5-6.3 dB", round(min(g), 1) == 5.5 and round(max(g), 1) == 6.3,
"%.3f to %.3f" % (min(g), max(g)))
chk("no stale 8.5 dB", "8.5$~dB" not in tex, "searched tex", needs_tex=True)
lin = (10 ** (min(g) / 10), 10 ** (max(g) / 10))
chk("about six times power", lin[0] < 6.5 and lin[1] > 5.5,
chk("about four times power", lin[0] < 4.5 and lin[1] > 3.4,
"%.2f to %.2f" % lin)
# blind vs permutation
j = rows("sec_jam_cmp.csv")
dmax = max(abs(float(r["blind"]) - float(r["perm_blind"])) for r in j)
chk("within 0.002", dmax <= 0.002, "%.5f" % dmax)
chk("no stale 0.0015 in jamming", "$0.0015$ of the proposed" not in tex, "ok", needs_tex=True)
chk("no stale 8.1 dB", "$8.1$~dB" not in tex, "searched tex", needs_tex=True)
# brute force
# --- Fig. 6: brute force ---------------------------------------------
b = rows("sec_brute_cmp.csv")
sm = float(b[-1]["ser_mask"])
chk("brute 0.76 both places", tex.count("$0.76$") >= 2, "%.4f measured" % sm, needs_tex=True)
chk("no stale 0.75 in summary",
"$0.75$ after $10^{6}$" not in tex, "summary row", needs_tex=True)
chk("brute 0.59 at 1e6", round(sm, 2) == 0.59, "%.4f" % sm)
chk("0.59 in tex", "$0.59$" in tex, "searched tex", needs_tex=True)
pad0 = next((x["K"] for x in b if float(x["ser_pad"]) < 0.27), None)
chk("index cipher collapses at 65536", pad0 == "65536", str(pad0))
# refresh
rs = {r["scheme"]: r for r in rows("refresh_summary.csv")}
# --- Fig. 7: known plaintext -----------------------------------------
kp = rows("kpa.csv")
legit = float([x for x in k if int(x["L"]) == 16][0]["legit_ser"])
thr = legit * 1.02
first20 = next((x["n_frames"] for x in kp
if int(x["snr_db"]) == 20 and float(x["eve_ser"]) <= thr), None)
first10 = next((x["n_frames"] for x in kp
if int(x["snr_db"]) == 10 and float(x["eve_ser"]) <= thr), None)
chk("KPA five frames at 20 dB", first20 == "5", "first N = %s" % first20)
chk("KPA twenty-four frames at 10 dB", first10 == "24", "first N = %s" % first10)
pk = rows("pkpa.csv")
p6 = float([x for x in pk if x["n_frames"] == "6"][0]["eve_ser"])
chk("perm KPA at N=6 near its own 0.258", abs(p6 - 0.258) < 0.005, "%.4f" % p6)
# --- refresh ----------------------------------------------------------
rs = {x["scheme"]: x for x in rows("refresh_summary.csv")}
chk("refresh 64.8 bits",
round(float(rs["Invariant"]["entropy_bits"]), 1) == 64.8,
"%.3f" % float(rs["Invariant"]["entropy_bits"]))
chk("fixed key 15.0 bits",
round(float(rs["None (fixed key)"]["entropy_bits"]), 1) == 15.0,
"%.4f" % float(rs["None (fixed key)"]["entropy_bits"]))
chk("invariant refresh free",
abs(float(rs["Invariant"]["legit"]) - float(rs["None (fixed key)"]["legit"]))
< 0.001, "%.4f vs %.4f" % (float(rs["Invariant"]["legit"]),
float(rs["None (fixed key)"]["legit"])))
# permutation KPA
pk = rows("pkpa.csv")
p6 = float([r for r in pk if r["n_frames"] == "6"][0]["eve_ser"])
chk("perm KPA at N=6 near 0.303", abs(p6 - 0.303) < 0.005, "%.4f" % p6)
# --- real tokens ------------------------------------------------------
import json
st = json.loads((base / "data" / "real_sec_stats.json").read_text())
rec = st["recovery"]["28"]
chk("headline recovery 78 vs 76 percent",
round(rec["legit"] * 100) == 78 and round(rec["oma"] * 100) == 76,
"%.1f vs %.1f" % (rec["legit"] * 100, rec["oma"] * 100))
chk("legit leads OMA at every point",
all(st["recovery"][s]["legit"] > st["recovery"][s]["oma"]
for s in st["recovery"]),
"checked %d points" % len(st["recovery"]))
# abstract
# --- abstract ---------------------------------------------------------
a = (tex.split(r"\begin{abstract}")[1].split(r"\end{abstract}")[0].strip()
if HAVE_TEX else "")
w = len(re.split(r"\s+", a)) if a else 0
chk("abstract <= 250 words", w <= 250, "%d words" % w, needs_tex=True)
chk("abstract has no abbreviations",
not re.findall(r"\b[A-Z]{2,}\b", a), str(re.findall(r"\b[A-Z]{2,}\b", a)), needs_tex=True)
not re.findall(r"\b[A-Z]{2,}\b", a), str(re.findall(r"\b[A-Z]{2,}\b", a)),
needs_tex=True)
print()
print("ALL CONSISTENT" if ok else "INCONSISTENCIES FOUND")
+52 -10
View File
@@ -149,9 +149,43 @@ def get_model(P=4, vu=16, d=64, U=4, iters=4000, seed=1, freeze_W=None, tag=""):
return m
def base_keys(U: int, Lp: int) -> torch.Tensor:
"""The structured key family: U non-constant rows of a Walsh-Hadamard
matrix, truncated to Lp entries.
Row 0 of the Sylvester construction is the all-ones vector, which any
adversary can write down without searching, so the users take rows
1..U. The construction exists at power-of-two orders, so for other
key lengths the next power-of-two order is truncated to Lp entries.
That truncation keeps the entries unit modulus and, at every length
the evaluation uses, keeps the rows exactly orthogonal as well; the
measured cross-correlation is reported alongside every sweep point.
Requires U <= Lp - 1 non-constant rows to exist."""
n = 1 << max(math.ceil(math.log2(max(Lp, U + 1))), 1)
H = hadamard(n)
if H.shape[0] - 1 < U:
raise ValueError(f"key length {Lp} admits only {H.shape[0]-1} "
f"non-constant rows, fewer than U={U}")
return torch.tensor(H[1:U + 1, :Lp].copy(), dtype=torch.float32)
def main_model(iters=4000, P=4, vu=16, d=64, U=4):
"""The main configuration used by every stage below.
The keys are frozen to the structured Walsh-Hadamard family rather
than learned. Unconstrained mask training converges to disjoint
sparse supports, that is, to an orthogonal slot allocation, which
collapses the superposition into OMA and leaves the key space far
smaller than a dense direction in R^L. The structured family is
dense, exactly orthogonal, and unit modulus, which is also the
condition the key-refresh invariance argument requires."""
return get_model(P=P, vu=vu, d=d, U=U, iters=iters,
freeze_W=base_keys(U, d // P))
def stage_A():
print("[A] security vs SNR (V=65536) ...")
m = get_model(iters=4000)
m = main_model()
snr = [float(v) for v in range(0, 21, 2)]
frames = 800_000
legit = eval_ser_sse(m, snr, frames=frames)
@@ -226,10 +260,14 @@ def oma_ser_keylen(L, snr_db, bits=16, n_grid=200_000):
if bits % L:
return float("nan")
M = 2 ** (bits // L)
# M-PAM levels +-A, +-3A, ..., +-(M-1)A with unit AVERAGE symbol energy
# give A^2 = 3/(M^2-1), so the distance to the decision boundary is A
# and the Q-function argument is h*sqrt(3*g/(M^2-1)). Using 6 instead
# of 3 would assume an average energy of two per dimension.
x = (np.arange(n_grid) + 0.5) / n_grid
h = np.sqrt(-np.log(1.0 - x))
g = 10.0 ** (snr_db / 10.0)
arg = np.clip(h * math.sqrt(6.0 * g / (M * M - 1.0)), 0, 38)
arg = np.clip(h * math.sqrt(3.0 * g / (M * M - 1.0)), 0, 38)
q = (1.0 - 1.0 / M) * np.array([math.erfc(v / math.sqrt(2.0))
for v in arg])
q = np.clip(q, 0.0, 1.0)
@@ -239,8 +277,12 @@ def oma_ser_keylen(L, snr_db, bits=16, n_grid=200_000):
def stage_B():
print("[B] key length (dense grid so the curve is smooth) ...")
rows = []
for d in [16, 24, 32, 40, 48, 56, 64, 80, 96, 128, 192, 256]:
m = get_model(d=d, iters=4000)
# L = d/P. Lengths 6, 10 and 14 are dropped because the
# truncated Walsh-Hadamard rows are not exactly orthogonal
# there, and L=4 admits only three non-constant rows for
# U=4 users.
for d in [32, 48, 64, 80, 96, 128, 192, 256]:
m = main_model(d=d) # same structured family as Fig. 2
lg = eval_ser_sse(m, [10.0], frames=500_000)[0]
ew = eve_wrong_mask(m.users, m.L, seed=20260813).to(DEVICE)
ev = eval_ser_eve(m, ew, [10.0], frames=500_000)[0]
@@ -255,7 +297,7 @@ def stage_B():
def stage_C():
print("[C] jamming vs JSR ...")
m = get_model(iters=4000)
m = main_model()
jsr = [-10.0, -5.0, 0.0, 5.0, 10.0, 15.0, 20.0]
blind = eval_ser_jam(m, 10.0, jsr, frames=500_000, mode="blind", target=0)
matched = eval_ser_jam(m, 10.0, jsr, frames=500_000, mode="matched", target=0)
@@ -280,7 +322,7 @@ def stage_D():
# Walsh-Hadamard rows (orthogonal). Row 0 of the Sylvester
# construction is the all-ones vector, which any adversary can write
# down, so it is excluded and the users take rows 1 to U.
Hd = torch.tensor(hadamard(Lp)[1:U + 1], dtype=torch.float32)
Hd = base_keys(U, Lp) # the main configuration's key family
fams["hadamard"] = Hd
ones = torch.ones(U, Lp) # the cheapest possible guess
rows = []
@@ -395,7 +437,7 @@ def stage_E():
attacker can BUILD from public knowledge at JSR 0 dB (matched if the
masks are public, blind if the PHY structure is secret)."""
print("[E] scheme comparison ...")
m = get_model(iters=4000)
m = main_model()
F = 400_000
d = m.P * m.L
set_seed(20260813)
@@ -506,7 +548,7 @@ def stage_F():
rho_max(K, L) is sampled by Monte Carlo and mapped through the
measured sensitivity curve of (i)."""
print("[F] attack difficulty ...")
m = get_model(iters=4000)
m = main_model()
F = 200_000
true_m = m.masks().detach().cpu()
gen = torch.Generator().manual_seed(31)
@@ -582,7 +624,7 @@ def stage_I():
unknown pad bits, which stay uniform, are all guessed right.
"""
print("[I] key sensitivity across schemes ...")
m = get_model(iters=4000)
m = main_model()
F = 600_000 # more frames per point for a smooth curve
TRIALS_MASK = 12 # independent substitute keys per point
d = m.P * m.L
@@ -726,7 +768,7 @@ def stage_L():
slot assignment is public and needs no key
"""
print("[L] jamming across schemes ...")
m = get_model(iters=4000)
m = main_model()
F = 300_000
d = m.P * m.L
gp = torch.Generator().manual_seed(11)
+2 -2
View File
@@ -25,7 +25,7 @@ import torch
from sse_lib import (DATA, DEVICE, SSE, rayleigh_gain, snr_to_sigma2,
set_seed, write_csv, eval_ser_sse)
from exp_full import get_model, eval_ser_eve
from exp_full import main_model, eval_ser_eve
SNRS = [0.0, 10.0, 20.0]
NFRAMES = [1, 2, 3, 4, 5, 6, 8, 10, 12, 16, 24, 32, 48, 64]
@@ -110,7 +110,7 @@ def key_correlation(est: torch.Tensor, true: torch.Tensor) -> float:
def main():
set_seed(SEED)
model = get_model(iters=4000)
model = main_model()
model.eval()
true_m = model.masks().detach()
legit = eval_ser_sse(model, [10.0], frames=200_000)[0]
+11 -5
View File
@@ -24,7 +24,7 @@ import numpy as np
import torch
from sse_lib import write_csv, set_seed, DATA, DEVICE
from exp_full import get_model, eval_scheme_permuted_eve, rayleigh_gain
from exp_full import main_model, eval_scheme_permuted_eve, rayleigh_gain
try:
from scipy.optimize import linear_sum_assignment
@@ -44,12 +44,18 @@ except ImportError: # greedy fallback
COLLECT_DB = 20.0
DECODE_DB = 10.0
TRIALS = 20
EVAL_FRAMES = 100_000
# The curve's variance is dominated by WHICH positions the recovered
# permutation gets wrong, not by the SER estimate inside one trial: the
# within-trial standard deviation at 50k frames is 2e-3 while the
# trial-to-trial spread is ~1.6e-2. Averaging over many independent
# collections is therefore what smooths the curve, so trials are raised
# and per-trial frames lowered at roughly constant total cost.
TRIALS = 120
EVAL_FRAMES = 50_000
def main():
m = get_model(iters=4000) # training needs grad
m = main_model() # training needs grad
m.eval()
_run(m)
@@ -68,7 +74,7 @@ def _run(m):
print(f"[P] permutation known-plaintext, collect {COLLECT_DB:.0f} dB, "
f"decode {DECODE_DB:.0f} dB ...")
rows = []
for nf in [1, 2, 3, 4, 5, 6, 8, 10, 12, 16, 24, 32, 48, 64]:
for nf in [1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 16, 20, 24, 32, 48, 64]:
fr, sr = [], []
for t in range(TRIALS):
g = torch.Generator().manual_seed(909 + 1000 * t + nf)
+2 -2
View File
@@ -29,7 +29,7 @@ import torch
import sse_lib as L
from sse_lib import (DATA, DEVICE, SSE, rayleigh_gain, snr_to_sigma2,
set_seed, write_csv)
from exp_full import get_model, eve_wrong_mask
from exp_full import main_model, eve_wrong_mask
SNR_GRID = [0, 4, 8, 12, 16, 20, 24, 28]
# headline recovery is meaningful only where the legitimate user clears
@@ -136,7 +136,7 @@ def main():
f"distinct tokens, max id {int(ids_all.max())}")
# keys and codebook trained on uniform indices, reused unchanged
model = get_model(P=P_MAX, vu=VU, d=64, U=U, iters=4000)
model = main_model(P=P_MAX, vu=VU, d=64, U=U)
model.eval()
eve_m = eve_wrong_mask(U, model.L, seed=20260813) # outsider
+2 -8
View File
@@ -45,7 +45,8 @@ import numpy as np
import torch
from sse_lib import DATA, DEVICE, SSE, write_csv, eval_ser_sse
from exp_full import hadamard, get_model, eval_ser_eve, eve_wrong_mask
from exp_full import (hadamard, get_model, base_keys, eval_ser_eve,
eve_wrong_mask)
from exp_kpa import collect_known_plaintext, solve_keys
SEED = 5150
@@ -53,13 +54,6 @@ BLOCKS = 24
FRAMES = 300_000
def base_keys(U: int, Lp: int) -> torch.Tensor:
"""The fixed orthogonal key set the codebook is trained around. Row 0
of the Sylvester construction is the all-ones vector, which any
adversary can write down, so the users take rows 1 to U."""
return torch.tensor(hadamard(Lp)[1:U + 1], dtype=torch.float32)
def kdf_invariant(seed: int, block: int, U: int, Lp: int):
"""Derive one block's key material from the invariance group."""
rng = np.random.default_rng([seed, block])
+49 -21
View File
@@ -11,9 +11,11 @@ Label dictionary is fixed here and copied verbatim into tables and prose.
fig_sec_kpa.pdf : eavesdropper SER vs known-plaintext frames (Fig. 7)
fig_sec_real.pdf : token error rate on real streams (Fig. 8)
Curves that coincide by construction are drawn deliberately layered, the
lower one wide and semi-transparent and the upper one narrow with open
markers, so every legend entry has a visible curve.
Curves that coincide by construction are drawn deliberately layered: the
lower one wide and semi-transparent, the upper one narrow with open
markers, and their markers staggered to different sample points through
markevery offsets. Marker size is uniform across every figure, so the
stagger, not the size, is what keeps each legend entry visible.
"""
from __future__ import annotations
from pathlib import Path
@@ -34,7 +36,7 @@ plt.rcParams.update({
"font.serif": ["DejaVu Serif", "Times New Roman"],
"font.size": 9,
"axes.labelsize": 9,
"legend.fontsize": 7.4,
"legend.fontsize": 6.6,
"xtick.labelsize": 8,
"ytick.labelsize": 8,
"axes.grid": True,
@@ -42,7 +44,7 @@ plt.rcParams.update({
"grid.linewidth": 0.4,
"grid.alpha": 0.6,
"lines.linewidth": 1.3,
"lines.markersize": 3.4,
"lines.markersize": 4.5,
"figure.figsize": (3.15, 2.36),
"pdf.fonttype": 42,
})
@@ -70,9 +72,9 @@ LBL = {
"outsider": "Outsider",
}
# deliberate-layering style for the LOWER of two coinciding curves
UNDER = dict(lw=2.6, ms=7, alpha=0.85)
UNDER = dict(lw=2.6, alpha=0.85) # thick filled line, layered under
# and for the curve riding on top of it
OVER = dict(lw=1.2, ms=4.5, mfc="none")
OVER = dict(lw=1.2, mfc="none") # thin open marker, rides on top
def load(name):
@@ -106,6 +108,27 @@ def save(fig, name):
f"{name}: axis label '{lbl.get_text()}' is clipped "
f"(label {b} outside figure {fbox}); shorten the "
f"label or widen the margin")
# No curve may pass under the legend box. Reading the code cannot
# reveal this, so the check is made on the rendered geometry, the
# same discipline as the clipping guard above.
leg = ax.get_legend()
if leg is not None:
lb = leg.get_window_extent()
for line in ax.get_lines():
# full-span reference lines (axhline/axvline) carry axes-
# fraction endpoints [0,1]; they are not data curves and,
# spanning the whole axis, would forbid any bottom legend
xd = list(line.get_xdata())
if xd == [0, 1] or list(line.get_ydata()) == [0, 1]:
continue
xy = line.get_xydata()
if len(xy) == 0:
continue
for px, py in ax.transData.transform(xy):
if lb.x0 <= px <= lb.x1 and lb.y0 <= py <= lb.y1:
raise RuntimeError(
f"{name}: a data curve passes under the legend "
f"box; move the legend or shrink it")
fig.savefig(FIG / f"{name}.pdf")
plt.close(fig)
print("[OK]", name)
@@ -117,11 +140,11 @@ def fig_snr():
fig, ax = plt.subplots()
# legitimate and OMA coincide by construction; layered deliberately
ax.semilogy(x, col(r, "legit"), color=C_LEGIT, marker="o", ls="-",
label=LBL["legit"], **UNDER)
markevery=(0, 3), label=LBL["legit"], **UNDER)
ax.semilogy(x, col(r, "oma"), color=C_OMA, marker="^", ls=":",
label=LBL["oma"], **OVER)
markevery=(1, 3), label=LBL["oma"], **OVER)
ax.semilogy(x, col(r, "eve_public"), color=C_PUB, marker="v",
ls="none", markersize=5.2, markerfacecolor="none",
ls="none", markevery=(2, 3), markerfacecolor="none",
label=LBL["eve_pub"])
ax.semilogy(x, col(r, "eve_wrong"), color=C_EVE, marker="s", ls="--",
label=LBL["eve_key"])
@@ -151,7 +174,9 @@ def fig_keylen():
ax.set_xlabel("Key length $L$")
ax.set_ylabel("SER")
ax.set_xscale("log", base=2)
ax.legend(loc="center right", bbox_to_anchor=(0.98, 0.72))
# the curves sweep the upper-left to lower-right diagonal, leaving the
# lower-left corner empty
ax.legend(loc="lower left")
save(fig, "fig_sec_keylen")
@@ -171,9 +196,9 @@ def fig_jam():
markevery=me, label=LBL["oma"] + ", targeted")
# the two blind curves agree to 0.002; deliberate layering
ax.plot(x, col(r, "blind"), color=C_LEGIT, marker="o", ls="-",
markevery=me, label=LBL["mask"] + ", blind", **UNDER)
markevery=(0, me), label=LBL["mask"] + ", blind", **UNDER)
ax.plot(x, col(r, "perm_blind"), color=C_EVE, marker="s", ls="-.",
markevery=me, label=LBL["perm"] + ", blind", **OVER)
markevery=(me // 2, me), label=LBL["perm"] + ", blind", **OVER)
nojam = float(load("sec_jam.csv")[0]["nojam"])
ax.axhline(nojam, color=C_OMA, ls=(0, (1, 3)), lw=0.9)
ax.text(max(x) - 0.6, nojam + 0.02, LBL["nojam"], ha="right",
@@ -194,11 +219,11 @@ def fig_sens():
x = col(r, "frac")
fig, ax = plt.subplots()
ax.plot(x, col(r, "ser_mask"), color=C_LEGIT, marker="o", ls="-",
label=LBL["mask"], **UNDER)
markevery=(0, 3), label=LBL["mask"], **UNDER)
ax.plot(x, col(r, "ser_perm"), color=C_EVE, marker="s", ls="--",
label=LBL["perm"], **OVER)
markevery=(1, 3), label=LBL["perm"], **OVER)
ax.plot(x, col(r, "ser_pad"), color=C_PUB, marker="v", ls="-.",
lw=1.2, ms=4.5, mfc="none", label=LBL["pad"])
markevery=(2, 3), lw=1.2, mfc="none", label=LBL["pad"])
chance = 1.0 - (1.0 / 16.0) ** 4
ax.axhline(chance, color=C_CH, ls=":", lw=0.9, label=LBL["chance"])
ax.set_xlabel("Fraction of the key recovered")
@@ -236,13 +261,13 @@ def fig_real():
fig, ax = plt.subplots()
# legitimate/OMA and insider/outsider coincide pairwise; layered
ax.semilogy(x, col(r, "ter_legit"), color=C_LEGIT, marker="o", ls="-",
label=LBL["legit"], **UNDER)
markevery=(0, 2), label=LBL["legit"], **UNDER)
ax.semilogy(x, col(r, "ter_oma"), color=C_OMA, marker="^", ls=":",
label=LBL["oma"], **OVER)
markevery=(1, 2), label=LBL["oma"], **OVER)
ax.semilogy(x, col(r, "ter_insider"), color=C_PUB, marker="v", ls="-.",
lw=2.6, alpha=0.85, ms=7, label=LBL["insider"])
markevery=(0, 2), lw=2.6, alpha=0.85, label=LBL["insider"])
ax.semilogy(x, col(r, "ter_eve"), color=C_EVE, marker="s", ls="--",
label=LBL["outsider"], **OVER)
markevery=(1, 2), label=LBL["outsider"], **OVER)
ax.set_xlabel("SNR (dB)")
ax.set_ylabel("TER")
ax.set_xlim(min(x), max(x))
@@ -280,7 +305,10 @@ def fig_kpa():
ax.set_xlabel("Known-plaintext frames $N$")
ax.set_ylabel("Eavesdropper SER")
ax.set_xscale("log", base=2)
ax.legend(loc="upper right")
# the 0 dB curve sweeps the upper-right, so anchor the legend at the
# top edge past the steep drops, above every curve at large N
ax.set_ylim(top=1.18)
ax.legend(loc="upper right", bbox_to_anchor=(1.0, 1.04))
save(fig, "fig_sec_kpa")
+28
View File
@@ -0,0 +1,28 @@
"""Run the stages that live outside exp_full, after the main sweep.
Order matters: exp_refresh trains its own model around the same base keys,
exp_kpa and exp_permkpa attack the main configuration, and exp_real_sec
reuses the main configuration on real token streams. Each writes only CSV.
"""
import runpy
import sys
import time
STAGES = [
("known-plaintext attack", "exp_kpa.py"),
("permutation known-plaintext attack", "exp_permkpa.py"),
("key-refresh layer", "exp_refresh.py"),
("real token streams", "exp_real_sec.py"),
]
for label, script in STAGES:
print(f"\n{'=' * 60}\n== {label} ({script})\n{'=' * 60}", flush=True)
t0 = time.time()
try:
runpy.run_path(script, run_name="__main__")
except Exception as exc: # keep going, report at end
print(f"[FAIL] {script}: {type(exc).__name__}: {exc}", flush=True)
sys.exit(1)
print(f"[done] {label} in {time.time() - t0:.0f} s", flush=True)
print("\nall remaining stages complete")