certoutage 0.1.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.
- certoutage/__init__.py +12 -0
- certoutage/_banks.py +45 -0
- certoutage/_generate.py +91 -0
- certoutage/_runtime.py +135 -0
- certoutage/_vendor/__init__.py +1 -0
- certoutage/_vendor/commun.py +61 -0
- certoutage/_vendor/nak_grouped.py +27 -0
- certoutage/_vendor/nak_thermal.py +42 -0
- certoutage/_vendor/oracles.py +132 -0
- certoutage/_vendor/ppp.py +33 -0
- certoutage/_vendor/thermal_backend.py +148 -0
- certoutage/api.py +284 -0
- certoutage/data/C_N64.npz +0 -0
- certoutage/data/C_N8.npz +0 -0
- certoutage/data/GAMMA_l0p1_e3.npz +0 -0
- certoutage/data/GAMMA_l0p1_e4.npz +0 -0
- certoutage/data/GAMMA_l1p0_e3.npz +0 -0
- certoutage/data/GAMMA_l1p0_e4.npz +0 -0
- certoutage/data/MANIFEST.json +318 -0
- certoutage/data/MINORANTS_N20.json +168 -0
- certoutage/data/MINORANTS_N24.json +168 -0
- certoutage/data/PPP_l0p1_e3.npz +0 -0
- certoutage/data/PPP_l0p1_e4.npz +0 -0
- certoutage/data/PPP_l1p0_e3.npz +0 -0
- certoutage/data/PPP_l1p0_e4.npz +0 -0
- certoutage/data/SIG_12.npz +0 -0
- certoutage/data/SIG_16.npz +0 -0
- certoutage/data/SIG_20.npz +0 -0
- certoutage/data/SIG_24.npz +0 -0
- certoutage/data/SIG_32.npz +0 -0
- certoutage/data/SIG_48.npz +0 -0
- certoutage/data/SIG_64.npz +0 -0
- certoutage/data/SIG_8.npz +0 -0
- certoutage/data/SIG_C_20.npz +0 -0
- certoutage/data/SIG_C_24.npz +0 -0
- certoutage/data/SIG_m2_N12.npz +0 -0
- certoutage/data/SIG_m2_N16.npz +0 -0
- certoutage/data/SIG_m2_N20.npz +0 -0
- certoutage/data/SIG_m2_N24.npz +0 -0
- certoutage/data/SIG_m2_N32.npz +0 -0
- certoutage/data/SIG_m2_N48.npz +0 -0
- certoutage/data/SIG_m2_N64.npz +0 -0
- certoutage/data/SIG_m2_N8.npz +0 -0
- certoutage/data/SIG_m3_N12.npz +0 -0
- certoutage/data/SIG_m3_N16.npz +0 -0
- certoutage/data/SIG_m3_N20.npz +0 -0
- certoutage/data/SIG_m3_N24.npz +0 -0
- certoutage/data/SIG_m3_N32.npz +0 -0
- certoutage/data/SIG_m3_N48.npz +0 -0
- certoutage/data/SIG_m3_N64.npz +0 -0
- certoutage/data/SIG_m3_N8.npz +0 -0
- certoutage/data/commun.npz +0 -0
- certoutage/data/m1_N64.npz +0 -0
- certoutage/data/m1_N8.npz +0 -0
- certoutage/data/m2_N8.npz +0 -0
- certoutage/data/m3_N8.npz +0 -0
- certoutage/models.py +206 -0
- certoutage/notices/ARCHIVE_LICENSE.txt +49 -0
- certoutage/notices/CC-BY-4.0.txt +396 -0
- certoutage/py.typed +0 -0
- certoutage-0.1.0.dist-info/METADATA +242 -0
- certoutage-0.1.0.dist-info/RECORD +68 -0
- certoutage-0.1.0.dist-info/WHEEL +5 -0
- certoutage-0.1.0.dist-info/licenses/LICENSE +27 -0
- certoutage-0.1.0.dist-info/licenses/LICENSES.md +71 -0
- certoutage-0.1.0.dist-info/licenses/docs/ARCHIVE_LICENSE.txt +49 -0
- certoutage-0.1.0.dist-info/licenses/docs/CC-BY-4.0.txt +396 -0
- certoutage-0.1.0.dist-info/top_level.txt +1 -0
certoutage/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Certificats numériques pour le modèle thermique RIS-NOMA de la Letter."""
|
|
2
|
+
from .models import (Model, Numerics, SNRGrid, Contract, Enclosure, SNRDecision,
|
|
3
|
+
ComparisonRow, ThresholdDifference)
|
|
4
|
+
from .api import (outage_enclosure, floor, required_snr, compare_approximations,
|
|
5
|
+
largest_interferer_bound, threshold_difference, clear_cache)
|
|
6
|
+
from ._banks import IntegrityError
|
|
7
|
+
|
|
8
|
+
__version__ = "0.1.0"
|
|
9
|
+
__all__ = ["Model", "Numerics", "SNRGrid", "Contract", "Enclosure", "SNRDecision",
|
|
10
|
+
"ComparisonRow", "ThresholdDifference", "outage_enclosure", "floor",
|
|
11
|
+
"required_snr", "compare_approximations", "largest_interferer_bound",
|
|
12
|
+
"threshold_difference", "clear_cache", "IntegrityError"]
|
certoutage/_banks.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Chargement sans écriture et sans réseau, vérification avant désérialisation."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from functools import lru_cache
|
|
5
|
+
from hashlib import sha256
|
|
6
|
+
from importlib.resources import files
|
|
7
|
+
from io import BytesIO
|
|
8
|
+
import json
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
MANIFEST_SHA256 = "0397d274f08924027840943648ca0816a4403832bace47a79642dee7cc7c5c18"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class IntegrityError(RuntimeError):
|
|
16
|
+
"""Une banque fournie ou son manifeste ne correspond pas à son empreinte."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@lru_cache(maxsize=1)
|
|
20
|
+
def manifest() -> dict:
|
|
21
|
+
content = files("certoutage").joinpath("data/MANIFEST.json").read_bytes()
|
|
22
|
+
if sha256(content).hexdigest() != MANIFEST_SHA256:
|
|
23
|
+
raise IntegrityError("Empreinte SHA-256 incorrecte : MANIFEST.json")
|
|
24
|
+
return json.loads(content)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def verified_bytes(name: str) -> bytes:
|
|
28
|
+
if name not in manifest():
|
|
29
|
+
raise ValueError(f"Banque non fournie : {name}")
|
|
30
|
+
content = files("certoutage").joinpath("data", name).read_bytes()
|
|
31
|
+
if sha256(content).hexdigest() != manifest()[name]["sha256"]:
|
|
32
|
+
raise IntegrityError(f"Empreinte SHA-256 incorrecte : {name}")
|
|
33
|
+
return content
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def arrays(name: str) -> dict[str, np.ndarray]:
|
|
37
|
+
with np.load(BytesIO(verified_bytes(name)), allow_pickle=False) as data:
|
|
38
|
+
result = {key: data[key] for key in data.files}
|
|
39
|
+
for arr in result.values():
|
|
40
|
+
arr.flags.writeable = False
|
|
41
|
+
return result
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def receipt(*names: str) -> tuple[tuple[str, str], ...]:
|
|
45
|
+
return tuple((name, manifest()[name]["sha256"]) for name in names)
|
certoutage/_generate.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Inversion PPP extraite de ppp/code/champ.py, désormais fonction pure.
|
|
2
|
+
|
|
3
|
+
M est paramétrable ; toutes les bornes de reste utilisent le M effectivement
|
|
4
|
+
choisi. Les queues et les masses résiduelles ne sont jamais renormalisées.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import math
|
|
9
|
+
import numpy as np
|
|
10
|
+
from flint import arb, acb, arb_mat
|
|
11
|
+
|
|
12
|
+
from ._vendor.commun import out, moment
|
|
13
|
+
from ._vendor.ppp import transform, envelopes
|
|
14
|
+
from ._vendor.thermal_backend import tighten, gamma_cdf
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _check_laplace(lam: str, eta: int, xlo, xhi, clo, chi) -> None:
|
|
18
|
+
"""Archive consistency guard; the omitted mass at +infinity contributes zero."""
|
|
19
|
+
wl, wh, _ = envelopes(clo, chi, xlo, xhi)
|
|
20
|
+
for s in ("0.1", "0.5", "1"):
|
|
21
|
+
lv = [(-arb(s) * arb(float(x))).exp() for x in xlo]
|
|
22
|
+
hv = [(-arb(s) * arb(float(x))).exp() for x in xhi]
|
|
23
|
+
lap_hi = (arb_mat([wl]) * arb_mat(len(lv), 1, lv))[0, 0]
|
|
24
|
+
lap_lo = (arb_mat([wh]) * arb_mat(len(hv), 1, hv))[0, 0]
|
|
25
|
+
exact = transform(arb(s), lam, eta).real
|
|
26
|
+
if not (lap_lo.lower() <= exact.upper() and lap_hi.upper() >= exact.lower()):
|
|
27
|
+
raise ArithmeticError(f"Contrôle de Laplace incohérent : lam={lam}, eta={eta}, "
|
|
28
|
+
f"s={s}, lower={lap_lo}, upper={lap_hi}, direct={exact}")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def environment_arrays(lam: str, eta: int, power: int, kind: str) -> dict:
|
|
32
|
+
B = 128
|
|
33
|
+
M = 1 << power
|
|
34
|
+
K = M // 2
|
|
35
|
+
c = arb(20) / B
|
|
36
|
+
H = math.floor(float((10 * arb(129).log() / arb(10).log() * 256).mid()))
|
|
37
|
+
xx = [(arb(j) * arb(10).log() / 2560).exp() - 1 for j in range(H + 1)] + [arb(B)]
|
|
38
|
+
xx[0] = arb(0)
|
|
39
|
+
xlo = np.array([max(0.0, out(x)[0]) for x in xx])
|
|
40
|
+
xhi = np.array([max(0.0, out(x)[1]) for x in xx])
|
|
41
|
+
xlo[0] = xhi[0] = 0
|
|
42
|
+
if kind == "GAMMA":
|
|
43
|
+
m1 = moment(lam, eta, 1, 1)
|
|
44
|
+
m2 = moment(lam, eta, 1, 2)
|
|
45
|
+
shape, scale = m1 * m1 / m2, m2 / m1
|
|
46
|
+
gcdf = np.array([out(gamma_cdf(x / scale, shape)) if j else (0.0, 0.0)
|
|
47
|
+
for j, x in enumerate(xx)]).T
|
|
48
|
+
clo, chi = tighten(*gcdf)
|
|
49
|
+
else:
|
|
50
|
+
alpha = arb(2) / eta
|
|
51
|
+
beta = arb.pi() ** 2 * arb(lam) * alpha / (2 * (arb.pi() * alpha / 2).sin())
|
|
52
|
+
zeta = beta * (2 * arb.pi() * K / B) ** alpha
|
|
53
|
+
freq = (arb.pi() * arb(lam) - zeta).exp() / arb.pi() * (arb(1) / (2 * K) + 1 / (alpha * zeta))
|
|
54
|
+
tail = (-arb(B) / 2 + moment(lam, eta, 1, 1)).exp()
|
|
55
|
+
# If the absolute Fourier remainder already exceeds one, avoid a
|
|
56
|
+
# costly inversion and possibly overflowing binary64 transport.
|
|
57
|
+
# These are still valid CDF bounds; keep the analytic tail at B.
|
|
58
|
+
if freq > 1:
|
|
59
|
+
clo, chi = np.zeros(len(xx)), np.ones(len(xx))
|
|
60
|
+
chi[0] = 0
|
|
61
|
+
clo[-1] = max(0.0, out(1 - tail)[0])
|
|
62
|
+
_check_laplace(lam, eta, xlo, xhi, clo, chi)
|
|
63
|
+
return dict(xlo=xlo, xhi=xhi, clo=clo, chi=chi)
|
|
64
|
+
alias = tail / arb(20).expm1()
|
|
65
|
+
a0 = 1 / arb(20).expm1()
|
|
66
|
+
coeff = [None] * M
|
|
67
|
+
for k in range(K + 1):
|
|
68
|
+
s = acb(c, 2 * arb.pi() * k / B)
|
|
69
|
+
v = transform(s, lam, eta) / s
|
|
70
|
+
if k == 0 or k == K:
|
|
71
|
+
coeff[k] = acb(v.real)
|
|
72
|
+
else:
|
|
73
|
+
coeff[k] = v
|
|
74
|
+
coeff[M - k] = v.conjugate()
|
|
75
|
+
ft = acb.dft(coeff, inverse=True)
|
|
76
|
+
del coeff
|
|
77
|
+
lo, hi = np.empty(M + 1), np.empty(M + 1)
|
|
78
|
+
for j in range(M):
|
|
79
|
+
ex = (arb(20) * j / M).exp()
|
|
80
|
+
v = ft[j].real * ex * M / B - a0
|
|
81
|
+
lo[j], hi[j] = out(v + arb(0, (freq * ex).upper()) + arb(0).union(alias))
|
|
82
|
+
del ft
|
|
83
|
+
lo[0] = hi[0] = 0
|
|
84
|
+
lo[M], hi[M] = out(1 - tail)[0], 1
|
|
85
|
+
lo, hi = tighten(lo, hi)
|
|
86
|
+
il = np.maximum(0, np.floor(np.nextafter(xlo * M / B, -np.inf))).astype(int)
|
|
87
|
+
ih = np.minimum(M, np.ceil(np.nextafter(xhi * M / B, np.inf))).astype(int)
|
|
88
|
+
clo, chi = lo[il], hi[ih]
|
|
89
|
+
clo[0] = chi[0] = 0
|
|
90
|
+
_check_laplace(lam, eta, xlo, xhi, clo, chi)
|
|
91
|
+
return dict(xlo=xlo, xhi=xhi, clo=clo, chi=chi)
|
certoutage/_runtime.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""Adaptateurs sans chdir, sans accès à l'archive et sans modification globale permanente."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from contextlib import contextmanager
|
|
5
|
+
from functools import lru_cache
|
|
6
|
+
import threading
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from flint import arb, arb_mat, ctx
|
|
10
|
+
|
|
11
|
+
from . import _banks
|
|
12
|
+
from .models import Model, Numerics
|
|
13
|
+
from ._vendor.commun import out, moment
|
|
14
|
+
from ._vendor.oracles import Signal as OriginalSignal, Environment as OriginalEnvironment
|
|
15
|
+
from ._vendor.ppp import envelopes
|
|
16
|
+
from ._vendor.nak_thermal import Thermal as OriginalThermal
|
|
17
|
+
from ._vendor.nak_grouped import Grouped
|
|
18
|
+
from ._generate import environment_arrays
|
|
19
|
+
|
|
20
|
+
_LOCK = threading.RLock()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@contextmanager
|
|
24
|
+
def arithmetic(bits: int):
|
|
25
|
+
# Arb has process-global settings. Our calls serialize and restore them.
|
|
26
|
+
# Other code changing ctx concurrently must use separate processes.
|
|
27
|
+
with _LOCK:
|
|
28
|
+
prec, threads = ctx.prec, ctx.threads
|
|
29
|
+
ctx.prec, ctx.threads = bits, 1
|
|
30
|
+
try:
|
|
31
|
+
yield
|
|
32
|
+
finally:
|
|
33
|
+
ctx.prec, ctx.threads = prec, threads
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Signal(OriginalSignal):
|
|
37
|
+
def __init__(self, N: int, m: int, chernoff: bool = False):
|
|
38
|
+
self.N = N
|
|
39
|
+
name = f"SIG_{N}.npz" if m == 1 else f"SIG_m{m}_N{N}.npz"
|
|
40
|
+
z = _banks.arrays(name)
|
|
41
|
+
self.names = [name]
|
|
42
|
+
data = {key: z[key] for key in ["exact", "gauss"]}
|
|
43
|
+
if chernoff:
|
|
44
|
+
extra = f"SIG_C_{N}.npz"
|
|
45
|
+
data["chernoff"] = _banks.arrays(extra)["chernoff"]
|
|
46
|
+
self.names.append(extra)
|
|
47
|
+
self.values = {method: (
|
|
48
|
+
[arb(float(x)) for x in np.maximum.accumulate(a[0, ::-1])],
|
|
49
|
+
[arb(float(x)) for x in np.minimum.accumulate(a[1])[::-1]])
|
|
50
|
+
for method, a in data.items()}
|
|
51
|
+
units = z["units128"] if m != 1 else np.arange(-64 * 128, 96 * 128 + 1)
|
|
52
|
+
thresholds = [out((-arb(int(j)) * arb(10).log() / 1280).exp()) for j in units[::-1]]
|
|
53
|
+
self.tlo = np.array([a for a, b in thresholds])
|
|
54
|
+
self.thi = np.array([b for a, b in thresholds])
|
|
55
|
+
self.size = len(units)
|
|
56
|
+
if not all(len(v[0]) == self.size for v in self.values.values()):
|
|
57
|
+
raise ArithmeticError("Dimensions incohérentes dans la banque de signal")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@lru_cache(maxsize=12)
|
|
61
|
+
def signal(N: int, m: int, chernoff: bool, bits: int) -> Signal:
|
|
62
|
+
return Signal(N, m, chernoff)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class Environment(OriginalEnvironment):
|
|
66
|
+
def __init__(self, model: Model, kind: str, numerics: Numerics):
|
|
67
|
+
self.lam, self.eta, self.kind = model.lam, model.eta, kind
|
|
68
|
+
self.names: list[str] = []
|
|
69
|
+
self.generated = False
|
|
70
|
+
if kind in ("mean", "none") or arb(model.lam).is_zero():
|
|
71
|
+
mean = arb(0) if kind == "none" else moment(model.lam, model.eta, 1, 1)
|
|
72
|
+
a, b = (0.0, 0.0) if mean.is_zero() else out(mean)
|
|
73
|
+
self.xlo, self.xhi = np.array([a]), np.array([b])
|
|
74
|
+
wl = wh = [arb(1)]
|
|
75
|
+
self.tail = arb(0)
|
|
76
|
+
else:
|
|
77
|
+
name = f"{kind}_l{str(float(model.lam)).replace('.', 'p')}_e{model.eta}.npz"
|
|
78
|
+
# Only exact decimal equality with the two archived intensities
|
|
79
|
+
# permits reuse; a rounded binary64 filename must never select a bank.
|
|
80
|
+
from decimal import Decimal
|
|
81
|
+
use_bank = Decimal(model.lam) in (Decimal("0.1"), Decimal(1))
|
|
82
|
+
if use_bank and name in _banks.manifest() and numerics.bank_policy == "auto":
|
|
83
|
+
data = _banks.arrays(name)
|
|
84
|
+
self.names = [name]
|
|
85
|
+
else:
|
|
86
|
+
data = environment_arrays(model.lam, model.eta, numerics.ppp_dft_power, kind)
|
|
87
|
+
self.generated = True
|
|
88
|
+
self.xlo, self.xhi = data["xlo"], data["xhi"]
|
|
89
|
+
wl, wh, self.tail = envelopes(data["clo"], data["chi"], self.xlo, self.xhi)
|
|
90
|
+
self.wl, self.wh = arb_mat([wl]), arb_mat([wh])
|
|
91
|
+
self.length = len(wl)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@lru_cache(maxsize=12)
|
|
95
|
+
def environment(model: Model, kind: str, numerics: Numerics) -> Environment:
|
|
96
|
+
return Environment(model, kind, numerics)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class Thermal(OriginalThermal):
|
|
100
|
+
"""Same rectangles as Table I; integrity-checked arrays replace cwd-based files."""
|
|
101
|
+
def __init__(self, N: int, m: int, chernoff: bool):
|
|
102
|
+
self.N = N
|
|
103
|
+
name = f"m{m}_N{N}.npz"
|
|
104
|
+
self.names = [name, "commun.npz"]
|
|
105
|
+
self.bank = _banks.arrays(name)
|
|
106
|
+
self.B = int(self.bank["B"])
|
|
107
|
+
self.dx = self.B / (1 << 19)
|
|
108
|
+
self.common = _banks.arrays("commun.npz")
|
|
109
|
+
self.levels, self.weights, self.arb_values = {}, {}, {}
|
|
110
|
+
if chernoff:
|
|
111
|
+
name = f"C_N{N}.npz"
|
|
112
|
+
self.bank.update(_banks.arrays(name))
|
|
113
|
+
self.names.append(name)
|
|
114
|
+
for method in (["exact", "gauss", "chernoff"] if chernoff else ["exact", "gauss"]):
|
|
115
|
+
self.arb_values[method] = ([arb(float(x)) for x in self.bank[method + "_lo"]],
|
|
116
|
+
[arb(float(x)) for x in self.bank[method + "_hi"]])
|
|
117
|
+
for J in range(9, 14):
|
|
118
|
+
step = 1 << (13 - J)
|
|
119
|
+
z, ph = self.common["z"][::step], self.common["phi"][:, ::step]
|
|
120
|
+
left, right = np.abs(10 + z[:-1]), np.abs(10 + z[1:])
|
|
121
|
+
ml = [(arb(float(x)) / (1 << J)).lower() for x in np.minimum(ph[0, :-1], ph[0, 1:])]
|
|
122
|
+
mh = [(arb(float(x)) / (1 << J)).upper() for x in np.maximum(ph[1, :-1], ph[1, 1:])]
|
|
123
|
+
self.levels[J] = (np.minimum(left, right), np.maximum(left, right), (ml, mh))
|
|
124
|
+
self.weights[J] = arb_mat([ml]), arb_mat([mh])
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@lru_cache(maxsize=1)
|
|
128
|
+
def thermal(N: int, m: int, chernoff: bool, bits: int) -> Grouped:
|
|
129
|
+
return Grouped(Thermal(N, m, chernoff))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def clear() -> None:
|
|
133
|
+
signal.cache_clear()
|
|
134
|
+
environment.cache_clear()
|
|
135
|
+
thermal.cache_clear()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Noyaux extraits de l’archive v7 ; voir docs/EXTRACTION.json."""
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Numerical routines for certified Poisson-interference calculations."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import json, csv, hashlib, time, os, math
|
|
4
|
+
from fractions import Fraction
|
|
5
|
+
import numpy as np
|
|
6
|
+
from flint import arb, acb, arb_mat, ctx
|
|
7
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
8
|
+
|
|
9
|
+
def out(x):
|
|
10
|
+
if not x.is_finite():
|
|
11
|
+
raise ArithmeticError(f"Boule Arb non finie : {x}")
|
|
12
|
+
lo = x.lower()
|
|
13
|
+
hi = x.upper()
|
|
14
|
+
a = np.nextafter(float(lo), -np.inf)
|
|
15
|
+
b = np.nextafter(float(hi), np.inf)
|
|
16
|
+
if not (arb(float(a)) <= lo and arb(float(b)) >= hi):
|
|
17
|
+
raise ArithmeticError(f"Transport binaire64 non extérieur : {x}, {a}, {b}")
|
|
18
|
+
return (a, b)
|
|
19
|
+
|
|
20
|
+
def hull(a, b):
|
|
21
|
+
return arb(float(a)).union(arb(float(b)))
|
|
22
|
+
|
|
23
|
+
def csvwrite(path, rows):
|
|
24
|
+
if not rows:
|
|
25
|
+
return
|
|
26
|
+
with Path(path).open('w') as f:
|
|
27
|
+
w = csv.DictWriter(f, fieldnames=list(rows[0]), lineterminator='\n')
|
|
28
|
+
w.writeheader()
|
|
29
|
+
w.writerows(rows)
|
|
30
|
+
|
|
31
|
+
def jswrite(name, value):
|
|
32
|
+
Path(name).write_text(json.dumps(value, indent=2, ensure_ascii=False) + '\n')
|
|
33
|
+
|
|
34
|
+
def sha(p):
|
|
35
|
+
return hashlib.sha256(Path(p).read_bytes()).hexdigest()
|
|
36
|
+
|
|
37
|
+
def constant_L():
|
|
38
|
+
C = arb(0)
|
|
39
|
+
for j, a in enumerate([1030, 603, 1090, 304, 30, 1]):
|
|
40
|
+
term = arb(1) if j == 0 else arb(j).sqrt() ** j * (-arb(j) / 2).exp()
|
|
41
|
+
C += a * term
|
|
42
|
+
return C / (4 * (2 * arb.pi()).sqrt())
|
|
43
|
+
|
|
44
|
+
def moment(lam, eta, R, j):
|
|
45
|
+
return 2 * arb.pi() * arb(str(lam)) * arb.fac_ui(j) * arb(R) ** (2 - j * eta) / (j * eta - 2)
|
|
46
|
+
|
|
47
|
+
def tail_near(w, lam, eta, R):
|
|
48
|
+
w = arb(w)
|
|
49
|
+
if w.is_zero():
|
|
50
|
+
return arb.pi() * arb(str(lam)) * (R * R - 1)
|
|
51
|
+
alpha = arb(2) / eta
|
|
52
|
+
return 2 * arb.pi() * arb(str(lam)) / eta * w ** (-alpha) * (w.gamma_upper(alpha) - (w * R ** eta).gamma_upper(alpha))
|
|
53
|
+
|
|
54
|
+
def poisson_tail(kappa, nmax):
|
|
55
|
+
n = arb(nmax + 1)
|
|
56
|
+
if not n > kappa:
|
|
57
|
+
raise ArithmeticError(f"Queue de Poisson : n doit dépasser kappa ({n}, {kappa})")
|
|
58
|
+
return (-kappa + n - n * (n / kappa).log()).exp()
|
|
59
|
+
|
|
60
|
+
def env_name(lam, eta, p):
|
|
61
|
+
return 'l' + str(lam).replace('.', 'p') + '_e' + str(eta) + '_p' + str(int(round(-math.log10(p))))
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Même somme de rectangles : regrouper les indices CDF répétés, dans Arb."""
|
|
2
|
+
from .commun import *
|
|
3
|
+
class Grouped:
|
|
4
|
+
def __init__(self,calc):
|
|
5
|
+
self.calc=calc;self.prefix={}
|
|
6
|
+
for J,(_,_,masses) in calc.levels.items():
|
|
7
|
+
pair=[]
|
|
8
|
+
for mass in masses:
|
|
9
|
+
prefix=[arb(0)]
|
|
10
|
+
for x in mass:prefix.append(prefix[-1]+x)
|
|
11
|
+
pair.append(prefix)
|
|
12
|
+
self.prefix[J]=pair
|
|
13
|
+
def dot(self,index,values,prefix):
|
|
14
|
+
cuts=np.r_[0,np.flatnonzero(index[1:]!=index[:-1])+1,len(index)]
|
|
15
|
+
weights=[prefix[int(b)]-prefix[int(a)] for a,b in zip(cuts[:-1],cuts[1:])]
|
|
16
|
+
vals=[values[int(index[int(a)])] for a in cuts[:-1]]
|
|
17
|
+
return (arb_mat([weights])*arb_mat(len(vals),1,vals))[0,0]
|
|
18
|
+
def point(self,db,methods=None,goal=.008):
|
|
19
|
+
calc=self.calc;aa=calc.amplitude(db,1)
|
|
20
|
+
for J in range(9,14):
|
|
21
|
+
il,ih=calc.indices(aa,J);outcome={}
|
|
22
|
+
for method,(lv,hv) in calc.arb_values.items():
|
|
23
|
+
if methods is not None and method not in methods:continue
|
|
24
|
+
lo=self.dot(il,lv,self.prefix[J][0]);hi=self.dot(ih,hv,self.prefix[J][1])+arb(float(calc.common['outside']))
|
|
25
|
+
outcome[method]=(max(0.,out(lo)[0]),min(1.,out(hi)[1]))
|
|
26
|
+
if all(arb(float(b))-arb(float(a))<=arb(str(goal))*arb(float(a)) for a,b in outcome.values()):break
|
|
27
|
+
return outcome,J
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from .thermal_backend import *
|
|
2
|
+
class Thermal:
|
|
3
|
+
def __init__(self,N,m=1,with_chernoff=False):
|
|
4
|
+
self.N=N
|
|
5
|
+
with np.load('banques/m%d_N%d.npz'%(m,N)) as f:self.bank={k:f[k] for k in f.files}
|
|
6
|
+
self.B=int(self.bank['B']);self.dx=self.B/M;self.common=np.load('banques/commun.npz');self.levels={};self.weights={}
|
|
7
|
+
self.arb_values={}
|
|
8
|
+
if with_chernoff:
|
|
9
|
+
with np.load('banques/C_N%d.npz'%N) as f:
|
|
10
|
+
self.bank.update({k:f[k] for k in ['chernoff_lo','chernoff_hi']})
|
|
11
|
+
for name in (['exact','gauss','chernoff'] if with_chernoff else ['exact','gauss']):
|
|
12
|
+
self.arb_values[name]=([arb(float(x)) for x in self.bank[name+'_lo']],[arb(float(x)) for x in self.bank[name+'_hi']])
|
|
13
|
+
for J in range(9,14):
|
|
14
|
+
step=1<<(13-J);z=self.common['z'][::step];ph=self.common['phi'][:,::step]
|
|
15
|
+
left=np.abs(10+z[:-1]);right=np.abs(10+z[1:]);tmin=np.minimum(left,right);tmax=np.maximum(left,right)
|
|
16
|
+
# Les extrêmes exportés sont des dyadiques exacts ; calculs de masse dans Arb.
|
|
17
|
+
ml=[(arb(float(x))/(1<<J)).lower() for x in np.minimum(ph[0,:-1],ph[0,1:])]
|
|
18
|
+
mh=[(arb(float(x))/(1<<J)).upper() for x in np.maximum(ph[1,:-1],ph[1,1:])]
|
|
19
|
+
self.levels[J]=(tmin,tmax,(ml,mh));self.weights[J]=(arb_mat([ml]),arb_mat([mh]))
|
|
20
|
+
def amplitude(self,db,user):
|
|
21
|
+
d=arb(str(db));ci=arb(10)/3 if user==1 else arb(5)/2;lam=arb(1)/(8 if user==1 else 64)
|
|
22
|
+
return outward((101*ci/((d*arb(10).log()/10).exp()*lam)).sqrt())
|
|
23
|
+
def indices(self,aa,J):
|
|
24
|
+
tmin,tmax,_=self.levels[J]
|
|
25
|
+
# IEEE sert seulement à choisir des indices conservateurs ; tous les produits/sommes sont Arb.
|
|
26
|
+
al=np.maximum(0,np.nextafter(aa[0]/tmax,-np.inf))
|
|
27
|
+
with np.errstate(divide='ignore'):ah=np.nextafter(aa[1]/tmin,np.inf)
|
|
28
|
+
il=np.minimum(M,np.floor(np.maximum(0,np.nextafter(al/self.dx,-np.inf)))).astype(np.int64)
|
|
29
|
+
ih=np.minimum(M,np.ceil(np.maximum(0,np.nextafter(ah/self.dx,np.inf)))).astype(np.int64)
|
|
30
|
+
return il,ih
|
|
31
|
+
def point(self,db,user=1,methods=('exact',),goal=.008):
|
|
32
|
+
aa=self.amplitude(db,user);out={}
|
|
33
|
+
for J in range(9,14):
|
|
34
|
+
il,ih=self.indices(aa,J);wl,wh=self.weights[J];length=len(il)
|
|
35
|
+
for name in methods:
|
|
36
|
+
lv,hv=self.arb_values[name]
|
|
37
|
+
lo=(wl*arb_mat(length,1,[lv[int(i)] for i in il]))[0,0]
|
|
38
|
+
hi=(wh*arb_mat(length,1,[hv[int(i)] for i in ih]))[0,0]+arb(float(self.common['outside']))
|
|
39
|
+
out[name]=(max(0.,outward(lo)[0]),min(1.,outward(hi)[1]))
|
|
40
|
+
a,b=out[methods[0]]
|
|
41
|
+
if a>0 and (arb(float(b))-arb(float(a)))<=arb(str(goal))*arb(float(a)):break
|
|
42
|
+
return out,J
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# Corrected public runtime: verifies the excluded left endpoint.
|
|
2
|
+
"""Numerical routines for certified Poisson-interference calculations."""
|
|
3
|
+
from .commun import *
|
|
4
|
+
from .ppp import envelopes
|
|
5
|
+
|
|
6
|
+
def down(x):
|
|
7
|
+
return np.maximum(0.0, np.nextafter(x, -np.inf))
|
|
8
|
+
|
|
9
|
+
def up(x):
|
|
10
|
+
return np.nextafter(x, np.inf)
|
|
11
|
+
|
|
12
|
+
class Signal:
|
|
13
|
+
|
|
14
|
+
def __init__(self, N):
|
|
15
|
+
self.N = N
|
|
16
|
+
with np.load(ROOT / f'banques/SIG_{N}.npz') as z:
|
|
17
|
+
self.values = {m: ([arb(float(x)) for x in np.maximum.accumulate(z[m][0, ::-1])], [arb(float(x)) for x in np.minimum.accumulate(z[m][1])[::-1]]) for m in ['exact', 'gauss']}
|
|
18
|
+
self.size = len(self.values['exact'][0])
|
|
19
|
+
thresholds = [out((-arb(j) * arb(10).log() / 1280).exp()) for j in range(96 * 128, -64 * 128 - 1, -1)]
|
|
20
|
+
self.tlo = np.array([a for a, b in thresholds])
|
|
21
|
+
self.thi = np.array([b for a, b in thresholds])
|
|
22
|
+
assert len(self.tlo) == self.size
|
|
23
|
+
|
|
24
|
+
def indices(self, yl, yh):
|
|
25
|
+
il = np.searchsorted(self.thi, yl, side='right') - 1
|
|
26
|
+
ih = np.searchsorted(self.tlo, yh, side='left')
|
|
27
|
+
return (il, ih)
|
|
28
|
+
|
|
29
|
+
def lookup(self, il, ih, method):
|
|
30
|
+
lv, hv = self.values[method]
|
|
31
|
+
n = self.size
|
|
32
|
+
low = [arb(0) if i < 0 else lv[min(int(i), n - 1)] for i in il]
|
|
33
|
+
high = [arb(1) if i >= n else hv[max(0, int(i))] for i in ih]
|
|
34
|
+
return (low, high)
|
|
35
|
+
|
|
36
|
+
class Environment:
|
|
37
|
+
|
|
38
|
+
def __init__(self, lam, eta, kind):
|
|
39
|
+
self.lam = lam
|
|
40
|
+
self.eta = eta
|
|
41
|
+
self.kind = kind
|
|
42
|
+
if kind == 'mean':
|
|
43
|
+
mean = moment(lam, eta, 1, 1)
|
|
44
|
+
a, b = out(mean)
|
|
45
|
+
self.xlo = np.array([a])
|
|
46
|
+
self.xhi = np.array([b])
|
|
47
|
+
wl = wh = [arb(1)]
|
|
48
|
+
self.tail = arb(0)
|
|
49
|
+
else:
|
|
50
|
+
name = 'l' + str(float(lam)).replace('.', 'p') + '_e' + str(eta)
|
|
51
|
+
with np.load(ROOT / f'banques/{kind}_{name}.npz') as z:
|
|
52
|
+
self.xlo = z['xlo']
|
|
53
|
+
self.xhi = z['xhi']
|
|
54
|
+
wl, wh, self.tail = envelopes(z['clo'], z['chi'], self.xlo, self.xhi)
|
|
55
|
+
self.wl = arb_mat([wl])
|
|
56
|
+
self.wh = arb_mat([wh])
|
|
57
|
+
self.length = len(wl)
|
|
58
|
+
|
|
59
|
+
def point(self, signal, units, convention, user, method='exact'):
|
|
60
|
+
if units is None:
|
|
61
|
+
if convention == 'C-INR':
|
|
62
|
+
return dict(lower=0.0, upper=0.0)
|
|
63
|
+
nlo = nhi = 0.0
|
|
64
|
+
else:
|
|
65
|
+
nlo, nhi = out((-arb(units) * arb(10).log() / 1280).exp())
|
|
66
|
+
if convention == 'C-INR':
|
|
67
|
+
yl = down(down(self.xlo + 1) * nlo)
|
|
68
|
+
yh = up(up(self.xhi + 1) * nhi)
|
|
69
|
+
else:
|
|
70
|
+
yl = down(self.xlo + nlo)
|
|
71
|
+
yh = up(self.xhi + nhi)
|
|
72
|
+
if user == 2:
|
|
73
|
+
yl = down(yl * 6)
|
|
74
|
+
yh = up(yh * 6)
|
|
75
|
+
il, ih = signal.indices(yl, yh)
|
|
76
|
+
low, high = signal.lookup(il, ih, method)
|
|
77
|
+
lo = (self.wl * arb_mat(self.length, 1, low))[0, 0]
|
|
78
|
+
hi = (self.wh * arb_mat(self.length, 1, high))[0, 0] + self.tail
|
|
79
|
+
return dict(lower=max(0.0, out(lo)[0]), upper=min(1.0, out(hi)[1]))
|
|
80
|
+
|
|
81
|
+
def dimension(fn, floor, target):
|
|
82
|
+
p = arb(str(target))
|
|
83
|
+
left = -40 * 16
|
|
84
|
+
right = 96 * 16
|
|
85
|
+
if arb(floor['lower']) > p:
|
|
86
|
+
return dict(status='INATTEIGNABLE', lower_db=None, upper_db=None, undecided=None, floor=floor)
|
|
87
|
+
|
|
88
|
+
def first(condition):
|
|
89
|
+
if condition(fn(left * 8)):
|
|
90
|
+
return left
|
|
91
|
+
if not condition(fn(right * 8)):
|
|
92
|
+
return None
|
|
93
|
+
a, b = (left, right)
|
|
94
|
+
while b - a > 1:
|
|
95
|
+
mid = (a + b) // 2
|
|
96
|
+
if condition(fn(mid * 8)):
|
|
97
|
+
b = mid
|
|
98
|
+
else:
|
|
99
|
+
a = mid
|
|
100
|
+
return b
|
|
101
|
+
good = first(lambda r: arb(r['upper']) <= p)
|
|
102
|
+
not_bad = first(lambda r: arb(r['lower']) <= p)
|
|
103
|
+
bad = not_bad - 1 if not_bad is not None else right
|
|
104
|
+
# The interval may be censored at the search boundary. Never invent an
|
|
105
|
+
# excluded point to the left of the domain, even if the first point is good.
|
|
106
|
+
if bad < left or not arb(fn(bad * 8)['lower']) > p:
|
|
107
|
+
return dict(status='CENSURE_GAUCHE' if good is not None else 'BORNE_GAUCHE_INDECISE',
|
|
108
|
+
lower_db=None, upper_db=good / 16 if good is not None else None,
|
|
109
|
+
undecided=None, floor=floor)
|
|
110
|
+
return dict(status='FINI' if good is not None else 'PLANCHER_INDECIDE' if arb(floor['upper']) >= p else 'HORS_GRILLE', lower_db=bad / 16, upper_db=good / 16 if good is not None else None, undecided=good - bad - 1 if good is not None else None, floor=floor)
|
|
111
|
+
|
|
112
|
+
def difference(a, b):
|
|
113
|
+
if a['status'] == 'FINI' and b['status'] == 'FINI':
|
|
114
|
+
return dict(status='FINI', lower=a['lower_db'] - b['upper_db'], upper=a['upper_db'] - b['lower_db'])
|
|
115
|
+
if a['status'] == 'FINI' and b['status'] == 'INATTEIGNABLE':
|
|
116
|
+
return dict(status='MOINS_INFINI', lower=None, upper=None)
|
|
117
|
+
if a['status'] == 'INATTEIGNABLE' and b['status'] == 'FINI':
|
|
118
|
+
return dict(status='PLUS_INFINI', lower=None, upper=None)
|
|
119
|
+
return dict(status='NON_DEFINI', lower=None, upper=None)
|
|
120
|
+
|
|
121
|
+
def calibration(fn, target):
|
|
122
|
+
a, b = (-40 * 128, 96 * 128)
|
|
123
|
+
middle = lambda r: (r['lower'] + r['upper']) / 2
|
|
124
|
+
assert middle(fn(a)) > target and middle(fn(b)) < target
|
|
125
|
+
while b - a > 1:
|
|
126
|
+
m = (a + b) // 2
|
|
127
|
+
if middle(fn(m)) > target:
|
|
128
|
+
a = m
|
|
129
|
+
else:
|
|
130
|
+
b = m
|
|
131
|
+
va, vb = (fn(a), fn(b))
|
|
132
|
+
return (a, va) if abs(middle(va) - target) <= abs(middle(vb) - target) else (b, vb)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Corrected public runtime: explicit domain guard; see CORRECTIONS.md.
|
|
2
|
+
"""Numerical routines for certified Poisson-interference calculations."""
|
|
3
|
+
from .commun import *
|
|
4
|
+
|
|
5
|
+
def require_eta(eta):
|
|
6
|
+
if eta not in (3, 4):
|
|
7
|
+
raise ValueError("Implemented path-loss exponents are eta=3 or eta=4")
|
|
8
|
+
return eta
|
|
9
|
+
|
|
10
|
+
def J(s, eta):
|
|
11
|
+
require_eta(eta)
|
|
12
|
+
s = acb(s)
|
|
13
|
+
if eta == 4:
|
|
14
|
+
rt = s.sqrt()
|
|
15
|
+
return rt / 2 * rt.atan()
|
|
16
|
+
t = 1 / s ** (arb(1) / 3)
|
|
17
|
+
rt3 = arb(3).sqrt()
|
|
18
|
+
return s ** (arb(2) / 3) * (arb.pi() / (2 * rt3) + (t + 1).log() / 3 - (t * t - t + 1).log() / 6 - ((2 * t - 1) / rt3).atan() / rt3)
|
|
19
|
+
|
|
20
|
+
def transform(s, lam, eta):
|
|
21
|
+
return (-2 * arb.pi() * arb(str(lam)) * J(s, eta)).exp()
|
|
22
|
+
|
|
23
|
+
def envelopes(cdf_lo, cdf_hi, xlo, xhi):
|
|
24
|
+
"""Two genuine discrete stochastic envelopes, not independent mass bounds."""
|
|
25
|
+
L = np.maximum.accumulate(np.clip(cdf_lo, 0, 1))
|
|
26
|
+
U = np.minimum.accumulate(np.clip(cdf_hi, 0, 1)[::-1])[::-1]
|
|
27
|
+
if not (np.all(L <= U) and L[0] == 0 and U[0] == 0):
|
|
28
|
+
raise ArithmeticError("CDF incohérentes : enveloppes croisées ou origine non nulle")
|
|
29
|
+
wl = [arb(float(b)) - arb(float(a)) for a, b in zip(np.r_[0.0, U[1:]], np.r_[U[1:], 1.0])]
|
|
30
|
+
wh = [arb(float(b)) - arb(float(a)) for a, b in zip(np.r_[0.0, L[:-1]], L)]
|
|
31
|
+
if not all(v >= 0 for v in wl + wh):
|
|
32
|
+
raise ArithmeticError("Les masses des enveloppes doivent être positives ou nulles")
|
|
33
|
+
return (wl, wh, arb(1) - arb(float(L[-1])))
|