File size: 6,976 Bytes
f138992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121e1fb
 
 
 
f138992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121e1fb
f138992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""E13: survival / reliability model (runs on CPU, e.g. the local M4).

From the per-bit catastrophe probability and the accumulated-dose sweep we model
the probability that a rendered frame is catastrophic after k independent upsets
as 1-(1-p_c)^k, validate it against the multi-upset measurements, and translate
it into a mean time between catastrophic frames for a model of B stored bits under
representative single-event-upset rates (ground, avionics, low-Earth orbit), with
and without the support guard.
"""
import argparse
import glob
import json
import math
import os

import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
plt.rcParams.update({"font.family": "serif", "mathtext.fontset": "cm", "font.size": 12,
                     "axes.labelsize": 12, "legend.fontsize": 10, "lines.linewidth": 1.9,
                     "lines.markersize": 5.5, "axes.grid": True, "grid.alpha": 0.25,
                     "savefig.dpi": 220, "savefig.bbox": "tight"})

# representative SEU rates (upsets per stored bit per hour), order-of-magnitude,
# from terrestrial/avionic/space soft-error literature.
SEU_RATE = {"ground": 1e-12, "avionics": 3e-10, "LEO": 1e-8}
CAT_PSNR = 25.0  # a frame is catastrophic if global PSNR falls below this


def per_bit_catastrophe(root):
    """p_c from the main campaign: fraction of uniform-random single-bit upsets
    that are catastrophic (footprint > 1% or non-finite), weighted over fields."""
    import numpy as np
    shards = glob.glob(os.path.join(root, "campaign", "shard_*_fp32.npz"))
    shards = [s for s in shards if not s.endswith("_guard.npz")]
    fr, cat = [], []
    for s in shards:
        d = np.load(s, allow_pickle=True); a = d["data"]; cols = list(d["cols"])
        ci = {c: i for i, c in enumerate(cols)}
        fr.append(a[:, ci["fracchg"]]); cat.append(a[:, ci["cat"]])
    if not fr:
        return None, None
    fr = np.concatenate(fr); cat = np.concatenate(cat)
    is_cat = (cat > 0.5) | (fr > 0.01)
    p_c = float(is_cat.mean())
    # guarded residual, if present
    g = glob.glob(os.path.join(root, "campaign", "shard_*_fp32_guard.npz"))
    pg = None
    if g:
        frg, catg = [], []
        for s in g:
            d = np.load(s, allow_pickle=True); a = d["data"]; cols = list(d["cols"]); ci = {c: i for i, c in enumerate(cols)}
            frg.append(a[:, ci["fracchg"]]); catg.append(a[:, ci["cat"]])
        frg = np.concatenate(frg); catg = np.concatenate(catg)
        pg = float(((catg > 0.5) | (frg > 0.01)).mean())
    return p_c, pg


def multiupset_pcat(root):
    """empirical P(catastrophic frame) vs k from the no-guard multi-upset sweep."""
    per_k = {}
    for fp in glob.glob(os.path.join(root, "multiupset", "multiupset_*_fp32.npz")):
        if fp.endswith("_guard.npz"):
            continue
        d = np.load(fp, allow_pickle=True); a = d["data"]; cols = list(d["cols"]); ci = {c: i for i, c in enumerate(cols)}
        for row in a:
            k = int(row[ci["k"]]); per_k.setdefault(k, []).append(row[ci["psnr"]])
    ks = sorted(per_k)
    pcat = {k: float(np.mean(np.array(per_k[k]) < CAT_PSNR)) for k in ks}
    return ks, pcat


def fmt_hours(h):
    if h <= 0:
        return "n/a"
    yr = h / 8760.0
    if yr >= 1e5:
        e = int(math.floor(math.log10(yr)))
        m = yr / 10 ** e
        return f"$\\sim{m:.0f}\\times10^{{{e}}}$ yr"
    if yr >= 10:
        return f"{yr:,.0f} yr".replace(",", "{,}")
    if yr >= 1:
        return f"{yr:.1f} yr"
    d = h / 24.0
    if d >= 1:
        return f"{d:.0f} d"
    return f"{h:.1f} h"


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--root", default="data_local")
    ap.add_argument("--out", default="../generated")
    ap.add_argument("--bits", type=float, default=2.55e8, help="stored bits in the model")
    args = ap.parse_args()
    os.makedirs(args.out, exist_ok=True)

    p_c, p_g = per_bit_catastrophe(args.root)
    ks, pcat = multiupset_pcat(args.root)
    macros = {}
    if p_c is None:
        p_c = 1e-3
    macros["pcUpset"] = f"{p_c*100:.3f}"
    macros["pcGuard"] = (f"{p_g*100:.4f}" if p_g is not None else "0.0000")
    B = args.bits
    macros["modelBits"] = f"{B/1e6:.0f}\\times10^6"

    # survival figure: empirical P(cat|k) vs the 1-(1-p_c)^k model
    plt.figure(figsize=(6.2, 4))
    if ks:
        ke = np.array(ks)
        plt.plot(ke, [pcat[k] for k in ks], "o", label="measured")
        kk = np.logspace(0, np.log10(max(ks)), 100)
        plt.plot(kk, 1 - (1 - p_c) ** kk, "-", label=r"$1-(1-p_c)^k$ model")
    plt.xscale("log"); plt.xlabel("simultaneous single-bit upsets $k$")
    plt.ylabel("P(catastrophic frame)"); plt.legend(); plt.grid(alpha=0.3)
    plt.savefig(os.path.join(args.out, "fig_survival.pdf"), bbox_inches="tight"); plt.close()

    # reliability table -> macros (MTBF for first catastrophic frame).
    # LaTeX command names must be letters only, so use camelCase keys.
    NM = {"ground": "Ground", "avionics": "Avionics", "LEO": "Leo"}
    for env, rate in SEU_RATE.items():
        ev_per_hr = rate * B * p_c
        mtbf = float("inf") if ev_per_hr <= 0 else 1.0 / ev_per_hr
        macros[f"mtbf{NM[env]}Ng"] = fmt_hours(mtbf)
        ev_g = rate * B * (p_g if p_g else 1e-9)
        mtbf_g = float("inf") if ev_g <= 0 else 1.0 / ev_g
        macros[f"mtbf{NM[env]}G"] = fmt_hours(mtbf_g)

    # emit a small table and macro file
    with open(os.path.join(args.out, "tab_survival.tex"), "w") as f:
        f.write("\\begin{table}[tbp]\n\\centering\n")
        f.write("\\caption{Estimated mean time between catastrophic frames for a "
                "model of $\\modelBits$ stored bits under representative single-event-upset "
                "rates, without and with the support guard. Rates are order-of-magnitude "
                "values from the soft-error literature.}\n\\label{tab:survival}\n")
        f.write("\\begin{tabular}{lrr}\n\\toprule\nEnvironment & no guard & support guard \\\\\n\\midrule\n")
        names = {"ground": "ground (sea level)", "avionics": "avionics ($\\sim$10 km)", "LEO": "low-Earth orbit"}
        NM = {"ground": "Ground", "avionics": "Avionics", "LEO": "Leo"}
        for env in ["ground", "avionics", "LEO"]:
            f.write(f"{names[env]} & {macros['mtbf'+NM[env]+'Ng']} & {macros['mtbf'+NM[env]+'G']} \\\\\n")
        f.write("\\bottomrule\n\\end{tabular}\n\\end{table}\n")

    with open(os.path.join(args.out, "survival_numbers.tex"), "w") as f:
        # provide safe defaults too
        defaults = {"pcUpset": "0.000", "pcGuard": "0.0000", "modelBits": "2.6\\times10^8"}
        for nm in ["Ground", "Avionics", "Leo"]:
            defaults[f"mtbf{nm}Ng"] = "n/a"; defaults[f"mtbf{nm}G"] = "n/a"
        for k, v in defaults.items():
            macros.setdefault(k, v)
        for k, v in macros.items():
            f.write(f"\\newcommand{{\\{k}}}{{{v}}}\n")
    print("SURVIVAL macros:", macros)


if __name__ == "__main__":
    main()